-
Notifications
You must be signed in to change notification settings - Fork 11
/
authhandler.go
60 lines (52 loc) · 1.61 KB
/
authhandler.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
package main
import (
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
)
func authenticate(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("programName")
password := r.FormValue("programPassword")
if len(name) == 0 || len(password) == 0 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Please provide name and password to obtain the token"))
return
}
if (name == "neo" && password == "keanu") || (name == "morpheus" && password == "lawrence") {
token, err := getToken(name)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error generating JWT token: " + err.Error()))
} else {
w.Header().Set("Authorization", "Bearer "+token)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Token: " + token))
}
} else {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Name and password do not match"))
return
}
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if len(tokenString) == 0 {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Missing Authorization Header"))
return
}
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
claims, err := verifyToken(tokenString)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Error verifying JWT token: " + err.Error()))
return
}
name := claims.(jwt.MapClaims)["name"].(string)
role := claims.(jwt.MapClaims)["role"].(string)
r.Header.Set("name", name)
r.Header.Set("role", role)
next.ServeHTTP(w, r)
})
}