package service import ( "encoding/base64" "fmt" "net/http" "sig-pub/api/pb" "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" "strconv" "time" "github.com/gin-gonic/gin" ) type AuthService struct { repo *repository.UserRepository aesKey []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.aesKey, err = base64.StdEncoding.DecodeString(aesKey) if err != nil { panic(err) } group.POST("login", svc.Login) // 登录接口 } 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 user == nil || user.UserId == 0 { // 不存在注册 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: fmt.Sprintf("sig-%s", strconv.FormatInt(uid, 36)), Password: req.Password, Role: pb.Role_User, CreateAt: now, UpdateAt: now, } err = s.repo.Create(user) if err != nil { ctx.JSON(http.StatusInternalServerError, resp.Fail(err.Error())) return } } // 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, user.Role, nil) token, err := session.RpcSubjectGenToken(s.aesKey, rpcSubject) if err != nil { ctx.JSON(http.StatusInternalServerError, resp.Fail(err.Error())) return } ctx.JSON(http.StatusOK, resp.Success(resp.H{ "token": token, "subject": rpcSubject, })) }