-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathUsersController.cs
275 lines (226 loc) · 8.32 KB
/
UsersController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
using System.Text.RegularExpressions;
using AutoMapper;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebApi.MinimalApi.Domain;
using WebApi.MinimalApi.Models;
namespace WebApi.MinimalApi.Controllers;
[Route("api/[controller]")]
[ApiController]
public class UsersController : Controller
{
private readonly IUserRepository userRepository;
private readonly IMapper mapper;
private readonly LinkGenerator linkGenerator;
public UsersController(IUserRepository userRepository, IMapper mapper, LinkGenerator linkGenerator)
{
this.userRepository = userRepository;
this.mapper = mapper;
this.linkGenerator = linkGenerator;
}
[HttpGet("{userId}", Name = nameof(GetUserById))]
[HttpHead("{userId}")]
public ActionResult<UserDto> GetUserById([FromRoute] Guid userId)
{
var userEntity = userRepository.FindById(userId);
if (userEntity is null)
return NotFound();
var userDto = mapper.Map<UserDto>(userEntity);
if (Request.Method == "HEAD")
{
Response.Body = Stream.Null;
}
return Ok(userDto);
}
[HttpPost]
[Produces("application/json", "application/xml")]
public IActionResult CreateUser([FromBody] CreateUserDto user)
{
if (user is null)
{
return BadRequest();
}
if (user.Login == "" || user.Login is null)
{
ModelState.AddModelError("login", "Error");
return UnprocessableEntity(ModelState);
}
if (!user.Login.All(char.IsLetterOrDigit))
{
ModelState.AddModelError("login", "Error");
}
if (!ModelState.IsValid)
{
return UnprocessableEntity(ModelState);
}
var userToCreate = mapper.Map<UserEntity>(user);
var createdUserEntity = userRepository.Insert(userToCreate);
return CreatedAtRoute(
nameof(GetUserById),
new { userId = createdUserEntity.Id },
createdUserEntity.Id);
}
[HttpPut("{userId}")]
[Produces("application/json", "application/xml")]
public IActionResult UpdateUser([FromBody] UpdateUserDto user, [FromRoute] string userId)
{
if (user is null)
{
return BadRequest();
}
var validationResult = ValidateUserDto(user);
if (validationResult != null)
{
return validationResult;
}
var userToUpdate = mapper.Map<UserEntity>(user);
if (!Guid.TryParse(userId, out var guid))
{
return BadRequest();
}
var userEntity = userRepository.FindById(guid);
if (userEntity == null)
{
var createdUserEntity = userRepository.Insert(userToUpdate);
return CreatedAtRoute(
nameof(GetUserById),
new { userId = createdUserEntity.Id },
createdUserEntity.Id);
}
userRepository.Update(userToUpdate);
return NoContent();
}
[HttpPatch("{userId}")]
public IActionResult PartiallyUpdateUser([FromBody] JsonPatchDocument<UpdateUserDto> patchDoc, [FromRoute] String userId)
{
if (patchDoc == null)
{
return BadRequest();
}
var validationResult = ValidatePatchDocument(patchDoc);
if (validationResult != null)
{
return validationResult;
}
if (!Guid.TryParse(userId, out var guid))
{
return NotFound();
}
var user = userRepository.FindById(guid);
if (user == null)
{
return NotFound();
}
var updateUserDto = mapper.Map<UpdateUserDto>(user);
patchDoc.ApplyTo(updateUserDto, ModelState);
TryValidateModel(updateUserDto);
return ModelState.IsValid ? NoContent() : UnprocessableEntity(ModelState);
}
[HttpDelete("{userId}")]
public IActionResult DeleteUser(string userId)
{
if (!Guid.TryParse(userId, out var guid))
{
return NotFound();
}
if (userRepository.FindById(guid) == null)
{
return NotFound();
}
userRepository.Delete(guid);
return NoContent();
}
[HttpGet]
public IActionResult GetUsers([FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 10)
{
if (pageNumber < 1)
pageNumber = 1;
if (pageSize < 1)
pageSize = 1;
if (pageSize > 20)
pageSize = 20;
var pageList = userRepository.GetPage(pageNumber, pageSize);
var users = mapper.Map<IEnumerable<UserDto>>(pageList);
var paginationHeader = new
{
previousPageLink = pageList.HasPrevious ?
linkGenerator.GetUriByAction(
HttpContext, nameof(GetUsers),
values: new { pageNumber = pageNumber - 1, pageSize }) : null,
nextPageLink = pageList.HasNext ?
linkGenerator.GetUriByAction(
HttpContext, nameof(GetUsers),
values: new { pageNumber = pageNumber + 1, pageSize }) : null,
totalCount = pageList.TotalCount,
pageSize = pageSize,
currentPage = pageNumber,
totalPages = (int)Math.Ceiling((double)pageList.TotalCount / pageSize)
};
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationHeader));
return Ok(users);
}
[HttpOptions]
public IActionResult Options()
{
Response.Headers.Add("Allow", "GET, POST, OPTIONS");
return Ok();
}
private IActionResult ValidateUserDto(UpdateUserDto userDto)
{
if (string.IsNullOrWhiteSpace(userDto.Login) || !userDto.Login.All(char.IsLetterOrDigit))
{
ModelState.AddModelError("login", "Login must contain only letters and digits and cannot be empty.");
return UnprocessableEntity(ModelState);
}
if (string.IsNullOrWhiteSpace(userDto.FirstName))
{
ModelState.AddModelError("firstName", "First name cannot be empty.");
return UnprocessableEntity(ModelState);
}
if (string.IsNullOrWhiteSpace(userDto.LastName))
{
ModelState.AddModelError("lastName", "Last name cannot be empty.");
return UnprocessableEntity(ModelState);
}
return null;
}
private IActionResult ValidatePatchDocument(JsonPatchDocument<UpdateUserDto> patchDoc)
{
foreach (var operation in patchDoc.Operations)
{
if (operation.path == "login")
{
if (ContainsSpecialCharacters(operation.value.ToString()))
{
ModelState.AddModelError("login", "Login must not contain special characters.");
return UnprocessableEntity(ModelState);
}
if (string.IsNullOrWhiteSpace(operation.value.ToString()))
{
ModelState.AddModelError("login", "Login cannot be empty.");
return UnprocessableEntity(ModelState);
}
}
else if (operation.path == "firstName" && string.IsNullOrWhiteSpace(operation.value.ToString()))
{
ModelState.AddModelError("firstName", "First name cannot be empty.");
return UnprocessableEntity(ModelState);
}
else if (operation.path == "lastName" && string.IsNullOrWhiteSpace(operation.value.ToString()))
{
ModelState.AddModelError("lastName", "Last name cannot be empty.");
return UnprocessableEntity(ModelState);
}
}
return null;
}
static bool ContainsSpecialCharacters(string str)
{
// регулярное выражение для проверки на наличие специальных символов
var pattern = @"[^a-zA-Z0-9а-яА-ЯёЁ]";
// Проверяем, соответствует ли строка шаблону
return Regex.IsMatch(str, pattern);
}
}