58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"madsky.ru/go-tracker/internal/model/user"
|
|
"madsky.ru/go-tracker/internal/server/helpers"
|
|
"madsky.ru/go-tracker/internal/server/response"
|
|
"net/http"
|
|
)
|
|
|
|
type UserContext struct {
|
|
}
|
|
|
|
func (app *Application) AuthMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
cookie, err := r.Cookie("token")
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, http.ErrNoCookie):
|
|
response.Error(w, errors.New("no authentication token"), http.StatusForbidden)
|
|
default:
|
|
response.Error(w, errors.New("unknown error"), http.StatusForbidden)
|
|
}
|
|
return
|
|
}
|
|
|
|
claims, err := helpers.VerifyToken(cookie.Value)
|
|
if err != nil {
|
|
response.Error(w, errors.New("invalid authentication token"), http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
u, err := app.Storage.User.FindById(app.Ctx, claims.UserId)
|
|
if err != nil {
|
|
response.Error(w, errors.New("user not found"), http.StatusBadRequest)
|
|
return
|
|
}
|
|
ctx := context.WithValue(r.Context(), UserContext{}, u)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
|
|
}
|
|
|
|
func (app *Application) LogRole(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
u := ctx.Value(UserContext{}).(*user.User)
|
|
|
|
isAdmin := u.Role == "admin"
|
|
|
|
fmt.Println(fmt.Sprintf("is admin: %v", isAdmin))
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|