budgeteer/login.go

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