package view import ( "encoding/base64" "github.com/valyala/fasthttp" "git.sr.ht/~gabrielgio/img" "git.sr.ht/~gabrielgio/img/pkg/ext" "git.sr.ht/~gabrielgio/img/pkg/service" "git.sr.ht/~gabrielgio/img/templates" ) type AuthView struct { userController *service.AuthController } func NewAuthView(userController *service.AuthController) *AuthView { return &AuthView{ userController: userController, } } func (v *AuthView) LoginView(ctx *fasthttp.RequestCtx) error { templates.WritePageTemplate(ctx, &templates.LoginPage{}) return nil } func (v *AuthView) Logout(ctx *fasthttp.RequestCtx) error { cook := fasthttp.Cookie{} cook.SetKey("auth") cook.SetValue("") cook.SetMaxAge(-1) cook.SetHTTPOnly(true) cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode) ctx.Response.Header.SetCookie(&cook) ctx.Redirect("/", 307) return nil } func (v *AuthView) Login(ctx *fasthttp.RequestCtx) error { username := ctx.FormValue("username") password := ctx.FormValue("password") auth, err := v.userController.Login(ctx, username, password) if err != nil { return err } base64Auth := base64.StdEncoding.EncodeToString(auth) cook := fasthttp.Cookie{} cook.SetKey("auth") cook.SetValue(base64Auth) cook.SetHTTPOnly(true) cook.SetSameSite(fasthttp.CookieSameSiteDefaultMode) ctx.Response.Header.SetCookie(&cook) redirect := string(ctx.FormValue("redirect")) if redirect == "" { ctx.Redirect("/", 307) } else { ctx.Redirect(redirect, 307) } return nil } func Index(ctx *fasthttp.RequestCtx) { ctx.Redirect("/login", 307) } func (v *AuthView) InitialRegisterView(ctx *fasthttp.RequestCtx) error { return img.Render[interface{}](ctx, "register.html", nil) } func (v *AuthView) InitialRegister(ctx *fasthttp.RequestCtx) error { username := ctx.FormValue("username") password := ctx.FormValue("password") path := ctx.FormValue("path") err := v.userController.InitialRegister(ctx, username, password, path) if err != nil { return err } ctx.Redirect("/login", 307) return nil } func (v *AuthView) SetMyselfIn(r *ext.Router) { r.GET("/login", v.LoginView) r.POST("/login", v.Login) r.GET("/logout", v.Logout) r.POST("/logout", v.Logout) r.GET("/initial", v.InitialRegisterView) r.POST("/initial", v.InitialRegister) }