-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
94 lines (79 loc) · 2.21 KB
/
Copy pathauth.go
File metadata and controls
94 lines (79 loc) · 2.21 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package handler
import (
"encoding/base64"
"net/http"
"clash-config-store/internal/service"
"clash-config-store/internal/util"
"github.com/gin-gonic/gin"
)
type registerRequest struct {
Email string `json:"email" binding:"required,email"`
Name string `json:"name" binding:"required"`
EncryptedPassword string `json:"encrypted_password" binding:"required"`
}
type loginRequest struct {
Email string `json:"email" binding:"required,email"`
EncryptedPassword string `json:"encrypted_password" binding:"required"`
}
// GetPublicKey 返回 RSA 公钥及过期时间,前端加密密码时使用
func GetPublicKey(c *gin.Context) {
pubPEM, expiresAt, err := util.GetRSAPublicKey()
if err != nil {
Fail(c, http.StatusInternalServerError, "获取公钥失败")
return
}
OK(c, gin.H{
"public_key": pubPEM,
"expires_at": expiresAt.Unix(),
})
}
// Register 注册新用户
func Register(c *gin.Context) {
var req registerRequest
if err := c.ShouldBindJSON(&req); err != nil {
BindFail(c, err)
return
}
password, err := decryptPassword(req.EncryptedPassword)
if err != nil {
Fail(c, http.StatusBadRequest, "密码解密失败,请刷新页面重试")
return
}
token, user, err := service.Register(req.Email, req.Name, password)
if err != nil {
Fail(c, http.StatusBadRequest, err.Error())
return
}
OK(c, gin.H{"token": token, "user": user})
}
// Login 用户登录
func Login(c *gin.Context) {
var req loginRequest
if err := c.ShouldBindJSON(&req); err != nil {
BindFail(c, err)
return
}
password, err := decryptPassword(req.EncryptedPassword)
if err != nil {
Fail(c, http.StatusBadRequest, "密码解密失败,请刷新页面重试")
return
}
token, user, err := service.Login(req.Email, password)
if err != nil {
Fail(c, http.StatusUnauthorized, err.Error())
return
}
OK(c, gin.H{"token": token, "user": user})
}
// decryptPassword base64 解码后用 RSA 私钥解密
func decryptPassword(encryptedB64 string) (string, error) {
ciphertext, err := base64.StdEncoding.DecodeString(encryptedB64)
if err != nil {
return "", err
}
plainBytes, err := util.RSADecrypt(ciphertext)
if err != nil {
return "", err
}
return string(plainBytes), nil
}