muyu-apiserver/rpc/system/internal/logic/changepasswordlogic.go
Chever John 71a2d912e2 feat: initial commit for muyu-apiserver
Go service with gateway, RPC, model layers and k8s deploy configs.

Made-with: Cursor
2026-02-28 15:29:16 +08:00

58 lines
1.4 KiB
Go

package logic
import (
"context"
"errors"
"muyu-apiserver/model"
"muyu-apiserver/rpc/system/internal/svc"
"muyu-apiserver/rpc/system/pb"
"github.com/zeromicro/go-zero/core/logx"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type ChangePasswordLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewChangePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePasswordLogic {
return &ChangePasswordLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *ChangePasswordLogic) ChangePassword(in *pb.ChangePasswordReq) (*pb.Empty, error) {
user, err := l.svcCtx.UserModel.FindOneByUserId(l.ctx, in.UserId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, status.Error(codes.NotFound, "user not found")
}
return nil, status.Error(codes.Internal, err.Error())
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(in.OldPassword))
if err != nil {
return nil, status.Error(codes.Unauthenticated, "incorrect old password")
}
hashedPw, err := bcrypt.GenerateFromPassword([]byte(in.NewPassword), bcrypt.DefaultCost)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
user.Password = string(hashedPw)
err = l.svcCtx.UserModel.Update(l.ctx, user)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &pb.Empty{}, nil
}