2021-06-01 10:51:35 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
2023-10-23 21:40:10 +02:00
|
|
|
"codeberg.org/genofire/golang-lib/web"
|
2021-06-01 10:51:35 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type login struct {
|
|
|
|
Username string `json:"username" example:"kukoon"`
|
|
|
|
Password string `json:"password" example:"super secret password"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// @Summary Login
|
|
|
|
// @Description Login by username and password, you will get a cookie of current session
|
2021-06-30 15:47:24 +02:00
|
|
|
// @Tags auth
|
2021-06-01 10:51:35 +02:00
|
|
|
// @Accept json
|
|
|
|
// @Produce json
|
|
|
|
// @Success 200 {object} User
|
|
|
|
// @Failure 400 {object} web.HTTPError
|
|
|
|
// @Failure 401 {object} web.HTTPError
|
|
|
|
// @Failure 500 {object} web.HTTPError
|
|
|
|
// @Router /api/v1/auth/login [post]
|
|
|
|
// @Param body body login false "login"
|
2021-07-19 17:59:08 +02:00
|
|
|
func apiLogin(r *gin.Engine, ws *web.Service) {
|
|
|
|
r.POST("/api/v1/auth/login", func(c *gin.Context) {
|
|
|
|
var data login
|
|
|
|
if err := c.BindJSON(&data); err != nil {
|
|
|
|
c.JSON(http.StatusBadRequest, web.HTTPError{
|
2021-07-22 18:16:05 +02:00
|
|
|
Message: web.ErrAPIInvalidRequestFormat.Error(),
|
2021-07-19 17:59:08 +02:00
|
|
|
Error: err.Error(),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2021-06-01 10:51:35 +02:00
|
|
|
|
2021-07-19 17:59:08 +02:00
|
|
|
d := &User{}
|
|
|
|
if err := ws.DB.Where(map[string]interface{}{"username": data.Username}).First(d).Error; err != nil {
|
|
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
2021-06-01 10:51:35 +02:00
|
|
|
c.JSON(http.StatusUnauthorized, web.HTTPError{
|
2021-07-22 18:16:05 +02:00
|
|
|
Message: ErrAPIUserNotFound.Error(),
|
2021-06-01 10:51:35 +02:00
|
|
|
Error: err.Error(),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2021-07-19 17:59:08 +02:00
|
|
|
c.JSON(http.StatusInternalServerError, web.HTTPError{
|
2021-07-22 18:16:05 +02:00
|
|
|
Message: web.ErrAPIInternalDatabase.Error(),
|
2021-07-19 17:59:08 +02:00
|
|
|
Error: err.Error(),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !d.ValidatePassword(data.Password) {
|
|
|
|
c.JSON(http.StatusUnauthorized, web.HTTPError{
|
2021-07-22 18:16:05 +02:00
|
|
|
Message: ErrAPIIncorrectPassword.Error(),
|
2021-07-19 17:59:08 +02:00
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
session := sessions.Default(c)
|
|
|
|
session.Set("user_id", d.ID.String())
|
|
|
|
if err := session.Save(); err != nil {
|
|
|
|
c.JSON(http.StatusBadRequest, web.HTTPError{
|
2021-07-22 18:16:05 +02:00
|
|
|
Message: ErrAPICreateSession.Error(),
|
2021-07-19 17:59:08 +02:00
|
|
|
Error: err.Error(),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2021-06-01 10:51:35 +02:00
|
|
|
|
2021-07-19 17:59:08 +02:00
|
|
|
c.JSON(http.StatusOK, d)
|
2021-06-01 10:51:35 +02:00
|
|
|
})
|
|
|
|
}
|