diff --git a/fs_template/reset_confirm.tpl b/fs_template/reset_confirm.tpl index 72dfba60..8ced71ad 100644 --- a/fs_template/reset_confirm.tpl +++ b/fs_template/reset_confirm.tpl @@ -102,28 +102,70 @@ button:hover { -
-

Reset Password

- -
- +
- - + +
-
- - + +
- - - +
-
+ \ No newline at end of file diff --git a/go.mod b/go.mod index a0803be1..01c94f65 100644 --- a/go.mod +++ b/go.mod @@ -92,6 +92,7 @@ require ( github.com/go-sql-driver/mysql v1.7.1 github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang/protobuf v1.5.3 // indirect + github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.17 // indirect @@ -102,6 +103,7 @@ require ( github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect + github.com/rs/cors v1.9.0 github.com/spaolacci/murmur3 v1.1.0 // indirect go.opentelemetry.io/otel v1.14.0 go.opentelemetry.io/otel/exporters/jaeger v1.14.0 // indirect diff --git a/go.sum b/go.sum index e2b9c05e..67d9f1b0 100644 --- a/go.sum +++ b/go.sum @@ -274,6 +274,8 @@ github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= @@ -482,6 +484,8 @@ github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTE github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rs/cors v1.9.0 h1:l9HGsTsHJcvW14Nk7J9KFz8bzeAWXn3CG6bgt7LsrAE= +github.com/rs/cors v1.9.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= diff --git a/server/auth/internal/handler/routes.go b/server/auth/internal/handler/routes.go index 19a54a86..19bbc47d 100644 --- a/server/auth/internal/handler/routes.go +++ b/server/auth/internal/handler/routes.go @@ -52,6 +52,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/api/auth/reset/password", Handler: UserResetPasswordHandler(serverCtx), }, + { + Method: http.MethodPost, + Path: "/api/auth/reset/password/html", + Handler: UserResetPasswordHtmlHandler(serverCtx), + }, { Method: http.MethodPost, Path: "/api/auth/debug/delete", diff --git a/server/auth/internal/handler/userresetpasswordhtmlhandler.go b/server/auth/internal/handler/userresetpasswordhtmlhandler.go new file mode 100644 index 00000000..142ae43f --- /dev/null +++ b/server/auth/internal/handler/userresetpasswordhtmlhandler.go @@ -0,0 +1,35 @@ +package handler + +import ( + "net/http" + "reflect" + + "fusenapi/utils/basic" + + "fusenapi/server/auth/internal/logic" + "fusenapi/server/auth/internal/svc" + "fusenapi/server/auth/internal/types" +) + +func UserResetPasswordHtmlHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + var req types.RequestUserResetHtml + userinfo, err := basic.RequestParse(w, r, svcCtx, &req) + if err != nil { + return + } + + // 创建一个业务逻辑层实例 + l := logic.NewUserResetPasswordHtmlLogic(r.Context(), svcCtx) + + rl := reflect.ValueOf(l) + basic.BeforeLogic(w, r, rl) + + resp := l.UserResetPasswordHtml(&req, userinfo) + + if !basic.AfterLogic(w, r, rl, resp) { + basic.NormalAfterLogic(w, r, resp) + } + } +} diff --git a/server/auth/internal/logic/useremailconfirmationlogic.go b/server/auth/internal/logic/useremailconfirmationlogic.go index 397d04ea..fff910f4 100644 --- a/server/auth/internal/logic/useremailconfirmationlogic.go +++ b/server/auth/internal/logic/useremailconfirmationlogic.go @@ -144,6 +144,10 @@ func (l *UserEmailConfirmationLogic) UserEmailConfirmation(req *types.RequestEma return resp.SetStatus(basic.CodeOAuthResetTokenDecryptErr, err.Error()) } + if time.Since(rt.CreateAt) > 30*time.Minute { + return resp.SetStatusWithMessage(basic.CodeOAuthConfirmationTimeoutErr, "Verification links expire after 30 minute.") + } + // TODO: 存储 if rt.OperateType != auth.OpTypeResetToken { return resp.SetStatus(basic.CodeOAuthTypeErr, "error OperateType: rt.OperateType != auth.OpTypeResetToken") diff --git a/server/auth/internal/logic/userregisterlogic.go b/server/auth/internal/logic/userregisterlogic.go index 83e0c5bb..b6107754 100644 --- a/server/auth/internal/logic/userregisterlogic.go +++ b/server/auth/internal/logic/userregisterlogic.go @@ -58,7 +58,7 @@ func (l *UserRegisterLogic) UserRegister(req *types.RequestUserRegister, userinf Password: req.Password, Platform: string(auth.PLATFORM_FUSEN), TraceId: uuid.NewString(), - CreateAt: time.Now(), + CreateAt: time.Now().UTC(), Extend: map[string]interface{}{ "first_name": req.FirstName, "last_name": req.LastName, diff --git a/server/auth/internal/logic/userresetpasswordhtmllogic.go b/server/auth/internal/logic/userresetpasswordhtmllogic.go new file mode 100644 index 00000000..af83f80f --- /dev/null +++ b/server/auth/internal/logic/userresetpasswordhtmllogic.go @@ -0,0 +1,61 @@ +package logic + +import ( + "fusenapi/utils/auth" + "fusenapi/utils/basic" + "net/http" + + "context" + + "fusenapi/server/auth/internal/svc" + "fusenapi/server/auth/internal/types" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" +) + +type UserResetPasswordHtmlLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext + ResetToken string +} + +func NewUserResetPasswordHtmlLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserResetPasswordHtmlLogic { + return &UserResetPasswordHtmlLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +// 处理进入前逻辑w,r +// func (l *UserResetPasswordHtmlLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) { +// } + +func (l *UserResetPasswordHtmlLogic) UserResetPasswordHtml(req *types.RequestUserResetHtml, userinfo *auth.UserInfo) (resp *basic.Response) { + // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) + // userinfo 传入值时, 一定不为null + + if len(req.ResetToken) <= 16 { + return resp.SetStatus(basic.CodeOAuthResetTokenDecryptErr) + } + + l.ResetToken = req.ResetToken + + return resp.SetStatus(basic.CodeOK) +} + +// 处理逻辑后 w,r 如:重定向, resp 必须重新处理 +func (l *UserResetPasswordHtmlLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) { + + err := tpls.ExecuteTemplate(w, "reset_confirm.tpl", map[string]string{ + "ResetToken": l.ResetToken, + "ResetPasswordLink": l.svcCtx.Config.MainAddress + "/api/auth/reset/password", + }) + if err != nil { + httpx.OkJsonCtx(l.ctx, w, resp.SetStatusWithMessage(basic.CodeTemplateErr, err.Error())) + } else { + httpx.Ok(w) + } +} diff --git a/server/auth/internal/logic/userresetpasswordlogic.go b/server/auth/internal/logic/userresetpasswordlogic.go index a8016ce2..067bdb3d 100644 --- a/server/auth/internal/logic/userresetpasswordlogic.go +++ b/server/auth/internal/logic/userresetpasswordlogic.go @@ -1,8 +1,11 @@ package logic import ( + "fmt" + "fusenapi/model/gmodel" "fusenapi/utils/auth" "fusenapi/utils/basic" + "fusenapi/utils/wevent" "time" "context" @@ -10,8 +13,8 @@ import ( "fusenapi/server/auth/internal/svc" "fusenapi/server/auth/internal/types" - "github.com/google/uuid" "github.com/zeromicro/go-zero/core/logx" + "gorm.io/gorm" ) type UserResetPasswordLogic struct { @@ -36,43 +39,75 @@ func (l *UserResetPasswordLogic) UserResetPassword(req *types.RequestUserResetPa // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - user, err := l.svcCtx.AllModels.FsUser.FindUserByEmail(context.TODO(), req.Email) + rt, err := l.svcCtx.ResetTokenManger.Decrypt(req.ResetToken) // ResetToken if err != nil { logx.Error(err) - return resp.SetStatus(basic.CodeRequestParamsErr, err.Error()) + return resp.SetStatus(basic.CodeOAuthResetTokenDecryptErr, err.Error()) } - token := &auth.ResetToken{ - // 操作的类型, 验证的token 必须要继承这个 - OperateType: auth.OpTypeResetToken, - UserId: userinfo.UserId, - Wid: req.Wid, - Email: req.Email, - OldPassword: *user.PasswordHash, - TraceId: uuid.NewString(), - CreateAt: time.Now().UTC(), + // TODO: 存储 + if rt.OperateType != auth.OpTypeResetToken { + return resp.SetStatus(basic.CodeOAuthTypeErr, "error OperateType: rt.OperateType != auth.OpTypeResetToken") } - clurl, err := l.svcCtx.ResetTokenManger.Encrypt(token) + if time.Since(rt.CreateAt) > 30*time.Minute { + return resp.SetStatusWithMessage(basic.CodeOAuthConfirmationTimeoutErr, "Verification links expire after 30 minute.") + } + + err = l.svcCtx.AllModels.FsUser.Transaction(l.ctx, func(tx *gorm.DB) error { + user := &gmodel.FsUser{Id: int64(rt.UserId)} + err := tx.Take(user).Error + if err != nil { + return err + } + if *user.PasswordHash != rt.OldPassword { + return fmt.Errorf("password had been reset") + } + return tx.Update("PasswordHash", rt.NewPassword).Error + }) + if err != nil { - logx.Error(err) - return resp.SetStatus(basic.CodeOAuthResetTokenEncryptErr, err.Error()) + return resp.SetStatus(basic.CodeDbSqlErr, err.Error()) } - userName := *user.FirstName + " " + *user.LastName - // 进入发送邮箱的系统 - EmailManager.EmailTasks <- &EmailFormat{ - TemplateName: "reset_password.tpl", - UniqueKey: "register-" + req.Email, - TargetEmail: req.Email, - CompanyName: "fusen", - ConfirmationLink: clurl, - SenderName: "support@fusenpack.com", - SenderTitle: "register-valid", - Extend: map[string]string{ - "UserName": userName, - }, - } // email进入队 + event := wevent.NewWebsocketEventSuccess(wevent.UserResetToken, rt.TraceId) + err = CommonNotify(l.svcCtx.Config.MainAddress, rt.Wid, event) + if err != nil { + logx.Error(err, rt.TraceId) + return resp.SetStatus(basic.CodeResetPasswordErr, err.Error()) + } + + // token := &auth.ResetToken{ + // // 操作的类型, 验证的token 必须要继承这个 + // OperateType: auth.OpTypeResetToken, + // UserId: userinfo.UserId, + // Wid: rt.Wid, + // Email: rt.Email, + // OldPassword: *user.PasswordHash, + // TraceId: uuid.NewString(), + // CreateAt: time.Now().UTC(), + // } + + // clurl, err := l.svcCtx.ResetTokenManger.Encrypt(token) + // if err != nil { + // logx.Error(err) + // return resp.SetStatus(basic.CodeOAuthResetTokenEncryptErr, err.Error()) + // } + + // userName := *user.FirstName + " " + *user.LastName + // // 进入发送邮箱的系统 + // EmailManager.EmailTasks <- &EmailFormat{ + // TemplateName: "reset_password.tpl", + // UniqueKey: "register-" + req.Email, + // TargetEmail: req.Email, + // CompanyName: "fusen", + // ConfirmationLink: clurl, + // SenderName: "support@fusenpack.com", + // SenderTitle: "register-valid", + // Extend: map[string]string{ + // "UserName": userName, + // }, + // } // email进入队 return resp.SetStatus(basic.CodeOK) diff --git a/server/auth/internal/logic/userresettokenlogic.go b/server/auth/internal/logic/userresettokenlogic.go index 5f141663..b13eaa49 100644 --- a/server/auth/internal/logic/userresettokenlogic.go +++ b/server/auth/internal/logic/userresettokenlogic.go @@ -36,8 +36,6 @@ func (l *UserResetTokenLogic) UserResetToken(req *types.RequestUserResetToken, u // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "废弃") - user, err := l.svcCtx.AllModels.FsUser.FindUserByEmail(context.TODO(), req.Email) if err != nil { logx.Error(err) @@ -47,7 +45,7 @@ func (l *UserResetTokenLogic) UserResetToken(req *types.RequestUserResetToken, u token := &auth.ResetToken{ // 操作的类型, 验证的token 必须要继承这个 OperateType: auth.OpTypeResetToken, - UserId: userinfo.UserId, + UserId: user.Id, Wid: req.Wid, Email: req.Email, OldPassword: *user.PasswordHash, @@ -55,17 +53,60 @@ func (l *UserResetTokenLogic) UserResetToken(req *types.RequestUserResetToken, u CreateAt: time.Now().UTC(), } - rtoken, err := l.svcCtx.ResetTokenManger.Encrypt(token) + resetToken, err := l.svcCtx.ResetTokenManger.Encrypt(token) if err != nil { logx.Error(err) return resp.SetStatus(basic.CodeOAuthResetTokenEncryptErr, err.Error()) } - data := types.DataResetToken{ - ResetToken: rtoken, - } + userName := *user.FirstName + " " + *user.LastName + // 进入发送邮箱的系统 + EmailManager.EmailTasks <- &EmailFormat{ + TemplateName: "reset_password.tpl", + UniqueKey: "reset_password-" + req.Email, + TargetEmail: req.Email, + CompanyName: "fusen", + ConfirmationLink: resetToken, // 跳转连接 + SenderName: "support@fusenpack.com", + SenderTitle: "register-valid", + Extend: map[string]string{ + "UserName": userName, + "ResetToken": resetToken, + }, + } // email进入队 - return resp.SetStatus(basic.CodeOK, data) + return resp.SetStatus(basic.CodeOK) + + // return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "废弃") + + // user, err := l.svcCtx.AllModels.FsUser.FindUserByEmail(context.TODO(), req.Email) + // if err != nil { + // logx.Error(err) + // return resp.SetStatus(basic.CodeRequestParamsErr, err.Error()) + // } + + // token := &auth.ResetToken{ + // // 操作的类型, 验证的token 必须要继承这个 + // OperateType: auth.OpTypeResetToken, + // UserId: userinfo.UserId, + // Wid: req.Wid, + // Email: req.Email, + // OldPassword: *user.PasswordHash, + // TraceId: uuid.NewString(), + // CreateAt: time.Now().UTC(), + // } + + // rtoken, err := l.svcCtx.ResetTokenManger.Encrypt(token) + // if err != nil { + // logx.Error(err) + // return resp.SetStatus(basic.CodeOAuthResetTokenEncryptErr, err.Error()) + // } + + // data := types.DataResetToken{ + // ResetToken: rtoken, + // } + + // return resp.SetStatus(basic.CodeOK, data) } // 处理逻辑后 w,r 如:重定向, resp 必须重新处理 diff --git a/server/auth/internal/logic/websocket_test.go b/server/auth/internal/logic/websocket_test.go index 25686261..812ab97e 100644 --- a/server/auth/internal/logic/websocket_test.go +++ b/server/auth/internal/logic/websocket_test.go @@ -4,14 +4,32 @@ import ( "bytes" "fmt" "fusenapi/utils/wevent" + "io" "log" + "net/http" "testing" "github.com/474420502/requests" "github.com/google/uuid" + "github.com/gorilla/mux" + "github.com/rs/cors" "github.com/zeromicro/go-zero/core/logx" ) +func TestPost(t *testing.T) { + r := mux.NewRouter() + + r.HandleFunc("/aaa", func(w http.ResponseWriter, r *http.Request) { + d, _ := io.ReadAll(r.Body) + log.Println(string(d)) + }).Methods("POST") + + handler := cors.Default().Handler(r) + + log.Println("Server listening on :2223") + log.Fatal(http.ListenAndServe(":2223", handler)) +} + func TestEmailTpl(t *testing.T) { data := map[string]string{ "CompanyName": "companyName", diff --git a/server/auth/internal/types/types.go b/server/auth/internal/types/types.go index ca86c6aa..9049c609 100644 --- a/server/auth/internal/types/types.go +++ b/server/auth/internal/types/types.go @@ -36,9 +36,13 @@ type DataResetToken struct { ResetToken string `json:"reset_token"` // 获取重置的token } +type RequestUserResetHtml struct { + ResetToken string `json:"reset_token"` +} + type RequestUserResetPassword struct { - Wid string `json:"wid"` - Email string `json:"email"` // email + ResetToken string `json:"reset_token"` + NewPassword string `json:"new_password"` } type RequestGoogleLogin struct { diff --git a/server_api/auth.api b/server_api/auth.api index b61bbb6f..9ddb3c27 100644 --- a/server_api/auth.api +++ b/server_api/auth.api @@ -28,12 +28,18 @@ service auth { @handler UserEmailRegisterHandler post /api/auth/oauth2/register(RequestEmailRegister) returns (response); + // 发送重置链接到email @handler UserResetTokenHandler post /api/auth/reset/token(RequestUserResetToken) returns (response); + // 重置密码 @handler UserResetPasswordHandler post /api/auth/reset/password(RequestUserResetPassword) returns (response); + // 获取重定向到html页面 + @handler UserResetPasswordHtmlHandler + post /api/auth/reset/password/html(RequestUserResetHtml) returns (response); + @handler DebugAuthDeleteHandler post /api/auth/debug/delete(RequestAuthDelete) returns (response); } @@ -88,10 +94,17 @@ type ( ResetToken string `json:"reset_token"` // 获取重置的token } + // RequestUserResetPassword 重置密码 + RequestUserResetHtml { + ResetToken string `json:"reset_token"` + } + // RequestUserResetPassword 重置密码 RequestUserResetPassword { - Wid string `json:"wid"` - Email string `json:"email"` // email + // Wid string `json:"wid"` + // Email string `json:"email"` // email + ResetToken string `json:"reset_token"` + NewPassword string `json:"new_password"` } ) diff --git a/shared/shared_state.go b/shared/shared_state.go index 85b6c45e..729adbef 100644 --- a/shared/shared_state.go +++ b/shared/shared_state.go @@ -27,7 +27,7 @@ func GetUserState(UserId int64, gdb *gorm.DB) (us *UserState, err error) { userState := &UserState{ UserId: UserId, PwdHash: auth.StringToHash(*user.PasswordHash), - UpdateAt: time.Now(), + UpdateAt: time.Now().UTC(), } return userState, nil