lens @ 5bb3d3ecabfc658035e69d5d5286cabaf44e3f73

 1package view
 2
 3import (
 4	"encoding/base64"
 5
 6	"github.com/valyala/fasthttp"
 7
 8	"git.sr.ht/~gabrielgio/img"
 9	"git.sr.ht/~gabrielgio/img/pkg/components/auth"
10	"git.sr.ht/~gabrielgio/img/pkg/ext"
11)
12
13type AuthView struct {
14	userController *auth.Controller
15}
16
17func NewAuthView(userController *auth.Controller) *AuthView {
18	return &AuthView{
19		userController: userController,
20	}
21}
22
23func (v *AuthView) LoginView(ctx *fasthttp.RequestCtx) error {
24	return img.Render[interface{}](ctx, "login.html", nil)
25}
26
27func (v *AuthView) Logout(ctx *fasthttp.RequestCtx) error {
28	cook := fasthttp.Cookie{}
29	cook.SetKey("auth")
30	cook.SetValue("")
31	cook.SetMaxAge(-1)
32	cook.SetHTTPOnly(true)
33	cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
34	ctx.Response.Header.SetCookie(&cook)
35
36	ctx.Redirect("/", 307)
37	return nil
38}
39
40func (v *AuthView) Login(ctx *fasthttp.RequestCtx) error {
41	username := ctx.FormValue("username")
42	password := ctx.FormValue("password")
43
44	auth, err := v.userController.Login(ctx, username, password)
45	if err != nil {
46		return err
47	}
48
49	base64Auth := base64.StdEncoding.EncodeToString(auth)
50
51	cook := fasthttp.Cookie{}
52	cook.SetKey("auth")
53	cook.SetValue(base64Auth)
54	cook.SetHTTPOnly(true)
55	cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
56	ctx.Response.Header.SetCookie(&cook)
57
58	redirect := string(ctx.FormValue("redirect"))
59	if redirect == "" {
60		ctx.Redirect("/", 307)
61	} else {
62		ctx.Redirect(redirect, 307)
63	}
64	return nil
65}
66
67func (v *AuthView) RegisterView(ctx *fasthttp.RequestCtx) error {
68	return img.Render[interface{}](ctx, "register.html", nil)
69}
70
71func (v *AuthView) Register(ctx *fasthttp.RequestCtx) error {
72	username := ctx.FormValue("username")
73	password := ctx.FormValue("password")
74
75	err := v.userController.Register(ctx, username, password)
76	if err != nil {
77		return err
78	}
79
80	ctx.Redirect("/login", 307)
81	return nil
82}
83
84func Index(ctx *fasthttp.RequestCtx) {
85	ctx.Redirect("/login", 307)
86}
87
88func (v *AuthView) SetMyselfIn(r *ext.Router) {
89	r.GET("/login", v.LoginView)
90	r.POST("/login", v.Login)
91
92	r.GET("/register", v.RegisterView)
93	r.POST("/register", v.Register)
94
95	r.GET("/logout", v.Logout)
96	r.POST("/logout", v.Logout)
97}