-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.go
More file actions
180 lines (158 loc) · 4.61 KB
/
auth.go
File metadata and controls
180 lines (158 loc) · 4.61 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"database/sql"
"encoding/json"
"net/http"
"sync"
"time"
"github.com/PiotrTopa/js8web/model"
"github.com/google/uuid"
)
const SESSION_COOKIE_NAME = "js8web_session"
const SESSION_MAX_AGE = 24 * time.Hour
type session struct {
username string
role string
createdAt time.Time
}
var (
sessionsMu sync.RWMutex
sessions = make(map[string]session)
)
func createSession(user *model.User) string {
token := uuid.New().String()
sessionsMu.Lock()
defer sessionsMu.Unlock()
sessions[token] = session{
username: user.Name,
role: user.Role,
createdAt: time.Now(),
}
return token
}
func getSession(token string) (session, bool) {
sessionsMu.RLock()
s, ok := sessions[token]
sessionsMu.RUnlock()
if !ok {
return s, false
}
if time.Since(s.createdAt) > SESSION_MAX_AGE {
sessionsMu.Lock()
delete(sessions, token)
sessionsMu.Unlock()
return s, false
}
return s, true
}
func deleteSession(token string) {
sessionsMu.Lock()
defer sessionsMu.Unlock()
delete(sessions, token)
}
func getSessionFromRequest(r *http.Request) (session, bool) {
cookie, err := r.Cookie(SESSION_COOKIE_NAME)
if err != nil {
return session{}, false
}
return getSession(cookie.Value)
}
// authRequired wraps an http.HandlerFunc and rejects unauthenticated requests.
func authRequired(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, ok := getSessionFromRequest(r)
if !ok {
w.Header().Set("Content-Type", "application/json")
http.Error(w, `{"error":"authentication required"}`, http.StatusUnauthorized)
return
}
next(w, r)
}
}
// roleRequired wraps an http.HandlerFunc and rejects requests from users
// whose role is not in the allowed list. Must be used after authRequired.
func roleRequired(roles []string, next http.HandlerFunc) http.HandlerFunc {
allowed := make(map[string]bool, len(roles))
for _, r := range roles {
allowed[r] = true
}
return func(w http.ResponseWriter, r *http.Request) {
s, ok := getSessionFromRequest(r)
if !ok {
w.Header().Set("Content-Type", "application/json")
http.Error(w, `{"error":"authentication required"}`, http.StatusUnauthorized)
return
}
if !allowed[s.role] {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(authResponse{Ok: false, Error: "insufficient permissions"})
return
}
next(w, r)
}
}
type loginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type authResponse struct {
Ok bool `json:"ok"`
Username string `json:"username,omitempty"`
Role string `json:"role,omitempty"`
Error string `json:"error,omitempty"`
}
func apiAuthLoginPost(w http.ResponseWriter, req *http.Request, db *sql.DB) {
var lr loginRequest
if err := json.NewDecoder(req.Body).Decode(&lr); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(authResponse{Ok: false, Error: "invalid request body"})
return
}
user, err := model.FetchUserByName(db, lr.Username)
if err != nil || !user.CheckPassword(lr.Password) {
logger.Sugar().Warnw("Failed login attempt", "username", lr.Username)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(authResponse{Ok: false, Error: "invalid username or password"})
return
}
token := createSession(user)
http.SetCookie(w, &http.Cookie{
Name: SESSION_COOKIE_NAME,
Value: token,
Path: "/",
MaxAge: int(SESSION_MAX_AGE.Seconds()),
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
logger.Sugar().Infow("User logged in", "username", user.Name, "role", user.Role)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(authResponse{Ok: true, Username: user.Name, Role: user.Role})
}
func apiAuthLogoutPost(w http.ResponseWriter, req *http.Request, db *sql.DB) {
cookie, err := req.Cookie(SESSION_COOKIE_NAME)
if err == nil {
deleteSession(cookie.Value)
}
http.SetCookie(w, &http.Cookie{
Name: SESSION_COOKIE_NAME,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(authResponse{Ok: true})
}
func apiAuthCheckGet(w http.ResponseWriter, req *http.Request, db *sql.DB) {
s, ok := getSessionFromRequest(req)
w.Header().Set("Content-Type", "application/json")
if !ok {
json.NewEncoder(w).Encode(authResponse{Ok: false})
return
}
json.NewEncoder(w).Encode(authResponse{Ok: true, Username: s.username, Role: s.role})
}