fix
This commit is contained in:
@@ -1,45 +0,0 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/home-user-auth/internal/svc"
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type AcceptCookieLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewAcceptCookieLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AcceptCookieLogic {
|
||||
return &AcceptCookieLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *AcceptCookieLogic) AcceptCookie(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
idtyp := userinfo.GetIdType()
|
||||
if idtyp == auth.IDTYPE_Guest {
|
||||
return resp.SetStatus(basic.CodeGuestDupErr)
|
||||
}
|
||||
|
||||
m := l.svcCtx.AllModels.FsGuest
|
||||
token, err := m.GenerateGuestID(l.ctx, &l.svcCtx.Config.Auth.AccessSecret)
|
||||
if err != nil {
|
||||
return resp.SetStatus(basic.CodeGuestGenErr)
|
||||
}
|
||||
return resp.SetStatus(basic.CodeOK, types.DataGuest{
|
||||
Token: token,
|
||||
})
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"net/smtp"
|
||||
"sync"
|
||||
"text/template"
|
||||
"time"
|
||||
)
|
||||
|
||||
var EmailManager *EmailSender
|
||||
|
||||
// EmailSender
|
||||
type EmailSender struct {
|
||||
lock sync.Mutex
|
||||
EmailTasks chan string // 处理email的队列
|
||||
Auth smtp.Auth // 邮箱发送处理
|
||||
FromEmail string // 发送的email, 公司email
|
||||
emailSending map[string]*EmailTask // 正在发送的邮件
|
||||
ResendTimeLimit time.Duration // 重发时间限制
|
||||
}
|
||||
|
||||
// EmailTask
|
||||
type EmailTask struct {
|
||||
Email string // email
|
||||
SendTime time.Time // 处理的任务时间
|
||||
}
|
||||
|
||||
// ProcessEmailTasks 处理邮件队列
|
||||
func (m *EmailSender) ProcessEmailTasks() {
|
||||
for {
|
||||
emailTarget, ok := <-m.EmailTasks
|
||||
if !ok {
|
||||
log.Println("Email task channel closed")
|
||||
break
|
||||
}
|
||||
|
||||
m.lock.Lock()
|
||||
_, isSending := m.emailSending[emailTarget]
|
||||
if isSending {
|
||||
m.lock.Unlock()
|
||||
continue
|
||||
}
|
||||
|
||||
m.emailSending[emailTarget] = &EmailTask{
|
||||
Email: emailTarget,
|
||||
SendTime: time.Now(),
|
||||
}
|
||||
m.lock.Unlock()
|
||||
|
||||
// TODO: Replace with actual email content
|
||||
content := []byte("Hello, this is a test email")
|
||||
err := smtp.SendMail(emailTarget, m.Auth, m.FromEmail, []string{emailTarget}, content)
|
||||
if err != nil {
|
||||
log.Printf("Failed to send email to %s: %v\n", emailTarget, err)
|
||||
m.Resend(emailTarget, content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resend 重发邮件
|
||||
func (m *EmailSender) Resend(emailTarget string, content []byte) {
|
||||
time.Sleep(m.ResendTimeLimit)
|
||||
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
|
||||
// Check if the email task still exists and has not been sent successfully
|
||||
if task, ok := m.emailSending[emailTarget]; ok && task.SendTime.Add(m.ResendTimeLimit).After(time.Now()) {
|
||||
err := smtp.SendMail(emailTarget, m.Auth, m.FromEmail, []string{emailTarget}, content)
|
||||
if err != nil {
|
||||
log.Printf("Failed to resend email to %s: %v\n", emailTarget, err)
|
||||
} else {
|
||||
delete(m.emailSending, emailTarget)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ClearExpiredTasks 清除过期的邮件任务
|
||||
func (m *EmailSender) ClearExpiredTasks() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
<-ticker.C
|
||||
|
||||
m.lock.Lock()
|
||||
for email, task := range m.emailSending {
|
||||
if task.SendTime.Add(m.ResendTimeLimit).Before(time.Now()) {
|
||||
delete(m.emailSending, email)
|
||||
}
|
||||
}
|
||||
m.lock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
// Initialize the email manager
|
||||
EmailManager = &EmailSender{
|
||||
EmailTasks: make(chan string, 10),
|
||||
Auth: smtp.PlainAuth(
|
||||
"",
|
||||
"user@example.com",
|
||||
"password",
|
||||
"smtp.gmail.com",
|
||||
),
|
||||
FromEmail: "user@example.com",
|
||||
emailSending: make(map[string]*EmailTask, 10),
|
||||
ResendTimeLimit: time.Minute * 1,
|
||||
}
|
||||
|
||||
// Start processing email tasks
|
||||
go EmailManager.ProcessEmailTasks()
|
||||
|
||||
// Start clearing expired tasks
|
||||
go EmailManager.ClearExpiredTasks()
|
||||
}
|
||||
|
||||
const emailTemplate = `Subject: Your {{.CompanyName}} Account Confirmation
|
||||
|
||||
Dear
|
||||
|
||||
Thank you for creating an account with {{.CompanyName}}. We're excited to have you on board!
|
||||
|
||||
Before we get started, we just need to confirm that this is the right email address. Please confirm your email address by clicking on the link below:
|
||||
|
||||
{{.ConfirmationLink}}
|
||||
|
||||
Once you've confirmed, you can get started with {{.CompanyName}}. If you have any questions, feel free to reply to this email. We're here to help!
|
||||
|
||||
If you did not create an account with us, please ignore this email.
|
||||
|
||||
Thanks,
|
||||
{{.SenderName}}
|
||||
{{.SenderTitle}}
|
||||
{{.CompanyName}}
|
||||
`
|
||||
|
||||
func RenderEmailTemplate(companyName, recipient, confirmationLink, senderName, senderTitle string) string {
|
||||
tmpl, err := template.New("email").Parse(emailTemplate)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
data := map[string]string{
|
||||
"CompanyName": companyName,
|
||||
"ConfirmationLink": confirmationLink,
|
||||
"SenderName": senderName,
|
||||
"SenderTitle": senderTitle,
|
||||
}
|
||||
|
||||
var result bytes.Buffer
|
||||
err = tmpl.Execute(&result, data)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
return result.String()
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/home-user-auth/internal/svc"
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
|
||||
"github.com/474420502/requests"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
"golang.org/x/net/proxy"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserGoogleLoginLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
|
||||
token string // 登录 token
|
||||
|
||||
isRegistered bool // 是否注册
|
||||
registerToken string // 注册邮箱的token
|
||||
oauthinfo *auth.OAuthInfo
|
||||
}
|
||||
|
||||
func NewUserGoogleLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserGoogleLoginLogic {
|
||||
return &UserGoogleLoginLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// func (l *UserGoogleLoginLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
|
||||
// log.Println(r, w)
|
||||
// }
|
||||
|
||||
func (l *UserGoogleLoginLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
||||
|
||||
if resp.Code == 200 {
|
||||
|
||||
if !l.isRegistered {
|
||||
now := time.Now()
|
||||
rtoken, err := auth.GenerateRegisterToken(
|
||||
&l.svcCtx.Config.Auth.AccessSecret,
|
||||
l.svcCtx.Config.Auth.AccessExpire,
|
||||
now.Unix(),
|
||||
l.oauthinfo.Id,
|
||||
l.oauthinfo.Platform,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
resp.SetStatus(basic.CodeOAuthRegisterTokenErr)
|
||||
}
|
||||
|
||||
l.registerToken = rtoken
|
||||
}
|
||||
|
||||
rurl := fmt.Sprintf(
|
||||
l.svcCtx.Config.MainAddress+"/oauth?token=%s&is_registered=%t®ister_token=%s",
|
||||
l.token,
|
||||
l.isRegistered,
|
||||
l.registerToken,
|
||||
)
|
||||
|
||||
html := fmt.Sprintf(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Redirect</title>
|
||||
<script type="text/javascript">
|
||||
window.onload = function() {
|
||||
window.location = "%s";
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
`, rurl)
|
||||
fmt.Fprintln(w, html)
|
||||
} else {
|
||||
httpx.OkJson(w, resp)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (l *UserGoogleLoginLogic) UserGoogleLogin(req *types.RequestGoogleLogin, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
|
||||
// userinfo 传入值时, 一定不为null
|
||||
|
||||
dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:1080", nil, proxy.Direct)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
customClient := &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Dial: dialer.Dial,
|
||||
},
|
||||
}
|
||||
|
||||
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, customClient)
|
||||
|
||||
var googleOauthConfig = &oauth2.Config{
|
||||
RedirectURL: "http://localhost:9900/api/user/oauth2/login/google",
|
||||
ClientID: l.svcCtx.Config.OAuth.Google.Appid,
|
||||
ClientSecret: l.svcCtx.Config.OAuth.Google.Secret,
|
||||
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"},
|
||||
Endpoint: google.Endpoint,
|
||||
}
|
||||
|
||||
token, err := googleOauthConfig.Exchange(ctx, req.Code)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
resp.SetStatus(basic.CodeApiErr)
|
||||
}
|
||||
ses := requests.NewSession()
|
||||
ses.Config().SetProxy("socks5://127.0.0.1:1080") // 代理 为了测试功能
|
||||
|
||||
r, err := ses.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken).Execute()
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeOAuthGoogleApiErr)
|
||||
}
|
||||
|
||||
log.Println(r.Json())
|
||||
|
||||
googleId := r.Json().Get("id").Int()
|
||||
user, err := l.svcCtx.AllModels.FsUser.FindUserByGoogleId(context.TODO(), googleId)
|
||||
if err != nil {
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeDbSqlErr)
|
||||
}
|
||||
|
||||
// 进入邮件注册流程
|
||||
if req.Email == "" {
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
|
||||
// 这里是注册模块, 发邮件, 通过邮件注册确认邮箱存在
|
||||
|
||||
// 邮箱验证格式错误
|
||||
if !auth.ValidateEmail(req.Email) {
|
||||
return resp.SetStatus(basic.CodeOAuthEmailErr)
|
||||
}
|
||||
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
|
||||
// 如果密码匹配,则生成 JWT Token。
|
||||
nowSec := time.Now().Unix()
|
||||
jwtToken, err := auth.GenerateJwtToken(&l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, nowSec, user.Id, 0)
|
||||
|
||||
// 如果生成 JWT Token 失败,则抛出错误并返回未认证的状态码。
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeServiceErr)
|
||||
}
|
||||
|
||||
l.token = jwtToken
|
||||
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"fusenapi/server/home-user-auth/internal/svc"
|
||||
"fusenapi/server/home-user-auth/internal/types"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserLoginLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
|
||||
token string
|
||||
}
|
||||
|
||||
func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
|
||||
return &UserLoginLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UserLoginLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
|
||||
if l.token != "" {
|
||||
w.Header().Add("Authorization", fmt.Sprintf("Bearer %s", l.token))
|
||||
}
|
||||
|
||||
httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
}
|
||||
|
||||
func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
// 创建一个 FsUserModel 对象 m 并实例化之,该对象用于操作 MySQL 数据库中的用户数据表。
|
||||
m := l.svcCtx.AllModels.FsUser
|
||||
|
||||
// 在用户数据表中根据登录名(email)查找用户记录,并返回 UserModel 类型的结构体对象 userModel。
|
||||
user, err := m.FindUserByEmail(l.ctx, req.Email)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return resp.SetStatus(basic.CodeEmailNotFoundErr)
|
||||
}
|
||||
|
||||
// 如果在用户数据表中找到了登录名匹配的用户记录,则判断密码是否匹配。
|
||||
if *user.PasswordHash != req.Password {
|
||||
logx.Info("密码错误")
|
||||
return resp.SetStatus(basic.CodePasswordErr)
|
||||
}
|
||||
|
||||
// 如果密码匹配,则生成 JWT Token。
|
||||
nowSec := time.Now().Unix()
|
||||
jwtToken, err := auth.GenerateJwtToken(&l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, nowSec, user.Id, 0)
|
||||
|
||||
// 如果生成 JWT Token 失败,则抛出错误并返回未认证的状态码。
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatus(basic.CodeUnAuth)
|
||||
}
|
||||
|
||||
// 如果更新 VerificationToken 字段失败,则返回未认证的状态码。
|
||||
if err != nil {
|
||||
return resp.SetStatus(basic.CodeUnAuth)
|
||||
}
|
||||
|
||||
// 构造 DataUserLogin 类型的数据对象 data 并设置其属性值为生成的 JWT Token。
|
||||
data := &types.DataUserLogin{
|
||||
Token: jwtToken,
|
||||
}
|
||||
|
||||
l.token = jwtToken
|
||||
|
||||
// 返回认证成功的状态码以及数据对象 data 和 JWT Token。
|
||||
return resp.SetStatus(basic.CodeOK, data)
|
||||
}
|
||||
Reference in New Issue
Block a user