Add User route and Refactor code
This commit is contained in:
parent
519749fd3a
commit
b311a41dc7
24 changed files with 902 additions and 489 deletions
53
server/middlewares/authorized.go
Normal file
53
server/middlewares/authorized.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue