2021-05-19 11:18:18 +03:00
package utils
import (
"errors"
2023-03-03 22:40:50 +03:00
"github.com/go-chi/chi/v5"
2021-05-19 11:18:18 +03:00
conf "github.com/muety/wakapi/config"
"github.com/muety/wakapi/middlewares"
"github.com/muety/wakapi/models"
"github.com/muety/wakapi/services"
"net/http"
)
// CheckEffectiveUser extracts the requested user from a URL (like '/users/{user}'), compares it with the currently authorized user and writes an HTTP error if they differ.
// Fallback can be used to manually set a value for '{user}' if none is present.
func CheckEffectiveUser ( w http . ResponseWriter , r * http . Request , userService services . IUserService , fallback string ) ( * models . User , error ) {
2023-01-17 12:39:41 +03:00
respondError := func ( code int , text string ) ( * models . User , error ) {
err := errors . New ( conf . ErrUnauthorized )
w . WriteHeader ( http . StatusUnauthorized )
w . Write ( [ ] byte ( err . Error ( ) ) )
return nil , err
}
2023-03-03 22:40:50 +03:00
userParam := chi . URLParam ( r , "user" )
if userParam == "" {
userParam = fallback
2021-05-19 11:18:18 +03:00
}
2023-01-17 12:39:41 +03:00
authorizedUser := middlewares . GetPrincipal ( r )
if authorizedUser == nil {
return respondError ( http . StatusUnauthorized , conf . ErrUnauthorized )
2023-03-03 22:40:50 +03:00
} else if userParam == "current" {
2023-01-17 12:39:41 +03:00
return authorizedUser , nil
2021-05-19 11:18:18 +03:00
}
2023-03-03 22:40:50 +03:00
if authorizedUser . ID != userParam && ! authorizedUser . IsAdmin {
2023-01-17 12:39:41 +03:00
return respondError ( http . StatusUnauthorized , conf . ErrUnauthorized )
2021-05-19 11:18:18 +03:00
}
2023-03-03 22:40:50 +03:00
requestedUser , err := userService . GetUserById ( userParam )
2023-01-17 12:39:41 +03:00
if err != nil {
return respondError ( http . StatusNotFound , "user not found" )
2021-05-19 11:18:18 +03:00
}
2022-06-29 10:46:46 +03:00
return requestedUser , nil
2021-05-19 11:18:18 +03:00
}