1package view
2
3import (
4 "encoding/base64"
5 "net/http"
6
7 "git.sr.ht/~gabrielgio/img/pkg/ext"
8 "git.sr.ht/~gabrielgio/img/pkg/service"
9 "git.sr.ht/~gabrielgio/img/templates"
10)
11
12type AuthView struct {
13 userController *service.AuthController
14}
15
16func NewAuthView(userController *service.AuthController) *AuthView {
17 return &AuthView{
18 userController: userController,
19 }
20}
21
22func (v *AuthView) LoginView(w http.ResponseWriter, r *http.Request) error {
23 templates.WritePageTemplate(w, &templates.LoginPage{})
24 return nil
25}
26
27func (v *AuthView) Logout(w http.ResponseWriter, r *http.Request) error {
28 cook := http.Cookie{
29 Name: "auth",
30 Value: "",
31 MaxAge: -1,
32 HttpOnly: true,
33 SameSite: http.SameSiteDefaultMode,
34 }
35 http.SetCookie(w, &cook)
36
37 http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
38 return nil
39}
40
41func (v *AuthView) Login(w http.ResponseWriter, r *http.Request) error {
42 var (
43 username = []byte(r.FormValue("username"))
44 password = []byte(r.FormValue("password"))
45 )
46
47 auth, err := v.userController.Login(r.Context(), username, password)
48 if err != nil {
49 return err
50 }
51
52 base64Auth := base64.StdEncoding.EncodeToString(auth)
53
54 cook := http.Cookie{
55 Name: "auth",
56 Value: base64Auth,
57 HttpOnly: true,
58 SameSite: http.SameSiteDefaultMode,
59 }
60 http.SetCookie(w, &cook)
61
62 redirect := r.FormValue("redirect")
63 if redirect == "" {
64 http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
65 } else {
66 http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
67 }
68 return nil
69}
70
71func Index(w http.ResponseWriter, r *http.Request) {
72 http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
73}
74
75func (v *AuthView) InitialRegisterView(w http.ResponseWriter, r *http.Request) error {
76 templates.WritePageTemplate(w, &templates.RegisterPage{})
77 return nil
78}
79
80func (v *AuthView) InitialRegister(w http.ResponseWriter, r *http.Request) error {
81 var (
82 username = []byte(r.FormValue("username"))
83 password = []byte(r.FormValue("password"))
84 path = []byte(r.FormValue("path"))
85 )
86
87 err := v.userController.InitialRegister(r.Context(), username, password, path)
88 if err != nil {
89 return err
90 }
91
92 http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
93 return nil
94}
95
96func (v *AuthView) SetMyselfIn(r *ext.Router) {
97 r.GET("/login", v.LoginView)
98 r.POST("/login", v.Login)
99
100 r.GET("/logout", v.Logout)
101 r.POST("/logout", v.Logout)
102
103 r.GET("/initial", v.InitialRegisterView)
104 r.POST("/initial", v.InitialRegister)
105}