-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
92 lines (75 loc) · 2.11 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
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
package auth
import (
"log"
"net/http"
"os"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
)
var (
user string
pass string
)
func BasicAuthentication(next http.HandlerFunc) http.HandlerFunc {
return func(response http.ResponseWriter, request *http.Request) {
user = os.Getenv("username")
pass = os.Getenv("password")
username, password, authOK := request.BasicAuth()
if !authOK {
http.Error(response, "Not authorized", http.StatusUnauthorized)
return
}
if username != user || password != pass {
http.Error(response, "Not authorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(response, request)
}
}
func GetToken() (string, error) {
signingKey := []byte("mysecretsigninkeyahasankabirappscode")
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"name": user,
"exp": time.Now().Add(600 * time.Second).Unix(),
})
tokenString, err := token.SignedString(signingKey)
return tokenString, err
}
func verifyToken(tokenString string) (jwt.Claims, error) {
signingKey := []byte("mysecretsigninkeyahasankabirappscode")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return signingKey, nil
})
if err != nil {
return nil, err
}
return token.Claims, err
}
func JWTAuthentication(next http.HandlerFunc) http.HandlerFunc {
return func(response http.ResponseWriter, request *http.Request) {
log.Println("in jwt auth func")
auth := os.Getenv("auth")
log.Println("auth: ", auth)
if auth == "false" {
next.ServeHTTP(response, request)
return
}
tokenString := request.Header.Get("Authorization")
if len(tokenString) == 0 {
response.WriteHeader(http.StatusUnauthorized)
response.Write([]byte("Missing Authorization Header"))
return
}
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
claims, err := verifyToken(tokenString)
if err != nil {
response.WriteHeader(http.StatusUnauthorized)
response.Write([]byte("Error verifying JWT token: " + err.Error()))
return
}
name := claims.(jwt.MapClaims)["name"].(string)
request.Header.Set("name", name)
next.ServeHTTP(response, request)
}
}