aboutsummaryrefslogtreecommitdiff
path: root/pkg/view/auth.go
blob: 5c83eba0225998cda97795f1747f3d73894e9f4d (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
package view

import (
	"encoding/base64"

	"github.com/valyala/fasthttp"

	"git.sr.ht/~gabrielgio/img"
	"git.sr.ht/~gabrielgio/img/pkg/components/auth"
	"git.sr.ht/~gabrielgio/img/pkg/ext"
)

type AuthView struct {
	userController *auth.Controller
}

func NewAuthView(userController *auth.Controller) *AuthView {
	return &AuthView{
		userController: userController,
	}
}

func (v *AuthView) LoginView(ctx *fasthttp.RequestCtx) error {
	return img.Render[interface{}](ctx, "login.html", 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 (v *AuthView) RegisterView(ctx *fasthttp.RequestCtx) error {
	return img.Render[interface{}](ctx, "register.html", nil)
}

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

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

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

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

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

	r.GET("/register", v.RegisterView)
	r.POST("/register", v.Register)

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