feat: user jwt login

This commit is contained in:
Noah Hsu
2022-06-25 21:34:44 +08:00
parent 306b90399c
commit c5295f4d72
16 changed files with 269 additions and 21 deletions

View File

@ -0,0 +1,50 @@
package common
import (
"github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors"
"time"
)
var SecretKey []byte
type UserClaims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
func GenerateToken(username string) (tokenString string, err error) {
claim := UserClaims{
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(12 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
}}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
tokenString, err = token.SignedString(SecretKey)
return tokenString, err
}
func ParseToken(tokenString string) (*UserClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
return SecretKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, errors.New("that's not even a token")
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, errors.New("token is expired")
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, errors.New("token not active yet")
} else {
return nil, errors.New("couldn't handle this token")
}
}
}
if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New("couldn't handle this token")
}

View File

@ -0,0 +1,48 @@
package common
import (
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type Resp struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func ErrorResp(c *gin.Context, err error, code int) {
log.Error(err.Error())
c.JSON(200, Resp{
Code: code,
Message: err.Error(),
Data: nil,
})
c.Abort()
}
func ErrorStrResp(c *gin.Context, str string, code int) {
log.Error(str)
c.JSON(200, Resp{
Code: code,
Message: str,
Data: nil,
})
c.Abort()
}
func SuccessResp(c *gin.Context, data ...interface{}) {
if len(data) == 0 {
c.JSON(200, Resp{
Code: 200,
Message: "success",
Data: nil,
})
return
}
c.JSON(200, Resp{
Code: 200,
Message: "success",
Data: data[0],
})
}