43 lines
834 B
Go
43 lines
834 B
Go
package midlleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"git.ostiwe.com/ostiwe-com/status/modules/jwt"
|
|
"git.ostiwe.com/ostiwe-com/status/repository"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func SetUserFromJWT() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
ctx := c.Request.Context()
|
|
token, err := jwt.AuthMiddleware.ParseToken(c)
|
|
if err != nil {
|
|
c.Writer.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
}
|
|
|
|
userRepo := repository.NewUserRepository()
|
|
subject, err := token.Claims.GetSubject()
|
|
if err != nil {
|
|
c.Writer.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
user, err := userRepo.FindByLogin(ctx, subject)
|
|
if err != nil || user == nil {
|
|
c.Writer.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
}
|
|
|
|
ctx = context.WithValue(ctx, "user", user)
|
|
|
|
c.Request = c.Request.WithContext(ctx)
|
|
|
|
c.Next()
|
|
}
|
|
}
|