From fcdecc38741dc8e3adb41897ee294aa6d1384128 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 10 Dec 2020 21:23:46 +0200 Subject: Added data validations of UserService requests --- API/Service/UserService.cs | 45 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) (limited to 'API/Service') diff --git a/API/Service/UserService.cs b/API/Service/UserService.cs index c673fac..b86687d 100644 --- a/API/Service/UserService.cs +++ b/API/Service/UserService.cs @@ -9,6 +9,9 @@ using Microsoft.AspNetCore.Mvc; using Models.Classes; using Models.DTOs; using Newtonsoft.Json; +using System; +using System.Web.Http; +using System.Collections.Generic; namespace API.Service { @@ -25,7 +28,13 @@ namespace API.Service public async Task CreateUser(UserDTO userDTO) { - //TODO: MAKE VALIDATIONS OF PROPER REQUEST + IEnumerable allUsers = this._dbRepository.Query(); + + foreach (var currUser in allUsers) + { + if (currUser.UserName == userDTO.UserName) + return HttpStatusCode.Forbidden; + } User user = this._userMapper.Map(userDTO); await this._dbRepository.AddAsync(user); @@ -35,22 +44,48 @@ namespace API.Service public async Task GetUserById(int id) { - User user = await this._dbRepository.FindByIdAsync(id); + User user = await this._dbRepository.FindByIdAsync(id) ?? + throw new HttpResponseException(HttpStatusCode.NotFound); + return JsonConvert.SerializeObject(user); } public async Task UpdateUser(int id, UserDTO userDTO) { + IEnumerable allUsers = this._dbRepository.Query(); + + bool userExists = false; + foreach (var currUser in allUsers) + { + if (currUser.Id == userDTO.Id) + { + userExists = true; + continue; + } + + if (currUser.UserName == userDTO.UserName) + return HttpStatusCode.Forbidden; + } + + if (!userExists) + return HttpStatusCode.NotFound; + User user = this._userMapper.Map(userDTO); await this._dbRepository.EditAsync(id, user); - return HttpStatusCode.OK; } public async Task DeleteUser(int id) { - await this._dbRepository.DeleteAsync(id); - + try // This skips having to query the database and check if the user doesn't exist + { + await this._dbRepository.DeleteAsync(id); + } + catch (ArgumentNullException) + { + return HttpStatusCode.NotFound; + } + return HttpStatusCode.OK; } } -- cgit v1.2.3