You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
2.1 KiB
106 lines
2.1 KiB
package app
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/go-chi/jwtauth/v5"
|
|
"github.com/lestrrat-go/jwx/v2/jwt"
|
|
"github.com/rs/xid"
|
|
"golang.org/x/crypto/bcrypt"
|
|
"gorm.io/gorm"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
|
|
return string(bytes), err
|
|
}
|
|
|
|
func CheckPasswordHash(password, hash string) bool {
|
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
|
return err == nil
|
|
}
|
|
|
|
func GenerateAuthToken(r *Request, uid uint) (*UserToken, error) {
|
|
code := xid.New().String()
|
|
|
|
rawToken, err := jwt.NewBuilder().
|
|
//Audience().
|
|
Expiration(time.Now().Add(time.Hour*24)).
|
|
Issuer(r.URL.Hostname()).
|
|
IssuedAt(time.Now()).
|
|
//JwtID().
|
|
//NotBefore().
|
|
//Subject().
|
|
Claim("uid", uid).
|
|
Claim("code", code).
|
|
Build()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
claims, err := rawToken.AsMap(r.Context())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, accessToken, err := tokenAuth.Encode(claims)
|
|
if err != nil {
|
|
return nil, NewError(1, "生成授权令牌失败")
|
|
}
|
|
|
|
if err = rawToken.Set(jwt.ExpirationKey, time.Now().Add(time.Hour*24*30)); err != nil {
|
|
return nil, err
|
|
}
|
|
if claims, err = rawToken.AsMap(r.Context()); err != nil {
|
|
return nil, err
|
|
}
|
|
_, refreshToken, err := tokenAuth.Encode(claims)
|
|
if err != nil {
|
|
return nil, NewError(1, "生成刷新令牌失败")
|
|
}
|
|
|
|
return &UserToken{
|
|
Code: code,
|
|
AccessToken: accessToken,
|
|
RefreshToken: refreshToken,
|
|
CreatedAt: time.Now(),
|
|
}, nil
|
|
}
|
|
|
|
func AuthInfo(r *Request) (*UserToken, uint, error) {
|
|
token, _, err := jwtauth.FromContext(r.Context())
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
ex := NewError(403, "错误令牌")
|
|
ex.Status = http.StatusForbidden
|
|
|
|
code, ok := token.Get("code")
|
|
if !ok {
|
|
return nil, 0, nil
|
|
}
|
|
if _, ok = code.(string); !ok {
|
|
return nil, 0, ex
|
|
}
|
|
|
|
uidUint, ok := token.Get("uid")
|
|
if !ok {
|
|
return nil, 0, ex
|
|
}
|
|
uid, ok := uidUint.(uint)
|
|
if !ok {
|
|
return nil, 0, ex
|
|
}
|
|
|
|
var ut UserToken
|
|
if err = DB.First(&ut, "code = ?", code).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, 0, ex
|
|
}
|
|
return nil, 0, err
|
|
}
|
|
|
|
return &ut, uid, nil
|
|
}
|
|
|