init
This commit is contained in:
77
app/internal/middleware/auth.go
Normal file
77
app/internal/middleware/auth.go
Normal file
@ -0,0 +1,77 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user