package service import ( "encoding/base64" "net/http" "sig-pub/internal/admin/args" repository "sig-pub/internal/admin/repoitory" "sig-pub/pkg/config" "sig-pub/pkg/data/entity" "sig-pub/pkg/resp" "sig-pub/pkg/session" "time" "github.com/gin-gonic/gin" ) type AuthService struct { repo *repository.UserRepository aesKeyBytes []byte } func NewAuthService(repo *repository.UserRepository) *AuthService { return &AuthService{ repo: repo, } } func (svc *AuthService) Route(group *gin.RouterGroup) { aesKey, err := config.GetString("aesTokenKey") if err != nil { panic(err) } svc.aesKeyBytes, err = base64.StdEncoding.DecodeString(aesKey) if err != nil { panic(err) } } func (s *AuthService) Login(ctx *gin.Context) { var req args.LoginReq if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, resp.Fail(err.Error())) return } if err := req.Validate(); err != nil { ctx.JSON(http.StatusBadRequest, resp.Fail(err.Error())) return } user, err := s.repo.FindByAccount(req.Account) if err != nil { ctx.JSON(http.StatusInternalServerError, resp.Fail(err.Error())) return } if len(req.Password) < 6 { ctx.JSON(http.StatusBadRequest, gin.H{"error": "password length must be at least 6"}) return } if user == nil { // 不存在注册 now := time.Now().UnixMilli() uid, err := s.repo.NextUid() if err != nil { ctx.JSON(http.StatusInternalServerError, resp.Fail(err.Error())) return } user = &entity.User{ UserId: uid, Account: req.Account, Username: req.Account, Password: req.Password, CreateAt: now, UpdateAt: now, } err = s.repo.Create(user) if err != nil { ctx.JSON(http.StatusInternalServerError, resp.Fail(err.Error())) return } // return nil, errors.New("not found account " + req.Account) } // verify password login if req.Password != user.Password { ctx.JSON(http.StatusBadRequest, resp.Fail("account or password error")) return } // generate token rpcSubject := session.NewRpcSubject(user.UserId, user.Account, nil) _ = rpcSubject // session.RpcSubjectGenToken() // res := &auth.ResLogin{Token: token, Subject: subject} return }