Verify Token
This commit is contained in:
parent
f62ba4a20e
commit
7c104b6fc2
44
main.go
44
main.go
@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@ -57,9 +58,52 @@ func restricted(c *gin.Context) {
|
||||
}
|
||||
|
||||
func login(c *gin.Context) {
|
||||
if verifyLogin(c) {
|
||||
c.Redirect(http.StatusTemporaryRedirect, "/api/v1/hello")
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "login.html", nil)
|
||||
}
|
||||
|
||||
func verifyLogin(c *gin.Context) bool {
|
||||
tokenString, err := c.Cookie("authentication")
|
||||
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(token, err) {
|
||||
c.SetCookie("authentication", "", -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 loginPost(c *gin.Context) {
|
||||
username, _ := c.GetPostForm("username")
|
||||
password, _ := c.GetPostForm("password")
|
||||
|
Loading…
x
Reference in New Issue
Block a user