|
|
@@ -1392,17 +1392,43 @@ func deleteUser(w http.ResponseWriter, db *sql.DB, r *http.Request) { |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// Checks if a user's entries are reasonable before database insertion. |
|
|
|
// This function is very important because it is the only thing preventing |
|
|
|
// anyone from creating an admin user. |
|
|
|
func (user *User) validate() error { |
|
|
|
_, err := mail.ParseAddress(user.Email) |
|
|
|
if err != nil { errors.New("Invalid email.") } |
|
|
|
|
|
|
|
if roles[user.Role] == 0 { |
|
|
|
errors.New("Invalid role.") |
|
|
|
} |
|
|
|
|
|
|
|
if roles[user.Role] == roles["Admin"] { |
|
|
|
errors.New("New user cannot be an Admin.") |
|
|
|
} |
|
|
|
|
|
|
|
if user.FirstName == "" { |
|
|
|
errors.New("Given name cannot be empty.") |
|
|
|
} |
|
|
|
|
|
|
|
if user.LastName == "" { |
|
|
|
errors.New("Surname cannot be empty.") |
|
|
|
} |
|
|
|
|
|
|
|
if user.Password == "" { |
|
|
|
errors.New("User must have a password.") |
|
|
|
} |
|
|
|
|
|
|
|
return nil |
|
|
|
} |
|
|
|
|
|
|
|
func createUser(w http.ResponseWriter, db *sql.DB, r *http.Request) { |
|
|
|
var user User |
|
|
|
err := json.NewDecoder(r.Body).Decode(&user) |
|
|
|
if err != nil { http.Error(w, "Invalid fields.", 422); return } |
|
|
|
|
|
|
|
_, err = mail.ParseAddress(user.Email) |
|
|
|
if err != nil { http.Error(w, "Invalid email.", 422); return } |
|
|
|
|
|
|
|
if roles[user.Role] == 0 { |
|
|
|
http.Error(w, "Invalid role.", 422) |
|
|
|
} |
|
|
|
|
|
|
|
err = user.validate() |
|
|
|
if err != nil { http.Error(w, err.Error(), 422); return } |
|
|
|
|
|
|
|
user, err = insertUser(db, user) |
|
|
|
if err != nil { http.Error(w, "Error creating user.", 422); return } |
|
|
@@ -2512,7 +2538,7 @@ func api(w http.ResponseWriter, r *http.Request) { |
|
|
|
getUser(w, db, r) |
|
|
|
case match(p, "/api/user", &args) && |
|
|
|
r.Method == http.MethodPost && |
|
|
|
guard(r, 3): |
|
|
|
guard(r, 1): |
|
|
|
createUser(w, db, r) |
|
|
|
case match(p, "/api/user", &args) && |
|
|
|
r.Method == http.MethodPatch && |
|
|
|