vikunja-api/pkg/routes/api/v1/user_add_update.go

86 lines
1.8 KiB
Go
Raw Normal View History

2018-06-10 11:11:41 +02:00
package v1
import (
2018-10-31 13:42:38 +01:00
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/routes/crud"
2018-06-10 11:11:41 +02:00
"github.com/labstack/echo"
"net/http"
"strconv"
)
2018-07-10 14:02:23 +02:00
// RegisterUser ...
2018-06-13 13:45:22 +02:00
func RegisterUser(c echo.Context) error {
// swagger:operation POST /register user register
// ---
// summary: Creates a new user account
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - name: body
// in: body
// schema:
2018-07-10 14:02:23 +02:00
// "$ref": "#/definitions/APIUserPassword"
2018-06-13 13:45:22 +02:00
// responses:
// "200":
// "$ref": "#/responses/User"
// "400":
// "$ref": "#/responses/Message"
// "500":
// "$ref": "#/responses/Message"
return userAddOrUpdate(c)
}
// userAddOrUpdate is the handler to add a user
func userAddOrUpdate(c echo.Context) error {
2018-06-10 11:11:41 +02:00
// TODO: prevent everyone from updating users
// Check for Request Content
2018-07-10 14:02:23 +02:00
var datUser *models.APIUserPassword
2018-06-10 11:11:41 +02:00
2018-06-13 13:45:22 +02:00
if err := c.Bind(&datUser); err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"No user model provided."})
2018-06-10 11:11:41 +02:00
}
// Check if we have an ID other than the one in the struct
id := c.Param("id")
if id != "" {
// Make int
userID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"Invalid ID."})
}
datUser.ID = userID
}
// Check if the user exists
2018-09-17 18:25:05 +02:00
var exists = true
2018-08-30 19:14:02 +02:00
_, err := models.GetUserByID(datUser.ID)
2018-06-10 11:11:41 +02:00
if err != nil {
2018-08-30 19:14:16 +02:00
if models.IsErrUserDoesNotExist(err) {
2018-09-17 18:25:05 +02:00
exists = false
2018-08-30 19:14:16 +02:00
} else {
return c.JSON(http.StatusInternalServerError, models.Message{"Could not check if the user exists."})
2018-08-30 19:14:02 +02:00
}
2018-06-10 11:11:41 +02:00
}
// Insert or update the user
var newUser models.User
if exists {
2018-06-13 13:45:22 +02:00
newUser, err = models.UpdateUser(datUser.APIFormat())
2018-06-10 11:11:41 +02:00
} else {
2018-06-13 13:45:22 +02:00
newUser, err = models.CreateUser(datUser.APIFormat())
2018-06-10 11:11:41 +02:00
}
if err != nil {
2018-10-06 15:04:14 +02:00
return crud.HandleHTTPError(err)
2018-06-10 11:11:41 +02:00
}
return c.JSON(http.StatusOK, newUser)
}