aboutsummaryrefslogtreecommitdiff
path: root/pkg/view/auth.go
blob: 631cfb30815cde5ec8694a09073da6a597b8e0a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package view

import (
	"encoding/base64"

	"github.com/valyala/fasthttp"

	"git.sr.ht/~gabrielgio/img/pkg/ext"
	"git.sr.ht/~gabrielgio/img/pkg/service"
	"git.sr.ht/~gabrielgio/img/templates"
)

type AuthView struct {
	userController *service.AuthController
}

func NewAuthView(userController *service.AuthController) *AuthView {
	return &AuthView{
		userController: userController,
	}
}

func (v *AuthView) LoginView(ctx *fasthttp.RequestCtx) error {
	templates.WritePageTemplate(ctx, &templates.LoginPage{})
	return nil
}

func (v *AuthView) Logout(ctx *fasthttp.RequestCtx) error {
	cook := fasthttp.Cookie{}
	cook.SetKey("auth")
	cook.SetValue("")
	cook.SetMaxAge(-1)
	cook.SetHTTPOnly(true)
	cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
	ctx.Response.Header.SetCookie(&cook)

	ctx.Redirect("/", 307)
	return nil
}

func (v *AuthView) Login(ctx *fasthttp.RequestCtx) error {
	username := ctx.FormValue("username")
	password := ctx.FormValue("password")

	auth, err := v.userController.Login(ctx, username, password)
	if err != nil {
		return err
	}

	base64Auth := base64.StdEncoding.EncodeToString(auth)

	cook := fasthttp.Cookie{}
	cook.SetKey("auth")
	cook.SetValue(base64Auth)
	cook.SetHTTPOnly(true)
	cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
	ctx.Response.Header.SetCookie(&cook)

	redirect := string(ctx.FormValue("redirect"))
	if redirect == "" {
		ctx.Redirect("/", 307)
	} else {
		ctx.Redirect(redirect, 307)
	}
	return nil
}

func Index(ctx *fasthttp.RequestCtx) {
	ctx.Redirect("/login", 307)
}

func (v *AuthView) InitialRegisterView(ctx *fasthttp.RequestCtx) error {
	templates.WritePageTemplate(ctx, &templates.RegisterPage{})
	return nil
}

func (v *AuthView) InitialRegister(ctx *fasthttp.RequestCtx) error {
	username := ctx.FormValue("username")
	password := ctx.FormValue("password")
	path := ctx.FormValue("path")

	err := v.userController.InitialRegister(ctx, username, password, path)
	if err != nil {
		return err
	}

	ctx.Redirect("/login", 307)
	return nil
}

func (v *AuthView) SetMyselfIn(r *ext.Router) {
	r.GET("/login", v.LoginView)
	r.POST("/login", v.Login)

	r.GET("/logout", v.Logout)
	r.POST("/logout", v.Logout)

	r.GET("/initial", v.InitialRegisterView)
	r.POST("/initial", v.InitialRegister)
}