lens @ 3b9d27649a31e5af3fb137ff5b3378e7b8f7b9ae

  1package view
  2
  3import (
  4	"encoding/base64"
  5
  6	"github.com/valyala/fasthttp"
  7
  8	"git.sr.ht/~gabrielgio/img/pkg/ext"
  9	"git.sr.ht/~gabrielgio/img/pkg/service"
 10	"git.sr.ht/~gabrielgio/img/templates"
 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	templates.WritePageTemplate(ctx, &templates.LoginPage{})
 25	return nil
 26}
 27
 28func (v *AuthView) Logout(ctx *fasthttp.RequestCtx) error {
 29	cook := fasthttp.Cookie{}
 30	cook.SetKey("auth")
 31	cook.SetValue("")
 32	cook.SetMaxAge(-1)
 33	cook.SetHTTPOnly(true)
 34	cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
 35	ctx.Response.Header.SetCookie(&cook)
 36
 37	ctx.Redirect("/", 307)
 38	return nil
 39}
 40
 41func (v *AuthView) Login(ctx *fasthttp.RequestCtx) error {
 42	username := ctx.FormValue("username")
 43	password := ctx.FormValue("password")
 44
 45	auth, err := v.userController.Login(ctx, username, password)
 46	if err != nil {
 47		return err
 48	}
 49
 50	base64Auth := base64.StdEncoding.EncodeToString(auth)
 51
 52	cook := fasthttp.Cookie{}
 53	cook.SetKey("auth")
 54	cook.SetValue(base64Auth)
 55	cook.SetHTTPOnly(true)
 56	cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
 57	ctx.Response.Header.SetCookie(&cook)
 58
 59	redirect := string(ctx.FormValue("redirect"))
 60	if redirect == "" {
 61		ctx.Redirect("/", 307)
 62	} else {
 63		ctx.Redirect(redirect, 307)
 64	}
 65	return nil
 66}
 67
 68func Index(ctx *fasthttp.RequestCtx) {
 69	ctx.Redirect("/login", 307)
 70}
 71
 72func (v *AuthView) InitialRegisterView(ctx *fasthttp.RequestCtx) error {
 73	templates.WritePageTemplate(ctx, &templates.RegisterPage{})
 74	return 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}