-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.go
88 lines (70 loc) · 1.76 KB
/
auth.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
package server
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/nokia-wroclaw/innovativeproject-togeather/backend/pkg/core"
)
type authHandler struct {
userService core.UserService
}
type registerUser struct {
Name string `json:"name,required"`
}
func (h *authHandler) register(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var payload registerUser
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
user, err := h.userService.Create(ctx, payload.Name)
if err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
respondJSON(w, http.StatusCreated, user)
}
type loginUser struct {
UserID int `json:"id,required"`
}
func (h *authHandler) login(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var payload loginUser
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
u, err := h.userService.Login(ctx, payload.UserID)
if err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
id := strconv.Itoa(payload.UserID)
c := &http.Cookie {
Name: CookieUserIDKey,
Value: id,
Path: "/",
MaxAge: 24*60*60,
HttpOnly: true,
}
http.SetCookie(w, c)
respondJSON(w, http.StatusOK, u)
}
func (h *authHandler) logout(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
_, ok := ctx.Value(UserKey).(*core.User)
if !ok {
respondError(w, http.StatusBadRequest, errors.New("unauthorized"))
return
}
_, err := r.Cookie(CookieUserIDKey)
if err != nil {
respondError(w, http.StatusBadRequest, err)
return
}
//http.SetCookie(w, c)
addCookie(w, CookieUserIDKey, "", -1, "/")
respondJSON(w, http.StatusNoContent, nil)
}