Add admin function to remove roles, rename addroles to editroles

This commit is contained in:
Christoph Kluge
2022-08-26 15:15:36 +02:00
parent 0186e886e4
commit c9954787c1
4 changed files with 85 additions and 12 deletions

View File

@@ -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) {

View File

@@ -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 {