Merge branch 'develop' of gitee.com:fusenpack/fusenapi into develop

This commit is contained in:
laodaming 2023-09-05 15:08:11 +08:00
commit fe270ed8e3
14 changed files with 321 additions and 57 deletions

View File

@ -102,28 +102,70 @@ button:hover {
</head>
<body>
<div class="container">
<h2>Reset Password</h2>
<form>
<form id="resetForm">
<div class="form-group">
<label for="newPassword">New Password</label>
<input id="newPassword" type="password" placeholder="New password" required pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$">
<label for="new_password">New Password</label>
<input id="new_password" type="password" placeholder="New password" required pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$">
</div>
<div class="form-group">
<label for="confirmPassword">Confirm Password</label>
<input id="confirmPassword" type="password" placeholder="Confirm password" required pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$">
<label for="confirm_password">Confirm Password</label>
<input id="confirm_password" type="password" placeholder="Confirm password" required pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$">
</div>
<button type="submit">Reset Password</button>
<button type="button" onclick="resetPassword()">Reset Password</button>
</form>
</div>
<script>
function resetPassword() {
const new_password = document.getElementById("new_password").value;
const confirm_password = document.getElementById("confirm_password").value;
if (new_password !== confirm_password) {
alert("Passwords do not match");
return;
}
sha256ToBase64(new_password).then((hash) => {
const data = {
new_password: hash,
reset_token: "{{.ResetToken}}",
};
fetch('{{.ResetPasswordLink}}', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
if (response.ok) {
console.log('Password reset successful');
// 在这里执行其他成功处理逻辑
} else {
console.error('Password reset failed');
// 在这里执行其他失败处理逻辑
}
})
.catch(error => {
console.error('Error:', error);
// 在这里处理其他错误情况
});
});
}
function sha256ToBase64(message) {
const msgBuffer = new TextEncoder().encode(message);
return crypto.subtle.digest('SHA-256', msgBuffer).then((hashBuffer) => {
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashBase64 = btoa(hashArray.reduce((str, byte) => str + String.fromCharCode(byte), ''));
return hashBase64;
});
}
</script>
</body>
</html>

2
go.mod
View File

@ -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

4
go.sum
View File

@ -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=

View File

@ -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",

View File

@ -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)
}
}
}

View File

@ -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")

View File

@ -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,

View File

@ -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)
}
}

View File

@ -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)

View File

@ -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 必须重新处理

View File

@ -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",

View File

@ -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 {

View File

@ -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"`
}
)

View File

@ -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