-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
49 lines (41 loc) · 1.28 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
package main
import (
"net/http"
"strings"
"github.com/golang-jwt/jwt"
"github.com/miermontoto/url/storage"
)
func DatabaseAuth(storage storage.Storage) func(http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || !storage.AuthenticateUser(username, password) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
r.Header.Set("X-User", username)
next.ServeHTTP(w, r)
}
}
}
func JWTAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
http.Error(w, "Missing token", http.StatusUnauthorized)
return
}
tokenString = tokenString[7:]
claims := &jwt.StandardClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil || !token.Valid {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
r.Header.Set("X-User", claims.Subject)
next.ServeHTTP(w, r)
}
}