1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
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)
}
|