diff --git a/internal/api/rest.go b/internal/api/rest.go index 801cbc3..adeafeb 100644 --- a/internal/api/rest.go +++ b/internal/api/rest.go @@ -580,14 +580,26 @@ func (api *RestApi) updateUser(rw http.ResponseWriter, r *http.Request) { return } - // TODO: Handle anything but roles... + // Get Values newrole := r.FormValue("add-role") - if err := api.Authentication.AddRole(r.Context(), mux.Vars(r)["id"], newrole); err != nil { - http.Error(rw, err.Error(), http.StatusUnprocessableEntity) - return - } + delrole := r.FormValue("remove-role") - rw.Write([]byte("success")) + // TODO: Handle anything but roles... + if (newrole != "") { + if err := api.Authentication.AddRole(r.Context(), mux.Vars(r)["id"], newrole); err != nil { + http.Error(rw, err.Error(), http.StatusUnprocessableEntity) + return + } + rw.Write([]byte("Add Role Success")) + } else if (delrole != "") { + if err := api.Authentication.RemoveRole(r.Context(), mux.Vars(r)["id"], delrole); err != nil { + http.Error(rw, err.Error(), http.StatusUnprocessableEntity) + return + } + rw.Write([]byte("Remove Role Success")) + } else { + http.Error(rw, "Not Add or Del?", http.StatusInternalServerError) + } } func (api *RestApi) updateConfiguration(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/auth/users.go b/internal/auth/users.go index 63f18c2..c2d9fdd 100644 --- a/internal/auth/users.go +++ b/internal/auth/users.go @@ -129,6 +129,37 @@ func (auth *Authentication) AddRole(ctx context.Context, username string, role s return nil } +func (auth *Authentication) RemoveRole(ctx context.Context, username string, role string) error { + user, err := auth.GetUser(username) + if err != nil { + return err + } + + if role != RoleAdmin && role != RoleApi && role != RoleUser { + return fmt.Errorf("invalid user role: %#v", role) + } + + var exists bool + var newroles []string + for _, r := range user.Roles { + if r != role { + newroles = append(newroles, r) // Append all roles not matching requested delete role + } else { + exists = true + } + } + + if (exists == true) { + var mroles, _ = json.Marshal(newroles) + if _, err := sq.Update("user").Set("roles", mroles).Where("user.username = ?", username).RunWith(auth.db).Exec(); err != nil { + return err + } + return nil + } else { + return fmt.Errorf("user %#v already does not have role %#v", username, role) + } +} + func FetchUser(ctx context.Context, db *sqlx.DB, username string) (*model.User, error) { me := GetUser(ctx) if me != nil && !me.HasRole(RoleAdmin) && me.Username != username { diff --git a/web/frontend/src/config/AdminSettings.svelte b/web/frontend/src/config/AdminSettings.svelte index 3564865..d1ce542 100644 --- a/web/frontend/src/config/AdminSettings.svelte +++ b/web/frontend/src/config/AdminSettings.svelte @@ -1,7 +1,7 @@