Prevent deletion of last admin account

This commit is contained in:
eikendev 2020-07-28 22:44:22 +02:00
parent 470a3f819d
commit c0ac5c3d16
No known key found for this signature in database
GPG key ID: A1BDB1B28C8EF694
2 changed files with 20 additions and 0 deletions

View file

@ -17,6 +17,7 @@ type UserDatabase interface {
GetUserByID(ID uint) (*model.User, error)
GetUserByName(name string) (*model.User, error)
GetApplications(user *model.User) ([]model.Application, error)
AdminUserCount() (int64, error)
}
// The UserDispatcher interface for relaying notifications.
@ -70,6 +71,16 @@ func (h *UserHandler) DeleteUser(ctx *gin.Context) {
return
}
if user.IsAdmin {
if count, err := h.DB.AdminUserCount(); err != nil {
ctx.AbortWithError(http.StatusInternalServerError, err)
return
} else if count == 1 {
ctx.AbortWithError(http.StatusBadRequest, errors.New("cannot delete last admin user"))
return
}
}
log.Printf("Deleting user %s.\n", user.Name)
applications, err := h.DB.GetApplications(user)

View file

@ -56,3 +56,12 @@ func (d *Database) GetApplications(user *model.User) ([]model.Application, error
return applications, err
}
// AdminUserCount returns the number of admins or an error.
func (d *Database) AdminUserCount() (int64, error) {
var users []model.User
query := d.gormdb.Where("is_admin = ?", true).Find(&users)
return query.RowsAffected, query.Error
}