lens @ e1c8bb1bd5381d8ade3c699a2d6b4fb373112880

 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 Index(ctx *fasthttp.RequestCtx) {
68	ctx.Redirect("/login", 307)
69}
70
71func (v *AuthView) SetMyselfIn(r *ext.Router) {
72	r.GET("/login", v.LoginView)
73	r.POST("/login", v.Login)
74
75	r.GET("/logout", v.Logout)
76	r.POST("/logout", v.Logout)
77}