Extract loginSuccess to login.go

This commit is contained in:
Jan Bader 2016-11-23 23:18:13 +01:00
parent aa055e944e
commit bd1b3416b4
2 changed files with 32 additions and 30 deletions

View File

@ -2,14 +2,21 @@ 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("authentication")
tokenString, err := c.Cookie(authCookie)
if err != nil {
return false
}
@ -22,7 +29,7 @@ func verifyLogin(c *gin.Context) bool {
})
if !verifyToken(c, token, err) {
c.SetCookie("authentication", "", -1, "", "", false, false)
c.SetCookie(authCookie, "", -1, "", "", false, false)
return false
}
@ -45,3 +52,25 @@ func verifyToken(c *gin.Context, token *jwt.Token, err error) bool {
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,
})
}

29
main.go
View File

@ -2,17 +2,10 @@ package main
import (
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"gopkg.in/gin-gonic/gin.v1"
)
const (
expiration = 72
secret = "uditapbzuditagscwxuqdflgzpbu´ßiaefnlmzeßtrubiadern"
)
func main() {
router := gin.Default()
@ -74,25 +67,5 @@ func loginPost(c *gin.Context) {
return
}
// Create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"usr": "jan",
"name": "Jan Bader",
"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("authentication", t, maxAge, "", "", false, true)
c.JSON(http.StatusOK, map[string]string{
"token": t,
})
return
loginSuccess(c, username, "Jan Bader")
}