Add API call for frontend to fetch list of valid roles from backend

- only relevant for admin config (addUser, editRole)
- admin only (double-checked)
This commit is contained in:
Christoph Kluge
2023-01-30 17:01:11 +01:00
parent 7d4f4ab2c8
commit 7fb94c33cf
5 changed files with 78 additions and 28 deletions

View File

@@ -76,6 +76,7 @@ func (api *RestApi) MountRoutes(r *mux.Router) {
if api.Authentication != nil {
r.HandleFunc("/jwt/", api.getJWT).Methods(http.MethodGet)
r.HandleFunc("/roles/", api.getRoles).Methods(http.MethodGet)
r.HandleFunc("/users/", api.createUser).Methods(http.MethodPost, http.MethodPut)
r.HandleFunc("/users/", api.getUsers).Methods(http.MethodGet)
r.HandleFunc("/users/", api.deleteUser).Methods(http.MethodDelete)
@@ -880,6 +881,22 @@ func (api *RestApi) getUsers(rw http.ResponseWriter, r *http.Request) {
json.NewEncoder(rw).Encode(users)
}
func (api *RestApi) getRoles(rw http.ResponseWriter, r *http.Request) {
user := auth.GetUser(r.Context())
if (!user.HasRole(auth.RoleAdmin)) {
http.Error(rw, "only admins are allowed to fetch a list of roles", http.StatusForbidden)
return
}
roles, err := auth.GetValidRoles(user)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(rw).Encode(roles)
}
func (api *RestApi) updateUser(rw http.ResponseWriter, r *http.Request) {
if user := auth.GetUser(r.Context()); !user.HasRole(auth.RoleAdmin) {
http.Error(rw, "only admins are allowed to update a user", http.StatusForbidden)

View File

@@ -12,6 +12,7 @@ import (
"net/http"
"os"
"time"
"fmt"
"github.com/ClusterCockpit/cc-backend/pkg/log"
"github.com/gorilla/sessions"
@@ -139,6 +140,15 @@ func IsValidRole(role string) bool {
return false
}
func GetValidRoles(user *User) ([5]string, error) {
var vals [5]string
if (!user.HasRole(RoleAdmin)) {
return vals, fmt.Errorf("%#v: only admins are allowed to fetch a list of roles", user.Username)
} else {
return validRoles, nil
}
}
func GetUser(ctx context.Context) *User {
x := ctx.Value(ContextUserKey)
if x == nil {