Example #1
0
File: users.go Project: 2cloud/api
func createUser(w http.ResponseWriter, r *twocloud.RequestBundle) {
	var req accountAndUserRequest
	body, err := ioutil.ReadAll(r.Request.Body)
	if err != nil {
		r.Log.Error(err.Error())
		Respond(w, r, http.StatusInternalServerError, "Internal server error.", []interface{}{})
		return
	}
	err = json.Unmarshal(body, &req)
	if err != nil {
		r.Log.Error(err.Error())
		Respond(w, r, http.StatusBadRequest, "Error decoding request.", []interface{}{})
		return
	}
	if req.Account.ID == 0 {
		Respond(w, r, http.StatusBadRequest, "Account ID must be specified.", []interface{}{})
		return
	}
	account, err := r.GetAccountByID(req.Account.ID)
	if err != nil {
		r.Log.Error(err.Error())
		Respond(w, r, http.StatusInternalServerError, "Internal server error", []interface{}{})
		return
	}
	if account.ID == 0 {
		Respond(w, r, http.StatusBadRequest, "Invalid Account ID", []interface{}{})
		return
	}
	if account.UserID != 0 {
		Respond(w, r, http.StatusConflict, "Account already registered.", []interface{}{})
		return
	}
	if req.User.Username == "" {
		Respond(w, r, http.StatusBadRequest, "Username must be specified.", []interface{}{})
		return
	}
	user, err := r.Register(req.User.Username, req.User.Email, req.User.Name.Given, req.User.Name.Family, true, false)
	if err != nil {
		if err == twocloud.MissingEmailError {
			Respond(w, r, http.StatusBadRequest, "Email must be specified.", []interface{}{})
			return
		} else if err == twocloud.UsernameTakenError {
			Respond(w, r, http.StatusConflict, "Username taken.", []interface{}{})
			return
		} else if err == twocloud.InvalidUsernameCharacterError || err == twocloud.InvalidUsernameLengthError {
			Respond(w, r, http.StatusBadRequest, err.Error(), []interface{}{})
			return
		}
		r.Log.Error(err.Error())
		Respond(w, r, http.StatusInternalServerError, "Internal server error.", []interface{}{})
		return
	}
	err = r.AssociateUserWithAccount(account, user.ID)
	if err != nil {
		r.Log.Error(err.Error())
		Respond(w, r, http.StatusInternalServerError, "Internal server error.", []interface{}{})
		return
	}
	setLastModified(w, user.LastActive)
	Respond(w, r, http.StatusCreated, "Successfully created a user account", []interface{}{user})
	return
}