-
Notifications
You must be signed in to change notification settings - Fork 0
/
signin.go
94 lines (80 loc) · 2.25 KB
/
signin.go
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
package user
import (
"encoding/json"
"io"
"net/http"
"time"
"github.com/toastate/toastainer/internal/api/auth"
"github.com/toastate/toastainer/internal/api/settings"
"github.com/toastate/toastainer/internal/config"
"github.com/toastate/toastainer/internal/db/objectdb"
"github.com/toastate/toastainer/internal/db/objectdb/objectdberror"
"github.com/toastate/toastainer/internal/utils"
)
type SigninRequest struct {
Email string `json:"email,omitempty"`
Password string `json:"password,omitempty"`
}
type SigninResponse struct {
Success bool `json:"success,omitempty"`
Session string `json:"session,omitempty"`
}
func Signin(w http.ResponseWriter, r *http.Request) {
sess, continu := signin(w, r)
if continu {
utils.SendSuccess(w, &SigninResponse{
Success: true,
Session: sess,
})
}
}
func CookieSignin(w http.ResponseWriter, r *http.Request) {
sess, continu := signin(w, r)
if continu {
http.SetCookie(w, &http.Cookie{
Name: "toastainer",
Value: sess,
Path: "/",
Domain: config.APIDomain,
Expires: time.Now().Add(24 * time.Hour),
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
utils.SendSuccess(w, &SigninResponse{
Success: true,
})
}
}
func signin(w http.ResponseWriter, r *http.Request) (string, bool) {
req := &SigninRequest{}
body, err := io.ReadAll(io.LimitReader(r.Body, settings.MaxBodySize))
if err != nil {
utils.SendError(w, "could not read request body: "+err.Error(), "invalidBody", 400)
return "", false
}
err = json.Unmarshal(body, req)
if err != nil {
utils.SendError(w, "malformed body: "+err.Error(), "invalidBody", 400)
return "", false
}
usr, err := objectdb.Client.GetUserByEmail(req.Email)
if err != nil {
if err == objectdberror.ErrNotFound {
utils.SendError(w, "email address not found", "notFound", 404)
return "", false
}
utils.SendInternalError(w, "Signin.GetUserByEmail", err)
return "", false
}
if !utils.CheckPasswordHash(req.Password, usr.Password) {
utils.SendError(w, "invalid credentials", "invalidCredentials", 401)
return "", false
}
sess, err := auth.CreateSession(usr, 24*time.Hour)
if err != nil {
utils.SendInternalError(w, "signup:auth.CreateSession", err)
return "", false
}
return sess, true
}