budgeteer/login.go
2016-12-03 20:30:40 +01:00

82 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
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, bool) {
tokenString, err := c.Cookie(authCookie)
if err != nil {
return nil, false
}
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
})
claims, ok := verifyToken(c, token, err)
if !ok {
c.SetCookie(authCookie, "", -1, "", "", false, false)
return nil, false
}
return claims, true
}
func verifyToken(c *gin.Context, token *jwt.Token, err error) (jwt.MapClaims, bool) {
if err != nil {
return nil, false
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return nil, false
}
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
return nil, false
}
return claims, true
}
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)
}