Repository navigation
Expand file tree
/
Copy pathauth.go
More file actions
98 lines (84 loc) · 2.68 KB
/
Copy pathauth.go
File metadata and controls
98 lines (84 loc) · 2.68 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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
const (
cookieName = "minedash_session"
jwtTTL = 24 * time.Hour
)
// loginRequest is the expected JSON body for POST /login.
type loginRequest struct {
Password string `json:"password"`
}
// loginHandler verifies the password against the bcrypt hash and issues a JWT cookie.
func loginHandler(cfg Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req loginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
errorJSON(w, http.StatusBadRequest, "invalid request body")
return
}
if err := bcrypt.CompareHashAndPassword([]byte(cfg.AuthPasswordHash), []byte(req.Password)); err != nil {
errorJSON(w, http.StatusUnauthorized, "invalid password")
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(jwtTTL)),
IssuedAt: jwt.NewNumericDate(time.Now()),
})
signed, err := token.SignedString([]byte(cfg.JWTSecret))
if err != nil {
errorJSON(w, http.StatusInternalServerError, "failed to create session")
return
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: signed,
Path: "/",
MaxAge: int(jwtTTL.Seconds()),
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
}
// logoutHandler clears the session cookie.
func logoutHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
writeJSON(w, http.StatusOK, map[string]string{"status": "logged out"})
}
}
// jwtMiddleware validates the JWT cookie before passing to the next handler.
// If the cookie is missing or invalid it returns 401.
func jwtMiddleware(cfg Config, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !hasSession(cfg, r) {
errorJSON(w, http.StatusUnauthorized, "invalid or expired session")
return
}
next.ServeHTTP(w, r)
})
}
// hasSession checks the signature and expiry rather than just cookie presence.
func hasSession(cfg Config, r *http.Request) bool {
cookie, err := r.Cookie(cookieName)
if err != nil {
return false
}
token, err := jwt.ParseWithClaims(cookie.Value, &jwt.RegisteredClaims{}, func(t *jwt.Token) (any, error) {
return []byte(cfg.JWTSecret), nil
}, jwt.WithValidMethods([]string{"HS256"}), jwt.WithExpirationRequired())
return err == nil && token.Valid
}