Пример #1
0
        public async Task <IActionResult> ExercisesCreate(
            [HttpTrigger(AuthorizationLevel.User, "post", Route = "exercises")]
            [RequestBodyType(typeof(ExerciseBody), "The exercise to create")] HttpRequest req,
            [SwaggerIgnore] ClaimsPrincipal user)
        {
            // user must be admin
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // deserialize request
            ExerciseBody exerciseBody;

            try {
                exerciseBody = await SerializationUtil.Deserialize <ExerciseBody>(req.Body);
            } catch (JsonException e) {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // create exercise
            Exercise createdExercise = await this.exerciseService.CreateExercise(exerciseBody);

            // get exercise
            ExerciseResponse response = await this.exerciseService.GetExerciseById(createdExercise.Id);

            return(new OkObjectResult(response));
        }
Пример #2
0
        public async Task <IActionResult> ComponentDelete(
            [HttpTrigger(AuthorizationLevel.User, "delete", Route = "locations/{locationId}/components/{componentId}")] HttpRequest req,
            int locationId, int componentId,
            [SwaggerIgnore] ClaimsPrincipal user)
        {
            // only admin can delete component
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // check if given location exists
            if (!await locationService.Exists(locationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // check if given component exists
            if (!await componentService.Exists(locationId, componentId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.COMPONENT_NOT_FOUND)));
            }

            // delete component
            bool isDeleted = await componentService.DeleteComponent(componentId);

            if (!isDeleted)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.COMPONENT_DELETE_FAILED)));
            }

            return(new OkResult());
        }
        public async Task <IActionResult> LocationDeleteEvent(
            [HttpTrigger(AuthorizationLevel.User, "delete", Route = "locations/{locationId}/events/{eventId}")] HttpRequest req,
            int locationId, int eventId, [SwaggerIgnore] ClaimsPrincipal user)
        {
            // check if user has admin rights
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // if location was not found
            if (!await locationService.Exists(locationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // if event was not found within location
            if (!await eventService.Exists(locationId, eventId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.EVENT_NOT_FOUND)));
            }

            // delete event
            bool isDeleted = await eventService.DeleteEvent(eventId);

            // if the event was not deleted
            if (!isDeleted)
            {
                return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.EVENT_DELETE_FAILED)));
            }

            return(new OkResult());
        }
        public void ForbiddenObjectResultHasStatusCode409()
        {
            // Arrange
            var result = new ForbiddenObjectResult("Some Message");

            // Assert
            Assert.Equal(403, result.StatusCode);
        }
Пример #5
0
        public async Task <IActionResult> ComponentUpdateById(
            [HttpTrigger(AuthorizationLevel.User, "put", Route = "locations/{locationId}/components/{componentId}")] HttpRequest req,
            int locationId, int componentId,
            [SwaggerIgnore] ClaimsPrincipal user)
        {
            // only admin can delete component
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // check if given location exists
            if (!await locationService.Exists(locationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // get the form data
            IFormCollection formdata = await req.ReadFormAsync();

            ComponentBody componentBody;

            try {
                componentBody = SerializationUtil.DeserializeFormData <ComponentBody>(formdata);
            }
            catch (ValidationException e) {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // check if given exercises exist
            foreach (int exerciseId in componentBody.Exercises)
            {
                if (!await exerciseService.Exists(exerciseId))
                {
                    return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_EXERCISE_PROVIDED)));
                }
            }

            // update component
            Component updatedComponent = await componentService.UpdateComponent(componentBody, locationId, componentId);

            // if component was not found within location
            if (updatedComponent == null)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.COMPONENT_NOT_FOUND)));
            }

            // get the updated component
            ComponentResponse response = await componentService.GetComponent(locationId, componentId);

            return(new OkObjectResult(response));
        }
Пример #6
0
        public async Task <IActionResult> ComponentCreate(
            [HttpTrigger(AuthorizationLevel.User, "post", Route = "locations/{locationId}/components")] HttpRequest req,
            int locationId,
            [SwaggerIgnore] ClaimsPrincipal user)
        {
            // check if user has admin rights
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // check if given location exists
            if (!await locationService.Exists(locationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // get the form data
            IFormCollection formdata = await req.ReadFormAsync();

            ComponentBody componentBody;

            try {
                componentBody = SerializationUtil.DeserializeFormData <ComponentBody>(formdata);
            }
            catch (ValidationException e) {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // check if all fields are filled in
            if (componentBody.Name == null || componentBody.Description == null || componentBody.Image == null || componentBody.Exercises == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_REQUEST_BODY)));
            }

            // check if given exercises exist
            foreach (int exerciseId in componentBody.Exercises)
            {
                if (!await exerciseService.Exists(exerciseId))
                {
                    return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_EXERCISE_PROVIDED)));
                }
            }

            // create new component
            int componentId = await componentService.CreateComponent(componentBody, locationId);

            // get the component
            ComponentResponse createdComponent = await componentService.GetComponent(locationId, componentId);

            return(new OkObjectResult(createdComponent));
        }
        /// <summary>
        /// Creates an <see cref="HttpException" /> that produces a Forbidden (403) response.
        /// </summary>
        /// <param name="response">The HTTP response.</param>
        /// <param name="error">The error to be returned to the client.</param>
        public static HttpException Forbidden(this HttpResponse response, object error)
        {
            var disposable = error as IDisposable;

            if (disposable != null)
            {
                response.RegisterForDispose(disposable);
            }

            var result = new ForbiddenObjectResult(error);

            return(new HttpException(result));
        }
Пример #8
0
        public async Task <IActionResult> BeaconCreate(
            [HttpTrigger(AuthorizationLevel.User, "post", Route = "beacons")]
            [RequestBodyType(typeof(BeaconBody), "The beacon to create")] HttpRequest req,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // only admin can update beacon
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // deserialize request
            BeaconBody beaconBody;

            try
            {
                beaconBody = await SerializationUtil.Deserialize <BeaconBody>(req.Body);
            }
            catch (JsonException e)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // check for required fields
            if (beaconBody.Name == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Name is required")));
            }
            if (beaconBody.LocationId == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "LocationId is required")));
            }
            if (beaconBody.Lat == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Latitude is required")));
            }
            if (beaconBody.Lng == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Longitude is required")));
            }

            if (!await locationService.Exists((int)beaconBody.LocationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // create user
            Beacon createdBeacon = await this.beaconService.CreateBeacon(beaconBody);

            return(new OkObjectResult(createdBeacon));
        }
Пример #9
0
        public async Task <IActionResult> ExercisesGetAll(
            [HttpTrigger(AuthorizationLevel.User, "get", Route = "exercises")] HttpRequest req,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // user must be admin
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // get list of exercises
            List <ExerciseResponse> exercises = await exerciseService.GetAllExercises();

            return(new OkObjectResult(exercises));
        }
        public async Task <IActionResult> UserGetEventRegistrations(
            [HttpTrigger(AuthorizationLevel.User, "get", Route = "users/{userId}/events")] HttpRequest req,
            int userId,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // non-admin can only view own registrations
            if (!userClaim.IsInRole(UserType.Admin.ToString()) && Int32.Parse(userClaim.FindFirstValue(ClaimTypes.NameIdentifier)) != userId)
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.CAN_ONLY_VIEW_OWN_REGISTRATIONS)));
            }

            List <EventResponse> response = await eventService.GetUserRegisteredEvents(userId);

            return(new OkObjectResult(response));
        }
Пример #11
0
        public async Task <IActionResult> LocationGetAll(
            [HttpTrigger(AuthorizationLevel.User, "get", Route = "beacons")] HttpRequest req,
            [SwaggerIgnore] ClaimsPrincipal userClaim)

        {
            // only admin can update beacon
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // get the locations
            List <Beacon> beacons = await beaconService.GetAllBeacons();

            return(new OkObjectResult(beacons));
        }
        public async Task <IActionResult> LocationEditEvent(
            [HttpTrigger(AuthorizationLevel.User, "put", Route = "locations/{locationId}/events/{eventId}")]
            [RequestBodyType(typeof(EventBody), "Event to edit")] HttpRequest req,
            int locationId, int eventId, [SwaggerIgnore] ClaimsPrincipal user)
        {
            // check if user has admin rights
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // check if given location exists
            if (!await locationService.Exists(locationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // get the form data
            IFormCollection formdata = await req.ReadFormAsync();

            EventBody eventBody;

            try
            {
                eventBody = SerializationUtil.DeserializeFormData <EventBody>(formdata);
            }
            catch (ValidationException e)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // update event
            Event updatedEvent = await eventService.UpdateEvent(eventBody, locationId, eventId);

            // get the updated event
            EventResponse response = await eventService.GetEvent(locationId, eventId);

            // if event was not found
            if (updatedEvent == null || response == null)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.EVENT_NOT_FOUND)));
            }

            return(new OkObjectResult(response));
        }
        public async Task <IActionResult> UserUpdate(
            [HttpTrigger(AuthorizationLevel.User, "put", Route = "users/{userId}")]
            [RequestBodyType(typeof(UserBody), "The user to update")] HttpRequest req,
            int userId,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // non-admin can only edit own account
            if (!userClaim.IsInRole(UserType.Admin.ToString()) && Int32.Parse(userClaim.FindFirstValue(ClaimTypes.NameIdentifier)) != userId)
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.CAN_ONLY_EDIT_OWN_ACCOUNT)));
            }

            // deserialize request
            UserBody userBody;

            try {
                userBody = await SerializationUtil.Deserialize <UserBody>(req.Body);
            } catch (JsonException e) {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // only admin can edit specific user type
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                if (userBody.Type != null && userBody.Type != UserType.User)
                {
                    return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_TO_SET_USER_TYPE)));
                }
            }

            // update user
            User updatedUser = await this.userService.UpdateUser(userId, userBody);

            // when user was not found
            if (updatedUser == null)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.USER_NOT_FOUND)));
            }

            // get the updated user
            UserResponse response = await userService.GetUser(updatedUser.Id);

            return(new OkObjectResult(response));
        }
Пример #14
0
        public async Task <IActionResult> WorkoutCreate(
            [HttpTrigger(AuthorizationLevel.User, "post", Route = "workouts")]
            [RequestBodyType(typeof(WorkoutBody), "The workout to create")] HttpRequest req,
            [SwaggerIgnore] ClaimsPrincipal user)
        {
            // check if user has admin rights
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // deserialize request
            WorkoutBody workoutBody;

            try {
                workoutBody = await SerializationUtil.Deserialize <WorkoutBody>(req.Body);
            }
            catch (JsonException e) {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // check if all fields are filled in
            if (workoutBody.Name == null || workoutBody.Type == null || workoutBody.Exercises == null || workoutBody.Exercises.Count == 0)
            {
                return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_REQUEST_BODY)));
            }

            // check if given exercises exist
            foreach (int exerciseId in workoutBody.Exercises)
            {
                if (!await exerciseService.Exists(exerciseId))
                {
                    return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_EXERCISE_PROVIDED)));
                }
            }

            // create new workout
            int workoutId = await workoutService.CreateWorkout(workoutBody);

            // get the created location
            WorkoutResponse createdWorkout = await workoutService.GetWorkout(workoutId);

            return(new OkObjectResult(createdWorkout));
        }
        public async Task <IActionResult> LocationCreateEvent(
            [HttpTrigger(AuthorizationLevel.User, "post", Route = "locations/{locationId}/events")]
            [RequestBodyType(typeof(EventBody), "Event to Create")] HttpRequest req,
            int locationId, [SwaggerIgnore] ClaimsPrincipal user)
        {
            // check if user is admin or organiser
            if (!user.IsInRole(UserType.Admin.ToString()) && !user.IsInRole(UserType.Organiser.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // if location does not exist
            if (!await locationService.Exists(locationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // get the form data
            IFormCollection formdata = await req.ReadFormAsync();

            EventBody eventBody;

            try {
                eventBody = SerializationUtil.DeserializeFormData <EventBody>(formdata);
            }
            catch (ValidationException e) {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // check if all fields are filled in
            if (eventBody.Title == null || eventBody.Description == null || eventBody.StartTime == null || eventBody.MaxRegistrations == null || eventBody.Image == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_REQUEST_BODY)));
            }

            // create new event
            int organiserId = Int32.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier));
            int eventId     = await eventService.CreateEvent(eventBody, locationId, organiserId);

            // get the created event
            EventResponse newEvent = await eventService.GetEvent(locationId, eventId);

            return(new OkObjectResult(newEvent));
        }
Пример #16
0
        public async Task <IActionResult> BeaconUpdate(
            [HttpTrigger(AuthorizationLevel.User, "put", Route = "beacons/{beaconId}")]
            [RequestBodyType(typeof(BeaconBody), "The beacon to update")] HttpRequest req,
            int beaconId,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // only admin can update beacon
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // deserialize request
            BeaconBody beaconBody;

            try
            {
                beaconBody = await SerializationUtil.Deserialize <BeaconBody>(req.Body);
            }
            catch (JsonException e)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            if (beaconBody.LocationId != null && !await locationService.Exists((int)beaconBody.LocationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // update beacon
            Beacon updatedBeacon = await this.beaconService.UpdateBeacon(beaconId, beaconBody);

            // when beacon was not found
            if (updatedBeacon == null)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.BEACON_NOT_FOUND)));
            }

            return(new OkObjectResult(updatedBeacon));
        }
        public async Task <IActionResult> UserDelete(
            [HttpTrigger(AuthorizationLevel.User, "delete", Route = "users/{userId}")] HttpRequest req,
            int userId,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // only admin can delete user
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_TO_DELETE_USER)));
            }

            // delete user
            bool isDeleted = await userService.DeleteUser(userId);

            // if user was not found
            if (!isDeleted)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.USER_NOT_FOUND)));
            }

            return(new OkResult());
        }
        public async Task <IActionResult> UsersGet(
            [HttpTrigger(AuthorizationLevel.User, "get", Route = "users/{userId}")] HttpRequest req,
            int userId,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // non-admin can only get own account
            if (!userClaim.IsInRole(UserType.Admin.ToString()) && Int32.Parse(userClaim.FindFirstValue(ClaimTypes.NameIdentifier)) != userId)
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.CAN_ONLY_VIEW_OWN_ACCOUNT)));
            }

            // get the user
            UserResponse user = await userService.GetUser(userId);

            // if the user was not found
            if (user == null)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.USER_NOT_FOUND)));
            }

            return(new OkObjectResult(user));
        }
Пример #19
0
        public async Task <IActionResult> ExercisesDelete(
            [HttpTrigger(AuthorizationLevel.User, "delete", Route = "exercises/{exerciseId}")] HttpRequest req,
            int exerciseId,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // only admin can delete exercise
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // delete exercise
            bool exerciseDeleted = await exerciseService.Delete(exerciseId);

            // if exercise was not found
            if (!exerciseDeleted)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.EXERCISE_NOT_FOUND)));
            }

            return(new OkResult());
        }
Пример #20
0
        public async Task <IActionResult> WorkoutDelete(
            [HttpTrigger(AuthorizationLevel.User, "delete", Route = "workouts/{workoutId}")] HttpRequest req,
            int workoutId,
            [SwaggerIgnore] ClaimsPrincipal user)
        {
            // only admin can delete workout
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // delete workout
            bool isDeleted = await workoutService.DeleteWorkout(workoutId);

            // if the workout was not found
            if (!isDeleted)
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.WORKOUT_NOT_FOUND)));
            }

            return(new OkResult());
        }
Пример #21
0
        public async Task <IActionResult> WorkoutUpdate(
            [HttpTrigger(AuthorizationLevel.User, "put", Route = "workouts/{workoutId}")]
            [RequestBodyType(typeof(WorkoutBody), "The workout to update")] HttpRequest req,
            int workoutId,
            [SwaggerIgnore] ClaimsPrincipal user)
        {
            // check if user has admin rights
            if (!user.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // check if requested workout exists
            if (!await workoutService.Exists(workoutId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.WORKOUT_NOT_FOUND)));
            }

            // deserialize request
            WorkoutBody workoutBody;

            try
            {
                workoutBody = await SerializationUtil.Deserialize <WorkoutBody>(req.Body);
            }
            catch (JsonException e)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // update workout
            await workoutService.UpdateWorkout(workoutBody, workoutId);

            // get the updated workout
            WorkoutResponse updatedWorkout = await workoutService.GetWorkout(workoutId);

            return(new OkObjectResult(updatedWorkout));
        }
Пример #22
0
        public async Task <IActionResult> Register(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "register")]
            [RequestBodyType(typeof(UserBody), "The user to create")] HttpRequest req)
        {
            // deserialize request
            UserBody userBody;

            try
            {
                userBody = await SerializationUtil.Deserialize <UserBody>(req.Body);
            }
            catch (JsonException e)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // check for required fields
            if (userBody.Name == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Name is required")));
            }
            if (userBody.Email == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Email is required")));
            }
            if (userBody.Password == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Password is required")));
            }
            if (userBody.Dateofbirth == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Dateofbirth is required")));
            }
            if (userBody.Gender == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Gender is required")));
            }

            // check for date of birth not in the future
            if (userBody.Dateofbirth >= DateTime.Now)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Dateofbirth can not be in the future")));
            }

            // cannot set user type
            if (userBody.Type != null && userBody.Type != UserType.User)
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_TO_SET_USER_TYPE)));
            }

            // check if there is already an user with this email
            if (!await userService.EmailExists(userBody.Email))
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Email does already exist")));
            }

            // create user
            User createdUser = await this.userService.CreateUser(userBody);

            // get the created user
            UserResponse response = await userService.GetUser(createdUser.Id);

            return(new OkObjectResult(response));
        }