login.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package admin_common
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. "sghgogs.com/sghblog/authorization-client/model/base"
  6. res "sghgogs.com/sghblog/authorization-client/model/response/common"
  7. "sghgogs.com/sghblog/authorization-client/response"
  8. "sghgogs.com/sghblog/authorization-client/utils"
  9. pb "sghgogs.com/sghblog/authorization-service/proto"
  10. "sghgogs.com/sghblog/common"
  11. )
  12. type Request struct {
  13. Username string `json:"username" binding:"required,max=15,min=5"` // 用户名
  14. Password string `json:"password" binding:"required,max=18,min=6"` // 密码
  15. }
  16. // Login
  17. // @summary 登录
  18. // @Description 登录API
  19. // @Tags Common
  20. // @Accept json
  21. // @Produce json
  22. // @Param body body Request true "请求body"
  23. // @Success 200 {object} response.ApiResponse{data=res.UserInfo} "成功"
  24. // @Failure 400 {object} response.ApiResponse "请求错误"
  25. // @Failure 500 {object} response.ApiResponse "内部错误"
  26. // @Router /v1/api/admin/login [post]
  27. func (svc *ApiAdminCommon) Login(c *gin.Context) {
  28. var req Request
  29. if err := c.BindJSON(&req); err != nil {
  30. c.JSON(http.StatusBadRequest, response.ErrorResponse(http.StatusBadRequest, err.Error()))
  31. return
  32. }
  33. if !common.ValidateUsername(req.Username) {
  34. c.JSON(http.StatusBadRequest, response.ErrorResponse(http.StatusBadRequest, "4到16位(字母,数字,下划线,减号)"))
  35. return
  36. }
  37. ctx, _ := utils.CreateContextWithToken(c, "authorizationservice", "CommonService.AdminLogin")
  38. info, err := svc.Service.AdminLogin(ctx, &pb.AdminLoginRequest{
  39. Username: req.Username,
  40. Password: req.Password,
  41. })
  42. if err != nil {
  43. code, mgs := response.MicroErrorRequest(err)
  44. c.JSON(code, response.ErrorResponse(code, mgs))
  45. return
  46. }
  47. user := info.User
  48. c.JSON(http.StatusOK, response.SuccessResponse(gin.H{
  49. "token": info.Token,
  50. "user": res.UserInfo{
  51. Id: user.Id,
  52. Username: user.Username,
  53. PhoneNumber: user.PhoneNumber,
  54. Email: user.Email,
  55. Avatar: user.Avatar,
  56. Roles: base.RolesToResponse(user.Roles),
  57. Teams: base.TeamsToResponse(user.Teams),
  58. },
  59. }))
  60. }