-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
43 lines (33 loc) · 1.23 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Copyright 2023 lichangao(李长傲) <changao.li.work@outlook.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://github.com/changaolee/skeleton.
package auth
import (
"time"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt"
)
// Encrypt 使用 bcrypt 加密纯文本.
func Encrypt(source string) (string, error) {
hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost)
return string(hashedBytes), err
}
// Compare 比较密文和明文是否相同.
func Compare(hashedPassword, password string) error {
return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
}
// Sign 基于给定的 secretID、secretKey、iss 和 aud 生成一个 JWT Token.
func Sign(secretID string, secretKey string, iss, aud string) string {
claims := jwt.MapClaims{
"exp": time.Now().Add(time.Minute).Unix(),
"iat": time.Now().Unix(),
"nbf": time.Now().Add(0).Unix(),
"aud": aud,
"iss": iss,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token.Header["kid"] = secretID
tokenString, _ := token.SignedString([]byte(secretKey))
return tokenString
}