Repository navigation
Expand file tree
/
Copy pathauth.go
More file actions
206 lines (175 loc) · 5.18 KB
/
Copy pathauth.go
File metadata and controls
206 lines (175 loc) · 5.18 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
const (
sessionCookieName = "funk_session"
sessionMaxAge = 7 * 24 * time.Hour
)
type AuthHandler struct {
configMgr *ConfigManager
}
func newAuthHandler(cm *ConfigManager) *AuthHandler {
return &AuthHandler{configMgr: cm}
}
func signSessionToken(timestamp int64, secret string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(fmt.Sprintf("%d", timestamp)))
signature := hex.EncodeToString(mac.Sum(nil))
return fmt.Sprintf("%d.%s", timestamp, signature)
}
func verifySessionToken(token string, secret string) bool {
parts := strings.Split(token, ".")
if len(parts) != 2 {
return false
}
ts, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return false
}
tokenTime := time.Unix(ts, 0)
if time.Since(tokenTime) > sessionMaxAge || time.Until(tokenTime) > 10*time.Minute {
return false
}
expectedSig := signSessionToken(ts, secret)
return hmac.Equal([]byte(token), []byte(expectedSig))
}
func (a *AuthHandler) isAuthenticated(r *http.Request) bool {
cookie, err := r.Cookie(sessionCookieName)
if err != nil || cookie.Value == "" {
return false
}
cfg := a.configMgr.Get()
return verifySessionToken(cookie.Value, cfg.SessionSecret)
}
func (a *AuthHandler) setSessionCookie(w http.ResponseWriter) {
cfg := a.configMgr.Get()
token := signSessionToken(time.Now().Unix(), cfg.SessionSecret)
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: token,
Path: "/",
MaxAge: int(sessionMaxAge.Seconds()),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
func (a *AuthHandler) clearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
func (a *AuthHandler) RequireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !a.isAuthenticated(r) {
writeJSONError(w, http.StatusUnauthorized, "Unauthorized")
return
}
next(w, r)
}
}
type loginRequest struct {
Password string `json:"password"`
}
func (a *AuthHandler) HandleLogin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeJSONError(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
var req loginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid request body")
return
}
cfg := a.configMgr.Get()
givenHash := hashPassword(req.Password, cfg.PasswordSalt)
if !hmac.Equal([]byte(givenHash), []byte(cfg.PasswordHash)) {
writeJSONError(w, http.StatusUnauthorized, "Incorrect password")
return
}
a.setSessionCookie(w)
writeJSON(w, http.StatusOK, map[string]interface{}{
"ok": true,
"is_default_password": cfg.IsDefaultPass,
})
}
func (a *AuthHandler) HandleLogout(w http.ResponseWriter, r *http.Request) {
a.clearSessionCookie(w)
writeJSON(w, http.StatusOK, map[string]interface{}{"ok": true})
}
func (a *AuthHandler) HandleMe(w http.ResponseWriter, r *http.Request) {
auth := a.isAuthenticated(r)
cfg := a.configMgr.Get()
writeJSON(w, http.StatusOK, map[string]interface{}{
"authenticated": auth,
"is_default_password": cfg.IsDefaultPass,
})
}
type changePasswordRequest struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
func (a *AuthHandler) HandleChangePassword(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeJSONError(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
var req changePasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON payload")
return
}
if len(req.NewPassword) < 4 {
writeJSONError(w, http.StatusBadRequest, "New password must be at least 4 characters")
return
}
cfg := a.configMgr.Get()
currentHash := hashPassword(req.CurrentPassword, cfg.PasswordSalt)
if !hmac.Equal([]byte(currentHash), []byte(cfg.PasswordHash)) {
writeJSONError(w, http.StatusBadRequest, "Current password is incorrect")
return
}
newSalt := generateRandomHex(16)
newHash := hashPassword(req.NewPassword, newSalt)
newSecret := generateRandomHex(32) // reset session secret to invalidate old sessions
err := a.configMgr.Update(func(c *AppConfig) error {
c.PasswordSalt = newSalt
c.PasswordHash = newHash
c.SessionSecret = newSecret
c.IsDefaultPass = false
return nil
})
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to save new password: "+err.Error())
return
}
a.setSessionCookie(w)
writeJSON(w, http.StatusOK, map[string]interface{}{
"ok": true,
"message": "Password changed successfully",
})
}
func writeJSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(data)
}
func writeJSONError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]interface{}{
"ok": false,
"error": message,
})
}