lens @ 3e435fc0d032a6cac0bdd15cdb138905ecdb7267

 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/ext"
10	"git.sr.ht/~gabrielgio/img/pkg/service"
11)
12
13type AuthView struct {
14	userController *service.AuthController
15}
16
17func NewAuthView(userController *service.AuthController) *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 Index(ctx *fasthttp.RequestCtx) {
68	ctx.Redirect("/login", 307)
69}
70
71func (v *AuthView) InitialRegisterView(ctx *fasthttp.RequestCtx) error {
72	return img.Render[interface{}](ctx, "register.html", nil)
73}
74
75func (v *AuthView) InitialRegister(ctx *fasthttp.RequestCtx) error {
76	username := ctx.FormValue("username")
77	password := ctx.FormValue("password")
78	path := ctx.FormValue("path")
79
80	err := v.userController.InitialRegister(ctx, username, password, path)
81	if err != nil {
82		return err
83	}
84
85	ctx.Redirect("/login", 307)
86	return nil
87}
88
89func (v *AuthView) SetMyselfIn(r *ext.Router) {
90	r.GET("/login", v.LoginView)
91	r.POST("/login", v.Login)
92
93	r.GET("/logout", v.Logout)
94	r.POST("/logout", v.Logout)
95
96	r.GET("/initial", v.InitialRegisterView)
97	r.POST("/initial", v.InitialRegister)
98}