78 lines
1.5 KiB
Go
78 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"git.heldm.com/held/qrcode/internal/app/repository"
|
|
"git.heldm.com/held/qrcode/internal/app/usecase/auth"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func UserAccessMiddlewareHTML() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if err := setUserToContext(c); err != nil {
|
|
c.Redirect(http.StatusFound, "/auth/login")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// JwtAuthUserMiddleware is middleware for jwt auth
|
|
func UserAccessMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if err := setUserToContext(c); err != nil {
|
|
switch {
|
|
case errors.Is(err, repository.ErrScanRow):
|
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
|
|
"status": http.StatusInternalServerError,
|
|
"msg": "internal server error",
|
|
"data": err.Error(),
|
|
})
|
|
c.Abort()
|
|
return
|
|
default:
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
|
"status": http.StatusUnauthorized,
|
|
"msg": "unauthorized",
|
|
"data": err.Error(),
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// AllAccessMiddleware is middleware for all access
|
|
func AllAccessMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
setUserToContext(c)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func setUserToContext(c *gin.Context) error {
|
|
myToken, err := auth.ExtractToken(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
userID, err := auth.ExtractUserID(myToken)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
user, err := repository.User().GetByID(c.Request.Context(), userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.Set("user", user)
|
|
return nil
|
|
}
|