package view import ( "encoding/base64" "errors" "net/http" "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(w http.ResponseWriter, r *http.Request) error { templates.WritePageTemplate(w, &templates.LoginPage{}, false) return nil } func (v *AuthView) Logout(w http.ResponseWriter, r *http.Request) error { cook := http.Cookie{ Name: "auth", Value: "", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteDefaultMode, } http.SetCookie(w, &cook) http.Redirect(w, r, "/", http.StatusTemporaryRedirect) return nil } func (v *AuthView) Login(w http.ResponseWriter, r *http.Request) error { var ( username = []byte(r.FormValue("username")) password = []byte(r.FormValue("password")) ) auth, err := v.userController.Login(r.Context(), username, password) if err != nil { return err } if errors.Is(err, service.InvalidLogin) { templates.WritePageTemplate(w, &templates.LoginPage{ Username: r.FormValue("username"), Err: err.Error(), }, false) return nil } if err != nil { return err } base64Auth := base64.StdEncoding.EncodeToString(auth) cook := http.Cookie{ Name: "auth", Value: base64Auth, HttpOnly: true, SameSite: http.SameSiteDefaultMode, } http.SetCookie(w, &cook) redirect := r.FormValue("redirect") if redirect == "" { http.Redirect(w, r, "/", http.StatusTemporaryRedirect) } else { http.Redirect(w, r, redirect, http.StatusTemporaryRedirect) } return nil } func Index(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/login", http.StatusTemporaryRedirect) } func (v *AuthView) InitialRegisterView(w http.ResponseWriter, r *http.Request) error { templates.WritePageTemplate(w, &templates.RegisterPage{}, false) return nil } func (v *AuthView) InitialRegister(w http.ResponseWriter, r *http.Request) error { var ( username = []byte(r.FormValue("username")) password = []byte(r.FormValue("password")) path = []byte(r.FormValue("path")) ) err := v.userController.InitialRegister(r.Context(), username, password, path) if err != nil { return err } http.Redirect(w, r, "/login", http.StatusTemporaryRedirect) 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) }