2023-07-27 02:18:49 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2023-07-28 04:15:56 +00:00
|
|
|
"fusenapi/utils/encryption_decryption"
|
2023-07-27 02:18:49 +00:00
|
|
|
"net/url"
|
|
|
|
)
|
|
|
|
|
2023-07-27 08:48:43 +00:00
|
|
|
type OperateType int8
|
|
|
|
|
|
|
|
const (
|
2023-08-11 09:39:18 +00:00
|
|
|
OpTypeRegister OperateType = 1 //注册的操作类型
|
|
|
|
OpTypeResetToken OperateType = 2 //重置密码类型
|
2023-07-27 08:48:43 +00:00
|
|
|
)
|
|
|
|
|
2023-07-27 02:18:49 +00:00
|
|
|
type ConfirmationLink[T any] struct {
|
2023-07-28 04:15:56 +00:00
|
|
|
// Secret []byte
|
|
|
|
SecretGCM *encryption_decryption.SecretGCM[T]
|
|
|
|
|
2023-07-27 02:18:49 +00:00
|
|
|
DefaultQueryKey string // 默认key 是 token
|
|
|
|
link *url.URL
|
|
|
|
}
|
|
|
|
|
2023-07-28 04:15:56 +00:00
|
|
|
func NewConfirmationLink[T any](key string, UrlStr string) *ConfirmationLink[T] {
|
2023-07-27 02:18:49 +00:00
|
|
|
u, err := url.Parse(UrlStr)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &ConfirmationLink[T]{
|
2023-07-28 04:15:56 +00:00
|
|
|
SecretGCM: encryption_decryption.NewSecretGCM[T](key),
|
2023-07-27 02:18:49 +00:00
|
|
|
DefaultQueryKey: "token",
|
|
|
|
link: u,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate 序列化链接传入需求的obj
|
|
|
|
func (cl *ConfirmationLink[T]) Generate(obj *T) (string, error) {
|
|
|
|
|
|
|
|
token, err := cl.Encrypt(obj)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return cl.GenerateWithToken(token)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateWithToken 序列化url带token
|
|
|
|
func (cl *ConfirmationLink[T]) GenerateWithToken(token string) (string, error) {
|
|
|
|
|
|
|
|
q := cl.link.Query()
|
|
|
|
if q.Has(cl.DefaultQueryKey) {
|
|
|
|
q.Set(cl.DefaultQueryKey, token)
|
|
|
|
} else {
|
|
|
|
q.Add(cl.DefaultQueryKey, token)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 生成确认链接
|
|
|
|
cl.link.RawQuery = q.Encode()
|
|
|
|
|
|
|
|
return cl.link.String(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cl *ConfirmationLink[T]) Encrypt(obj *T) (string, error) {
|
2023-07-28 04:15:56 +00:00
|
|
|
return cl.SecretGCM.Encrypt(obj)
|
2023-07-27 02:18:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cl *ConfirmationLink[T]) Decrypt(ciphertext string) (*T, error) {
|
2023-07-28 04:15:56 +00:00
|
|
|
return cl.SecretGCM.Decrypt(ciphertext)
|
2023-07-27 02:18:49 +00:00
|
|
|
}
|