gin-server/security/controller/auth.go

63 lines
1.5 KiB
Go

package controller
import (
"gin-server/lib/messages"
"gin-server/security"
"github.com/astaxie/beego/validation"
"github.com/gin-gonic/gin"
"gin-server/security/service"
"gin-server/lib/app"
"net/http"
)
type auth struct {
Username string `valid:"Required; MaxSize(50)"`
Password string `valid:"Required; MaxSize(50)"`
}
// @Summary Get Auth
// @Produce json
// @Param username query string true "userName"
// @Param password query string true "password"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /auth [get]
func GetAuth(c *gin.Context) {
appG := app.Gin{C: c}
valid := validation.Validation{}
username := c.Query("username")
password := c.Query("password")
a := auth{Username: username, Password: password}
ok, _ := valid.Valid(&a)
if !ok {
app.MarkErrors(valid.Errors)
appG.Response(http.StatusBadRequest, messages.INVALID_PARAMS, nil)
return
}
authService := service.Auth{Username: username, Password: password}
isExist, err := authService.Check()
if err != nil {
appG.Response(http.StatusInternalServerError, messages.ERROR_AUTH_CHECK_TOKEN_FAIL, nil)
return
}
if !isExist {
appG.Response(http.StatusUnauthorized, messages.ERROR_AUTH, nil)
return
}
token, err := security.GenerateToken(username, password)
if err != nil {
appG.Response(http.StatusInternalServerError, messages.ERROR_AUTH_TOKEN, nil)
return
}
appG.Response(http.StatusOK, messages.SUCCESS, map[string]string{
"token": token,
})
}