Mercurial > gemma
diff auth/token.go @ 119:29e56c342c9f
Added first middleware for JWT token extraction. TODO: Add second one to check against logged in users.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Tue, 26 Jun 2018 18:29:26 +0200 |
parents | |
children | bb9120d28950 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/auth/token.go Tue Jun 26 18:29:26 2018 +0200 @@ -0,0 +1,40 @@ +package auth + +import ( + "time" + + "gemma.intevation.de/gemma/config" + + jwt "github.com/dgrijalva/jwt-go" +) + +type Claims struct { + jwt.StandardClaims + + User string `json:"user"` + Roles []string `json:"roles"` +} + +const maxTokenValid = time.Hour * 3 + +func NewToken(user string, roles []string) (string, error) { + + // Create the Claims + claims := &Claims{ + StandardClaims: jwt.StandardClaims{ + ExpiresAt: jwt.TimeFunc().Add(maxTokenValid).Unix(), + }, + User: user, + Roles: roles, + } + + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + return token.SignedString(config.Config.JWTSignKey) +} + +func TokenToClaims(token string) (*Claims, error) { + claims := &Claims{} + _, err := jwt.ParseWithClaims(token, claims, + func(*jwt.Token) (interface{}, error) { return config.Config.JWTSignKey, nil }) + return claims, err +}