@@ -1,8 +1,12 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/yauthdev/yauth/server/constants"
|
||||
"github.com/yauthdev/yauth/server/enum"
|
||||
@@ -37,3 +41,34 @@ func CreateAuthToken(user UserAuthInfo, tokenType enum.TokenType) (string, error
|
||||
|
||||
return t.SignedString([]byte(constants.JWT_SECRET))
|
||||
}
|
||||
|
||||
func GetAuthToken(gc *gin.Context) (string, error) {
|
||||
token := ""
|
||||
cookie, err := gc.Request.Cookie(constants.COOKIE_NAME)
|
||||
if err != nil {
|
||||
// try to check in auth header for cookie
|
||||
log.Println("cookie not found checking headers")
|
||||
auth := gc.Request.Header.Get("Authorization")
|
||||
if auth == "" {
|
||||
return "", errors.New(`Unauthorized`)
|
||||
}
|
||||
|
||||
token = strings.TrimPrefix(auth, "Bearer ")
|
||||
} else {
|
||||
token = cookie.Value
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func VerifyAuthToken(token string) (*UserAuthClaim, error) {
|
||||
claims := &UserAuthClaim{}
|
||||
_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(constants.JWT_SECRET), nil
|
||||
})
|
||||
if err != nil {
|
||||
return claims, err
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
@@ -15,3 +15,14 @@ func SetCookie(gc *gin.Context, token string) {
|
||||
|
||||
gc.SetCookie(constants.COOKIE_NAME, token, 3600, "/", GetFrontendHost(), secure, httpOnly)
|
||||
}
|
||||
|
||||
func DeleteCookie(gc *gin.Context) {
|
||||
secure := true
|
||||
httpOnly := true
|
||||
|
||||
if !constants.IS_PROD {
|
||||
secure = false
|
||||
}
|
||||
|
||||
gc.SetCookie(constants.COOKIE_NAME, "", -1, "/", GetFrontendHost(), secure, httpOnly)
|
||||
}
|
||||
|
Reference in New Issue
Block a user