lens @ 1d9d5f40fe4092657f529bdba18f6f52511eea00

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