Move login.go to jwt subpackage
This commit is contained in:
85
jwt/login.go
Normal file
85
jwt/login.go
Normal file
@ -0,0 +1,85 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"gopkg.in/gin-gonic/gin.v1"
|
||||
)
|
||||
|
||||
const (
|
||||
expiration = 72
|
||||
secret = "uditapbzuditagscwxuqdflgzpbu´ßiaefnlmzeßtrubiadern"
|
||||
authCookie = "authentication"
|
||||
)
|
||||
|
||||
func verifyLogin(c *gin.Context) (jwt.MapClaims, error) {
|
||||
tokenString, err := c.Cookie(authCookie)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
c.SetCookie(authCookie, "", -1, "", "", false, false)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, err := verifyToken(token)
|
||||
if err != nil {
|
||||
c.SetCookie(authCookie, "", -1, "", "", false, false)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func verifyToken(token *jwt.Token) (jwt.MapClaims, error) {
|
||||
if !token.Valid {
|
||||
return nil, fmt.Errorf("Token is not valid")
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Claims are not of Type MapClaims")
|
||||
}
|
||||
|
||||
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
|
||||
return nil, fmt.Errorf("Claims have expired")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func loginSuccess(c *gin.Context, username string, name string) {
|
||||
// Create token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"usr": username,
|
||||
"name": name,
|
||||
"exp": time.Now().Add(time.Hour * expiration).Unix(),
|
||||
})
|
||||
|
||||
// Generate encoded token and send it as response.
|
||||
t, err := token.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
maxAge := (int)((expiration * time.Hour).Seconds())
|
||||
c.SetCookie(authCookie, t, maxAge, "", "", false, true)
|
||||
|
||||
c.JSON(http.StatusOK, map[string]string{
|
||||
"token": t,
|
||||
})
|
||||
}
|
||||
|
||||
func clearLogin(c *gin.Context) {
|
||||
c.SetCookie(authCookie, "", -1, "", "", false, true)
|
||||
}
|
Reference in New Issue
Block a user