auth.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package admin
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "github.com/metarare/metarare_api/common"
  6. "github.com/metarare/metarare_api/helpers/gerror"
  7. "github.com/metarare/metarare_api/models"
  8. "gorm.io/gorm"
  9. )
  10. type AdminAuthV1Router struct {
  11. group *gin.RouterGroup
  12. mDB *gorm.DB
  13. rDB *gorm.DB
  14. }
  15. func NewAdminAuthV1Router(r common.Router, basePath string) AdminAuthV1Router {
  16. a := AdminAuthV1Router{
  17. group: r.Version.Group(basePath),
  18. mDB: r.Db.MasterDB,
  19. rDB: r.Db.ReadDB,
  20. }
  21. a.group.POST("signin", a.adminSignin)
  22. // a.group.POST("", a.registerAdmin)
  23. return a
  24. }
  25. // adminSignin godoc
  26. // @Summary signin
  27. // @Description 어드민 로그인
  28. // @Schemes
  29. // @Tags admin
  30. // @Accept json
  31. // @Produce json
  32. // @Param AccountInfo body AccountInfo true "body struct"
  33. // @Success 200 {object} AdminAuthContainer
  34. // @Router /admin/auth/signin [post]
  35. func (a AdminAuthV1Router) adminSignin(c *gin.Context) {
  36. request := AccountInfo{}
  37. if err := c.ShouldBindJSON(&request); err != nil {
  38. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  39. return
  40. }
  41. admin := models.Admin{}
  42. if err := a.rDB.Where("email = ? AND password = ? AND status = 'stable'", request.Email, request.Password).Find(&admin).Error; err != nil {
  43. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  44. return
  45. } else if admin.ID == 0 {
  46. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.NotFoundRecord, nil, err)
  47. return
  48. }
  49. authenitcation := AdminAuthContainer{}
  50. if err := a.rDB.Where("admin_id = ?", admin.ID).Find(&authenitcation.Permission).Error; err != nil {
  51. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  52. return
  53. }
  54. standardClaims, customClaims := common.MakeClaims(int64(admin.ID))
  55. _, authContainer := common.MakeSession(standardClaims, customClaims)
  56. authenitcation.AccessToken = authContainer.AccessToken
  57. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, authenitcation, nil)
  58. return
  59. }