forked from markcheno/go-vue-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
47 lines (40 loc) · 1.31 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
package auth
import (
"net/http"
"time"
jwtmiddleware "github.com/auth0/go-jwt-middleware"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/context"
"github.com/markcheno/go-vue-starter/models"
)
// signingKey set up a global string for our secret
var signingKey = []byte("knrjkevdckjh")
// JwtMiddleware handler for jwt tokens
var JwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return signingKey, nil
},
UserProperty: "user",
Debug: false,
SigningMethod: jwt.SigningMethodHS256,
})
// GetToken create a jwt token with user claims
func GetToken(user *models.User) string {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["uuid"] = user.UUID
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
signedToken, _ := token.SignedString(signingKey)
return signedToken
}
// GetJSONToken create a JSON token string
func GetJSONToken(user *models.User) string {
token := GetToken(user)
jsontoken := "{\"id_token\": \"" + token + "\"}"
return jsontoken
}
// GetUserClaimsFromContext return "user" claims as a map from request
func GetUserClaimsFromContext(req *http.Request) map[string]interface{} {
claims := context.Get(req, "user").(*jwt.Token).Claims.(jwt.MapClaims)
return claims
}