aeus-admin/service/profile.go

114 lines
2.7 KiB
Go

package service
import (
"context"
"git.nobla.cn/golang/aeus-admin/models"
"git.nobla.cn/golang/aeus-admin/pb"
"git.nobla.cn/golang/aeus/middleware/auth"
"git.nobla.cn/golang/aeus/pkg/errors"
"gorm.io/gorm"
)
type (
profileOptions struct {
db *gorm.DB
}
ProfileOption func(o *profileOptions)
ProfileService struct {
opts *profileOptions
}
)
func WithProfileDB(db *gorm.DB) ProfileOption {
return func(o *profileOptions) {
o.db = db
}
}
func (s *ProfileService) getUidFromContext(ctx context.Context) (string, error) {
if claims, ok := auth.FromContext(ctx); !ok {
return "", errors.ErrAccessDenied
} else {
return claims.GetSubject()
}
}
func (s *ProfileService) GetProfile(ctx context.Context, req *pb.GetProfileRequest) (res *pb.GetProfileResponse, err error) {
if req.Uid == "" {
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
return
}
}
res = &pb.GetProfileResponse{}
tx := s.opts.db.WithContext(ctx)
err = tx.Table("users AS u").Select("u.uid as uid", "u.username", "u.avatar", "u.email", "u.description", "u.role_id as role").Where("u.uid=? ", req.Uid).First(res).Error
return
}
func (s *ProfileService) UpdateProfile(ctx context.Context, req *pb.UpdateProfileRequest) (res *pb.UpdateProfileResponse, err error) {
if req.Uid == "" {
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
return
}
}
userModel := &models.User{}
tx := s.opts.db.WithContext(ctx)
if err = tx.Where("uid=?", req.Uid).First(userModel).Error; err != nil {
return
}
if req.Avatar != "" {
userModel.Avatar = req.Avatar
}
if req.Email != "" {
userModel.Email = req.Email
}
if req.Username != "" {
userModel.Username = req.Username
}
if req.Description != "" {
userModel.Description = req.Description
}
if err = tx.Save(userModel).Error; err == nil {
res = &pb.UpdateProfileResponse{
Uid: userModel.Uid,
}
}
return
}
func (s *ProfileService) ResetPassword(ctx context.Context, req *pb.ResetPasswordRequest) (res *pb.ResetPasswordResponse, err error) {
if req.Uid == "" {
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
return
}
}
userModel := &models.User{}
tx := s.opts.db.WithContext(ctx)
if err = tx.Where("uid=?", req.Uid).First(userModel).Error; err != nil {
return
}
if userModel.Password == req.OldPassword {
if err = tx.Where("uid=?", req.Uid).Model(&models.User{}).UpdateColumn("password", req.NewPassword).Error; err == nil {
res = &pb.ResetPasswordResponse{
Uid: userModel.Uid,
}
}
} else {
err = errors.Format(errors.AccessDenied, "invalid old password")
}
return
}
func NewProfileService(cbs ...ProfileOption) *ProfileService {
opts := &profileOptions{}
for _, cb := range cbs {
cb(opts)
}
return &ProfileService{
opts: opts,
}
}