54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
|
|
package middlewares
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"github.com/go-chi/chi/v5"
|
||
|
|
"net/http"
|
||
|
|
"recipe-manager/enums/permissions"
|
||
|
|
"recipe-manager/models"
|
||
|
|
)
|
||
|
|
|
||
|
|
func Authorize(p []permissions.Permission, nextRoute http.HandlerFunc) http.HandlerFunc {
|
||
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
user := r.Context().Value("user").(*models.User)
|
||
|
|
|
||
|
|
for _, pm := range p {
|
||
|
|
if !user.Permissions.IsHavePermission(pm) {
|
||
|
|
// If not have permission response unauthorized
|
||
|
|
w.WriteHeader(http.StatusUnauthorized)
|
||
|
|
err := json.NewEncoder(w).Encode("Unauthorized")
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
return
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
nextRoute.ServeHTTP(w, r)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func OwnOrAuthorize(p []permissions.Permission, nextRoute http.HandlerFunc) http.HandlerFunc {
|
||
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
reqUserID := chi.URLParam(r, "id")
|
||
|
|
user := r.Context().Value("user").(*models.User)
|
||
|
|
|
||
|
|
if reqUserID == "" {
|
||
|
|
// If not have permission response unauthorized
|
||
|
|
w.WriteHeader(http.StatusUnauthorized)
|
||
|
|
err := json.NewEncoder(w).Encode("Unauthorized")
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
if reqUserID == user.ID {
|
||
|
|
nextRoute.ServeHTTP(w, r)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
Authorize(p, nextRoute)
|
||
|
|
}
|
||
|
|
}
|