diff --git a/Do-Svyazi.User.sln b/Do-Svyazi.User.sln index 0b9ecd9..55d843e 100644 --- a/Do-Svyazi.User.sln +++ b/Do-Svyazi.User.sln @@ -24,7 +24,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Do-Svyazi.User.Web.Controll EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Do-Svyazi.User.Web.ApiClient", "Source\Presentation\Do-Svyazi.User.Web.ApiClient\Do-Svyazi.User.Web.ApiClient.csproj", "{A5520DDE-4790-46C6-BD8B-FD65BD5E32B9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CQRS.Tests", "Source\Tests\CQRS.Tests\CQRS.Tests.csproj", "{86C8E30B-B631-46E7-A0DD-815D0F447079}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Unit.Tests", "Source\Tests\Unit.Tests\Unit.Tests.csproj", "{86C8E30B-B631-46E7-A0DD-815D0F447079}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Integration.Tests", "Source\Tests\Integration.Tests\Integration.Tests.csproj", "{83F47902-3FCC-4D11-A780-5590930C224C}" EndProject diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/Register.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterAdminCommand.cs similarity index 71% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/Register.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterAdminCommand.cs index 80f109e..8ec3564 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/Register.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterAdminCommand.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Authenticate.Commands; -public record Register(RegisterModel model) +public record RegisterAdminCommand(RegisterModel model) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterAdmin.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterCommand.cs similarity index 63% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterAdmin.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterCommand.cs index 2804a68..3e14125 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterAdmin.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Commands/RegisterCommand.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Authenticate.Commands; -public record RegisterAdmin(RegisterModel model) - : IRequest; \ No newline at end of file +public record RegisterCommand(RegisterModel model) + : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateCommandHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateCommandHandler.cs index 94c446d..620cc4a 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateCommandHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateCommandHandler.cs @@ -2,84 +2,72 @@ using Do_Svyazi.User.Application.CQRS.Handlers; using Do_Svyazi.User.Domain.Authenticate; using Do_Svyazi.User.Domain.Exceptions; +using Do_Svyazi.User.Domain.Users; using MediatR; using Microsoft.AspNetCore.Identity; namespace Do_Svyazi.User.Application.CQRS.Authenticate.Handlers; -public class AuthenticateCommandHandler - : ICommandHandler, - ICommandHandler +public class AuthenticateCommandHandler : + ICommandHandler, + ICommandHandler { - private readonly UserManager _userManager; + private readonly UserManager _userManager; private readonly RoleManager _roleManager; - public AuthenticateCommandHandler(UserManager userManager, RoleManager roleManager) + public AuthenticateCommandHandler( + UserManager userManager, + RoleManager roleManager) { _userManager = userManager; _roleManager = roleManager; } - public async Task Handle(Register request, CancellationToken cancellationToken) + public async Task Handle(RegisterCommand request, CancellationToken cancellationToken) { - MessageIdentityUser? userExists = await _userManager.FindByNameAsync(request.model.NickName); - - if (userExists != null) - { - throw new Do_Svyazi_User_BusinessLogicException( - "User already exists"); - } - - MessageIdentityUser user = new () - { - SecurityStamp = Guid.NewGuid().ToString(), - UserName = request.model.NickName, - Email = request.model.Email, - }; - - IdentityResult? result = await _userManager.CreateAsync(user, request.model.Password); - if (!result.Succeeded) - { - throw new Do_Svyazi_User_BusinessLogicException( - "User creation failed! Please check user details and try again."); - } + RegisterModel registerModel = request.model; - return Unit.Value; + if (await _userManager.FindByNameAsync(registerModel.UserName) is not null) + throw new Do_Svyazi_User_BusinessLogicException("User already exists"); + + MessengerUser user = CreateIdentityUser(registerModel); + + if (!(await _userManager.CreateAsync(user, registerModel.Password)).Succeeded) + throw new Do_Svyazi_User_BusinessLogicException("User creation failed! Please check user details and try again."); + + return user.Id; } - public async Task Handle(RegisterAdmin request, CancellationToken cancellationToken) + public async Task Handle(RegisterAdminCommand request, CancellationToken cancellationToken) { - MessageIdentityUser userExists = await _userManager.FindByNameAsync(request.model.NickName); - if (userExists != null) - { - throw new Do_Svyazi_User_BusinessLogicException( - "User already exists"); - } - - MessageIdentityUser user = new () - { - SecurityStamp = Guid.NewGuid().ToString(), - UserName = request.model.NickName, - }; - IdentityResult? result = await _userManager.CreateAsync(user, request.model.Password); - if (!result.Succeeded) - { - throw new Do_Svyazi_User_BusinessLogicException( - "User creation failed! Please check user details and try again."); - } + RegisterModel registerModel = request.model; + + MessengerUser user = await GetUserByUsernameOrEmail(registerModel); + + if (!await _roleManager.RoleExistsAsync(MessageIdentityRole.Admin)) + await _roleManager.CreateAsync(new MessageIdentityRole(MessageIdentityRole.Admin)); + + if (!await _roleManager.RoleExistsAsync(MessageIdentityRole.User)) + await _roleManager.CreateAsync(new MessageIdentityRole(MessageIdentityRole.User)); if (await _roleManager.RoleExistsAsync(MessageIdentityRole.Admin)) - { await _userManager.AddToRoleAsync(user, MessageIdentityRole.Admin); - await _roleManager.CreateAsync(new MessageIdentityRole(MessageIdentityRole.User)); - } - if (await _roleManager.RoleExistsAsync(MessageIdentityRole.User)) - { + if (await _roleManager.RoleExistsAsync(MessageIdentityRole.Admin)) await _userManager.AddToRoleAsync(user, MessageIdentityRole.User); - await _roleManager.CreateAsync(new MessageIdentityRole(MessageIdentityRole.Admin)); - } return Unit.Value; } + + private MessengerUser CreateIdentityUser(RegisterModel userModel) => + new (userModel.Name, userModel.UserName, userModel.Email, userModel.PhoneNumber); + + private async Task GetUserByUsernameOrEmail(RegisterModel registerModel) + { + MessengerUser user = await _userManager.FindByNameAsync(registerModel.UserName) + ?? await _userManager.FindByEmailAsync(registerModel.Email) + ?? throw new Do_Svyazi_User_NotFoundException($"User with userName {registerModel.UserName} or email {registerModel.Email} was not found"); + + return user; + } } \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateQueryHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateQueryHandler.cs index c123b69..3a8c586 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateQueryHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Handlers/AuthenticateQueryHandler.cs @@ -1,61 +1,107 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; +using AutoMapper; +using AutoMapper.QueryableExtensions; using Do_Svyazi.User.Application.CQRS.Authenticate.Queries; using Do_Svyazi.User.Application.CQRS.Handlers; using Do_Svyazi.User.Domain.Authenticate; +using Do_Svyazi.User.Domain.Exceptions; +using Do_Svyazi.User.Domain.Users; +using Do_Svyazi.User.Dtos.Users; using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace Do_Svyazi.User.Application.CQRS.Authenticate.Handlers; -public class AuthenticateQueryHandler - : IQueryHandler +public class AuthenticateQueryHandler : + IQueryHandler, + IQueryHandler, + IQueryHandler> { - private readonly UserManager _userManager; + private const string NameType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; + + private readonly UserManager _userManager; private readonly IConfiguration _configuration; + private readonly IMapper _mapper; - public AuthenticateQueryHandler(UserManager userManager, IConfiguration configuration) + public AuthenticateQueryHandler(UserManager userManager, IConfiguration configuration, IMapper mapper) { _userManager = userManager; _configuration = configuration; + _mapper = mapper; } - public async Task Handle(Login request, CancellationToken cancellationToken) + public async Task Handle(LoginRequest request, CancellationToken cancellationToken) { - var token = new JwtSecurityToken(); - MessageIdentityUser user = await _userManager.FindByNameAsync(request.model.NickName); - if (user != null && await _userManager.CheckPasswordAsync(user, request.model.Password)) + LoginModel loginModel = request.model; + MessengerUser user = await GetUserByUsernameOrEmail(loginModel); + + if (!await _userManager.CheckPasswordAsync(user, loginModel.Password)) + throw new UnauthorizedAccessException("Can't login with this credentials"); + + IList? userRoles = await _userManager.GetRolesAsync(user); + + var authClaims = new List { - IList? userRoles = await _userManager.GetRolesAsync(user); + new Claim(ClaimTypes.Name, user.UserName), + new Claim(JwtRegisteredClaimNames.Jti, $"{user.Id}"), + new Claim(JwtRegisteredClaimNames.Email, $"{user.Email}"), + }; - var authClaims = new List - { - new Claim(ClaimTypes.Name, user.UserName), - new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), - }; - authClaims - .AddRange(userRoles - .Select(userRole => new Claim(ClaimTypes.Role, userRole))); + authClaims + .AddRange(userRoles + .Select(userRole => new Claim(ClaimTypes.Role, userRole))); - token = GetToken(authClaims); - } + return GetToken(authClaims); + } - return token; + public async Task Handle(AuthenticateByJwtRequest request, CancellationToken cancellationToken) + { + var token = new JwtSecurityToken(request.jwtToken); + string userNickName = token.Claims.First(x => x.Type == NameType).Value; + + var identityUser = await _userManager.FindByNameAsync(userNickName); + return new AuthenticateResponse(identityUser.Id, token.ValidTo); } + public async Task> Handle(GetUsersRequest request, CancellationToken cancellationToken) + => await _userManager.Users + .ProjectTo(_mapper.ConfigurationProvider) + .ToListAsync(cancellationToken: cancellationToken); + private JwtSecurityToken GetToken(List authClaims) { var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"])); + var time = DateTime.UtcNow.AddHours(int.Parse(_configuration["JWT:Expires"])); + var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], - expires: DateTime.Now.AddHours(int.Parse(_configuration["JWT:Expires"])), + notBefore: DateTime.UtcNow, + expires: DateTime.UtcNow.AddHours(int.Parse(_configuration["JWT:Expires"])), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)); return token; } + + private async Task GetUserByUsernameOrEmail(LoginModel loginModel) + { + MessengerUser? user = default; + + if (loginModel.UserName is not null) + user = await _userManager.FindByNameAsync(loginModel.UserName); + + if (user is null && loginModel.Email is not null) + user = await _userManager.FindByEmailAsync(loginModel.Email); + + if (user is null) + throw new Do_Svyazi_User_NotFoundException($"User {loginModel.UserName} to login was not found"); + + return user; + } } \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/AuthenticateByJwtRequest.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/AuthenticateByJwtRequest.cs new file mode 100644 index 0000000..6b24e23 --- /dev/null +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/AuthenticateByJwtRequest.cs @@ -0,0 +1,8 @@ +using MediatR; + +namespace Do_Svyazi.User.Application.CQRS.Authenticate.Queries; + +public record AuthenticateByJwtRequest(string jwtToken) + : IRequest; + +public record AuthenticateResponse(Guid userId, DateTime validTo); \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/GetUsersRequest.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/GetUsersRequest.cs new file mode 100644 index 0000000..008e942 --- /dev/null +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/GetUsersRequest.cs @@ -0,0 +1,7 @@ +using Do_Svyazi.User.Dtos.Users; +using MediatR; + +namespace Do_Svyazi.User.Application.CQRS.Authenticate.Queries; + +public record GetUsersRequest + : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/Login.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/LoginRequest.cs similarity index 81% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/Login.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/LoginRequest.cs index 8ba61cb..296ad9c 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/Login.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Authenticate/Queries/LoginRequest.cs @@ -4,5 +4,5 @@ namespace Do_Svyazi.User.Application.CQRS.Authenticate.Queries; -public record Login(LoginModel model) +public record LoginRequest(LoginModel model) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddSavedMessages.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddChannelCommand.cs similarity index 54% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddSavedMessages.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddChannelCommand.cs index 9868dbe..ee392ff 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddSavedMessages.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddChannelCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Commands; -public record AddSavedMessages(Guid userId, string name, string description) +public record AddChannelCommand(Guid adminId, string name, string description) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddGroupChat.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddGroupChatCommand.cs similarity index 54% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddGroupChat.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddGroupChatCommand.cs index 5e8f593..baa9869 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddGroupChat.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddGroupChatCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Commands; -public record AddGroupChat(Guid adminId, string name, string description) +public record AddGroupChatCommand(Guid adminId, string name, string description) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddPersonalChat.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddPersonalChat.cs deleted file mode 100644 index 51f18f0..0000000 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddPersonalChat.cs +++ /dev/null @@ -1,6 +0,0 @@ -using MediatR; - -namespace Do_Svyazi.User.Application.CQRS.Chats.Commands; - -public record AddPersonalChat(Guid firstUserId, Guid secondUserId, string name, string description) - : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddPersonalChatCommand.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddPersonalChatCommand.cs new file mode 100644 index 0000000..b233078 --- /dev/null +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddPersonalChatCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace Do_Svyazi.User.Application.CQRS.Chats.Commands; + +public record AddPersonalChatCommand(Guid firstUserId, Guid secondUserId, string name, string description) + : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddChannel.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddSavedMessagesCommand.cs similarity index 53% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddChannel.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddSavedMessagesCommand.cs index 5886aff..e5d0b1f 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddChannel.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddSavedMessagesCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Commands; -public record AddChannel(Guid adminId, string name, string description) +public record AddSavedMessagesCommand(Guid userId, string name, string description) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddUserToChat.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddUserToChatCommand.cs similarity index 61% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddUserToChat.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddUserToChatCommand.cs index 44b3250..103bfc0 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddUserToChat.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/AddUserToChatCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Commands; -public record AddUserToChat(Guid userId, Guid chatId) +public record AddUserToChatCommand(Guid userId, Guid chatId) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/DeleteUserFromChat.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/DeleteUserFromChatCommand.cs similarity index 57% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/DeleteUserFromChat.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/DeleteUserFromChatCommand.cs index 6a9410d..dd04423 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/DeleteUserFromChat.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Commands/DeleteUserFromChatCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Commands; -public record DeleteUserFromChat(Guid userId, Guid chatId) +public record DeleteUserFromChatCommand(Guid userId, Guid chatId) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsCommandHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsCommandHandler.cs index 92eca02..b58b00a 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsCommandHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsCommandHandler.cs @@ -5,30 +5,35 @@ using Do_Svyazi.User.Domain.Exceptions; using Do_Svyazi.User.Domain.Users; using MediatR; +using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace Do_Svyazi.User.Application.CQRS.Chats.Handlers; public class ChatsCommandHandler : - ICommandHandler, - ICommandHandler, - ICommandHandler, - ICommandHandler, - ICommandHandler, - ICommandHandler + ICommandHandler, + ICommandHandler, + ICommandHandler, + ICommandHandler, + ICommandHandler, + ICommandHandler { private readonly IDbContext _context; + private readonly UserManager _userManager; - public ChatsCommandHandler(IDbContext context) => _context = context; + public ChatsCommandHandler(UserManager userManager, IDbContext context) + { + _userManager = userManager; + _context = context; + } - public async Task Handle(AddChannel request, CancellationToken cancellationToken) + public async Task Handle(AddChannelCommand request, CancellationToken cancellationToken) { - MessengerUser user = await _context.Users - .SingleOrDefaultAsync(user => user.Id == request.adminId, cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException( + MessengerUser user = await _userManager.FindByIdAsync($"{request.adminId}") + ?? throw new Do_Svyazi_User_NotFoundException( $"User with id = {request.adminId} to create a channel was not found"); - Chat chat = new Channel(user, request.name, request.description); + var chat = new Channel(user, request.name, request.description); var chatAdmin = chat.Users.Single(); await _context.ChatUsers.AddAsync(chatAdmin, cancellationToken); @@ -38,14 +43,13 @@ public async Task Handle(AddChannel request, CancellationToken cancellatio return chat.Id; } - public async Task Handle(AddGroupChat request, CancellationToken cancellationToken) + public async Task Handle(AddGroupChatCommand request, CancellationToken cancellationToken) { - MessengerUser user = await _context.Users - .SingleOrDefaultAsync(user => user.Id == request.adminId, cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException( + MessengerUser user = await _userManager.FindByIdAsync($"{request.adminId}") + ?? throw new Do_Svyazi_User_NotFoundException( $"User with id = {request.adminId} to create a group chat was not found"); - GroupChat chat = new GroupChat(user, request.name, request.description); + var chat = new GroupChat(user, request.name, request.description); var chatAdmin = chat.Users.Single(); await _context.ChatUsers.AddAsync(chatAdmin, cancellationToken); @@ -55,34 +59,30 @@ public async Task Handle(AddGroupChat request, CancellationToken cancellat return chat.Id; } - public async Task Handle(AddPersonalChat request, CancellationToken cancellationToken) + public async Task Handle(AddPersonalChatCommand request, CancellationToken cancellationToken) { - MessengerUser firstUser = - await _context.Users.SingleOrDefaultAsync(user => user.Id == request.firstUserId, cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException( - $"User with id = {request.firstUserId} to create a personal chat was not found"); + MessengerUser firstUser = await _userManager.FindByIdAsync($"{request.firstUserId}") + ?? throw new Do_Svyazi_User_NotFoundException( + $"User with id = {request.firstUserId} to create a personal chat was not found"); - MessengerUser secondUser = - await _context.Users.SingleOrDefaultAsync(user => user.Id == request.secondUserId, cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException( - $"User with id = {request.secondUserId} to create a personal chat was not found"); + MessengerUser secondUser = await _userManager.FindByIdAsync($"{request.secondUserId}") + ?? throw new Do_Svyazi_User_NotFoundException( + $"User with id = {request.secondUserId} to create a personal chat was not found"); Chat chat = new PersonalChat(firstUser, secondUser, request.name, request.description); - _context.Users.Update(firstUser); - _context.Users.Update(secondUser); + await _context.ChatUsers.AddRangeAsync(chat.Users, cancellationToken); await _context.Chats.AddAsync(chat, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return chat.Id; } - public async Task Handle(AddSavedMessages request, CancellationToken cancellationToken) + public async Task Handle(AddSavedMessagesCommand request, CancellationToken cancellationToken) { - MessengerUser user = - await _context.Users.SingleOrDefaultAsync(user => user.Id == request.userId, cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException( - $"User with id = {request.userId} to create saved messages chat not found"); + MessengerUser user = await _userManager.FindByIdAsync($"{request.userId}") + ?? throw new Do_Svyazi_User_NotFoundException( + $"User with id = {request.userId} to create saved messages chat not found"); Chat chat = new SavedMessages(user, request.name, request.description); var chatAdmin = chat.Users.Single(); @@ -94,20 +94,17 @@ await _context.Users.SingleOrDefaultAsync(user => user.Id == request.userId, can return chat.Id; } - public async Task Handle(AddUserToChat request, CancellationToken cancellationToken) + public async Task Handle(AddUserToChatCommand request, CancellationToken cancellationToken) { Chat chat = await _context.Chats .Include(chat => chat.Users) - .ThenInclude(user => user.User) - .Include(chat => chat.Users) - .ThenInclude(user => user.Role) + .ThenInclude(user => user.Role) .SingleOrDefaultAsync(chat => chat.Id == request.chatId, cancellationToken) ?? throw new Do_Svyazi_User_NotFoundException( $"Chat with id = {request.chatId} to add user {request.userId} was not found"); - MessengerUser messengerUser = await _context.Users - .SingleOrDefaultAsync(user => user.Id == request.userId, cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException( + MessengerUser messengerUser = await _userManager.FindByIdAsync($"{request.userId}") + ?? throw new Do_Svyazi_User_NotFoundException( $"User with id = {request.userId} to be added into chat with id = {request.chatId} not found"); ChatUser newChatUser = chat.AddUser(messengerUser); @@ -118,20 +115,16 @@ public async Task Handle(AddUserToChat request, CancellationToken cancella return Unit.Value; } - public async Task Handle(DeleteUserFromChat request, CancellationToken cancellationToken) + public async Task Handle(DeleteUserFromChatCommand request, CancellationToken cancellationToken) { Chat chat = await _context.Chats .Include(chat => chat.Users) - .ThenInclude(user => user.User) - .Include(chat => chat.Users) - .ThenInclude(user => user.Role) + .ThenInclude(user => user.Role) .SingleOrDefaultAsync(chat => chat.Id == request.chatId, cancellationToken) ?? throw new Do_Svyazi_User_NotFoundException($"Chat with id {request.chatId} not found"); - MessengerUser messengerUser = await _context.Users - .SingleOrDefaultAsync(user => user.Id == request.userId, cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException( - $"User with id {request.userId} not found"); + MessengerUser messengerUser = await _userManager.FindByIdAsync($"{request.userId}") + ?? throw new Do_Svyazi_User_NotFoundException($"User with id {request.userId} not found"); var removedUser = chat.RemoveUser(messengerUser); diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsQueryHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsQueryHandler.cs index 6065df6..f512635 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsQueryHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Handlers/ChatsQueryHandler.cs @@ -4,17 +4,17 @@ using Do_Svyazi.User.Application.DbContexts; using Do_Svyazi.User.Domain.Chats; using Do_Svyazi.User.Domain.Exceptions; -using Do_Svyazi.User.Domain.Users; using Do_Svyazi.User.Dtos.Chats; +using Do_Svyazi.User.Dtos.Users; using Microsoft.EntityFrameworkCore; namespace Do_Svyazi.User.Application.CQRS.Chats.Handlers; public class ChatsQueryHandler : - IQueryHandler, - IQueryHandler>, - IQueryHandler>, - IQueryHandler> + IQueryHandler, + IQueryHandler>, + IQueryHandler>, + IQueryHandler> { private readonly IDbContext _context; private readonly IMapper _mapper; @@ -25,7 +25,7 @@ public ChatsQueryHandler(IDbContext context, IMapper mapper) _mapper = mapper; } - public async Task Handle(GetChatById request, CancellationToken cancellationToken) + public async Task Handle(GetChatByIdQuery request, CancellationToken cancellationToken) { Chat chat = await _context.Chats .Include(chat => chat.Users) @@ -36,7 +36,7 @@ public async Task Handle(GetChatById request, CancellationToke return _mapper.Map(chat); } - public async Task> Handle(GetChats request, CancellationToken cancellationToken) + public async Task> Handle(GetChatsQuery request, CancellationToken cancellationToken) { List chats = await _context.Chats .Include(chat => chat.Users) @@ -46,7 +46,7 @@ public async Task> Handle(GetChats request return _mapper.Map>(chats); } - public async Task> Handle(GetUserIdsByChatId request, CancellationToken cancellationToken) + public async Task> Handle(GetUserIdsByChatIdQuery request, CancellationToken cancellationToken) { Chat chat = await _context.Chats .Include(chat => chat.Users) @@ -58,16 +58,14 @@ public async Task> Handle(GetUserIdsByChatId request, return _mapper.Map>(userIds); } - public async Task> Handle(GetUsersByChatId request, CancellationToken cancellationToken) + public async Task> Handle(GetUsersByChatIdQuery request, CancellationToken cancellationToken) { Chat chat = await _context.Chats - .Include(chat => chat.Users) - .ThenInclude(user => user.User) .Include(chat => chat.Users) .ThenInclude(user => user.Role) .SingleOrDefaultAsync(chat => chat.Id == request.chatId, cancellationToken) ?? throw new Do_Svyazi_User_NotFoundException($"Chat with id = {request.chatId} to get users was not found"); - return _mapper.Map>(chat.Users); + return _mapper.Map>(chat.Users); } } \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatById.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatByIdQuery.cs similarity index 76% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatById.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatByIdQuery.cs index a7308cf..6dd8016 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatById.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatByIdQuery.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Queries; -public record GetChatById(Guid chatId) +public record GetChatByIdQuery(Guid chatId) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChats.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatsQuery.cs similarity index 85% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChats.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatsQuery.cs index 7b4ab43..7c29859 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChats.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetChatsQuery.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Queries; -public record GetChats +public record GetChatsQuery : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUserIdsByChatId.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUserIdsByChatIdQuery.cs similarity index 69% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUserIdsByChatId.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUserIdsByChatIdQuery.cs index b115b78..318e57b 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUserIdsByChatId.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUserIdsByChatIdQuery.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Chats.Queries; using MediatR; -public record GetUserIdsByChatId(Guid chatId) +public record GetUserIdsByChatIdQuery(Guid chatId) : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUsersByChatId.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUsersByChatId.cs deleted file mode 100644 index 807fd77..0000000 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUsersByChatId.cs +++ /dev/null @@ -1,8 +0,0 @@ -using Do_Svyazi.User.Domain.Users; - -namespace Do_Svyazi.User.Application.CQRS.Chats.Queries; - -using MediatR; - -public record GetUsersByChatId(Guid chatId) - : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUsersByChatIdQuery.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUsersByChatIdQuery.cs new file mode 100644 index 0000000..63c535a --- /dev/null +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Chats/Queries/GetUsersByChatIdQuery.cs @@ -0,0 +1,8 @@ +using Do_Svyazi.User.Dtos.Users; + +namespace Do_Svyazi.User.Application.CQRS.Chats.Queries; + +using MediatR; + +public record GetUsersByChatIdQuery(Guid chatId) + : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/ChangeUserRoleInChat.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/ChangeUserRoleInChat.cs index d0fee20..4608e44 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/ChangeUserRoleInChat.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/ChangeUserRoleInChat.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Roles.Commands; -public record ChangeRoleForUserById(Guid userId, Guid chatId, RoleDto role) +public record ChangeRoleForUserByIdCommand(Guid userId, Guid chatId, RoleDto role) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/CreateRoleForChat.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/CreateRoleForChatCommand.cs similarity index 65% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/CreateRoleForChat.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/CreateRoleForChatCommand.cs index 6c38645..4292cb8 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/CreateRoleForChat.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Commands/CreateRoleForChatCommand.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Roles.Commands; -public record CreateRoleForChat(RoleDto role, Guid chatId) +public record CreateRoleForChatCommand(RoleDto role, Guid chatId) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesCommandHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesCommandHandler.cs index d7ea98c..deb5f15 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesCommandHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesCommandHandler.cs @@ -11,13 +11,13 @@ namespace Do_Svyazi.User.Application.CQRS.Roles.Handlers; public class RolesCommandHandler : - ICommandHandler, - IRequestHandler + ICommandHandler, + IRequestHandler { private readonly IDbContext _context; public RolesCommandHandler(IDbContext context) => _context = context; - public async Task Handle(ChangeRoleForUserById request, CancellationToken cancellationToken) + public async Task Handle(ChangeRoleForUserByIdCommand request, CancellationToken cancellationToken) { ChatUser chatUser = await _context.ChatUsers @@ -60,7 +60,7 @@ await _context.ChatUsers return Unit.Value; } - public async Task Handle(CreateRoleForChat request, CancellationToken cancellationToken) + public async Task Handle(CreateRoleForChatCommand request, CancellationToken cancellationToken) { Chat chat = await _context.Chats.FindAsync(request.chatId) ?? throw new Do_Svyazi_User_NotFoundException( diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesQueryHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesQueryHandler.cs index 82e010c..4e26f27 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesQueryHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Handlers/RolesQueryHandler.cs @@ -10,7 +10,7 @@ namespace Do_Svyazi.User.Application.CQRS.Roles.Handlers; public class RolesQueryHandler - : IQueryHandler + : IQueryHandler { private readonly IDbContext _context; private readonly IMapper _mapper; @@ -21,7 +21,7 @@ public RolesQueryHandler(IDbContext context, IMapper mapper) _mapper = mapper; } - public async Task Handle(GetRoleByUserId request, CancellationToken cancellationToken) + public async Task Handle(GetRoleByUserIdQuery request, CancellationToken cancellationToken) { ChatUser chatUser = await _context.ChatUsers diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Queries/GetRoleByUserId.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Queries/GetRoleByUserIdQuery.cs similarity index 68% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Queries/GetRoleByUserId.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Queries/GetRoleByUserIdQuery.cs index fdd3230..a13911d 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Queries/GetRoleByUserId.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Roles/Queries/GetRoleByUserIdQuery.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Roles.Queries; -public record GetRoleByUserId(Guid userId, Guid chatId) +public record GetRoleByUserIdQuery(Guid userId, Guid chatId) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/AddUser.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/AddUserCommand.cs similarity index 54% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/AddUser.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/AddUserCommand.cs index 0c0c053..94fc899 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/AddUser.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/AddUserCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Commands; -public record AddUser(string name, string nickName, string description) +public record AddUserCommand(string name, string nickName, string description) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserDescriptionById.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserDescriptionByIdCommand.cs similarity index 52% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserDescriptionById.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserDescriptionByIdCommand.cs index 03b8997..daa01e2 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserDescriptionById.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserDescriptionByIdCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Commands; -public record ChangeUserDescriptionById(Guid userId, string description) +public record ChangeUserDescriptionByIdCommand(Guid userId, string description) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNameById.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNameByIdCommand.cs similarity index 57% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNameById.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNameByIdCommand.cs index c1f2125..e82f5e3 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNameById.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNameByIdCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Commands; -public record ChangeUserNameById(Guid userId, string name) +public record ChangeUserNameByIdCommand(Guid userId, string name) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNickNameById.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNickNameById.cs index 4631a5c..aab8419 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNickNameById.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/ChangeUserNickNameById.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Commands; -public record SetUserNickNameById(Guid userId, string nickName) +public record SetUserNickNameByIdCommand(Guid userId, string userName) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/DeleteUser.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/DeleteUserCommand.cs similarity index 66% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/DeleteUser.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/DeleteUserCommand.cs index 7cec04d..a4121a8 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/DeleteUser.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Commands/DeleteUserCommand.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Commands; -public record DeleteUser(Guid userId) +public record DeleteUserCommand(Guid userId) : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersCommandHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersCommandHandler.cs index 1ea6c0c..6298ada 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersCommandHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersCommandHandler.cs @@ -1,92 +1,69 @@ using Do_Svyazi.User.Application.CQRS.Handlers; using Do_Svyazi.User.Application.CQRS.Users.Commands; -using Do_Svyazi.User.Application.DbContexts; using Do_Svyazi.User.Domain.Exceptions; using Do_Svyazi.User.Domain.Users; using MediatR; +using Microsoft.AspNetCore.Identity; namespace Do_Svyazi.User.Application.CQRS.Users.Handlers; public class UsersCommandHandler : - IQueryHandler, - IQueryHandler, - IQueryHandler, - IQueryHandler, - IQueryHandler + IQueryHandler, + IQueryHandler, + IQueryHandler, + IQueryHandler { - private readonly IDbContext _context; - public UsersCommandHandler(IDbContext context) => _context = context; + private readonly UserManager _userManager; + public UsersCommandHandler(UserManager userManager) => _userManager = userManager; - public async Task Handle(AddUser request, CancellationToken cancellationToken) + public async Task Handle(ChangeUserDescriptionByIdCommand request, CancellationToken cancellationToken) { - if (NickNameExists(request.nickName)) - { - throw new Do_Svyazi_User_BusinessLogicException( - $"User with nickname = {request.nickName} already exists in messenger"); - } - - MessengerUser messengerUser = new (request.name, request.nickName, request.description); - - await _context.Users.AddAsync(messengerUser, cancellationToken); - await _context.SaveChangesAsync(cancellationToken); - - return messengerUser.Id; - } - - public async Task Handle(ChangeUserDescriptionById request, CancellationToken cancellationToken) - { - MessengerUser messengerUser = await _context.Users.FindAsync(request.userId) ?? + MessengerUser messengerUser = await _userManager.FindByIdAsync($"{request.userId}") ?? throw new Do_Svyazi_User_NotFoundException( $"User with id {request.userId} to change description was not found"); messengerUser.ChangeDescription(request.description); - _context.Users.Update(messengerUser); - await _context.SaveChangesAsync(cancellationToken); + await _userManager.UpdateAsync(messengerUser); return Unit.Value; } - public async Task Handle(ChangeUserNameById request, CancellationToken cancellationToken) + public async Task Handle(ChangeUserNameByIdCommand request, CancellationToken cancellationToken) { - MessengerUser messengerUser = await _context.Users.FindAsync(request.userId) ?? + var messengerUser = await _userManager.FindByIdAsync($"{request.userId}") ?? throw new Do_Svyazi_User_NotFoundException($"User with id {request.userId} to change name was not found"); messengerUser.ChangeName(request.name); - _context.Users.Update(messengerUser); - await _context.SaveChangesAsync(cancellationToken); + await _userManager.UpdateAsync(messengerUser); return Unit.Value; } - public async Task Handle(SetUserNickNameById request, CancellationToken cancellationToken) + public async Task Handle(SetUserNickNameByIdCommand request, CancellationToken cancellationToken) { - MessengerUser messengerUser = await _context.Users.FindAsync(request.userId) ?? + var messengerUser = await _userManager.FindByIdAsync($"{request.userId}") ?? throw new Do_Svyazi_User_NotFoundException( - $"User with id {request.userId} to change nickName was not found"); - - if (NickNameExists(request.nickName)) - throw new Do_Svyazi_User_BusinessLogicException($"Nickname = {request.nickName} already exists in messenger"); + $"User with id {request.userId} to change userName was not found"); - messengerUser.ChangeNickName(request.nickName); + if (IsNickNameExist(request.userName)) + throw new Do_Svyazi_User_BusinessLogicException($"Nickname = {request.userName} already exists in messenger"); - _context.Users.Update(messengerUser); - await _context.SaveChangesAsync(cancellationToken); + await _userManager.SetUserNameAsync(messengerUser, request.userName); return Unit.Value; } - public async Task Handle(DeleteUser request, CancellationToken cancellationToken) + public async Task Handle(DeleteUserCommand request, CancellationToken cancellationToken) { - MessengerUser messengerUser = await _context.Users.FindAsync(request.userId) ?? + var messengerUser = await _userManager.FindByIdAsync($"{request.userId}") ?? throw new Do_Svyazi_User_NotFoundException($"Can't find user with id = {request.userId} to delete"); - _context.Users.Remove(messengerUser); - await _context.SaveChangesAsync(cancellationToken); + await _userManager.DeleteAsync(messengerUser); return Unit.Value; } - private bool NickNameExists(string nickName) => _context.Users.Any(user => user.NickName == nickName); + private bool IsNickNameExist(string nickName) => _userManager.FindByNameAsync(nickName) is null; } \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersQueryHandler.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersQueryHandler.cs index 2e24e06..8520f46 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersQueryHandler.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Handlers/UsersQueryHandler.cs @@ -7,26 +7,29 @@ using Do_Svyazi.User.Domain.Users; using Do_Svyazi.User.Dtos.Chats; using Do_Svyazi.User.Dtos.Users; +using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace Do_Svyazi.User.Application.CQRS.Users.Handlers; public class UsersQueryHandler : - IQueryHandler>, - IQueryHandler>, - IQueryHandler, - IQueryHandler> + IQueryHandler>, + IQueryHandler>, + IQueryHandler, + IQueryHandler> { + private readonly UserManager _userManager; private readonly IDbContext _context; private readonly IMapper _mapper; - public UsersQueryHandler(IDbContext context, IMapper mapper) + public UsersQueryHandler(UserManager userManager, IDbContext context, IMapper mapper) { + _userManager = userManager; _context = context; _mapper = mapper; } - public async Task> Handle(GetAllChatsByUserId request, CancellationToken cancellationToken) + public async Task> Handle(GetAllChatsByUserIdQuery request, CancellationToken cancellationToken) => await _context.ChatUsers .Include(user => user.Chat) .Where(user => user.MessengerUserId == request.userId) @@ -34,19 +37,22 @@ public async Task> Handle(GetAllChatsByUserId re .ProjectTo(_mapper.ConfigurationProvider) .ToListAsync(cancellationToken); - public async Task> Handle(GetAllChatsIdsByUserId request, CancellationToken cancellationToken) + public async Task> Handle(GetAllChatsIdsByUserIdQuery request, CancellationToken cancellationToken) => await _context.ChatUsers .Where(user => user.MessengerUserId == request.userId) .Select(chatUser => chatUser.ChatId) .ToListAsync(cancellationToken); - public async Task Handle(GetUser request, CancellationToken cancellationToken) - => await _context.Users - .SingleOrDefaultAsync(user => user.Id == request.userId, cancellationToken: cancellationToken) ?? - throw new Do_Svyazi_User_NotFoundException($"User with id = {request.userId} doesn't exist"); + public async Task Handle(GetUserQuery request, CancellationToken cancellationToken) + { + var user = await _userManager.FindByIdAsync($"{request.userId}") + ?? throw new Do_Svyazi_User_NotFoundException($"User with id = {request.userId} doesn't exist"); + + return _mapper.Map(user); + } - public async Task> Handle(GetUsers request, CancellationToken cancellationToken) - => await _context.Users + public async Task> Handle(GetUsersQuery request, CancellationToken cancellationToken) + => await _userManager.Users .ProjectTo(_mapper.ConfigurationProvider) .ToListAsync(cancellationToken: cancellationToken); } \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsByUserId.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsByUserIdQuery.cs similarity index 74% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsByUserId.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsByUserIdQuery.cs index 7da9958..969b95a 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsByUserId.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsByUserIdQuery.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Queries; -public record GetAllChatsByUserId(Guid userId) +public record GetAllChatsByUserIdQuery(Guid userId) : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsIdsByUserId.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsIdsByUserIdQuery.cs similarity index 66% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsIdsByUserId.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsIdsByUserIdQuery.cs index ea991e0..46dc476 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsIdsByUserId.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetAllChatsIdsByUserIdQuery.cs @@ -2,5 +2,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Queries; -public record GetAllChatsIdsByUserId(Guid userId) +public record GetAllChatsIdsByUserIdQuery(Guid userId) : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUser.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUser.cs deleted file mode 100644 index c4dc1ca..0000000 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUser.cs +++ /dev/null @@ -1,7 +0,0 @@ -using Do_Svyazi.User.Domain.Users; -using MediatR; - -namespace Do_Svyazi.User.Application.CQRS.Users.Queries; - -public record GetUser(Guid userId) - : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUserQuery.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUserQuery.cs new file mode 100644 index 0000000..cb1af4a --- /dev/null +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUserQuery.cs @@ -0,0 +1,7 @@ +using Do_Svyazi.User.Dtos.Users; +using MediatR; + +namespace Do_Svyazi.User.Application.CQRS.Users.Queries; + +public record GetUserQuery(Guid userId) + : IRequest; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUsers.cs b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUsersQuery.cs similarity index 85% rename from Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUsers.cs rename to Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUsersQuery.cs index 4c2eaf3..cf2688d 100644 --- a/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUsers.cs +++ b/Source/Application/Do-Svyazi.User.Application/CQRS/Users/Queries/GetUsersQuery.cs @@ -3,5 +3,5 @@ namespace Do_Svyazi.User.Application.CQRS.Users.Queries; -public record GetUsers +public record GetUsersQuery : IRequest>; \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Application/DbContexts/IDbContext.cs b/Source/Application/Do-Svyazi.User.Application/DbContexts/IDbContext.cs index 7d4ca41..5d80fc9 100644 --- a/Source/Application/Do-Svyazi.User.Application/DbContexts/IDbContext.cs +++ b/Source/Application/Do-Svyazi.User.Application/DbContexts/IDbContext.cs @@ -8,7 +8,6 @@ namespace Do_Svyazi.User.Application.DbContexts; public interface IDbContext { public DbSet Chats { get; init; } - public DbSet Users { get; init; } public DbSet ChatUsers { get; init; } public DbSet Roles { get; init; } Task SaveChangesAsync(CancellationToken cancellationToken); diff --git a/Source/Application/Do-Svyazi.User.Application/Do-Svyazi.User.Application.csproj b/Source/Application/Do-Svyazi.User.Application/Do-Svyazi.User.Application.csproj index cf78f83..7cf4e60 100644 --- a/Source/Application/Do-Svyazi.User.Application/Do-Svyazi.User.Application.csproj +++ b/Source/Application/Do-Svyazi.User.Application/Do-Svyazi.User.Application.csproj @@ -6,6 +6,7 @@ enable True enable + true diff --git a/Source/Application/Do-Svyazi.User.Dtos/Mapping/MappingProfile.cs b/Source/Application/Do-Svyazi.User.Dtos/Mapping/MappingProfile.cs index 73e995c..5f53b2d 100644 --- a/Source/Application/Do-Svyazi.User.Dtos/Mapping/MappingProfile.cs +++ b/Source/Application/Do-Svyazi.User.Dtos/Mapping/MappingProfile.cs @@ -20,6 +20,7 @@ public MappingProfile() .Select(user => user.MessengerUserId))); CreateMap(); + CreateMap(); CreateMap(); } } \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Dtos/Users/ChatUserDto.cs b/Source/Application/Do-Svyazi.User.Dtos/Users/ChatUserDto.cs new file mode 100644 index 0000000..4e0aab8 --- /dev/null +++ b/Source/Application/Do-Svyazi.User.Dtos/Users/ChatUserDto.cs @@ -0,0 +1,10 @@ +using Do_Svyazi.User.Dtos.Roles; + +namespace Do_Svyazi.User.Dtos.Users; + +public record ChatUserDto +{ + public string ChatUserName { get; init; } + public Guid MessengerUserId { get; init; } + public RoleDto Role { get; init; } +} \ No newline at end of file diff --git a/Source/Application/Do-Svyazi.User.Dtos/Users/MessengerUserDto.cs b/Source/Application/Do-Svyazi.User.Dtos/Users/MessengerUserDto.cs index f020df6..fc27df2 100644 --- a/Source/Application/Do-Svyazi.User.Dtos/Users/MessengerUserDto.cs +++ b/Source/Application/Do-Svyazi.User.Dtos/Users/MessengerUserDto.cs @@ -4,6 +4,6 @@ public record MessengerUserDto { public Guid Id { get; init; } public string? Name { get; init; } - public string? NickName { get; init; } + public string? UserName { get; init; } public string? Description { get; init; } } \ No newline at end of file diff --git a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/LoginModel.cs b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/LoginModel.cs index b73ceb9..59ea5f5 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/LoginModel.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/LoginModel.cs @@ -2,21 +2,13 @@ namespace Do_Svyazi.User.Domain.Authenticate; -public class LoginModel +public record LoginModel { - public Guid Id { get; protected init; } = Guid.NewGuid(); - - [Required(ErrorMessage = "NickName is required")] - public string NickName { get; set; } + public string? UserName { get; init; } + public string? Email { get; init; } [Required(ErrorMessage = "Password is required")] - public string? Password { get; set; } - - public override int GetHashCode() => HashCode.Combine(Id, NickName); - public override bool Equals(object? obj) => Equals(obj as LoginModel); + public string? Password { get; init; } - private bool Equals(LoginModel? login) => - login is not null && - Id.Equals(login.Id) && - NickName.Equals(login.NickName); + public override int GetHashCode() => HashCode.Combine(UserName, Email); } \ No newline at end of file diff --git a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityRole.cs b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityRole.cs index dec0468..4103c51 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityRole.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityRole.cs @@ -4,13 +4,23 @@ namespace Do_Svyazi.User.Domain.Authenticate; public class MessageIdentityRole : IdentityRole { - public const string Admin = "Admin"; - public const string User = "User"; + public const string Admin = nameof(Admin); + public const string ChatCreator = nameof(ChatCreator); + public const string ChatAdmin = nameof(ChatAdmin); + public const string User = nameof(User); public MessageIdentityRole(string roleName) : base(roleName) { } + public MessageIdentityRole(string roleName, Guid chatId) + : base(roleName) + { + ChatId = chatId; + } + protected MessageIdentityRole() { } + + public Guid ChatId { get; set; } } \ No newline at end of file diff --git a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityUser.cs b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityUser.cs index dcdd7d9..0239f07 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityUser.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/MessageIdentityUser.cs @@ -1,5 +1,5 @@ -using Microsoft.AspNetCore.Identity; - -namespace Do_Svyazi.User.Domain.Authenticate; - -public class MessageIdentityUser : IdentityUser { } \ No newline at end of file +// using Microsoft.AspNetCore.Identity; +// +// namespace Do_Svyazi.User.Domain.Authenticate; +// +// public class MessageIdentityUser : IdentityUser { } \ No newline at end of file diff --git a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/RegisterModel.cs b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/RegisterModel.cs index 80859d1..001a963 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Authenticate/RegisterModel.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Authenticate/RegisterModel.cs @@ -4,15 +4,16 @@ namespace Do_Svyazi.User.Domain.Authenticate; public record RegisterModel { - [Required(ErrorMessage = "Name is required")] + [Required(ErrorMessage = "UserName is required")] + public string UserName { get; init; } + public string Name { get; init; } - [Required(ErrorMessage = "NickName is required")] - public string NickName { get; init; } [Required(ErrorMessage = "Email is required")] - public string? Email { get; set; } + public string Email { get; init; } [Required(ErrorMessage = "Password is required")] - public string? Password { get; set; } + public string Password { get; init; } + public string PhoneNumber { get; init; } } \ No newline at end of file diff --git a/Source/Domain/Do-Svyazi.User.Domain/Chats/Channel.cs b/Source/Domain/Do-Svyazi.User.Domain/Chats/Channel.cs index 30db63f..171d209 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Chats/Channel.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Chats/Channel.cs @@ -143,9 +143,9 @@ public override void ChangeUserRole(MessengerUser user, Role role) throw new ArgumentNullException(nameof(user), $"User to change role in chat {Name} is null"); if (role is null) - throw new ArgumentNullException(nameof(role), $"Role to change in user {user.NickName} in chat {Name} is null"); + throw new ArgumentNullException(nameof(role), $"Role to change in user {user.UserName} in chat {Name} is null"); - ChatUser chatUser = GetUser(user.NickName); + ChatUser chatUser = GetUser(user.Id); chatUser.ChangeRole(role); } diff --git a/Source/Domain/Do-Svyazi.User.Domain/Chats/Chat.cs b/Source/Domain/Do-Svyazi.User.Domain/Chats/Chat.cs index 09a5786..2176504 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Chats/Chat.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Chats/Chat.cs @@ -49,10 +49,6 @@ public virtual void ChangeDescription(string description) public IReadOnlyCollection GetUsersByRole(Role role) => Users.Where(user => user.Role.Equals(role)).ToList(); - public ChatUser GetUser(string nickName) => - Users.SingleOrDefault(user => user.User.NickName == nickName) - ?? throw new Do_Svyazi_User_NotFoundException($"User is not found in chat {Name}"); - public ChatUser GetUser(Guid id) => Users.SingleOrDefault(user => user.MessengerUserId == id) ?? throw new Do_Svyazi_User_NotFoundException($"User is not found in chat {Name}"); diff --git a/Source/Domain/Do-Svyazi.User.Domain/Chats/GroupChat.cs b/Source/Domain/Do-Svyazi.User.Domain/Chats/GroupChat.cs index 73245c1..580a1ab 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Chats/GroupChat.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Chats/GroupChat.cs @@ -150,7 +150,7 @@ public override void ChangeUserRole(MessengerUser user, Role role) if (role is null) throw new ArgumentNullException(nameof(role), $"Role to set to user {user.Name} in chat {Name} is null"); - ChatUser chatUser = GetUser(user.NickName); + ChatUser chatUser = GetUser(user.Id); chatUser.ChangeRole(role); } diff --git a/Source/Domain/Do-Svyazi.User.Domain/Chats/PersonalChat.cs b/Source/Domain/Do-Svyazi.User.Domain/Chats/PersonalChat.cs index 1772df7..3e97a9f 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Chats/PersonalChat.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Chats/PersonalChat.cs @@ -52,7 +52,7 @@ public PersonalChat(MessengerUser firstMessengerUser, MessengerUser secondMessen BaseAdminRole = _baseAdminRole; BaseUserRole = _baseUserRole; - ChatUser firstUser = CreateChatUser(secondMessengerUser, _baseAdminRole); + ChatUser firstUser = CreateChatUser(firstMessengerUser, _baseAdminRole); ChatUser secondUser = CreateChatUser(secondMessengerUser, _baseAdminRole); Users.AddRange(new[] { firstUser, secondUser }); diff --git a/Source/Domain/Do-Svyazi.User.Domain/Users/ChatUser.cs b/Source/Domain/Do-Svyazi.User.Domain/Users/ChatUser.cs index 2385945..1a48f48 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Users/ChatUser.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Users/ChatUser.cs @@ -7,32 +7,31 @@ public class ChatUser { public ChatUser(MessengerUser user, Chat chat, Role role) { - User = user ?? throw new ArgumentNullException(nameof(user), $"User to create chatUser in chat {chat.Name} is null"); - Chat = chat ?? throw new ArgumentNullException(nameof(chat), $"Chat to create chatUser to {user.NickName} is null"); - Role = role ?? throw new ArgumentNullException(nameof(role), $"Role to create chatUser to {user.NickName} is null"); + Chat = chat ?? throw new ArgumentNullException(nameof(chat), $"Chat to create chatUser with name {user.UserName} is null"); + Role = role ?? throw new ArgumentNullException(nameof(role), $"Role to create chatUser with userName {user.UserName} and {role} is null"); ChatId = chat.Id; MessengerUserId = user.Id; + ChatUserName = user.UserName; } public ChatUser() { } - public MessengerUser User { get; init; } public Guid Id { get; init; } = Guid.NewGuid(); + public string ChatUserName { get; init; } public Guid MessengerUserId { get; init; } public Chat Chat { get; init; } public Guid ChatId { get; init; } public Role Role { get; private set; } public void ChangeRole(Role role) => - Role = role ?? throw new ArgumentNullException(nameof(role), $"Role to set to {User.NickName} in chat {Chat.Name} is null"); + Role = role ?? throw new ArgumentNullException(nameof(role), $"Role to set in chat {Chat.Name} is null"); public override bool Equals(object? obj) => Equals(obj as ChatUser); - public override int GetHashCode() => HashCode.Combine(Chat, User); + public override int GetHashCode() => HashCode.Combine(ChatId, MessengerUserId); private bool Equals(ChatUser? chatUser) => chatUser is not null && - User.Id.Equals(chatUser.User.Id) && Chat.Id.Equals(chatUser.Chat.Id) && MessengerUserId.Equals(chatUser.MessengerUserId); } \ No newline at end of file diff --git a/Source/Domain/Do-Svyazi.User.Domain/Users/MessengerUser.cs b/Source/Domain/Do-Svyazi.User.Domain/Users/MessengerUser.cs index 054ea35..ecebb8b 100644 --- a/Source/Domain/Do-Svyazi.User.Domain/Users/MessengerUser.cs +++ b/Source/Domain/Do-Svyazi.User.Domain/Users/MessengerUser.cs @@ -1,36 +1,31 @@ +using Microsoft.AspNetCore.Identity; + namespace Do_Svyazi.User.Domain.Users; -public class MessengerUser +public class MessengerUser : IdentityUser { private const string DefaultDescription = "No description"; - public MessengerUser(string name, string nickName, string? description = null) + public MessengerUser(string name, string nickName, string? email, string? phoneNumber, string? description = null) + : base(nickName) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name), "User name can't be null"); if (string.IsNullOrWhiteSpace(nickName)) - throw new ArgumentNullException(nameof(nickName), "User nickName can't be null"); + throw new ArgumentNullException(nameof(nickName), "User userName can't be null"); + Id = Guid.NewGuid(); + Email = email; + PhoneNumber = phoneNumber; Name = name; - NickName = nickName; Description = string.IsNullOrEmpty(description) ? DefaultDescription : description; } public MessengerUser() { } - public Guid Id { get; protected init; } = Guid.NewGuid(); public string Name { get; private set; } - public string NickName { get; private set; } public string Description { get; private set; } - public virtual void ChangeNickName(string nickName) - { - if (string.IsNullOrWhiteSpace(nickName)) - throw new ArgumentNullException(nameof(nickName), "User nickName to change is null"); - - NickName = nickName; - } - public virtual void ChangeName(string name) { if (string.IsNullOrWhiteSpace(name)) diff --git a/Source/Infrastructure/Do-Svyazi.User.DataAccess/ApplicationDbContext.cs b/Source/Infrastructure/Do-Svyazi.User.DataAccess/ApplicationDbContext.cs index c50328d..8442997 100644 --- a/Source/Infrastructure/Do-Svyazi.User.DataAccess/ApplicationDbContext.cs +++ b/Source/Infrastructure/Do-Svyazi.User.DataAccess/ApplicationDbContext.cs @@ -1,20 +1,15 @@ using Do_Svyazi.User.Domain.Authenticate; +using Do_Svyazi.User.Domain.Users; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; -namespace Do_Svyazi.User.DataAccess +namespace Do_Svyazi.User.DataAccess; + +public class ApplicationDbContext : IdentityDbContext { - public class ApplicationDbContext : IdentityDbContext + public ApplicationDbContext(DbContextOptions options) + : base(options) { - public ApplicationDbContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } - - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - } + Database.EnsureCreated(); } } \ No newline at end of file diff --git a/Source/Infrastructure/Do-Svyazi.User.DataAccess/DoSvaziDbContext.cs b/Source/Infrastructure/Do-Svyazi.User.DataAccess/DoSvaziDbContext.cs index aa6ebd6..04a4bd6 100644 --- a/Source/Infrastructure/Do-Svyazi.User.DataAccess/DoSvaziDbContext.cs +++ b/Source/Infrastructure/Do-Svyazi.User.DataAccess/DoSvaziDbContext.cs @@ -17,7 +17,6 @@ public DoSvaziDbContext(DbContextOptions options) protected DoSvaziDbContext() { } public virtual DbSet Chats { get; init; } - public virtual DbSet Users { get; init; } public virtual DbSet ChatUsers { get; init; } public virtual DbSet Roles { get; init; } diff --git a/Source/Infrastructure/Do-Svyazi.User.Web.Api/Do-Svyazi.User.Web.Api.csproj b/Source/Infrastructure/Do-Svyazi.User.Web.Api/Do-Svyazi.User.Web.Api.csproj index 4d2f79f..aa25df4 100644 --- a/Source/Infrastructure/Do-Svyazi.User.Web.Api/Do-Svyazi.User.Web.Api.csproj +++ b/Source/Infrastructure/Do-Svyazi.User.Web.Api/Do-Svyazi.User.Web.Api.csproj @@ -49,4 +49,8 @@ + + + + diff --git a/Source/Infrastructure/Do-Svyazi.User.Web.Api/Extensions/ServiceCollectionExtensions.cs b/Source/Infrastructure/Do-Svyazi.User.Web.Api/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..bbd209a --- /dev/null +++ b/Source/Infrastructure/Do-Svyazi.User.Web.Api/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,121 @@ +using System.Text; +using Do_Svyazi.User.Application.DbContexts; +using Do_Svyazi.User.DataAccess; +using Do_Svyazi.User.Domain.Authenticate; +using Do_Svyazi.User.Domain.Users; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi.Models; + +namespace Do_Svyazi.User.Web.Api.Extensions; + +public static class ServiceCollectionExtensions +{ + public static IServiceCollection AddAuthServices(this IServiceCollection services, IConfiguration configuration) + { + services.AddIdentity(options => + { + options.Password = new PasswordOptions + { + RequireDigit = true, + RequireNonAlphanumeric = false, + RequireUppercase = true, + RequireLowercase = true, + RequiredLength = 6, + }; + + options.User = new UserOptions + { + RequireUniqueEmail = true, + }; + }) + .AddEntityFrameworkStores() + .AddDefaultTokenProviders(); + + services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; + }).AddJwtBearer(options => + { + options.SaveToken = true; + options.RequireHttpsMetadata = false; + options.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuer = true, + ValidateAudience = false, + ValidAudience = configuration["JWT:ValidAudience"], + ValidIssuer = configuration["JWT:ValidIssuer"], + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"])), + }; + }); + + services.AddAuthorization(); + + return services; + } + + public static IServiceCollection AddDomainServices(this IServiceCollection services, IConfiguration configuration) + { + services.AddDbContext(optionsBuilder => + { + optionsBuilder.EnableSensitiveDataLogging(); + optionsBuilder.UseSqlite(configuration.GetConnectionString("Database")); + }); + + services.AddDbContext(options => + { + options.EnableSensitiveDataLogging(); + options.UseSqlite(configuration.GetConnectionString("Identity")); + }); + + return services; + } + + public static IServiceCollection AddSwaggerServices(this IServiceCollection services) + { + services.AddSwaggerGen(opt => + { + opt.UseInlineDefinitionsForEnums(); + + opt.SwaggerDoc("v2.1.0", new OpenApiInfo + { + Title = "Do-Svyazi User module", + Version = "v2.1.0", + Description = "Do Svyazi User API", + }); + + var securityScheme = new OpenApiSecurityScheme + { + Description = "JWT Authorization header using the bearer scheme", + Name = "JWT Authentication", + In = ParameterLocation.Header, + Type = SecuritySchemeType.Http, + Scheme = "Bearer", + BearerFormat = "JWT", + Reference = new OpenApiReference + { + Id = JwtBearerDefaults.AuthenticationScheme, + Type = ReferenceType.SecurityScheme, + }, + }; + + opt.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme); + + opt.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + securityScheme, + new List() + }, + }); + }); + + return services; + } +} \ No newline at end of file diff --git a/Source/Infrastructure/Do-Svyazi.User.Web.Api/Startup.cs b/Source/Infrastructure/Do-Svyazi.User.Web.Api/Startup.cs index e9b6de0..7c06ef1 100644 --- a/Source/Infrastructure/Do-Svyazi.User.Web.Api/Startup.cs +++ b/Source/Infrastructure/Do-Svyazi.User.Web.Api/Startup.cs @@ -1,20 +1,14 @@ -using System.Text; using Do_Svyazi.User.Application.CQRS.Users.Queries; -using Do_Svyazi.User.Application.DbContexts; -using Do_Svyazi.User.DataAccess; -using Do_Svyazi.User.Domain.Authenticate; using Do_Svyazi.User.Dtos.Mapping; +using Do_Svyazi.User.Web.Api.Extensions; +using Do_Svyazi.User.Web.Controllers.Middlewares; using Do_Svyazi.User.Web.Controllers.Tools; using MediatR; -using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Microsoft.IdentityModel.Tokens; namespace Do_Svyazi.User.Web.Api; @@ -26,78 +20,39 @@ public class Startup public void ConfigureServices(IServiceCollection services) { - services.AddControllers() + services + .AddControllers() .AddDo_SvyaziControllers() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); - services.AddDbContext(optionsBuilder => - { - optionsBuilder.EnableSensitiveDataLogging(); - optionsBuilder.UseSqlite(Configuration.GetConnectionString("Database")); - }); + services + .AddDomainServices(Configuration) + .AddAuthServices(Configuration) + .AddSwaggerServices() + .AddEndpointsApiExplorer(); - services.AddDbContext(options => - { - options.EnableSensitiveDataLogging(); - options.UseSqlite(Configuration.GetConnectionString("Identity")); - }); - - services.AddIdentity() - .AddEntityFrameworkStores() - .AddDefaultTokenProviders(); - - services.AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - }).AddJwtBearer(options => - { - options.SaveToken = true; - options.RequireHttpsMetadata = false; - options.TokenValidationParameters = new TokenValidationParameters() - { - ValidateIssuer = true, - ValidateAudience = true, - ValidAudience = Configuration["JWT:ValidAudience"], - ValidIssuer = Configuration["JWT:ValidIssuer"], - IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])), - }; - }); - - services.AddEndpointsApiExplorer(); - services.AddSwaggerDocument(settings => - { - settings.Title = "Do-Svyazi.User"; - settings.PostProcess = document => - { - document.Info.Version = "v1"; - document.Info.Title = "Do-Svyazi.User"; - document.Info.Description = "Do-Svyazi.User module"; - }; - }); - - services.AddMediatR(typeof(GetUsers).Assembly); + services.AddMediatR(typeof(GetUsersQuery).Assembly); services.AddAutoMapper(typeof(MappingProfile).Assembly); } + [Obsolete("Obsolete")] public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); - app.UseOpenApi(); - app.UseSwaggerUi3(c => - { - c.DocumentTitle = "Do-Svyazi.User"; - c.DocumentPath = "/swagger/v1/swagger.json"; - }); + app.UseSwagger(settings => { settings.RouteTemplate = "/swagger/{documentName}/swagger.json"; }); + app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/v2.1.0/swagger.json", "Do-Svyazi User API")); app.UseHttpsRedirection(); + + app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); - app.UseRouting(); + + app.UseMiddleware(); + app.UseMiddleware(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Client.cs b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Client.cs index 92af68b..0e01add 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Client.cs +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Client.cs @@ -4,6 +4,9 @@ // //---------------------- +#nullable enable + +using Do_Svyazi.User.Web.ApiClient.Backend; using Do_Svyazi.User.Web.ApiClient.Contracts; #pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." @@ -20,7 +23,7 @@ namespace Do_Svyazi.User.Web.ApiClient using System = global::System; [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - internal partial class AuthenticateClient : IAuthenticateClient + public partial class AuthenticateClient : Do_SvyaziClientBase, IAuthenticateClient { private string _baseUrl = ""; private System.Net.Http.HttpClient _httpClient; @@ -54,33 +57,108 @@ public string BaseUrl partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual System.Threading.Tasks.Task LoginAsync(Login model) + public virtual async System.Threading.Tasks.Task> GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - return LoginAsync(model, System.Threading.CancellationToken.None); + var urlBuilder_ = new System.Text.StringBuilder(); + urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/GetAll"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) + { + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task LoginAsync(Login model, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task LoginAsync(LoginRequest model, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (model == null) throw new System.ArgumentNullException("model"); var urlBuilder_ = new System.Text.StringBuilder(); - urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/login"); + urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/Login"); var client_ = _httpClient; var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); @@ -103,12 +181,25 @@ public virtual async System.Threading.Tasks.Task LoginAsync(Login ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; - if (status_ == 200 || status_ == 206) + if (status_ == 200) + { + return; + } + else + if (status_ == 401) { - var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); - var fileResponse_ = new FileResponse(status_, headers_, responseStream_, null, response_); - disposeClient_ = false; disposeResponse_ = false; // response and client are disposed by FileResponse - return fileResponse_; + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); } else { @@ -130,33 +221,26 @@ public virtual async System.Threading.Tasks.Task LoginAsync(Login } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task RegisterAsync(Register model) - { - return RegisterAsync(model, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task RegisterAsync(Register model, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task RegisterAsync(RegisterCommand model, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (model == null) throw new System.ArgumentNullException("model"); var urlBuilder_ = new System.Text.StringBuilder(); - urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/register"); + urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/Register"); var client_ = _httpClient; var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); @@ -179,12 +263,30 @@ public virtual async System.Threading.Tasks.Task RegisterAsync(Reg ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; - if (status_ == 200 || status_ == 206) + if (status_ == 200) { - var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); - var fileResponse_ = new FileResponse(status_, headers_, responseStream_, null, response_); - disposeClient_ = false; disposeResponse_ = false; // response and client are disposed by FileResponse - return fileResponse_; + return; + } + else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; } else { @@ -206,33 +308,112 @@ public virtual async System.Threading.Tasks.Task RegisterAsync(Reg } } + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual System.Threading.Tasks.Task RegisterAdminAsync(RegisterAdmin model) + public virtual async System.Threading.Tasks.Task AuthenticateByJwtAsync(string? jwtToken, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - return RegisterAdminAsync(model, System.Threading.CancellationToken.None); + var urlBuilder_ = new System.Text.StringBuilder(); + urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/AuthenticateByJwt"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) + { + + if (jwtToken == null) + throw new System.ArgumentNullException("jwtToken"); + request_.Headers.TryAddWithoutValidation("jwtToken", ConvertToString(jwtToken, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task RegisterAdminAsync(RegisterAdmin model, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task RegisterAdminAsync(RegisterAdminCommand model, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (model == null) throw new System.ArgumentNullException("model"); var urlBuilder_ = new System.Text.StringBuilder(); - urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/register-admin"); + urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Authenticate/RegisterAdmin"); var client_ = _httpClient; var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); @@ -255,12 +436,30 @@ public virtual async System.Threading.Tasks.Task RegisterAdminAsyn ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; - if (status_ == 200 || status_ == 206) + if (status_ == 200) + { + return; + } + else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) { - var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); - var fileResponse_ = new FileResponse(status_, headers_, responseStream_, null, response_); - disposeClient_ = false; disposeResponse_ = false; // response and client are disposed by FileResponse - return fileResponse_; + return; } else { @@ -301,7 +500,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { if (response == null || response.Content == null) { - return new ObjectResponseResult(default(T), string.Empty); + return new ObjectResponseResult(default(T)!, string.Empty); } if (ReadResponseAsString) @@ -310,7 +509,7 @@ protected virtual async System.Threading.Tasks.Task> Rea try { var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); + return new ObjectResponseResult(typedBody!, responseText); } catch (Newtonsoft.Json.JsonException exception) { @@ -328,7 +527,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); + return new ObjectResponseResult(typedBody!, string.Empty); } } catch (Newtonsoft.Json.JsonException exception) @@ -339,7 +538,7 @@ protected virtual async System.Threading.Tasks.Task> Rea } } - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + private string ConvertToString(object? value, System.Globalization.CultureInfo cultureInfo) { if (value == null) { @@ -386,7 +585,7 @@ private string ConvertToString(object value, System.Globalization.CultureInfo cu } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - internal partial class ChatClient : IChatClient + public partial class ChatClient : Do_SvyaziClientBase, IChatClient { private string _baseUrl = ""; private System.Net.Http.HttpClient _httpClient; @@ -420,15 +619,9 @@ public string BaseUrl partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetChatsAsync() - { - return GetChatsAsync(System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetChatsAsync(System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task> GetChatsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Chat/GetChats"); @@ -437,7 +630,7 @@ public string BaseUrl var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -465,7 +658,7 @@ public string BaseUrl var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); @@ -473,6 +666,22 @@ public string BaseUrl return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -492,15 +701,9 @@ public string BaseUrl } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetChatByIdAsync(System.Guid chatId) - { - return GetChatByIdAsync(chatId, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetChatByIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task GetChatByIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (chatId == null) throw new System.ArgumentNullException("chatId"); @@ -514,7 +717,7 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -550,6 +753,22 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -569,15 +788,9 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetUserIdsByChatIdAsync(System.Guid chatId) - { - return GetUserIdsByChatIdAsync(chatId, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetUserIdsByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task> GetUserIdsByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (chatId == null) throw new System.ArgumentNullException("chatId"); @@ -591,7 +804,7 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -619,7 +832,7 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); @@ -627,6 +840,22 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -646,15 +875,9 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetUsersByChatIdAsync(System.Guid chatId) - { - return GetUsersByChatIdAsync(chatId, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetUsersByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task> GetUsersByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (chatId == null) throw new System.ArgumentNullException("chatId"); @@ -668,7 +891,7 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -696,7 +919,7 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); @@ -704,6 +927,22 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -723,15 +962,9 @@ public virtual async System.Threading.Tasks.Task GetChatByIdAs } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task AddChannelAsync(AddChannel addChannelCommand) - { - return AddChannelAsync(addChannelCommand, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task AddChannelAsync(AddChannel addChannelCommand, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task AddChannelAsync(AddChannelCommand addChannelCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (addChannelCommand == null) throw new System.ArgumentNullException("addChannelCommand"); @@ -743,7 +976,7 @@ public virtual async System.Threading.Tasks.Task AddChannelAsync(AddChannel addC var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(addChannelCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); @@ -776,6 +1009,27 @@ public virtual async System.Threading.Tasks.Task AddChannelAsync(AddChannel addC return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 201) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -795,15 +1049,9 @@ public virtual async System.Threading.Tasks.Task AddChannelAsync(AddChannel addC } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChat addGroupChatCommand) - { - return AddGroupChatAsync(addGroupChatCommand, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChat addGroupChatCommand, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChatCommand addGroupChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (addGroupChatCommand == null) throw new System.ArgumentNullException("addGroupChatCommand"); @@ -815,7 +1063,7 @@ public virtual async System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChat var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(addGroupChatCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); @@ -848,6 +1096,27 @@ public virtual async System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChat return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 201) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -867,15 +1136,9 @@ public virtual async System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChat } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task AddPersonalChatAsync(AddPersonalChat addPersonalChatCommand) - { - return AddPersonalChatAsync(addPersonalChatCommand, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task AddPersonalChatAsync(AddPersonalChat addPersonalChatCommand, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task AddPersonalChatAsync(AddPersonalChatCommand addPersonalChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (addPersonalChatCommand == null) throw new System.ArgumentNullException("addPersonalChatCommand"); @@ -887,7 +1150,7 @@ public virtual async System.Threading.Tasks.Task AddPersonalChatAsync(AddPersona var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(addPersonalChatCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); @@ -920,6 +1183,27 @@ public virtual async System.Threading.Tasks.Task AddPersonalChatAsync(AddPersona return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 201) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -939,15 +1223,9 @@ public virtual async System.Threading.Tasks.Task AddPersonalChatAsync(AddPersona } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedMessages addSavedMessagesCommand) - { - return AddSavedMessagesAsync(addSavedMessagesCommand, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedMessages addSavedMessagesCommand, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedMessagesCommand addSavedMessagesCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (addSavedMessagesCommand == null) throw new System.ArgumentNullException("addSavedMessagesCommand"); @@ -959,7 +1237,7 @@ public virtual async System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedM var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(addSavedMessagesCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); @@ -992,6 +1270,27 @@ public virtual async System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedM return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 201) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1011,15 +1310,9 @@ public virtual async System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedM } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task AddUserToChatAsync(AddUserToChat addUserToChatCommand) - { - return AddUserToChatAsync(addUserToChatCommand, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task AddUserToChatAsync(AddUserToChat addUserToChatCommand, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task AddUserToChatAsync(AddUserToChatCommand addUserToChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (addUserToChatCommand == null) throw new System.ArgumentNullException("addUserToChatCommand"); @@ -1031,7 +1324,7 @@ public virtual async System.Threading.Tasks.Task AddUserToChatAsync(AddUserToCha var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(addUserToChatCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); @@ -1064,6 +1357,27 @@ public virtual async System.Threading.Tasks.Task AddUserToChatAsync(AddUserToCha return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1083,15 +1397,9 @@ public virtual async System.Threading.Tasks.Task AddUserToChatAsync(AddUserToCha } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteUserFromChat deleteUserFromChatCommand) - { - return DeleteUserFromChatAsync(deleteUserFromChatCommand, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteUserFromChat deleteUserFromChatCommand, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteUserFromChatCommand deleteUserFromChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (deleteUserFromChatCommand == null) throw new System.ArgumentNullException("deleteUserFromChatCommand"); @@ -1103,7 +1411,7 @@ public virtual async System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteU var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(deleteUserFromChatCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); @@ -1136,6 +1444,27 @@ public virtual async System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteU return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1174,7 +1503,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { if (response == null || response.Content == null) { - return new ObjectResponseResult(default(T), string.Empty); + return new ObjectResponseResult(default(T)!, string.Empty); } if (ReadResponseAsString) @@ -1183,7 +1512,7 @@ protected virtual async System.Threading.Tasks.Task> Rea try { var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); + return new ObjectResponseResult(typedBody!, responseText); } catch (Newtonsoft.Json.JsonException exception) { @@ -1201,7 +1530,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); + return new ObjectResponseResult(typedBody!, string.Empty); } } catch (Newtonsoft.Json.JsonException exception) @@ -1212,7 +1541,7 @@ protected virtual async System.Threading.Tasks.Task> Rea } } - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + private string ConvertToString(object? value, System.Globalization.CultureInfo cultureInfo) { if (value == null) { @@ -1259,7 +1588,7 @@ private string ConvertToString(object value, System.Globalization.CultureInfo cu } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - internal partial class RolesClient : IRolesClient + public partial class RolesClient : Do_SvyaziClientBase, IRolesClient { private string _baseUrl = ""; private System.Net.Http.HttpClient _httpClient; @@ -1293,15 +1622,9 @@ public string BaseUrl partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetRoleByUserIdAsync(System.Guid userId, System.Guid chatId) - { - return GetRoleByUserIdAsync(userId, chatId, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetRoleByUserIdAsync(System.Guid userId, System.Guid chatId, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task GetRoleByUserIdAsync(System.Guid userId, System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (userId == null) throw new System.ArgumentNullException("userId"); @@ -1319,7 +1642,7 @@ public virtual async System.Threading.Tasks.Task GetRoleByUserIdAsync(S var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -1355,6 +1678,22 @@ public virtual async System.Threading.Tasks.Task GetRoleByUserIdAsync(S return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1374,18 +1713,12 @@ public virtual async System.Threading.Tasks.Task GetRoleByUserIdAsync(S } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRoleForChat createRoleForChat) - { - return CreateRoleForChatAsync(createRoleForChat, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRoleForChat createRoleForChat, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRoleForChatCommand createRoleForChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - if (createRoleForChat == null) - throw new System.ArgumentNullException("createRoleForChat"); + if (createRoleForChatCommand == null) + throw new System.ArgumentNullException("createRoleForChatCommand"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Roles/CreateRoleForChat"); @@ -1394,9 +1727,9 @@ public virtual async System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRo var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { - var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(createRoleForChat, _settings.Value)); + var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(createRoleForChatCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); @@ -1427,6 +1760,27 @@ public virtual async System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRo return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1446,18 +1800,12 @@ public virtual async System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRo } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(ChangeRoleForUserById changeRoleForUserById) - { - return ChangeRoleForUserByIdAsync(changeRoleForUserById, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(ChangeRoleForUserById changeRoleForUserById, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(ChangeRoleForUserByIdCommand changeRoleForUserByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - if (changeRoleForUserById == null) - throw new System.ArgumentNullException("changeRoleForUserById"); + if (changeRoleForUserByIdCommand == null) + throw new System.ArgumentNullException("changeRoleForUserByIdCommand"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Roles/ChangeRoleForUserById"); @@ -1466,9 +1814,9 @@ public virtual async System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(Chan var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { - var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(changeRoleForUserById, _settings.Value)); + var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(changeRoleForUserByIdCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); @@ -1499,6 +1847,27 @@ public virtual async System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(Chan return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1537,7 +1906,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { if (response == null || response.Content == null) { - return new ObjectResponseResult(default(T), string.Empty); + return new ObjectResponseResult(default(T)!, string.Empty); } if (ReadResponseAsString) @@ -1546,7 +1915,7 @@ protected virtual async System.Threading.Tasks.Task> Rea try { var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); + return new ObjectResponseResult(typedBody!, responseText); } catch (Newtonsoft.Json.JsonException exception) { @@ -1564,7 +1933,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); + return new ObjectResponseResult(typedBody!, string.Empty); } } catch (Newtonsoft.Json.JsonException exception) @@ -1575,7 +1944,7 @@ protected virtual async System.Threading.Tasks.Task> Rea } } - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + private string ConvertToString(object? value, System.Globalization.CultureInfo cultureInfo) { if (value == null) { @@ -1622,7 +1991,7 @@ private string ConvertToString(object value, System.Globalization.CultureInfo cu } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - internal partial class UserClient : IUserClient + public partial class UserClient : Do_SvyaziClientBase, IUserClient { private string _baseUrl = ""; private System.Net.Http.HttpClient _httpClient; @@ -1656,15 +2025,9 @@ public string BaseUrl partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetUsersAsync() - { - return GetUsersAsync(System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetUsersAsync(System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task> GetUsersAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/User/GetAll"); @@ -1673,7 +2036,7 @@ public string BaseUrl var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -1701,7 +2064,7 @@ public string BaseUrl var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); @@ -1709,6 +2072,22 @@ public string BaseUrl return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1728,15 +2107,9 @@ public string BaseUrl } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetUserAsync(System.Guid userId) - { - return GetUserAsync(userId, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetUserAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task GetUserAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (userId == null) throw new System.ArgumentNullException("userId"); @@ -1750,7 +2123,7 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -1778,7 +2151,7 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); @@ -1786,6 +2159,22 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1805,15 +2194,9 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetAllChatsByUserIdAsync(System.Guid userId) - { - return GetAllChatsByUserIdAsync(userId, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetAllChatsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task> GetAllChatsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (userId == null) throw new System.ArgumentNullException("userId"); @@ -1827,7 +2210,7 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -1855,7 +2238,7 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); @@ -1863,6 +2246,22 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1882,15 +2281,9 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task> GetAllChatsIdsByUserIdAsync(System.Guid userId) - { - return GetAllChatsIdsByUserIdAsync(userId, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task> GetAllChatsIdsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task> GetAllChatsIdsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (userId == null) throw new System.ArgumentNullException("userId"); @@ -1904,7 +2297,7 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); @@ -1932,7 +2325,7 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); @@ -1940,6 +2333,22 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -1959,18 +2368,12 @@ public virtual async System.Threading.Tasks.Task GetUserAsync(Sys } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNickNameById setUserNickNameById) - { - return SetNickNameByIdAsync(setUserNickNameById, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNickNameById setUserNickNameById, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNickNameByIdCommand setUserNickNameByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - if (setUserNickNameById == null) - throw new System.ArgumentNullException("setUserNickNameById"); + if (setUserNickNameByIdCommand == null) + throw new System.ArgumentNullException("setUserNickNameByIdCommand"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/User/SetNickNameById"); @@ -1979,9 +2382,9 @@ public virtual async System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNic var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { - var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(setUserNickNameById, _settings.Value)); + var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(setUserNickNameByIdCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); @@ -2012,6 +2415,27 @@ public virtual async System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNic return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -2031,18 +2455,12 @@ public virtual async System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNic } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task DeleteUserAsync(DeleteUser deleteUser) - { - return DeleteUserAsync(deleteUser, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUser deleteUser, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUserCommand deleteUserCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - if (deleteUser == null) - throw new System.ArgumentNullException("deleteUser"); + if (deleteUserCommand == null) + throw new System.ArgumentNullException("deleteUserCommand"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/User/DeleteUser"); @@ -2051,9 +2469,9 @@ public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUser dele var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { - var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(deleteUser, _settings.Value)); + var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(deleteUserCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); @@ -2084,6 +2502,27 @@ public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUser dele return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -2103,18 +2542,12 @@ public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUser dele } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task AddUserAsync(AddUser addUser) - { - return AddUserAsync(addUser, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task AddUserAsync(AddUser addUser, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task AddUserAsync(AddUserCommand addUserCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - if (addUser == null) - throw new System.ArgumentNullException("addUser"); + if (addUserCommand == null) + throw new System.ArgumentNullException("addUserCommand"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/User/AddUser"); @@ -2123,9 +2556,9 @@ public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUser dele var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { - var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(addUser, _settings.Value)); + var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(addUserCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); @@ -2162,6 +2595,32 @@ public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUser dele return objectResponse_.Object; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 201) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -2181,18 +2640,12 @@ public virtual async System.Threading.Tasks.Task DeleteUserAsync(DeleteUser dele } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUserDescriptionById changeUserDescriptionById) - { - return ChangeDescriptionAsync(changeUserDescriptionById, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUserDescriptionById changeUserDescriptionById, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUserDescriptionByIdCommand changeUserDescriptionByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - if (changeUserDescriptionById == null) - throw new System.ArgumentNullException("changeUserDescriptionById"); + if (changeUserDescriptionByIdCommand == null) + throw new System.ArgumentNullException("changeUserDescriptionByIdCommand"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/User/ChangeDescription"); @@ -2201,9 +2654,9 @@ public virtual async System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUs var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { - var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(changeUserDescriptionById, _settings.Value)); + var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(changeUserDescriptionByIdCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); @@ -2234,6 +2687,27 @@ public virtual async System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUs return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -2253,18 +2727,12 @@ public virtual async System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUs } } - /// A server side error occurred. - public virtual System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameById changeUserNameById) - { - return ChangeNameAsync(changeUserNameById, System.Threading.CancellationToken.None); - } - /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - public virtual async System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameById changeUserNameById, System.Threading.CancellationToken cancellationToken) + public virtual async System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameByIdCommand changeUserNameByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { - if (changeUserNameById == null) - throw new System.ArgumentNullException("changeUserNameById"); + if (changeUserNameByIdCommand == null) + throw new System.ArgumentNullException("changeUserNameByIdCommand"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/User/ChangeName"); @@ -2273,9 +2741,9 @@ public virtual async System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameB var disposeClient_ = false; try { - using (var request_ = new System.Net.Http.HttpRequestMessage()) + using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false)) { - var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(changeUserNameById, _settings.Value)); + var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(changeUserNameByIdCommand, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); @@ -2306,6 +2774,27 @@ public virtual async System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameB return; } else + if (status_ == 401) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new Do_Svyazi_User_ApiClient_Exception("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new Do_Svyazi_User_ApiClient_Exception("A server side error occurred.", status_, responseText_, headers_, null); + } + else + if (status_ == 204) + { + return; + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Do_Svyazi_User_ApiClient_Exception("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); @@ -2344,7 +2833,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { if (response == null || response.Content == null) { - return new ObjectResponseResult(default(T), string.Empty); + return new ObjectResponseResult(default(T)!, string.Empty); } if (ReadResponseAsString) @@ -2353,7 +2842,7 @@ protected virtual async System.Threading.Tasks.Task> Rea try { var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); + return new ObjectResponseResult(typedBody!, responseText); } catch (Newtonsoft.Json.JsonException exception) { @@ -2371,7 +2860,7 @@ protected virtual async System.Threading.Tasks.Task> Rea { var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); + return new ObjectResponseResult(typedBody!, string.Empty); } } catch (Newtonsoft.Json.JsonException exception) @@ -2382,7 +2871,7 @@ protected virtual async System.Threading.Tasks.Task> Rea } } - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + private string ConvertToString(object? value, System.Globalization.CultureInfo cultureInfo) { if (value == null) { diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Contracts.cs b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Contracts.cs index db8a73c..fbd2f47 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Contracts.cs +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do-Svyazi.User.Contracts.cs @@ -4,6 +4,10 @@ // //---------------------- +#nullable enable + +using Do_Svyazi.User.Web.ApiClient.Backend; + #pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." #pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." #pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' @@ -20,203 +24,155 @@ namespace Do_Svyazi.User.Web.ApiClient.Contracts [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial interface IAuthenticateClient { - /// A server side error occurred. - System.Threading.Tasks.Task LoginAsync(Login model); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task LoginAsync(Login model, System.Threading.CancellationToken cancellationToken); + System.Threading.Tasks.Task> GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task RegisterAsync(Register model); + System.Threading.Tasks.Task LoginAsync(LoginRequest model, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task RegisterAsync(Register model, System.Threading.CancellationToken cancellationToken); + System.Threading.Tasks.Task RegisterAsync(RegisterCommand model, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task RegisterAdminAsync(RegisterAdmin model); + System.Threading.Tasks.Task AuthenticateByJwtAsync(string? jwtToken, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task RegisterAdminAsync(RegisterAdmin model, System.Threading.CancellationToken cancellationToken); + System.Threading.Tasks.Task RegisterAdminAsync(RegisterAdminCommand model, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial interface IChatClient { - /// A server side error occurred. - System.Threading.Tasks.Task> GetChatsAsync(); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task> GetChatsAsync(System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task GetChatByIdAsync(System.Guid chatId); + System.Threading.Tasks.Task> GetChatsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task GetChatByIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task> GetUserIdsByChatIdAsync(System.Guid chatId); + System.Threading.Tasks.Task GetChatByIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task> GetUserIdsByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task> GetUsersByChatIdAsync(System.Guid chatId); + System.Threading.Tasks.Task> GetUserIdsByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task> GetUsersByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task AddChannelAsync(AddChannel addChannelCommand); + System.Threading.Tasks.Task> GetUsersByChatIdAsync(System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task AddChannelAsync(AddChannel addChannelCommand, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChat addGroupChatCommand); + System.Threading.Tasks.Task AddChannelAsync(AddChannelCommand addChannelCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChat addGroupChatCommand, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task AddPersonalChatAsync(AddPersonalChat addPersonalChatCommand); + System.Threading.Tasks.Task AddGroupChatAsync(AddGroupChatCommand addGroupChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task AddPersonalChatAsync(AddPersonalChat addPersonalChatCommand, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedMessages addSavedMessagesCommand); + System.Threading.Tasks.Task AddPersonalChatAsync(AddPersonalChatCommand addPersonalChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedMessages addSavedMessagesCommand, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task AddUserToChatAsync(AddUserToChat addUserToChatCommand); + System.Threading.Tasks.Task AddSavedMessagesAsync(AddSavedMessagesCommand addSavedMessagesCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task AddUserToChatAsync(AddUserToChat addUserToChatCommand, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteUserFromChat deleteUserFromChatCommand); + System.Threading.Tasks.Task AddUserToChatAsync(AddUserToChatCommand addUserToChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteUserFromChat deleteUserFromChatCommand, System.Threading.CancellationToken cancellationToken); + System.Threading.Tasks.Task DeleteUserFromChatAsync(DeleteUserFromChatCommand deleteUserFromChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial interface IRolesClient { - /// A server side error occurred. - System.Threading.Tasks.Task GetRoleByUserIdAsync(System.Guid userId, System.Guid chatId); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task GetRoleByUserIdAsync(System.Guid userId, System.Guid chatId, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRoleForChat createRoleForChat); + System.Threading.Tasks.Task GetRoleByUserIdAsync(System.Guid userId, System.Guid chatId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRoleForChat createRoleForChat, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(ChangeRoleForUserById changeRoleForUserById); + System.Threading.Tasks.Task CreateRoleForChatAsync(CreateRoleForChatCommand createRoleForChatCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(ChangeRoleForUserById changeRoleForUserById, System.Threading.CancellationToken cancellationToken); + System.Threading.Tasks.Task ChangeRoleForUserByIdAsync(ChangeRoleForUserByIdCommand changeRoleForUserByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial interface IUserClient { - /// A server side error occurred. - System.Threading.Tasks.Task> GetUsersAsync(); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task> GetUsersAsync(System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task GetUserAsync(System.Guid userId); + System.Threading.Tasks.Task> GetUsersAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task GetUserAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task> GetAllChatsByUserIdAsync(System.Guid userId); + System.Threading.Tasks.Task GetUserAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task> GetAllChatsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task> GetAllChatsIdsByUserIdAsync(System.Guid userId); + System.Threading.Tasks.Task> GetAllChatsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task> GetAllChatsIdsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNickNameById setUserNickNameById); + System.Threading.Tasks.Task> GetAllChatsIdsByUserIdAsync(System.Guid userId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNickNameById setUserNickNameById, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task DeleteUserAsync(DeleteUser deleteUser); + System.Threading.Tasks.Task SetNickNameByIdAsync(SetUserNickNameByIdCommand setUserNickNameByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task DeleteUserAsync(DeleteUser deleteUser, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task AddUserAsync(AddUser addUser); + System.Threading.Tasks.Task DeleteUserAsync(DeleteUserCommand deleteUserCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task AddUserAsync(AddUser addUser, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUserDescriptionById changeUserDescriptionById); + System.Threading.Tasks.Task AddUserAsync(AddUserCommand addUserCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUserDescriptionById changeUserDescriptionById, System.Threading.CancellationToken cancellationToken); - - /// A server side error occurred. - System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameById changeUserNameById); + System.Threading.Tasks.Task ChangeDescriptionAsync(ChangeUserDescriptionByIdCommand changeUserDescriptionByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// A server side error occurred. - System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameById changeUserNameById, System.Threading.CancellationToken cancellationToken); + System.Threading.Tasks.Task ChangeNameAsync(ChangeUserNameByIdCommand changeUserNameByIdCommand, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Login + public partial class MessengerUser : IdentityUserOfGuid { - [Newtonsoft.Json.JsonProperty("model", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public LoginModel Model { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public MessengerUser(int @accessFailedCount, string? @concurrencyStamp, string @description, string? @email, bool @emailConfirmed, System.Guid @id, bool @lockoutEnabled, System.DateTime? @lockoutEnd, string @name, string? @normalizedEmail, string? @normalizedUserName, string? @passwordHash, string? @phoneNumber, bool @phoneNumberConfirmed, string? @securityStamp, bool @twoFactorEnabled, string? @userName) + + : base(accessFailedCount, concurrencyStamp, email, emailConfirmed, id, lockoutEnabled, lockoutEnd, normalizedEmail, normalizedUserName, passwordHash, phoneNumber, phoneNumberConfirmed, securityStamp, twoFactorEnabled, userName) + + { + + this.Name = @name; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; } + + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Description { get; } public string ToJson() { @@ -224,26 +180,98 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static Login FromJson(string data) + public static MessengerUser FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class LoginModel + public partial class IdentityUserOfGuid { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid Id { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("nickName", Required = Newtonsoft.Json.Required.Always)] - public string NickName { get; set; } + public IdentityUserOfGuid(int @accessFailedCount, string? @concurrencyStamp, string? @email, bool @emailConfirmed, System.Guid @id, bool @lockoutEnabled, System.DateTime? @lockoutEnd, string? @normalizedEmail, string? @normalizedUserName, string? @passwordHash, string? @phoneNumber, bool @phoneNumberConfirmed, string? @securityStamp, bool @twoFactorEnabled, string? @userName) - [Newtonsoft.Json.JsonProperty("password", Required = Newtonsoft.Json.Required.Always)] - public string Password { get; set; } + { + + this.Id = @id; + + this.UserName = @userName; + + this.NormalizedUserName = @normalizedUserName; + + this.Email = @email; + + this.NormalizedEmail = @normalizedEmail; + + this.EmailConfirmed = @emailConfirmed; + + this.PasswordHash = @passwordHash; + + this.SecurityStamp = @securityStamp; + + this.ConcurrencyStamp = @concurrencyStamp; + + this.PhoneNumber = @phoneNumber; + + this.PhoneNumberConfirmed = @phoneNumberConfirmed; + + this.TwoFactorEnabled = @twoFactorEnabled; + + this.LockoutEnd = @lockoutEnd; + + this.LockoutEnabled = @lockoutEnabled; + + this.AccessFailedCount = @accessFailedCount; + + } [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid Id { get; } + + [Newtonsoft.Json.JsonProperty("userName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? UserName { get; } + + [Newtonsoft.Json.JsonProperty("normalizedUserName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? NormalizedUserName { get; } + + [Newtonsoft.Json.JsonProperty("email", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Email { get; } + + [Newtonsoft.Json.JsonProperty("normalizedEmail", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? NormalizedEmail { get; } + + [Newtonsoft.Json.JsonProperty("emailConfirmed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool EmailConfirmed { get; } + + [Newtonsoft.Json.JsonProperty("passwordHash", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? PasswordHash { get; } + + [Newtonsoft.Json.JsonProperty("securityStamp", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? SecurityStamp { get; } + + [Newtonsoft.Json.JsonProperty("concurrencyStamp", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? ConcurrencyStamp { get; } + + [Newtonsoft.Json.JsonProperty("phoneNumber", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? PhoneNumber { get; } + + [Newtonsoft.Json.JsonProperty("phoneNumberConfirmed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool PhoneNumberConfirmed { get; } + + [Newtonsoft.Json.JsonProperty("twoFactorEnabled", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool TwoFactorEnabled { get; } + + [Newtonsoft.Json.JsonProperty("lockoutEnd", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.DateTime? LockoutEnd { get; } + + [Newtonsoft.Json.JsonProperty("lockoutEnabled", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool LockoutEnabled { get; } + + [Newtonsoft.Json.JsonProperty("accessFailedCount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public int AccessFailedCount { get; } public string ToJson() { @@ -251,50 +279,62 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static LoginModel FromJson(string data) + public static IdentityUserOfGuid FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Register + public partial class ProblemDetails { - [Newtonsoft.Json.JsonProperty("model", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public RegisterModel Model { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public ProblemDetails(string? @detail, System.Collections.Generic.Dictionary @extensions, string? @instance, int? @status, string? @title, string? @type) - public string ToJson() { - return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); + this.Type = @type; - } - public static Register FromJson(string data) - { + this.Title = @title; - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + this.Status = @status; - } + this.Detail = @detail; - } + this.Instance = @instance; - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class RegisterModel - { - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] - public string Name { get; set; } + this.Extensions = @extensions; - [Newtonsoft.Json.JsonProperty("nickName", Required = Newtonsoft.Json.Required.Always)] - public string NickName { get; set; } + } [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Type { get; } - [Newtonsoft.Json.JsonProperty("email", Required = Newtonsoft.Json.Required.Always)] - public string Email { get; set; } + [Newtonsoft.Json.JsonProperty("title", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Title { get; } - [Newtonsoft.Json.JsonProperty("password", Required = Newtonsoft.Json.Required.Always)] - public string Password { get; set; } + [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public int? Status { get; } + + [Newtonsoft.Json.JsonProperty("detail", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Detail { get; } + + [Newtonsoft.Json.JsonProperty("instance", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Instance { get; } + + [Newtonsoft.Json.JsonProperty("extensions", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.Dictionary Extensions { get; } + + private System.Collections.Generic.IDictionary _additionalProperties = new System.Collections.Generic.Dictionary(); + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties; } + set { _additionalProperties = value; } + } public string ToJson() { @@ -302,20 +342,28 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static RegisterModel FromJson(string data) + public static ProblemDetails FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class RegisterAdmin + public partial class LoginRequest { - [Newtonsoft.Json.JsonProperty("model", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public RegisterModel Model { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public LoginRequest(LoginModel @model) + + { + + this.Model = @model; + + } [Newtonsoft.Json.JsonProperty("model", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public LoginModel Model { get; } public string ToJson() { @@ -323,35 +371,38 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static RegisterAdmin FromJson(string data) + public static LoginRequest FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class MessengerChatDto + public partial class LoginModel { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid Id { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public LoginModel(string? @email, string @password, string? @userName) - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + { - [Newtonsoft.Json.JsonProperty("creator", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public MessengerUserDto Creator { get; set; } + this.UserName = @userName; - [Newtonsoft.Json.JsonProperty("users", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.ObjectModel.ObservableCollection Users { get; set; } + this.Email = @email; - [Newtonsoft.Json.JsonProperty("roles", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.ObjectModel.ObservableCollection Roles { get; set; } + this.Password = @password; + + } [Newtonsoft.Json.JsonProperty("userName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? UserName { get; } + + [Newtonsoft.Json.JsonProperty("email", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Email { get; } + + [Newtonsoft.Json.JsonProperty("password", Required = Newtonsoft.Json.Required.Always)] + public string Password { get; } public string ToJson() { @@ -359,29 +410,28 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static MessengerChatDto FromJson(string data) + public static LoginModel FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class MessengerUserDto + public partial class RegisterCommand { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid Id { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public RegisterCommand(RegisterModel @model) - [Newtonsoft.Json.JsonProperty("nickName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string NickName { get; set; } + { - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + this.Model = @model; + + } [Newtonsoft.Json.JsonProperty("model", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public RegisterModel Model { get; } public string ToJson() { @@ -389,53 +439,48 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static MessengerUserDto FromJson(string data) + public static RegisterCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class RoleDto + public partial class RegisterModel { - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("canEditMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanEditMessages { get; set; } + public RegisterModel(string @email, string @name, string @password, string @phoneNumber, string @userName) - [Newtonsoft.Json.JsonProperty("canDeleteMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanDeleteMessages { get; set; } + { - [Newtonsoft.Json.JsonProperty("canWriteMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanWriteMessages { get; set; } + this.UserName = @userName; - [Newtonsoft.Json.JsonProperty("canReadMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanReadMessages { get; set; } + this.Name = @name; - [Newtonsoft.Json.JsonProperty("canAddUsers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanAddUsers { get; set; } + this.Email = @email; - [Newtonsoft.Json.JsonProperty("canDeleteUsers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanDeleteUsers { get; set; } + this.Password = @password; - [Newtonsoft.Json.JsonProperty("canPinMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanPinMessages { get; set; } + this.PhoneNumber = @phoneNumber; - [Newtonsoft.Json.JsonProperty("canSeeChannelMembers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanSeeChannelMembers { get; set; } + } [Newtonsoft.Json.JsonProperty("userName", Required = Newtonsoft.Json.Required.Always)] + public string UserName { get; } - [Newtonsoft.Json.JsonProperty("canInviteOtherUsers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanInviteOtherUsers { get; set; } + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; } - [Newtonsoft.Json.JsonProperty("canEditChannelDescription", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanEditChannelDescription { get; set; } + [Newtonsoft.Json.JsonProperty("email", Required = Newtonsoft.Json.Required.Always)] + public string Email { get; } - [Newtonsoft.Json.JsonProperty("canDeleteChat", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanDeleteChat { get; set; } + [Newtonsoft.Json.JsonProperty("password", Required = Newtonsoft.Json.Required.Always)] + public string Password { get; } + + [Newtonsoft.Json.JsonProperty("phoneNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string PhoneNumber { get; } public string ToJson() { @@ -443,47 +488,33 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static RoleDto FromJson(string data) + public static RegisterModel FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public enum ActionOption + public partial class AuthenticateResponse { + [Newtonsoft.Json.JsonConstructor] - Unavailable = 0, + public AuthenticateResponse(System.Guid @userId, System.DateTime @validTo) - Enabled = 1, - - Disabled = 2, - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class ChatUser - { - [Newtonsoft.Json.JsonProperty("user", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public MessengerUser User { get; set; } + { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid Id { get; set; } + this.UserId = @userId; - [Newtonsoft.Json.JsonProperty("messengerUserId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid MessengerUserId { get; set; } + this.ValidTo = @validTo; - [Newtonsoft.Json.JsonProperty("chat", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Chat Chat { get; set; } + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } - [Newtonsoft.Json.JsonProperty("chatId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid ChatId { get; set; } - - [Newtonsoft.Json.JsonProperty("role", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Role Role { get; set; } + [Newtonsoft.Json.JsonProperty("validTo", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.DateTime ValidTo { get; } public string ToJson() { @@ -491,32 +522,28 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static ChatUser FromJson(string data) + public static AuthenticateResponse FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class MessengerUser + public partial class RegisterAdminCommand { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid Id { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public RegisterAdminCommand(RegisterModel @model) - [Newtonsoft.Json.JsonProperty("nickName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string NickName { get; set; } + { - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + this.Model = @model; - [Newtonsoft.Json.JsonProperty("chats", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.ObjectModel.ObservableCollection Chats { get; set; } + } [Newtonsoft.Json.JsonProperty("model", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public RegisterModel Model { get; } public string ToJson() { @@ -524,41 +551,48 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static MessengerUser FromJson(string data) + public static RegisterAdminCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public abstract partial class Chat + public partial class MessengerChatDto { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid Id { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public MessengerChatDto(string? @description, System.Guid @id, string? @name, System.Collections.ObjectModel.ObservableCollection @roles, System.Collections.ObjectModel.ObservableCollection @users) - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + { - [Newtonsoft.Json.JsonProperty("creator", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public MessengerUser Creator { get; set; } + this.Id = @id; - [Newtonsoft.Json.JsonProperty("creatorId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid CreatorId { get; set; } + this.Name = @name; - [Newtonsoft.Json.JsonProperty("maxUsersAmount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public int MaxUsersAmount { get; set; } + this.Description = @description; + + this.Users = @users; + + this.Roles = @roles; + + } [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid Id { get; } + + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Name { get; } + + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Description { get; } [Newtonsoft.Json.JsonProperty("users", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.ObjectModel.ObservableCollection Users { get; set; } + public System.Collections.ObjectModel.ObservableCollection Users { get; } [Newtonsoft.Json.JsonProperty("roles", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.ObjectModel.ObservableCollection Roles { get; set; } + public System.Collections.ObjectModel.ObservableCollection Roles { get; } public string ToJson() { @@ -566,59 +600,134 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static Chat FromJson(string data) + public static MessengerChatDto FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Role + public partial class RoleDto { - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid Id { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("chat", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Chat Chat { get; set; } + public RoleDto(ActionOption @canAddUsers, ActionOption @canDeleteChat, ActionOption @canDeleteMessages, ActionOption @canDeleteUsers, ActionOption @canEditChannelDescription, ActionOption @canEditMessages, ActionOption @canInviteOtherUsers, ActionOption @canPinMessages, ActionOption @canReadMessages, ActionOption @canSeeChannelMembers, ActionOption @canWriteMessages, string @name) - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + { + + this.Name = @name; + + this.CanEditMessages = @canEditMessages; + + this.CanDeleteMessages = @canDeleteMessages; + + this.CanWriteMessages = @canWriteMessages; + + this.CanReadMessages = @canReadMessages; + + this.CanAddUsers = @canAddUsers; + + this.CanDeleteUsers = @canDeleteUsers; + + this.CanPinMessages = @canPinMessages; + + this.CanSeeChannelMembers = @canSeeChannelMembers; + + this.CanInviteOtherUsers = @canInviteOtherUsers; + + this.CanEditChannelDescription = @canEditChannelDescription; + + this.CanDeleteChat = @canDeleteChat; + + } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; } [Newtonsoft.Json.JsonProperty("canEditMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanEditMessages { get; set; } + public ActionOption CanEditMessages { get; } [Newtonsoft.Json.JsonProperty("canDeleteMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanDeleteMessages { get; set; } + public ActionOption CanDeleteMessages { get; } [Newtonsoft.Json.JsonProperty("canWriteMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanWriteMessages { get; set; } + public ActionOption CanWriteMessages { get; } [Newtonsoft.Json.JsonProperty("canReadMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanReadMessages { get; set; } + public ActionOption CanReadMessages { get; } [Newtonsoft.Json.JsonProperty("canAddUsers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanAddUsers { get; set; } + public ActionOption CanAddUsers { get; } [Newtonsoft.Json.JsonProperty("canDeleteUsers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanDeleteUsers { get; set; } + public ActionOption CanDeleteUsers { get; } [Newtonsoft.Json.JsonProperty("canPinMessages", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanPinMessages { get; set; } + public ActionOption CanPinMessages { get; } [Newtonsoft.Json.JsonProperty("canSeeChannelMembers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanSeeChannelMembers { get; set; } + public ActionOption CanSeeChannelMembers { get; } [Newtonsoft.Json.JsonProperty("canInviteOtherUsers", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanInviteOtherUsers { get; set; } + public ActionOption CanInviteOtherUsers { get; } [Newtonsoft.Json.JsonProperty("canEditChannelDescription", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanEditChannelDescription { get; set; } + public ActionOption CanEditChannelDescription { get; } [Newtonsoft.Json.JsonProperty("canDeleteChat", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public ActionOption CanDeleteChat { get; set; } + public ActionOption CanDeleteChat { get; } + + public string ToJson() + { + + return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); + + } + public static RoleDto FromJson(string data) + { + + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] + public enum ActionOption + { + + Unavailable = 0, + + Enabled = 1, + + Disabled = 2, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class ChatUserDto + { + [Newtonsoft.Json.JsonConstructor] + + public ChatUserDto(string @chatUserName, System.Guid @messengerUserId, RoleDto @role) + + { + + this.ChatUserName = @chatUserName; + + this.MessengerUserId = @messengerUserId; + + this.Role = @role; + + } [Newtonsoft.Json.JsonProperty("chatUserName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string ChatUserName { get; } + + [Newtonsoft.Json.JsonProperty("messengerUserId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid MessengerUserId { get; } + + [Newtonsoft.Json.JsonProperty("role", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public RoleDto Role { get; } public string ToJson() { @@ -626,26 +735,38 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static Role FromJson(string data) + public static ChatUserDto FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class AddChannel + public partial class AddChannelCommand { - [Newtonsoft.Json.JsonProperty("adminId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid AdminId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public AddChannelCommand(System.Guid @adminId, string @description, string @name) + + { + + this.AdminId = @adminId; + + this.Name = @name; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("adminId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid AdminId { get; } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public string Name { get; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + public string Description { get; } public string ToJson() { @@ -653,26 +774,38 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static AddChannel FromJson(string data) + public static AddChannelCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class AddGroupChat + public partial class AddGroupChatCommand { - [Newtonsoft.Json.JsonProperty("adminId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid AdminId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public AddGroupChatCommand(System.Guid @adminId, string @description, string @name) + + { + + this.AdminId = @adminId; + + this.Name = @name; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("adminId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid AdminId { get; } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public string Name { get; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + public string Description { get; } public string ToJson() { @@ -680,29 +813,43 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static AddGroupChat FromJson(string data) + public static AddGroupChatCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class AddPersonalChat + public partial class AddPersonalChatCommand { - [Newtonsoft.Json.JsonProperty("firstUserId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid FirstUserId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public AddPersonalChatCommand(string @description, System.Guid @firstUserId, string @name, System.Guid @secondUserId) + + { + + this.FirstUserId = @firstUserId; + + this.SecondUserId = @secondUserId; + + this.Name = @name; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("firstUserId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid FirstUserId { get; } [Newtonsoft.Json.JsonProperty("secondUserId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid SecondUserId { get; set; } + public System.Guid SecondUserId { get; } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public string Name { get; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + public string Description { get; } public string ToJson() { @@ -710,26 +857,38 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static AddPersonalChat FromJson(string data) + public static AddPersonalChatCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class AddSavedMessages + public partial class AddSavedMessagesCommand { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public AddSavedMessagesCommand(string @description, string @name, System.Guid @userId) + + { + + this.UserId = @userId; + + this.Name = @name; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public string Name { get; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + public string Description { get; } public string ToJson() { @@ -737,23 +896,33 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static AddSavedMessages FromJson(string data) + public static AddSavedMessagesCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class AddUserToChat + public partial class AddUserToChatCommand { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public AddUserToChatCommand(System.Guid @chatId, System.Guid @userId) + + { + + this.UserId = @userId; + + this.ChatId = @chatId; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } [Newtonsoft.Json.JsonProperty("chatId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid ChatId { get; set; } + public System.Guid ChatId { get; } public string ToJson() { @@ -761,23 +930,33 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static AddUserToChat FromJson(string data) + public static AddUserToChatCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class DeleteUserFromChat + public partial class DeleteUserFromChatCommand { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public DeleteUserFromChatCommand(System.Guid @chatId, System.Guid @userId) + + { + + this.UserId = @userId; + + this.ChatId = @chatId; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } [Newtonsoft.Json.JsonProperty("chatId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid ChatId { get; set; } + public System.Guid ChatId { get; } public string ToJson() { @@ -785,23 +964,33 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static DeleteUserFromChat FromJson(string data) + public static DeleteUserFromChatCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class CreateRoleForChat + public partial class CreateRoleForChatCommand { - [Newtonsoft.Json.JsonProperty("role", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public RoleDto Role { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public CreateRoleForChatCommand(System.Guid @chatId, RoleDto @role) + + { + + this.Role = @role; + + this.ChatId = @chatId; + + } [Newtonsoft.Json.JsonProperty("role", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public RoleDto Role { get; } [Newtonsoft.Json.JsonProperty("chatId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid ChatId { get; set; } + public System.Guid ChatId { get; } public string ToJson() { @@ -809,26 +998,38 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static CreateRoleForChat FromJson(string data) + public static CreateRoleForChatCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class ChangeRoleForUserById + public partial class ChangeRoleForUserByIdCommand { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public ChangeRoleForUserByIdCommand(System.Guid @chatId, RoleDto @role, System.Guid @userId) + + { + + this.UserId = @userId; + + this.ChatId = @chatId; + + this.Role = @role; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } [Newtonsoft.Json.JsonProperty("chatId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid ChatId { get; set; } + public System.Guid ChatId { get; } [Newtonsoft.Json.JsonProperty("role", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public RoleDto Role { get; set; } + public RoleDto Role { get; } public string ToJson() { @@ -836,23 +1037,43 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static ChangeRoleForUserById FromJson(string data) + public static ChangeRoleForUserByIdCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class SetUserNickNameById + public partial class MessengerUserDto { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("nickName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string NickName { get; set; } + public MessengerUserDto(string? @description, System.Guid @id, string? @name, string? @userName) + + { + + this.Id = @id; + + this.Name = @name; + + this.UserName = @userName; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid Id { get; } + + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Name { get; } + + [Newtonsoft.Json.JsonProperty("userName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? UserName { get; } + + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string? Description { get; } public string ToJson() { @@ -860,20 +1081,33 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static SetUserNickNameById FromJson(string data) + public static MessengerUserDto FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class DeleteUser + public partial class SetUserNickNameByIdCommand { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public SetUserNickNameByIdCommand(System.Guid @userId, string @userName) + + { + + this.UserId = @userId; + + this.UserName = @userName; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } + + [Newtonsoft.Json.JsonProperty("userName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string UserName { get; } public string ToJson() { @@ -881,26 +1115,28 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static DeleteUser FromJson(string data) + public static SetUserNickNameByIdCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class AddUser + public partial class DeleteUserCommand { - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("nickName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string NickName { get; set; } + public DeleteUserCommand(System.Guid @userId) - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + { + + this.UserId = @userId; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } public string ToJson() { @@ -908,23 +1144,38 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static AddUser FromJson(string data) + public static DeleteUserCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class ChangeUserDescriptionById + public partial class AddUserCommand { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] + + public AddUserCommand(string @description, string @name, string @nickName) + + { + + this.Name = @name; + + this.NickName = @nickName; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; } + + [Newtonsoft.Json.JsonProperty("nickName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string NickName { get; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + public string Description { get; } public string ToJson() { @@ -932,23 +1183,33 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static ChangeUserDescriptionById FromJson(string data) + public static AddUserCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class ChangeUserNameById + public partial class ChangeUserDescriptionByIdCommand { - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Guid UserId { get; set; } + [Newtonsoft.Json.JsonConstructor] - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public ChangeUserDescriptionByIdCommand(string @description, System.Guid @userId) + + { + + this.UserId = @userId; + + this.Description = @description; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } + + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Description { get; } public string ToJson() { @@ -956,62 +1217,61 @@ public string ToJson() return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); } - public static ChangeUserNameById FromJson(string data) + public static ChangeUserDescriptionByIdCommand FromJson(string data) { - return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); } } - [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class FileResponse : System.IDisposable + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class ChangeUserNameByIdCommand { - private System.IDisposable _client; - private System.IDisposable _response; + [Newtonsoft.Json.JsonConstructor] - public int StatusCode { get; private set; } + public ChangeUserNameByIdCommand(string @name, System.Guid @userId) - public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } + { - public System.IO.Stream Stream { get; private set; } + this.UserId = @userId; - public bool IsPartial - { - get { return StatusCode == 206; } - } + this.Name = @name; + + } [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Guid UserId { get; } + + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; } - public FileResponse(int statusCode, System.Collections.Generic.IReadOnlyDictionary> headers, System.IO.Stream stream, System.IDisposable client, System.IDisposable response) + public string ToJson() { - StatusCode = statusCode; - Headers = headers; - Stream = stream; - _client = client; - _response = response; - } - public void Dispose() + return Newtonsoft.Json.JsonConvert.SerializeObject(this, new Newtonsoft.Json.JsonSerializerSettings()); + + } + public static ChangeUserNameByIdCommand FromJson(string data) { - Stream.Dispose(); - if (_response != null) - _response.Dispose(); - if (_client != null) - _client.Dispose(); + + return Newtonsoft.Json.JsonConvert.DeserializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()); + } + } + [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.16.0.0 (NJsonSchema v10.7.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class Do_Svyazi_User_ApiClient_Exception : System.Exception { public int StatusCode { get; private set; } - public string Response { get; private set; } + public string? Response { get; private set; } public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } - public Do_Svyazi_User_ApiClient_Exception(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) + public Do_Svyazi_User_ApiClient_Exception(string message, int statusCode, string? response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception? innerException) : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) { StatusCode = statusCode; @@ -1030,7 +1290,7 @@ public partial class Do_Svyazi_User_ApiClient_Exception : Do_Svyazi_Use { public TResult Result { get; private set; } - public Do_Svyazi_User_ApiClient_Exception(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) + public Do_Svyazi_User_ApiClient_Exception(string message, int statusCode, string? response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception? innerException) : base(message, statusCode, response, headers, innerException) { Result = result; diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do_SvyaziClientBase.cs b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do_SvyaziClientBase.cs new file mode 100644 index 0000000..cd89447 --- /dev/null +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Backend/Do_SvyaziClientBase.cs @@ -0,0 +1,21 @@ +namespace Do_Svyazi.User.Web.ApiClient.Backend; + +public abstract class Do_SvyaziClientBase +{ + public string BearerToken { get; private set; } + + public void SetBearerToken(string token) + { + BearerToken = token; + } + + // Called by implementing swagger client classes + public Task CreateHttpRequestMessageAsync(CancellationToken cancellationToken) + { + var msg = new HttpRequestMessage(); + + msg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BearerToken); + return Task.FromResult(msg); + } + +} \ No newline at end of file diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/do-svyazi.user.clients.ts b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/do-svyazi.user.clients.ts index b6cde42..65ffaf3 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/do-svyazi.user.clients.ts +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/do-svyazi.user.clients.ts @@ -14,9 +14,11 @@ import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, CancelToken } fr import * as moment from 'moment'; export interface IAuthenticateClient { - login(model: Login): Promise; - register(model: Register): Promise; - registerAdmin(model: RegisterAdmin): Promise; + getAll(): Promise; + login(model: LoginRequest): Promise; + register(model: RegisterCommand): Promise; + authenticateByJwt(jwtToken: string | null): Promise; + registerAdmin(model: RegisterAdminCommand): Promise; } export class AuthenticateClient implements IAuthenticateClient { @@ -32,20 +34,85 @@ export class AuthenticateClient implements IAuthenticateClient { } - login(model: Login , cancelToken?: CancelToken | undefined): Promise { - let url_ = this.baseUrl + "/api/Authenticate/login"; + getAll( cancelToken?: CancelToken | undefined): Promise { + let url_ = this.baseUrl + "/api/Authenticate/GetAll"; + url_ = url_.replace(/[?&]$/, ""); + + let options_: AxiosRequestConfig = { + method: "GET", + url: url_, + headers: { + "Accept": "application/json" + }, + cancelToken + }; + + return this.instance.request(options_).catch((_error: any) => { + if (isAxiosError(_error) && _error.response) { + return _error.response; + } else { + throw _error; + } + }).then((_response: AxiosResponse) => { + return this.processGetAll(_response); + }); + } + + protected processGetAll(response: AxiosResponse): Promise { + const status = response.status; + let _headers: any = {}; + if (response.headers && typeof response.headers === "object") { + for (let k in response.headers) { + if (response.headers.hasOwnProperty(k)) { + _headers[k] = response.headers[k]; + } + } + } + let _mappings: { source: any, target: any }[] = []; + if (status === 200) { + const _responseText = response.data; + let result200: any = null; + let resultData200 = _responseText; + if (Array.isArray(resultData200)) { + result200 = [] as any; + for (let item of resultData200) + result200!.push(MessengerUser.fromJS(item, _mappings)); + } + else { + result200 = null; + } + return Promise.resolve(result200); + + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status !== 200 && status !== 204) { + const _responseText = response.data; + return throwException("An unexpected server error occurred.", status, _responseText, _headers); + } + return Promise.resolve(null as any); + } + + login(model: LoginRequest , cancelToken?: CancelToken | undefined): Promise { + let url_ = this.baseUrl + "/api/Authenticate/Login"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(model); let options_: AxiosRequestConfig = { data: content_, - responseType: "blob", method: "POST", url: url_, headers: { "Content-Type": "application/json", - "Accept": "application/octet-stream" }, cancelToken }; @@ -61,7 +128,7 @@ export class AuthenticateClient implements IAuthenticateClient { }); } - protected processLogin(response: AxiosResponse): Promise { + protected processLogin(response: AxiosResponse): Promise { const status = response.status; let _headers: any = {}; if (response.headers && typeof response.headers === "object") { @@ -71,32 +138,41 @@ export class AuthenticateClient implements IAuthenticateClient { } } } - if (status === 200 || status === 206) { - const contentDisposition = response.headers ? response.headers["content-disposition"] : undefined; - const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined; - const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined; - return Promise.resolve({ fileName: fileName, status: status, data: new Blob([response.data], { type: response.headers["content-type"] }), headers: _headers }); + let _mappings: { source: any, target: any }[] = []; + if (status === 200) { + const _responseText = response.data; + return Promise.resolve(null as any); + + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); } - return Promise.resolve(null as any); + return Promise.resolve(null as any); } - register(model: Register , cancelToken?: CancelToken | undefined): Promise { - let url_ = this.baseUrl + "/api/Authenticate/register"; + register(model: RegisterCommand , cancelToken?: CancelToken | undefined): Promise { + let url_ = this.baseUrl + "/api/Authenticate/Register"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(model); let options_: AxiosRequestConfig = { data: content_, - responseType: "blob", method: "POST", url: url_, headers: { "Content-Type": "application/json", - "Accept": "application/octet-stream" }, cancelToken }; @@ -112,7 +188,7 @@ export class AuthenticateClient implements IAuthenticateClient { }); } - protected processRegister(response: AxiosResponse): Promise { + protected processRegister(response: AxiosResponse): Promise { const status = response.status; let _headers: any = {}; if (response.headers && typeof response.headers === "object") { @@ -122,32 +198,106 @@ export class AuthenticateClient implements IAuthenticateClient { } } } - if (status === 200 || status === 206) { - const contentDisposition = response.headers ? response.headers["content-disposition"] : undefined; - const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined; - const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined; - return Promise.resolve({ fileName: fileName, status: status, data: new Blob([response.data], { type: response.headers["content-type"] }), headers: _headers }); + let _mappings: { source: any, target: any }[] = []; + if (status === 200) { + const _responseText = response.data; + return Promise.resolve(null as any); + + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + + } else if (status !== 200 && status !== 204) { + const _responseText = response.data; + return throwException("An unexpected server error occurred.", status, _responseText, _headers); + } + return Promise.resolve(null as any); + } + + authenticateByJwt(jwtToken: string | null , cancelToken?: CancelToken | undefined): Promise { + let url_ = this.baseUrl + "/api/Authenticate/AuthenticateByJwt"; + url_ = url_.replace(/[?&]$/, ""); + + let options_: AxiosRequestConfig = { + method: "GET", + url: url_, + headers: { + "jwtToken": jwtToken !== undefined && jwtToken !== null ? "" + jwtToken : "", + "Accept": "application/json" + }, + cancelToken + }; + + return this.instance.request(options_).catch((_error: any) => { + if (isAxiosError(_error) && _error.response) { + return _error.response; + } else { + throw _error; + } + }).then((_response: AxiosResponse) => { + return this.processAuthenticateByJwt(_response); + }); + } + + protected processAuthenticateByJwt(response: AxiosResponse): Promise { + const status = response.status; + let _headers: any = {}; + if (response.headers && typeof response.headers === "object") { + for (let k in response.headers) { + if (response.headers.hasOwnProperty(k)) { + _headers[k] = response.headers[k]; + } + } + } + let _mappings: { source: any, target: any }[] = []; + if (status === 200) { + const _responseText = response.data; + let result200: any = null; + let resultData200 = _responseText; + result200 = AuthenticateResponse.fromJS(resultData200, _mappings); + return Promise.resolve(result200); + + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); } - return Promise.resolve(null as any); + return Promise.resolve(null as any); } - registerAdmin(model: RegisterAdmin , cancelToken?: CancelToken | undefined): Promise { - let url_ = this.baseUrl + "/api/Authenticate/register-admin"; + registerAdmin(model: RegisterAdminCommand , cancelToken?: CancelToken | undefined): Promise { + let url_ = this.baseUrl + "/api/Authenticate/RegisterAdmin"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(model); let options_: AxiosRequestConfig = { data: content_, - responseType: "blob", method: "POST", url: url_, headers: { "Content-Type": "application/json", - "Accept": "application/octet-stream" }, cancelToken }; @@ -163,7 +313,7 @@ export class AuthenticateClient implements IAuthenticateClient { }); } - protected processRegisterAdmin(response: AxiosResponse): Promise { + protected processRegisterAdmin(response: AxiosResponse): Promise { const status = response.status; let _headers: any = {}; if (response.headers && typeof response.headers === "object") { @@ -173,16 +323,31 @@ export class AuthenticateClient implements IAuthenticateClient { } } } - if (status === 200 || status === 206) { - const contentDisposition = response.headers ? response.headers["content-disposition"] : undefined; - const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined; - const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined; - return Promise.resolve({ fileName: fileName, status: status, data: new Blob([response.data], { type: response.headers["content-type"] }), headers: _headers }); + let _mappings: { source: any, target: any }[] = []; + if (status === 200) { + const _responseText = response.data; + return Promise.resolve(null as any); + + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); } - return Promise.resolve(null as any); + return Promise.resolve(null as any); } } @@ -190,13 +355,13 @@ export interface IChatClient { getChats(): Promise; getChatById(chatId: string): Promise; getUserIdsByChatId(chatId: string): Promise; - getUsersByChatId(chatId: string): Promise; - addChannel(addChannelCommand: AddChannel): Promise; - addGroupChat(addGroupChatCommand: AddGroupChat): Promise; - addPersonalChat(addPersonalChatCommand: AddPersonalChat): Promise; - addSavedMessages(addSavedMessagesCommand: AddSavedMessages): Promise; - addUserToChat(addUserToChatCommand: AddUserToChat): Promise; - deleteUserFromChat(deleteUserFromChatCommand: DeleteUserFromChat): Promise; + getUsersByChatId(chatId: string): Promise; + addChannel(addChannelCommand: AddChannelCommand): Promise; + addGroupChat(addGroupChatCommand: AddGroupChatCommand): Promise; + addPersonalChat(addPersonalChatCommand: AddPersonalChatCommand): Promise; + addSavedMessages(addSavedMessagesCommand: AddSavedMessagesCommand): Promise; + addUserToChat(addUserToChatCommand: AddUserToChatCommand): Promise; + deleteUserFromChat(deleteUserFromChatCommand: DeleteUserFromChatCommand): Promise; } export class ChatClient implements IChatClient { @@ -261,6 +426,17 @@ export class ChatClient implements IChatClient { } return Promise.resolve(result200); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -314,6 +490,17 @@ export class ChatClient implements IChatClient { result200 = MessengerChatDto.fromJS(resultData200, _mappings); return Promise.resolve(result200); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -359,6 +546,7 @@ export class ChatClient implements IChatClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; let result200: any = null; @@ -373,6 +561,17 @@ export class ChatClient implements IChatClient { } return Promise.resolve(result200); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -380,7 +579,7 @@ export class ChatClient implements IChatClient { return Promise.resolve(null as any); } - getUsersByChatId(chatId: string , cancelToken?: CancelToken | undefined): Promise { + getUsersByChatId(chatId: string , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Chat/GetUsersByChatId?"; if (chatId === undefined || chatId === null) throw new Error("The parameter 'chatId' must be defined and cannot be null."); @@ -408,7 +607,7 @@ export class ChatClient implements IChatClient { }); } - protected processGetUsersByChatId(response: AxiosResponse): Promise { + protected processGetUsersByChatId(response: AxiosResponse): Promise { const status = response.status; let _headers: any = {}; if (response.headers && typeof response.headers === "object") { @@ -426,21 +625,32 @@ export class ChatClient implements IChatClient { if (Array.isArray(resultData200)) { result200 = [] as any; for (let item of resultData200) - result200!.push(ChatUser.fromJS(item, _mappings)); + result200!.push(ChatUserDto.fromJS(item, _mappings)); } else { result200 = null; } - return Promise.resolve(result200); + return Promise.resolve(result200); + + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); } - return Promise.resolve(null as any); + return Promise.resolve(null as any); } - addChannel(addChannelCommand: AddChannel , cancelToken?: CancelToken | undefined): Promise { + addChannel(addChannelCommand: AddChannelCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Chat/AddChannel"; url_ = url_.replace(/[?&]$/, ""); @@ -477,10 +687,26 @@ export class ChatClient implements IChatClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 201) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -488,7 +714,7 @@ export class ChatClient implements IChatClient { return Promise.resolve(null as any); } - addGroupChat(addGroupChatCommand: AddGroupChat , cancelToken?: CancelToken | undefined): Promise { + addGroupChat(addGroupChatCommand: AddGroupChatCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Chat/AddGroupChat"; url_ = url_.replace(/[?&]$/, ""); @@ -525,10 +751,26 @@ export class ChatClient implements IChatClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 201) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -536,7 +778,7 @@ export class ChatClient implements IChatClient { return Promise.resolve(null as any); } - addPersonalChat(addPersonalChatCommand: AddPersonalChat , cancelToken?: CancelToken | undefined): Promise { + addPersonalChat(addPersonalChatCommand: AddPersonalChatCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Chat/AddPersonalChat"; url_ = url_.replace(/[?&]$/, ""); @@ -573,10 +815,26 @@ export class ChatClient implements IChatClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 201) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -584,7 +842,7 @@ export class ChatClient implements IChatClient { return Promise.resolve(null as any); } - addSavedMessages(addSavedMessagesCommand: AddSavedMessages , cancelToken?: CancelToken | undefined): Promise { + addSavedMessages(addSavedMessagesCommand: AddSavedMessagesCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Chat/AddSavedMessages"; url_ = url_.replace(/[?&]$/, ""); @@ -621,10 +879,26 @@ export class ChatClient implements IChatClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 201) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -632,7 +906,7 @@ export class ChatClient implements IChatClient { return Promise.resolve(null as any); } - addUserToChat(addUserToChatCommand: AddUserToChat , cancelToken?: CancelToken | undefined): Promise { + addUserToChat(addUserToChatCommand: AddUserToChatCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Chat/AddUserToChat"; url_ = url_.replace(/[?&]$/, ""); @@ -669,10 +943,26 @@ export class ChatClient implements IChatClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -680,7 +970,7 @@ export class ChatClient implements IChatClient { return Promise.resolve(null as any); } - deleteUserFromChat(deleteUserFromChatCommand: DeleteUserFromChat , cancelToken?: CancelToken | undefined): Promise { + deleteUserFromChat(deleteUserFromChatCommand: DeleteUserFromChatCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Chat/DeleteUserFromChat"; url_ = url_.replace(/[?&]$/, ""); @@ -717,10 +1007,26 @@ export class ChatClient implements IChatClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -731,8 +1037,8 @@ export class ChatClient implements IChatClient { export interface IRolesClient { getRoleByUserId(userId: string, chatId: string): Promise; - createRoleForChat(createRoleForChat: CreateRoleForChat): Promise; - changeRoleForUserById(changeRoleForUserById: ChangeRoleForUserById): Promise; + createRoleForChat(createRoleForChatCommand: CreateRoleForChatCommand): Promise; + changeRoleForUserById(changeRoleForUserByIdCommand: ChangeRoleForUserByIdCommand): Promise; } export class RolesClient implements IRolesClient { @@ -798,6 +1104,17 @@ export class RolesClient implements IRolesClient { result200 = RoleDto.fromJS(resultData200, _mappings); return Promise.resolve(result200); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -805,11 +1122,11 @@ export class RolesClient implements IRolesClient { return Promise.resolve(null as any); } - createRoleForChat(createRoleForChat: CreateRoleForChat , cancelToken?: CancelToken | undefined): Promise { + createRoleForChat(createRoleForChatCommand: CreateRoleForChatCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Roles/CreateRoleForChat"; url_ = url_.replace(/[?&]$/, ""); - const content_ = JSON.stringify(createRoleForChat); + const content_ = JSON.stringify(createRoleForChatCommand); let options_: AxiosRequestConfig = { data: content_, @@ -842,10 +1159,26 @@ export class RolesClient implements IRolesClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -853,11 +1186,11 @@ export class RolesClient implements IRolesClient { return Promise.resolve(null as any); } - changeRoleForUserById(changeRoleForUserById: ChangeRoleForUserById , cancelToken?: CancelToken | undefined): Promise { + changeRoleForUserById(changeRoleForUserByIdCommand: ChangeRoleForUserByIdCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/Roles/ChangeRoleForUserById"; url_ = url_.replace(/[?&]$/, ""); - const content_ = JSON.stringify(changeRoleForUserById); + const content_ = JSON.stringify(changeRoleForUserByIdCommand); let options_: AxiosRequestConfig = { data: content_, @@ -890,10 +1223,26 @@ export class RolesClient implements IRolesClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -904,14 +1253,14 @@ export class RolesClient implements IRolesClient { export interface IUserClient { getAll(): Promise; - getUser(userId: string): Promise; + getUser(userId: string): Promise; getAllChatsByUserId(userId: string): Promise; getAllChatsIdsByUserId(userId: string): Promise; - setNickNameById(setUserNickNameById: SetUserNickNameById): Promise; - deleteUser(deleteUser: DeleteUser): Promise; - addUser(addUser: AddUser): Promise; - changeDescription(changeUserDescriptionById: ChangeUserDescriptionById): Promise; - changeName(changeUserNameById: ChangeUserNameById): Promise; + setNickNameById(setUserNickNameByIdCommand: SetUserNickNameByIdCommand): Promise; + deleteUser(deleteUserCommand: DeleteUserCommand): Promise; + addUser(addUserCommand: AddUserCommand): Promise; + changeDescription(changeUserDescriptionByIdCommand: ChangeUserDescriptionByIdCommand): Promise; + changeName(changeUserNameByIdCommand: ChangeUserNameByIdCommand): Promise; } export class UserClient implements IUserClient { @@ -976,6 +1325,17 @@ export class UserClient implements IUserClient { } return Promise.resolve(result200); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -983,7 +1343,7 @@ export class UserClient implements IUserClient { return Promise.resolve(null as any); } - getUser(userId: string , cancelToken?: CancelToken | undefined): Promise { + getUser(userId: string , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/User/GetUser?"; if (userId === undefined || userId === null) throw new Error("The parameter 'userId' must be defined and cannot be null."); @@ -1011,7 +1371,7 @@ export class UserClient implements IUserClient { }); } - protected processGetUser(response: AxiosResponse): Promise { + protected processGetUser(response: AxiosResponse): Promise { const status = response.status; let _headers: any = {}; if (response.headers && typeof response.headers === "object") { @@ -1026,14 +1386,25 @@ export class UserClient implements IUserClient { const _responseText = response.data; let result200: any = null; let resultData200 = _responseText; - result200 = MessengerUser.fromJS(resultData200, _mappings); - return Promise.resolve(result200); + result200 = MessengerUserDto.fromJS(resultData200, _mappings); + return Promise.resolve(result200); + + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); } - return Promise.resolve(null as any); + return Promise.resolve(null as any); } getAllChatsByUserId(userId: string , cancelToken?: CancelToken | undefined): Promise { @@ -1089,6 +1460,17 @@ export class UserClient implements IUserClient { } return Promise.resolve(result200); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -1134,6 +1516,7 @@ export class UserClient implements IUserClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; let result200: any = null; @@ -1148,6 +1531,17 @@ export class UserClient implements IUserClient { } return Promise.resolve(result200); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -1155,11 +1549,11 @@ export class UserClient implements IUserClient { return Promise.resolve(null as any); } - setNickNameById(setUserNickNameById: SetUserNickNameById , cancelToken?: CancelToken | undefined): Promise { + setNickNameById(setUserNickNameByIdCommand: SetUserNickNameByIdCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/User/SetNickNameById"; url_ = url_.replace(/[?&]$/, ""); - const content_ = JSON.stringify(setUserNickNameById); + const content_ = JSON.stringify(setUserNickNameByIdCommand); let options_: AxiosRequestConfig = { data: content_, @@ -1192,10 +1586,26 @@ export class UserClient implements IUserClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -1203,11 +1613,11 @@ export class UserClient implements IUserClient { return Promise.resolve(null as any); } - deleteUser(deleteUser: DeleteUser , cancelToken?: CancelToken | undefined): Promise { + deleteUser(deleteUserCommand: DeleteUserCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/User/DeleteUser"; url_ = url_.replace(/[?&]$/, ""); - const content_ = JSON.stringify(deleteUser); + const content_ = JSON.stringify(deleteUserCommand); let options_: AxiosRequestConfig = { data: content_, @@ -1240,10 +1650,26 @@ export class UserClient implements IUserClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -1251,11 +1677,11 @@ export class UserClient implements IUserClient { return Promise.resolve(null as any); } - addUser(addUser: AddUser , cancelToken?: CancelToken | undefined): Promise { + addUser(addUserCommand: AddUserCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/User/AddUser"; url_ = url_.replace(/[?&]$/, ""); - const content_ = JSON.stringify(addUser); + const content_ = JSON.stringify(addUserCommand); let options_: AxiosRequestConfig = { data: content_, @@ -1289,6 +1715,7 @@ export class UserClient implements IUserClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; let result200: any = null; @@ -1297,18 +1724,37 @@ export class UserClient implements IUserClient { return Promise.resolve(result200); - } else if (status !== 200 && status !== 204) { + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 201) { + const _responseText = response.data; + let result201: any = null; + let resultData201 = _responseText; + result201 = resultData201 !== undefined ? resultData201 : null; + + return Promise.resolve(result201); + + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); } return Promise.resolve(null as any); } - changeDescription(changeUserDescriptionById: ChangeUserDescriptionById , cancelToken?: CancelToken | undefined): Promise { + changeDescription(changeUserDescriptionByIdCommand: ChangeUserDescriptionByIdCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/User/ChangeDescription"; url_ = url_.replace(/[?&]$/, ""); - const content_ = JSON.stringify(changeUserDescriptionById); + const content_ = JSON.stringify(changeUserDescriptionByIdCommand); let options_: AxiosRequestConfig = { data: content_, @@ -1341,10 +1787,26 @@ export class UserClient implements IUserClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); + } else if (status === 401) { + const _responseText = response.data; + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); + + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); + + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); + } else if (status !== 200 && status !== 204) { const _responseText = response.data; return throwException("An unexpected server error occurred.", status, _responseText, _headers); @@ -1352,11 +1814,11 @@ export class UserClient implements IUserClient { return Promise.resolve(null as any); } - changeName(changeUserNameById: ChangeUserNameById , cancelToken?: CancelToken | undefined): Promise { + changeName(changeUserNameByIdCommand: ChangeUserNameByIdCommand , cancelToken?: CancelToken | undefined): Promise { let url_ = this.baseUrl + "/api/User/ChangeName"; url_ = url_.replace(/[?&]$/, ""); - const content_ = JSON.stringify(changeUserNameById); + const content_ = JSON.stringify(changeUserNameByIdCommand); let options_: AxiosRequestConfig = { data: content_, @@ -1389,58 +1851,52 @@ export class UserClient implements IUserClient { } } } + let _mappings: { source: any, target: any }[] = []; if (status === 200) { const _responseText = response.data; return Promise.resolve(null as any); - } else if (status !== 200 && status !== 204) { + } else if (status === 401) { const _responseText = response.data; - return throwException("An unexpected server error occurred.", status, _responseText, _headers); - } - return Promise.resolve(null as any); - } -} + let result401: any = null; + let resultData401 = _responseText; + result401 = ProblemDetails.fromJS(resultData401, _mappings); + return throwException("A server side error occurred.", status, _responseText, _headers, result401); -export class Login implements ILogin { - model!: LoginModel; + } else if (status === 500) { + const _responseText = response.data; + return throwException("A server side error occurred.", status, _responseText, _headers); - constructor(data?: ILogin) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } + } else if (status === 204) { + const _responseText = response.data; + return Promise.resolve(null as any); - init(_data?: any, _mappings?: any) { - if (_data) { - this.model = _data["model"] ? LoginModel.fromJS(_data["model"], _mappings) : undefined; + } else if (status !== 200 && status !== 204) { + const _responseText = response.data; + return throwException("An unexpected server error occurred.", status, _responseText, _headers); } + return Promise.resolve(null as any); } - - static fromJS(data: any, _mappings?: any): Login | null { - data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, Login); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["model"] = this.model ? this.model.toJSON() : undefined; - return data; - } -} - -export interface ILogin { - model: LoginModel; } -export class LoginModel implements ILoginModel { +export class IdentityUserOfGuid implements IIdentityUserOfGuid { id!: string; - nickName!: string; - password!: string; - - constructor(data?: ILoginModel) { + userName!: string | undefined; + normalizedUserName!: string | undefined; + email!: string | undefined; + normalizedEmail!: string | undefined; + emailConfirmed!: boolean; + passwordHash!: string | undefined; + securityStamp!: string | undefined; + concurrencyStamp!: string | undefined; + phoneNumber!: string | undefined; + phoneNumberConfirmed!: boolean; + twoFactorEnabled!: boolean; + lockoutEnd!: moment.Moment | undefined; + lockoutEnabled!: boolean; + accessFailedCount!: number; + + constructor(data?: IIdentityUserOfGuid) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1452,72 +1908,111 @@ export class LoginModel implements ILoginModel { init(_data?: any, _mappings?: any) { if (_data) { this.id = _data["id"]; - this.nickName = _data["nickName"]; - this.password = _data["password"]; + this.userName = _data["userName"]; + this.normalizedUserName = _data["normalizedUserName"]; + this.email = _data["email"]; + this.normalizedEmail = _data["normalizedEmail"]; + this.emailConfirmed = _data["emailConfirmed"]; + this.passwordHash = _data["passwordHash"]; + this.securityStamp = _data["securityStamp"]; + this.concurrencyStamp = _data["concurrencyStamp"]; + this.phoneNumber = _data["phoneNumber"]; + this.phoneNumberConfirmed = _data["phoneNumberConfirmed"]; + this.twoFactorEnabled = _data["twoFactorEnabled"]; + this.lockoutEnd = _data["lockoutEnd"] ? moment.parseZone(_data["lockoutEnd"].toString()) : undefined; + this.lockoutEnabled = _data["lockoutEnabled"]; + this.accessFailedCount = _data["accessFailedCount"]; } } - static fromJS(data: any, _mappings?: any): LoginModel | null { + static fromJS(data: any, _mappings?: any): IdentityUserOfGuid | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, LoginModel); + return createInstance(data, _mappings, IdentityUserOfGuid); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["id"] = this.id; - data["nickName"] = this.nickName; - data["password"] = this.password; + data["userName"] = this.userName; + data["normalizedUserName"] = this.normalizedUserName; + data["email"] = this.email; + data["normalizedEmail"] = this.normalizedEmail; + data["emailConfirmed"] = this.emailConfirmed; + data["passwordHash"] = this.passwordHash; + data["securityStamp"] = this.securityStamp; + data["concurrencyStamp"] = this.concurrencyStamp; + data["phoneNumber"] = this.phoneNumber; + data["phoneNumberConfirmed"] = this.phoneNumberConfirmed; + data["twoFactorEnabled"] = this.twoFactorEnabled; + data["lockoutEnd"] = this.lockoutEnd ? this.lockoutEnd.toISOString(true) : undefined; + data["lockoutEnabled"] = this.lockoutEnabled; + data["accessFailedCount"] = this.accessFailedCount; return data; } } -export interface ILoginModel { +export interface IIdentityUserOfGuid { id: string; - nickName: string; - password: string; -} - -export class Register implements IRegister { - model!: RegisterModel; + userName: string | undefined; + normalizedUserName: string | undefined; + email: string | undefined; + normalizedEmail: string | undefined; + emailConfirmed: boolean; + passwordHash: string | undefined; + securityStamp: string | undefined; + concurrencyStamp: string | undefined; + phoneNumber: string | undefined; + phoneNumberConfirmed: boolean; + twoFactorEnabled: boolean; + lockoutEnd: moment.Moment | undefined; + lockoutEnabled: boolean; + accessFailedCount: number; +} + +export class MessengerUser extends IdentityUserOfGuid implements IMessengerUser { + name!: string; + description!: string; - constructor(data?: IRegister) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } + constructor(data?: IMessengerUser) { + super(data); } - init(_data?: any, _mappings?: any) { + override init(_data?: any, _mappings?: any) { + super.init(_data); if (_data) { - this.model = _data["model"] ? RegisterModel.fromJS(_data["model"], _mappings) : undefined; + this.name = _data["name"]; + this.description = _data["description"]; } } - static fromJS(data: any, _mappings?: any): Register | null { + static override fromJS(data: any, _mappings?: any): MessengerUser | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, Register); + return createInstance(data, _mappings, MessengerUser); } - toJSON(data?: any) { + override toJSON(data?: any) { data = typeof data === 'object' ? data : {}; - data["model"] = this.model ? this.model.toJSON() : undefined; + data["name"] = this.name; + data["description"] = this.description; + super.toJSON(data); return data; } } -export interface IRegister { - model: RegisterModel; +export interface IMessengerUser extends IIdentityUserOfGuid { + name: string; + description: string; } -export class RegisterModel implements IRegisterModel { - name!: string; - nickName!: string; - email!: string; - password!: string; +export class ProblemDetails implements IProblemDetails { + type!: string | undefined; + title!: string | undefined; + status!: number | undefined; + detail!: string | undefined; + instance!: string | undefined; + extensions!: { [key: string]: any; }; - constructor(data?: IRegisterModel) { + constructor(data?: IProblemDetails) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1528,39 +2023,57 @@ export class RegisterModel implements IRegisterModel { init(_data?: any, _mappings?: any) { if (_data) { - this.name = _data["name"]; - this.nickName = _data["nickName"]; - this.email = _data["email"]; - this.password = _data["password"]; + this.type = _data["type"]; + this.title = _data["title"]; + this.status = _data["status"]; + this.detail = _data["detail"]; + this.instance = _data["instance"]; + if (_data["extensions"]) { + this.extensions = {} as any; + for (let key in _data["extensions"]) { + if (_data["extensions"].hasOwnProperty(key)) + (this.extensions)![key] = _data["extensions"][key]; + } + } } } - static fromJS(data: any, _mappings?: any): RegisterModel | null { + static fromJS(data: any, _mappings?: any): ProblemDetails | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, RegisterModel); + return createInstance(data, _mappings, ProblemDetails); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; - data["name"] = this.name; - data["nickName"] = this.nickName; - data["email"] = this.email; - data["password"] = this.password; + data["type"] = this.type; + data["title"] = this.title; + data["status"] = this.status; + data["detail"] = this.detail; + data["instance"] = this.instance; + if (this.extensions) { + data["extensions"] = {}; + for (let key in this.extensions) { + if (this.extensions.hasOwnProperty(key)) + (data["extensions"])[key] = this.extensions[key]; + } + } return data; } } -export interface IRegisterModel { - name: string; - nickName: string; - email: string; - password: string; +export interface IProblemDetails { + type: string | undefined; + title: string | undefined; + status: number | undefined; + detail: string | undefined; + instance: string | undefined; + extensions: { [key: string]: any; }; } -export class RegisterAdmin implements IRegisterAdmin { - model!: RegisterModel; +export class LoginRequest implements ILoginRequest { + model!: LoginModel; - constructor(data?: IRegisterAdmin) { + constructor(data?: ILoginRequest) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1571,13 +2084,13 @@ export class RegisterAdmin implements IRegisterAdmin { init(_data?: any, _mappings?: any) { if (_data) { - this.model = _data["model"] ? RegisterModel.fromJS(_data["model"], _mappings) : undefined; + this.model = _data["model"] ? LoginModel.fromJS(_data["model"], _mappings) : undefined; } } - static fromJS(data: any, _mappings?: any): RegisterAdmin | null { + static fromJS(data: any, _mappings?: any): LoginRequest | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, RegisterAdmin); + return createInstance(data, _mappings, LoginRequest); } toJSON(data?: any) { @@ -1587,19 +2100,16 @@ export class RegisterAdmin implements IRegisterAdmin { } } -export interface IRegisterAdmin { - model: RegisterModel; +export interface ILoginRequest { + model: LoginModel; } -export class MessengerChatDto implements IMessengerChatDto { - id!: string; - name!: string | undefined; - description!: string | undefined; - creator!: MessengerUserDto | undefined; - users!: string[]; - roles!: RoleDto[]; +export class LoginModel implements ILoginModel { + userName!: string | undefined; + email!: string | undefined; + password!: string; - constructor(data?: IMessengerChatDto) { + constructor(data?: ILoginModel) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1610,64 +2120,36 @@ export class MessengerChatDto implements IMessengerChatDto { init(_data?: any, _mappings?: any) { if (_data) { - this.id = _data["id"]; - this.name = _data["name"]; - this.description = _data["description"]; - this.creator = _data["creator"] ? MessengerUserDto.fromJS(_data["creator"], _mappings) : undefined; - if (Array.isArray(_data["users"])) { - this.users = [] as any; - for (let item of _data["users"]) - this.users!.push(item); - } - if (Array.isArray(_data["roles"])) { - this.roles = [] as any; - for (let item of _data["roles"]) - this.roles!.push(RoleDto.fromJS(item, _mappings)); - } + this.userName = _data["userName"]; + this.email = _data["email"]; + this.password = _data["password"]; } } - static fromJS(data: any, _mappings?: any): MessengerChatDto | null { + static fromJS(data: any, _mappings?: any): LoginModel | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, MessengerChatDto); + return createInstance(data, _mappings, LoginModel); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; - data["id"] = this.id; - data["name"] = this.name; - data["description"] = this.description; - data["creator"] = this.creator ? this.creator.toJSON() : undefined; - if (Array.isArray(this.users)) { - data["users"] = []; - for (let item of this.users) - data["users"].push(item); - } - if (Array.isArray(this.roles)) { - data["roles"] = []; - for (let item of this.roles) - data["roles"].push(item.toJSON()); - } + data["userName"] = this.userName; + data["email"] = this.email; + data["password"] = this.password; return data; } } -export interface IMessengerChatDto { - id: string; - name: string | undefined; - description: string | undefined; - creator: MessengerUserDto | undefined; - users: string[]; - roles: RoleDto[]; +export interface ILoginModel { + userName: string | undefined; + email: string | undefined; + password: string; } -export class MessengerUserDto implements IMessengerUserDto { - id!: string; - name!: string | undefined; - nickName!: string | undefined; - description!: string | undefined; +export class RegisterCommand implements IRegisterCommand { + model!: RegisterModel; - constructor(data?: IMessengerUserDto) { + constructor(data?: IRegisterCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1678,50 +2160,34 @@ export class MessengerUserDto implements IMessengerUserDto { init(_data?: any, _mappings?: any) { if (_data) { - this.id = _data["id"]; - this.name = _data["name"]; - this.nickName = _data["nickName"]; - this.description = _data["description"]; + this.model = _data["model"] ? RegisterModel.fromJS(_data["model"], _mappings) : undefined; } } - static fromJS(data: any, _mappings?: any): MessengerUserDto | null { + static fromJS(data: any, _mappings?: any): RegisterCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, MessengerUserDto); + return createInstance(data, _mappings, RegisterCommand); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; - data["id"] = this.id; - data["name"] = this.name; - data["nickName"] = this.nickName; - data["description"] = this.description; + data["model"] = this.model ? this.model.toJSON() : undefined; return data; } } -export interface IMessengerUserDto { - id: string; - name: string | undefined; - nickName: string | undefined; - description: string | undefined; +export interface IRegisterCommand { + model: RegisterModel; } -export class RoleDto implements IRoleDto { +export class RegisterModel implements IRegisterModel { + userName!: string; name!: string; - canEditMessages!: ActionOption; - canDeleteMessages!: ActionOption; - canWriteMessages!: ActionOption; - canReadMessages!: ActionOption; - canAddUsers!: ActionOption; - canDeleteUsers!: ActionOption; - canPinMessages!: ActionOption; - canSeeChannelMembers!: ActionOption; - canInviteOtherUsers!: ActionOption; - canEditChannelDescription!: ActionOption; - canDeleteChat!: ActionOption; + email!: string; + password!: string; + phoneNumber!: string; - constructor(data?: IRoleDto) { + constructor(data?: IRegisterModel) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1732,74 +2198,43 @@ export class RoleDto implements IRoleDto { init(_data?: any, _mappings?: any) { if (_data) { + this.userName = _data["userName"]; this.name = _data["name"]; - this.canEditMessages = _data["canEditMessages"]; - this.canDeleteMessages = _data["canDeleteMessages"]; - this.canWriteMessages = _data["canWriteMessages"]; - this.canReadMessages = _data["canReadMessages"]; - this.canAddUsers = _data["canAddUsers"]; - this.canDeleteUsers = _data["canDeleteUsers"]; - this.canPinMessages = _data["canPinMessages"]; - this.canSeeChannelMembers = _data["canSeeChannelMembers"]; - this.canInviteOtherUsers = _data["canInviteOtherUsers"]; - this.canEditChannelDescription = _data["canEditChannelDescription"]; - this.canDeleteChat = _data["canDeleteChat"]; + this.email = _data["email"]; + this.password = _data["password"]; + this.phoneNumber = _data["phoneNumber"]; } } - static fromJS(data: any, _mappings?: any): RoleDto | null { + static fromJS(data: any, _mappings?: any): RegisterModel | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, RoleDto); + return createInstance(data, _mappings, RegisterModel); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; + data["userName"] = this.userName; data["name"] = this.name; - data["canEditMessages"] = this.canEditMessages; - data["canDeleteMessages"] = this.canDeleteMessages; - data["canWriteMessages"] = this.canWriteMessages; - data["canReadMessages"] = this.canReadMessages; - data["canAddUsers"] = this.canAddUsers; - data["canDeleteUsers"] = this.canDeleteUsers; - data["canPinMessages"] = this.canPinMessages; - data["canSeeChannelMembers"] = this.canSeeChannelMembers; - data["canInviteOtherUsers"] = this.canInviteOtherUsers; - data["canEditChannelDescription"] = this.canEditChannelDescription; - data["canDeleteChat"] = this.canDeleteChat; + data["email"] = this.email; + data["password"] = this.password; + data["phoneNumber"] = this.phoneNumber; return data; } } -export interface IRoleDto { +export interface IRegisterModel { + userName: string; name: string; - canEditMessages: ActionOption; - canDeleteMessages: ActionOption; - canWriteMessages: ActionOption; - canReadMessages: ActionOption; - canAddUsers: ActionOption; - canDeleteUsers: ActionOption; - canPinMessages: ActionOption; - canSeeChannelMembers: ActionOption; - canInviteOtherUsers: ActionOption; - canEditChannelDescription: ActionOption; - canDeleteChat: ActionOption; -} - -export enum ActionOption { - Unavailable = 0, - Enabled = 1, - Disabled = 2, + email: string; + password: string; + phoneNumber: string; } -export class ChatUser implements IChatUser { - user!: MessengerUser; - id!: string; - messengerUserId!: string; - chat!: Chat; - chatId!: string; - role!: Role; +export class AuthenticateResponse implements IAuthenticateResponse { + userId!: string; + validTo!: moment.Moment; - constructor(data?: IChatUser) { + constructor(data?: IAuthenticateResponse) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1810,49 +2245,33 @@ export class ChatUser implements IChatUser { init(_data?: any, _mappings?: any) { if (_data) { - this.user = _data["user"] ? MessengerUser.fromJS(_data["user"], _mappings) : undefined; - this.id = _data["id"]; - this.messengerUserId = _data["messengerUserId"]; - this.chat = _data["chat"] ? Chat.fromJS(_data["chat"], _mappings) : undefined; - this.chatId = _data["chatId"]; - this.role = _data["role"] ? Role.fromJS(_data["role"], _mappings) : undefined; + this.userId = _data["userId"]; + this.validTo = _data["validTo"] ? moment.parseZone(_data["validTo"].toString()) : undefined; } } - static fromJS(data: any, _mappings?: any): ChatUser | null { + static fromJS(data: any, _mappings?: any): AuthenticateResponse | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, ChatUser); + return createInstance(data, _mappings, AuthenticateResponse); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; - data["user"] = this.user ? this.user.toJSON() : undefined; - data["id"] = this.id; - data["messengerUserId"] = this.messengerUserId; - data["chat"] = this.chat ? this.chat.toJSON() : undefined; - data["chatId"] = this.chatId; - data["role"] = this.role ? this.role.toJSON() : undefined; + data["userId"] = this.userId; + data["validTo"] = this.validTo ? this.validTo.toISOString(true) : undefined; return data; } } -export interface IChatUser { - user: MessengerUser; - id: string; - messengerUserId: string; - chat: Chat; - chatId: string; - role: Role; +export interface IAuthenticateResponse { + userId: string; + validTo: moment.Moment; } -export class MessengerUser implements IMessengerUser { - id!: string; - name!: string; - nickName!: string; - description!: string; - chats!: Chat[]; +export class RegisterAdminCommand implements IRegisterAdminCommand { + model!: RegisterModel; - constructor(data?: IMessengerUser) { + constructor(data?: IRegisterAdminCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1863,57 +2282,34 @@ export class MessengerUser implements IMessengerUser { init(_data?: any, _mappings?: any) { if (_data) { - this.id = _data["id"]; - this.name = _data["name"]; - this.nickName = _data["nickName"]; - this.description = _data["description"]; - if (Array.isArray(_data["chats"])) { - this.chats = [] as any; - for (let item of _data["chats"]) - this.chats!.push(Chat.fromJS(item, _mappings)); - } + this.model = _data["model"] ? RegisterModel.fromJS(_data["model"], _mappings) : undefined; } } - static fromJS(data: any, _mappings?: any): MessengerUser | null { + static fromJS(data: any, _mappings?: any): RegisterAdminCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, MessengerUser); + return createInstance(data, _mappings, RegisterAdminCommand); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; - data["id"] = this.id; - data["name"] = this.name; - data["nickName"] = this.nickName; - data["description"] = this.description; - if (Array.isArray(this.chats)) { - data["chats"] = []; - for (let item of this.chats) - data["chats"].push(item.toJSON()); - } + data["model"] = this.model ? this.model.toJSON() : undefined; return data; } } -export interface IMessengerUser { - id: string; - name: string; - nickName: string; - description: string; - chats: Chat[]; +export interface IRegisterAdminCommand { + model: RegisterModel; } -export abstract class Chat implements IChat { +export class MessengerChatDto implements IMessengerChatDto { id!: string; - name!: string; - description!: string; - creator!: MessengerUser; - creatorId!: string; - maxUsersAmount!: number; - users!: ChatUser[]; - roles!: Role[]; + name!: string | undefined; + description!: string | undefined; + users!: string[]; + roles!: RoleDto[]; - constructor(data?: IChat) { + constructor(data?: IMessengerChatDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -1927,25 +2323,22 @@ export abstract class Chat implements IChat { this.id = _data["id"]; this.name = _data["name"]; this.description = _data["description"]; - this.creator = _data["creator"] ? MessengerUser.fromJS(_data["creator"], _mappings) : undefined; - this.creatorId = _data["creatorId"]; - this.maxUsersAmount = _data["maxUsersAmount"]; if (Array.isArray(_data["users"])) { this.users = [] as any; for (let item of _data["users"]) - this.users!.push(ChatUser.fromJS(item, _mappings)); + this.users!.push(item); } if (Array.isArray(_data["roles"])) { this.roles = [] as any; for (let item of _data["roles"]) - this.roles!.push(Role.fromJS(item, _mappings)); + this.roles!.push(RoleDto.fromJS(item, _mappings)); } } } - static fromJS(data: any, _mappings?: any): Chat | null { + static fromJS(data: any, _mappings?: any): MessengerChatDto | null { data = typeof data === 'object' ? data : {}; - throw new Error("The abstract class 'Chat' cannot be instantiated."); + return createInstance(data, _mappings, MessengerChatDto); } toJSON(data?: any) { @@ -1953,13 +2346,10 @@ export abstract class Chat implements IChat { data["id"] = this.id; data["name"] = this.name; data["description"] = this.description; - data["creator"] = this.creator ? this.creator.toJSON() : undefined; - data["creatorId"] = this.creatorId; - data["maxUsersAmount"] = this.maxUsersAmount; if (Array.isArray(this.users)) { data["users"] = []; for (let item of this.users) - data["users"].push(item.toJSON()); + data["users"].push(item); } if (Array.isArray(this.roles)) { data["roles"] = []; @@ -1970,20 +2360,15 @@ export abstract class Chat implements IChat { } } -export interface IChat { +export interface IMessengerChatDto { id: string; - name: string; - description: string; - creator: MessengerUser; - creatorId: string; - maxUsersAmount: number; - users: ChatUser[]; - roles: Role[]; + name: string | undefined; + description: string | undefined; + users: string[]; + roles: RoleDto[]; } -export class Role implements IRole { - id!: string; - chat!: Chat; +export class RoleDto implements IRoleDto { name!: string; canEditMessages!: ActionOption; canDeleteMessages!: ActionOption; @@ -1997,7 +2382,7 @@ export class Role implements IRole { canEditChannelDescription!: ActionOption; canDeleteChat!: ActionOption; - constructor(data?: IRole) { + constructor(data?: IRoleDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2008,8 +2393,6 @@ export class Role implements IRole { init(_data?: any, _mappings?: any) { if (_data) { - this.id = _data["id"]; - this.chat = _data["chat"] ? Chat.fromJS(_data["chat"], _mappings) : undefined; this.name = _data["name"]; this.canEditMessages = _data["canEditMessages"]; this.canDeleteMessages = _data["canDeleteMessages"]; @@ -2025,15 +2408,13 @@ export class Role implements IRole { } } - static fromJS(data: any, _mappings?: any): Role | null { + static fromJS(data: any, _mappings?: any): RoleDto | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, Role); + return createInstance(data, _mappings, RoleDto); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; - data["id"] = this.id; - data["chat"] = this.chat ? this.chat.toJSON() : undefined; data["name"] = this.name; data["canEditMessages"] = this.canEditMessages; data["canDeleteMessages"] = this.canDeleteMessages; @@ -2050,9 +2431,7 @@ export class Role implements IRole { } } -export interface IRole { - id: string; - chat: Chat; +export interface IRoleDto { name: string; canEditMessages: ActionOption; canDeleteMessages: ActionOption; @@ -2067,12 +2446,60 @@ export interface IRole { canDeleteChat: ActionOption; } -export class AddChannel implements IAddChannel { +export enum ActionOption { + Unavailable = 0, + Enabled = 1, + Disabled = 2, +} + +export class ChatUserDto implements IChatUserDto { + chatUserName!: string; + messengerUserId!: string; + role!: RoleDto; + + constructor(data?: IChatUserDto) { + if (data) { + for (var property in data) { + if (data.hasOwnProperty(property)) + (this)[property] = (data)[property]; + } + } + } + + init(_data?: any, _mappings?: any) { + if (_data) { + this.chatUserName = _data["chatUserName"]; + this.messengerUserId = _data["messengerUserId"]; + this.role = _data["role"] ? RoleDto.fromJS(_data["role"], _mappings) : undefined; + } + } + + static fromJS(data: any, _mappings?: any): ChatUserDto | null { + data = typeof data === 'object' ? data : {}; + return createInstance(data, _mappings, ChatUserDto); + } + + toJSON(data?: any) { + data = typeof data === 'object' ? data : {}; + data["chatUserName"] = this.chatUserName; + data["messengerUserId"] = this.messengerUserId; + data["role"] = this.role ? this.role.toJSON() : undefined; + return data; + } +} + +export interface IChatUserDto { + chatUserName: string; + messengerUserId: string; + role: RoleDto; +} + +export class AddChannelCommand implements IAddChannelCommand { adminId!: string; name!: string; description!: string; - constructor(data?: IAddChannel) { + constructor(data?: IAddChannelCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2089,9 +2516,9 @@ export class AddChannel implements IAddChannel { } } - static fromJS(data: any, _mappings?: any): AddChannel | null { + static fromJS(data: any, _mappings?: any): AddChannelCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, AddChannel); + return createInstance(data, _mappings, AddChannelCommand); } toJSON(data?: any) { @@ -2103,18 +2530,18 @@ export class AddChannel implements IAddChannel { } } -export interface IAddChannel { +export interface IAddChannelCommand { adminId: string; name: string; description: string; } -export class AddGroupChat implements IAddGroupChat { +export class AddGroupChatCommand implements IAddGroupChatCommand { adminId!: string; name!: string; description!: string; - constructor(data?: IAddGroupChat) { + constructor(data?: IAddGroupChatCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2131,9 +2558,9 @@ export class AddGroupChat implements IAddGroupChat { } } - static fromJS(data: any, _mappings?: any): AddGroupChat | null { + static fromJS(data: any, _mappings?: any): AddGroupChatCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, AddGroupChat); + return createInstance(data, _mappings, AddGroupChatCommand); } toJSON(data?: any) { @@ -2145,19 +2572,19 @@ export class AddGroupChat implements IAddGroupChat { } } -export interface IAddGroupChat { +export interface IAddGroupChatCommand { adminId: string; name: string; description: string; } -export class AddPersonalChat implements IAddPersonalChat { +export class AddPersonalChatCommand implements IAddPersonalChatCommand { firstUserId!: string; secondUserId!: string; name!: string; description!: string; - constructor(data?: IAddPersonalChat) { + constructor(data?: IAddPersonalChatCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2175,9 +2602,9 @@ export class AddPersonalChat implements IAddPersonalChat { } } - static fromJS(data: any, _mappings?: any): AddPersonalChat | null { + static fromJS(data: any, _mappings?: any): AddPersonalChatCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, AddPersonalChat); + return createInstance(data, _mappings, AddPersonalChatCommand); } toJSON(data?: any) { @@ -2190,19 +2617,19 @@ export class AddPersonalChat implements IAddPersonalChat { } } -export interface IAddPersonalChat { +export interface IAddPersonalChatCommand { firstUserId: string; secondUserId: string; name: string; description: string; } -export class AddSavedMessages implements IAddSavedMessages { +export class AddSavedMessagesCommand implements IAddSavedMessagesCommand { userId!: string; name!: string; description!: string; - constructor(data?: IAddSavedMessages) { + constructor(data?: IAddSavedMessagesCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2219,9 +2646,9 @@ export class AddSavedMessages implements IAddSavedMessages { } } - static fromJS(data: any, _mappings?: any): AddSavedMessages | null { + static fromJS(data: any, _mappings?: any): AddSavedMessagesCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, AddSavedMessages); + return createInstance(data, _mappings, AddSavedMessagesCommand); } toJSON(data?: any) { @@ -2233,17 +2660,17 @@ export class AddSavedMessages implements IAddSavedMessages { } } -export interface IAddSavedMessages { +export interface IAddSavedMessagesCommand { userId: string; name: string; description: string; } -export class AddUserToChat implements IAddUserToChat { +export class AddUserToChatCommand implements IAddUserToChatCommand { userId!: string; chatId!: string; - constructor(data?: IAddUserToChat) { + constructor(data?: IAddUserToChatCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2259,9 +2686,9 @@ export class AddUserToChat implements IAddUserToChat { } } - static fromJS(data: any, _mappings?: any): AddUserToChat | null { + static fromJS(data: any, _mappings?: any): AddUserToChatCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, AddUserToChat); + return createInstance(data, _mappings, AddUserToChatCommand); } toJSON(data?: any) { @@ -2272,16 +2699,16 @@ export class AddUserToChat implements IAddUserToChat { } } -export interface IAddUserToChat { +export interface IAddUserToChatCommand { userId: string; chatId: string; } -export class DeleteUserFromChat implements IDeleteUserFromChat { +export class DeleteUserFromChatCommand implements IDeleteUserFromChatCommand { userId!: string; chatId!: string; - constructor(data?: IDeleteUserFromChat) { + constructor(data?: IDeleteUserFromChatCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2297,9 +2724,9 @@ export class DeleteUserFromChat implements IDeleteUserFromChat { } } - static fromJS(data: any, _mappings?: any): DeleteUserFromChat | null { + static fromJS(data: any, _mappings?: any): DeleteUserFromChatCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, DeleteUserFromChat); + return createInstance(data, _mappings, DeleteUserFromChatCommand); } toJSON(data?: any) { @@ -2310,16 +2737,16 @@ export class DeleteUserFromChat implements IDeleteUserFromChat { } } -export interface IDeleteUserFromChat { +export interface IDeleteUserFromChatCommand { userId: string; chatId: string; } -export class CreateRoleForChat implements ICreateRoleForChat { +export class CreateRoleForChatCommand implements ICreateRoleForChatCommand { role!: RoleDto; chatId!: string; - constructor(data?: ICreateRoleForChat) { + constructor(data?: ICreateRoleForChatCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2335,9 +2762,9 @@ export class CreateRoleForChat implements ICreateRoleForChat { } } - static fromJS(data: any, _mappings?: any): CreateRoleForChat | null { + static fromJS(data: any, _mappings?: any): CreateRoleForChatCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, CreateRoleForChat); + return createInstance(data, _mappings, CreateRoleForChatCommand); } toJSON(data?: any) { @@ -2348,17 +2775,17 @@ export class CreateRoleForChat implements ICreateRoleForChat { } } -export interface ICreateRoleForChat { +export interface ICreateRoleForChatCommand { role: RoleDto; chatId: string; } -export class ChangeRoleForUserById implements IChangeRoleForUserById { +export class ChangeRoleForUserByIdCommand implements IChangeRoleForUserByIdCommand { userId!: string; chatId!: string; role!: RoleDto; - constructor(data?: IChangeRoleForUserById) { + constructor(data?: IChangeRoleForUserByIdCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2375,9 +2802,9 @@ export class ChangeRoleForUserById implements IChangeRoleForUserById { } } - static fromJS(data: any, _mappings?: any): ChangeRoleForUserById | null { + static fromJS(data: any, _mappings?: any): ChangeRoleForUserByIdCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, ChangeRoleForUserById); + return createInstance(data, _mappings, ChangeRoleForUserByIdCommand); } toJSON(data?: any) { @@ -2389,17 +2816,63 @@ export class ChangeRoleForUserById implements IChangeRoleForUserById { } } -export interface IChangeRoleForUserById { +export interface IChangeRoleForUserByIdCommand { userId: string; chatId: string; role: RoleDto; } -export class SetUserNickNameById implements ISetUserNickNameById { +export class MessengerUserDto implements IMessengerUserDto { + id!: string; + name!: string | undefined; + userName!: string | undefined; + description!: string | undefined; + + constructor(data?: IMessengerUserDto) { + if (data) { + for (var property in data) { + if (data.hasOwnProperty(property)) + (this)[property] = (data)[property]; + } + } + } + + init(_data?: any, _mappings?: any) { + if (_data) { + this.id = _data["id"]; + this.name = _data["name"]; + this.userName = _data["userName"]; + this.description = _data["description"]; + } + } + + static fromJS(data: any, _mappings?: any): MessengerUserDto | null { + data = typeof data === 'object' ? data : {}; + return createInstance(data, _mappings, MessengerUserDto); + } + + toJSON(data?: any) { + data = typeof data === 'object' ? data : {}; + data["id"] = this.id; + data["name"] = this.name; + data["userName"] = this.userName; + data["description"] = this.description; + return data; + } +} + +export interface IMessengerUserDto { + id: string; + name: string | undefined; + userName: string | undefined; + description: string | undefined; +} + +export class SetUserNickNameByIdCommand implements ISetUserNickNameByIdCommand { userId!: string; - nickName!: string; + userName!: string; - constructor(data?: ISetUserNickNameById) { + constructor(data?: ISetUserNickNameByIdCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2411,32 +2884,32 @@ export class SetUserNickNameById implements ISetUserNickNameById { init(_data?: any, _mappings?: any) { if (_data) { this.userId = _data["userId"]; - this.nickName = _data["nickName"]; + this.userName = _data["userName"]; } } - static fromJS(data: any, _mappings?: any): SetUserNickNameById | null { + static fromJS(data: any, _mappings?: any): SetUserNickNameByIdCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, SetUserNickNameById); + return createInstance(data, _mappings, SetUserNickNameByIdCommand); } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["userId"] = this.userId; - data["nickName"] = this.nickName; + data["userName"] = this.userName; return data; } } -export interface ISetUserNickNameById { +export interface ISetUserNickNameByIdCommand { userId: string; - nickName: string; + userName: string; } -export class DeleteUser implements IDeleteUser { +export class DeleteUserCommand implements IDeleteUserCommand { userId!: string; - constructor(data?: IDeleteUser) { + constructor(data?: IDeleteUserCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2451,9 +2924,9 @@ export class DeleteUser implements IDeleteUser { } } - static fromJS(data: any, _mappings?: any): DeleteUser | null { + static fromJS(data: any, _mappings?: any): DeleteUserCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, DeleteUser); + return createInstance(data, _mappings, DeleteUserCommand); } toJSON(data?: any) { @@ -2463,16 +2936,16 @@ export class DeleteUser implements IDeleteUser { } } -export interface IDeleteUser { +export interface IDeleteUserCommand { userId: string; } -export class AddUser implements IAddUser { +export class AddUserCommand implements IAddUserCommand { name!: string; nickName!: string; description!: string; - constructor(data?: IAddUser) { + constructor(data?: IAddUserCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2489,9 +2962,9 @@ export class AddUser implements IAddUser { } } - static fromJS(data: any, _mappings?: any): AddUser | null { + static fromJS(data: any, _mappings?: any): AddUserCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, AddUser); + return createInstance(data, _mappings, AddUserCommand); } toJSON(data?: any) { @@ -2503,17 +2976,17 @@ export class AddUser implements IAddUser { } } -export interface IAddUser { +export interface IAddUserCommand { name: string; nickName: string; description: string; } -export class ChangeUserDescriptionById implements IChangeUserDescriptionById { +export class ChangeUserDescriptionByIdCommand implements IChangeUserDescriptionByIdCommand { userId!: string; description!: string; - constructor(data?: IChangeUserDescriptionById) { + constructor(data?: IChangeUserDescriptionByIdCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2529,9 +3002,9 @@ export class ChangeUserDescriptionById implements IChangeUserDescriptionById { } } - static fromJS(data: any, _mappings?: any): ChangeUserDescriptionById | null { + static fromJS(data: any, _mappings?: any): ChangeUserDescriptionByIdCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, ChangeUserDescriptionById); + return createInstance(data, _mappings, ChangeUserDescriptionByIdCommand); } toJSON(data?: any) { @@ -2542,16 +3015,16 @@ export class ChangeUserDescriptionById implements IChangeUserDescriptionById { } } -export interface IChangeUserDescriptionById { +export interface IChangeUserDescriptionByIdCommand { userId: string; description: string; } -export class ChangeUserNameById implements IChangeUserNameById { +export class ChangeUserNameByIdCommand implements IChangeUserNameByIdCommand { userId!: string; name!: string; - constructor(data?: IChangeUserNameById) { + constructor(data?: IChangeUserNameByIdCommand) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) @@ -2567,9 +3040,9 @@ export class ChangeUserNameById implements IChangeUserNameById { } } - static fromJS(data: any, _mappings?: any): ChangeUserNameById | null { + static fromJS(data: any, _mappings?: any): ChangeUserNameByIdCommand | null { data = typeof data === 'object' ? data : {}; - return createInstance(data, _mappings, ChangeUserNameById); + return createInstance(data, _mappings, ChangeUserNameByIdCommand); } toJSON(data?: any) { @@ -2580,7 +3053,7 @@ export class ChangeUserNameById implements IChangeUserNameById { } } -export interface IChangeUserNameById { +export interface IChangeUserNameByIdCommand { userId: string; name: string; } @@ -2646,13 +3119,6 @@ function createInstance(data: any, mappings: any, type: any): T | null { return result; } -export interface FileResponse { - data: Blob; - status: number; - fileName?: string; - headers?: { [name: string]: any }; -} - export class Do_Svyazi_User_ApiClient_Exception extends Error { override message: string; status: number; @@ -2678,10 +3144,7 @@ export class Do_Svyazi_User_ApiClient_Exception extends Error { } function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any { - if (result !== null && result !== undefined) - throw result; - else - throw new Do_Svyazi_User_ApiClient_Exception(message, status, response, headers, null); + throw new Do_Svyazi_User_ApiClient_Exception(message, status, response, headers, result); } function isAxiosError(obj: any | undefined): obj is AxiosError { diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package-lock.json b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package-lock.json index 2e92b54..85a2a1c 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package-lock.json +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package-lock.json @@ -1,13 +1,14 @@ { "name": "@do-svyazi/user.clients", - "version": "2.0.0", + "version": "2.1.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@do-svyazi/user.clients", - "version": "2.0.0", + "version": "2.1.0", "dependencies": { + "@types/node": "^18.0.3", "asynckit": "^0.4.0", "axios": "^0.27.2", "combined-stream": "^1.0.8", @@ -20,6 +21,11 @@ }, "devDependencies": {} }, + "node_modules/@types/node": { + "version": "18.0.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.3.tgz", + "integrity": "sha512-HzNRZtp4eepNitP+BD6k2L6DROIDG4Q0fm4x+dwfsr6LGmROENnok75VGw40628xf+iR24WeMFcHuuBDUAzzsQ==" + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -114,6 +120,11 @@ } }, "dependencies": { + "@types/node": { + "version": "18.0.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.3.tgz", + "integrity": "sha512-HzNRZtp4eepNitP+BD6k2L6DROIDG4Q0fm4x+dwfsr6LGmROENnok75VGw40628xf+iR24WeMFcHuuBDUAzzsQ==" + }, "asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package.json b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package.json index 6f3db8e..8f02e3e 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package.json +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/Frontend/package.json @@ -3,15 +3,15 @@ "version": "2.1.0", "description": "User module clients", "dependencies": { - "axios": "^0.27.2", + "@types/node": "^18.0.3", "asynckit": "^0.4.0", - "follow-redirects": "^1.15.1", + "axios": "^0.27.2", "combined-stream": "^1.0.8", - "form-data": "^4.0.0", "delayed-stream": "^1.0.0", - "mime-types": "^2.1.35", + "follow-redirects": "^1.15.1", + "form-data": "^4.0.0", "mime-db": "^1.52.0", + "mime-types": "^2.1.35", "moment": "^2.29.3" - }, - "devDependencies": {} + } } diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/nswag.json b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/nswag.json index 5b16940..f598733 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/nswag.json +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/nswag.json @@ -46,7 +46,7 @@ "createWebHostBuilderMethod": null, "startupType": null, "allowNullableBodyParameters": true, - "output": "openApiContracts.json", + "output": "swagger.json", "outputType": "OpenApi3", "newLineBehavior": "Auto", "assemblyPaths": [], @@ -57,25 +57,25 @@ }, "codeGenerators": { "openApiToCSharpClient": { - "clientBaseClass": null, + "clientBaseClass": "Do_SvyaziClientBase", "configurationClass": null, "generateClientClasses": true, "generateClientInterfaces": true, "clientBaseInterface": null, "injectHttpClient": true, - "disposeHttpClient": false, + "disposeHttpClient": true, "protectedMethods": [], "generateExceptionClasses": true, "exceptionClass": "Do_Svyazi_User_ApiClient_Exception", "wrapDtoExceptions": true, "useHttpClientCreationMethod": false, "httpClientType": "System.Net.Http.HttpClient", - "useHttpRequestMessageCreationMethod": false, + "useHttpRequestMessageCreationMethod": true, "useBaseUrl": true, "generateBaseUrlProperty": true, "generateSyncMethods": false, "exposeJsonSerializerSettings": false, - "clientClassAccessModifier": "internal", + "clientClassAccessModifier": "public", "typeAccessModifier": "public", "generateContractsOutput": true, "contractsNamespace": "Do_Svyazi.User.Web.ApiClient.Contracts", @@ -88,14 +88,14 @@ "queryNullValue": "", "className": "{controller}Client", "operationGenerationMode": "MultipleClientsFromOperationId", - "additionalNamespaceUsages": [], - "additionalContractNamespaceUsages": [], - "generateOptionalParameters": false, + "additionalNamespaceUsages": ["Do_Svyazi.User.Web.ApiClient.Backend"], + "additionalContractNamespaceUsages": ["Do_Svyazi.User.Web.ApiClient.Backend"], + "generateOptionalParameters": true, "generateJsonMethods": true, "enforceFlagEnums": false, "parameterArrayType": "System.Collections.Generic.IEnumerable", "parameterDictionaryType": "System.Collections.Generic.IDictionary", - "responseArrayType": "System.Collections.ObjectModel.ObservableCollection", + "responseArrayType": "System.Collections.Generic.IReadOnlyList", "responseDictionaryType": "System.Collections.Generic.Dictionary", "wrapResponses": false, "wrapResponseMethods": [], @@ -115,7 +115,7 @@ "dictionaryInstanceType": "System.Collections.Generic.Dictionary", "arrayBaseType": "System.Collections.ObjectModel.ObservableCollection", "dictionaryBaseType": "System.Collections.Generic.Dictionary", - "classStyle": "Poco", + "classStyle": "Record", "generateDefaultValues": true, "generateDataAnnotations": false, "excludedTypeNames": [], @@ -130,7 +130,7 @@ "inlineNamedAny": false, "generateDtoTypes": true, "generateOptionalPropertiesAsNullable": false, - "generateNullableReferenceTypes": false, + "generateNullableReferenceTypes": true, "templateDirectory": null, "typeNameGeneratorType": null, "propertyNameGeneratorType": null, @@ -157,9 +157,9 @@ "generateClientInterfaces": true, "generateOptionalParameters": true, "exportTypes": true, - "wrapDtoExceptions": false, + "wrapDtoExceptions": true, "exceptionClass": "Do_Svyazi_User_ApiClient_Exception", - "clientBaseClass": "", + "clientBaseClass": null, "wrapResponses": false, "wrapResponseMethods": [], "generateResponseClasses": true, diff --git a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/openApiContracts.json b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/swagger.json similarity index 62% rename from Source/Presentation/Do-Svyazi.User.Web.ApiClient/openApiContracts.json rename to Source/Presentation/Do-Svyazi.User.Web.ApiClient/swagger.json index 9ed813a..b81dc19 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.ApiClient/openApiContracts.json +++ b/Source/Presentation/Do-Svyazi.User.Web.ApiClient/swagger.json @@ -6,7 +6,43 @@ "version": "2.1.0" }, "paths": { - "/api/Authenticate/login": { + "/api/Authenticate/GetAll": { + "get": { + "tags": [ + "Authenticate" + ], + "operationId": "Authenticate_GetAll", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MessengerUser" + } + } + } + } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + } + } + } + }, + "/api/Authenticate/Login": { "post": { "tags": [ "Authenticate" @@ -17,7 +53,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Login" + "$ref": "#/components/schemas/LoginRequest" } } }, @@ -26,20 +62,25 @@ }, "responses": { "200": { + "description": "" + }, + "401": { "description": "", "content": { - "application/octet-stream": { + "application/json": { "schema": { - "type": "string", - "format": "binary" + "$ref": "#/components/schemas/ProblemDetails" } } } + }, + "500": { + "description": "" } } } }, - "/api/Authenticate/register": { + "/api/Authenticate/Register": { "post": { "tags": [ "Authenticate" @@ -50,7 +91,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Register" + "$ref": "#/components/schemas/RegisterCommand" } } }, @@ -59,20 +100,73 @@ }, "responses": { "200": { + "description": "" + }, + "401": { "description": "", "content": { - "application/octet-stream": { + "application/json": { "schema": { - "type": "string", - "format": "binary" + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" + } + } + } + }, + "/api/Authenticate/AuthenticateByJwt": { + "get": { + "tags": [ + "Authenticate" + ], + "operationId": "Authenticate_AuthenticateByJwt", + "parameters": [ + { + "name": "jwtToken", + "in": "header", + "required": true, + "schema": { + "type": "string", + "nullable": true + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthenticateResponse" + } + } + } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" } } } + }, + "500": { + "description": "" } } } }, - "/api/Authenticate/register-admin": { + "/api/Authenticate/RegisterAdmin": { "post": { "tags": [ "Authenticate" @@ -83,7 +177,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RegisterAdmin" + "$ref": "#/components/schemas/RegisterAdminCommand" } } }, @@ -92,15 +186,23 @@ }, "responses": { "200": { + "description": "" + }, + "401": { "description": "", "content": { - "application/octet-stream": { + "application/json": { "schema": { - "type": "string", - "format": "binary" + "$ref": "#/components/schemas/ProblemDetails" } } } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -124,6 +226,19 @@ } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" } } } @@ -156,6 +271,19 @@ } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" } } } @@ -192,6 +320,19 @@ } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" } } } @@ -222,11 +363,24 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/ChatUser" + "$ref": "#/components/schemas/ChatUserDto" } } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" } } } @@ -242,7 +396,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddChannel" + "$ref": "#/components/schemas/AddChannelCommand" } } }, @@ -252,6 +406,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "201": { + "description": "" } } } @@ -267,7 +437,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddGroupChat" + "$ref": "#/components/schemas/AddGroupChatCommand" } } }, @@ -277,6 +447,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "201": { + "description": "" } } } @@ -292,7 +478,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddPersonalChat" + "$ref": "#/components/schemas/AddPersonalChatCommand" } } }, @@ -302,6 +488,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "201": { + "description": "" } } } @@ -317,7 +519,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddSavedMessages" + "$ref": "#/components/schemas/AddSavedMessagesCommand" } } }, @@ -327,6 +529,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "201": { + "description": "" } } } @@ -342,7 +560,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddUserToChat" + "$ref": "#/components/schemas/AddUserToChatCommand" } } }, @@ -352,6 +570,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -367,7 +601,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeleteUserFromChat" + "$ref": "#/components/schemas/DeleteUserFromChatCommand" } } }, @@ -377,6 +611,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -419,6 +669,19 @@ } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" } } } @@ -430,11 +693,11 @@ ], "operationId": "Roles_CreateRoleForChat", "requestBody": { - "x-name": "createRoleForChat", + "x-name": "createRoleForChatCommand", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateRoleForChat" + "$ref": "#/components/schemas/CreateRoleForChatCommand" } } }, @@ -444,6 +707,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -455,11 +734,11 @@ ], "operationId": "Roles_ChangeRoleForUserById", "requestBody": { - "x-name": "changeRoleForUserById", + "x-name": "changeRoleForUserByIdCommand", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChangeRoleForUserById" + "$ref": "#/components/schemas/ChangeRoleForUserByIdCommand" } } }, @@ -469,6 +748,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -492,6 +787,19 @@ } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" } } } @@ -520,10 +828,23 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MessengerUser" + "$ref": "#/components/schemas/MessengerUserDto" + } + } + } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" } } } + }, + "500": { + "description": "" } } } @@ -559,8 +880,21 @@ } } } - } - } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + } + } } }, "/api/User/GetAllChatsIdsByUserId": { @@ -595,6 +929,19 @@ } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" } } } @@ -606,11 +953,11 @@ ], "operationId": "User_SetNickNameById", "requestBody": { - "x-name": "setUserNickNameById", + "x-name": "setUserNickNameByIdCommand", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetUserNickNameById" + "$ref": "#/components/schemas/SetUserNickNameByIdCommand" } } }, @@ -620,6 +967,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -631,11 +994,11 @@ ], "operationId": "User_DeleteUser", "requestBody": { - "x-name": "deleteUser", + "x-name": "deleteUserCommand", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeleteUser" + "$ref": "#/components/schemas/DeleteUserCommand" } } }, @@ -645,6 +1008,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -656,11 +1035,11 @@ ], "operationId": "User_AddUser", "requestBody": { - "x-name": "addUser", + "x-name": "addUserCommand", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AddUser" + "$ref": "#/components/schemas/AddUserCommand" } } }, @@ -678,6 +1057,30 @@ } } } + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "201": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "string", + "format": "guid" + } + } + } } } } @@ -689,11 +1092,11 @@ ], "operationId": "User_ChangeDescription", "requestBody": { - "x-name": "changeUserDescriptionById", + "x-name": "changeUserDescriptionByIdCommand", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChangeUserDescriptionById" + "$ref": "#/components/schemas/ChangeUserDescriptionByIdCommand" } } }, @@ -703,6 +1106,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -714,11 +1133,11 @@ ], "operationId": "User_ChangeName", "requestBody": { - "x-name": "changeUserNameById", + "x-name": "changeUserNameByIdCommand", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChangeUserNameById" + "$ref": "#/components/schemas/ChangeUserNameByIdCommand" } } }, @@ -728,6 +1147,22 @@ "responses": { "200": { "description": "" + }, + "401": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "500": { + "description": "" + }, + "204": { + "description": "" } } } @@ -735,7 +1170,122 @@ }, "components": { "schemas": { - "Login": { + "MessengerUser": { + "allOf": [ + { + "$ref": "#/components/schemas/IdentityUserOfGuid" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + } + } + } + ] + }, + "IdentityUserOfGuid": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "format": "guid" + }, + "userName": { + "type": "string", + "nullable": true + }, + "normalizedUserName": { + "type": "string", + "nullable": true + }, + "email": { + "type": "string", + "nullable": true + }, + "normalizedEmail": { + "type": "string", + "nullable": true + }, + "emailConfirmed": { + "type": "boolean" + }, + "passwordHash": { + "type": "string", + "nullable": true + }, + "securityStamp": { + "type": "string", + "nullable": true + }, + "concurrencyStamp": { + "type": "string", + "nullable": true + }, + "phoneNumber": { + "type": "string", + "nullable": true + }, + "phoneNumberConfirmed": { + "type": "boolean" + }, + "twoFactorEnabled": { + "type": "boolean" + }, + "lockoutEnd": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "lockoutEnabled": { + "type": "boolean" + }, + "accessFailedCount": { + "type": "integer", + "format": "int32" + } + } + }, + "ProblemDetails": { + "type": "object", + "additionalProperties": { + "nullable": true + }, + "properties": { + "type": { + "type": "string", + "nullable": true + }, + "title": { + "type": "string", + "nullable": true + }, + "status": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "detail": { + "type": "string", + "nullable": true + }, + "instance": { + "type": "string", + "nullable": true + }, + "extensions": { + "type": "object", + "additionalProperties": {} + } + } + }, + "LoginRequest": { "type": "object", "additionalProperties": false, "properties": { @@ -748,17 +1298,16 @@ "type": "object", "additionalProperties": false, "required": [ - "nickName", "password" ], "properties": { - "id": { + "userName": { "type": "string", - "format": "guid" + "nullable": true }, - "nickName": { + "email": { "type": "string", - "minLength": 1 + "nullable": true }, "password": { "type": "string", @@ -766,7 +1315,7 @@ } } }, - "Register": { + "RegisterCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -779,19 +1328,17 @@ "type": "object", "additionalProperties": false, "required": [ - "name", - "nickName", + "userName", "email", "password" ], "properties": { - "name": { + "userName": { "type": "string", "minLength": 1 }, - "nickName": { - "type": "string", - "minLength": 1 + "name": { + "type": "string" }, "email": { "type": "string", @@ -800,10 +1347,27 @@ "password": { "type": "string", "minLength": 1 + }, + "phoneNumber": { + "type": "string" + } + } + }, + "AuthenticateResponse": { + "type": "object", + "additionalProperties": false, + "properties": { + "userId": { + "type": "string", + "format": "guid" + }, + "validTo": { + "type": "string", + "format": "date-time" } } }, - "RegisterAdmin": { + "RegisterAdminCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -828,14 +1392,6 @@ "type": "string", "nullable": true }, - "creator": { - "nullable": true, - "oneOf": [ - { - "$ref": "#/components/schemas/MessengerUserDto" - } - ] - }, "users": { "type": "array", "items": { @@ -851,28 +1407,6 @@ } } }, - "MessengerUserDto": { - "type": "object", - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "format": "guid" - }, - "name": { - "type": "string", - "nullable": true - }, - "nickName": { - "type": "string", - "nullable": true - }, - "description": { - "type": "string", - "nullable": true - } - } - }, "RoleDto": { "type": "object", "additionalProperties": false, @@ -929,148 +1463,23 @@ 2 ] }, - "ChatUser": { + "ChatUserDto": { "type": "object", "additionalProperties": false, "properties": { - "user": { - "$ref": "#/components/schemas/MessengerUser" - }, - "id": { - "type": "string", - "format": "guid" + "chatUserName": { + "type": "string" }, "messengerUserId": { "type": "string", "format": "guid" }, - "chat": { - "$ref": "#/components/schemas/Chat" - }, - "chatId": { - "type": "string", - "format": "guid" - }, "role": { - "$ref": "#/components/schemas/Role" - } - } - }, - "MessengerUser": { - "type": "object", - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "format": "guid" - }, - "name": { - "type": "string" - }, - "nickName": { - "type": "string" - }, - "description": { - "type": "string" - }, - "chats": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Chat" - } - } - } - }, - "Chat": { - "type": "object", - "x-abstract": true, - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "format": "guid" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "creator": { - "$ref": "#/components/schemas/MessengerUser" - }, - "creatorId": { - "type": "string", - "format": "guid" - }, - "maxUsersAmount": { - "type": "integer", - "format": "int32" - }, - "users": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ChatUser" - } - }, - "roles": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Role" - } - } - } - }, - "Role": { - "type": "object", - "additionalProperties": false, - "properties": { - "id": { - "type": "string", - "format": "guid" - }, - "chat": { - "$ref": "#/components/schemas/Chat" - }, - "name": { - "type": "string" - }, - "canEditMessages": { - "$ref": "#/components/schemas/ActionOption" - }, - "canDeleteMessages": { - "$ref": "#/components/schemas/ActionOption" - }, - "canWriteMessages": { - "$ref": "#/components/schemas/ActionOption" - }, - "canReadMessages": { - "$ref": "#/components/schemas/ActionOption" - }, - "canAddUsers": { - "$ref": "#/components/schemas/ActionOption" - }, - "canDeleteUsers": { - "$ref": "#/components/schemas/ActionOption" - }, - "canPinMessages": { - "$ref": "#/components/schemas/ActionOption" - }, - "canSeeChannelMembers": { - "$ref": "#/components/schemas/ActionOption" - }, - "canInviteOtherUsers": { - "$ref": "#/components/schemas/ActionOption" - }, - "canEditChannelDescription": { - "$ref": "#/components/schemas/ActionOption" - }, - "canDeleteChat": { - "$ref": "#/components/schemas/ActionOption" + "$ref": "#/components/schemas/RoleDto" } } }, - "AddChannel": { + "AddChannelCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1086,7 +1495,7 @@ } } }, - "AddGroupChat": { + "AddGroupChatCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1102,7 +1511,7 @@ } } }, - "AddPersonalChat": { + "AddPersonalChatCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1122,7 +1531,7 @@ } } }, - "AddSavedMessages": { + "AddSavedMessagesCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1138,7 +1547,7 @@ } } }, - "AddUserToChat": { + "AddUserToChatCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1152,7 +1561,7 @@ } } }, - "DeleteUserFromChat": { + "DeleteUserFromChatCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1166,7 +1575,7 @@ } } }, - "CreateRoleForChat": { + "CreateRoleForChatCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1179,7 +1588,7 @@ } } }, - "ChangeRoleForUserById": { + "ChangeRoleForUserByIdCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1196,7 +1605,29 @@ } } }, - "SetUserNickNameById": { + "MessengerUserDto": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "format": "guid" + }, + "name": { + "type": "string", + "nullable": true + }, + "userName": { + "type": "string", + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + } + } + }, + "SetUserNickNameByIdCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1204,12 +1635,12 @@ "type": "string", "format": "guid" }, - "nickName": { + "userName": { "type": "string" } } }, - "DeleteUser": { + "DeleteUserCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1219,7 +1650,7 @@ } } }, - "AddUser": { + "AddUserCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1234,7 +1665,7 @@ } } }, - "ChangeUserDescriptionById": { + "ChangeUserDescriptionByIdCommand": { "type": "object", "additionalProperties": false, "properties": { @@ -1247,7 +1678,7 @@ } } }, - "ChangeUserNameById": { + "ChangeUserNameByIdCommand": { "type": "object", "additionalProperties": false, "properties": { diff --git a/Source/Presentation/Do-Svyazi.User.Web.Controllers/AuthenticateController.cs b/Source/Presentation/Do-Svyazi.User.Web.Controllers/AuthenticateController.cs index 08af849..1ce044d 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.Controllers/AuthenticateController.cs +++ b/Source/Presentation/Do-Svyazi.User.Web.Controllers/AuthenticateController.cs @@ -1,22 +1,36 @@ using System.IdentityModel.Tokens.Jwt; using Do_Svyazi.User.Application.CQRS.Authenticate.Commands; using Do_Svyazi.User.Application.CQRS.Authenticate.Queries; +using Do_Svyazi.User.Domain.Authenticate; +using Do_Svyazi.User.Domain.Users; using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Do_Svyazi.User.Web.Controllers; -[Route("api/[controller]")] [ApiController] +[Route("api/[controller]")] +[ProducesResponseType(StatusCodes.Status200OK)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status500InternalServerError)] public class AuthenticateController : ControllerBase { private readonly IMediator _mediator; public AuthenticateController(IMediator mediator) => _mediator = mediator; - [HttpPost] - [Route("login")] - public async Task Login([FromBody] Login model, CancellationToken cancellationToken) + [HttpGet(nameof(GetAll))] + [Authorize(Roles = MessageIdentityRole.Admin)] + public async Task>> GetAll(CancellationToken cancellationToken) + { + var response = await _mediator.Send(new GetUsersRequest(), cancellationToken); + return Ok(response); + } + + [HttpPost(nameof(Login))] + public async Task Login([FromBody] LoginRequest model, CancellationToken cancellationToken) { JwtSecurityToken token = await _mediator.Send(model, cancellationToken); return Ok(new @@ -26,19 +40,27 @@ public async Task Login([FromBody] Login model, CancellationToken }); } - [HttpPost] - [Route("register")] - public async Task Register([FromBody] Register model, CancellationToken cancellationToken) + [HttpPost(nameof(Register))] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Register([FromBody] RegisterCommand model, CancellationToken cancellationToken) { - await _mediator.Send(model, cancellationToken); - return Ok(); + var result = await _mediator.Send(model, cancellationToken); + return Ok(result); + } + + [HttpGet(nameof(AuthenticateByJwt))] + public async Task> AuthenticateByJwt( + [FromHeader] string jwtToken, CancellationToken cancellationToken) + { + var result = await _mediator.Send(new AuthenticateByJwtRequest(jwtToken), cancellationToken); + return Ok(result); } - [HttpPost] - [Route("register-admin")] - public async Task RegisterAdmin([FromBody] RegisterAdmin model, CancellationToken cancellationToken) + [HttpPost(nameof(RegisterAdmin))] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task RegisterAdmin([FromBody] RegisterAdminCommand model, CancellationToken cancellationToken) { await _mediator.Send(model, cancellationToken); - return Ok(); + return NoContent(); } } \ No newline at end of file diff --git a/Source/Presentation/Do-Svyazi.User.Web.Controllers/ChatController.cs b/Source/Presentation/Do-Svyazi.User.Web.Controllers/ChatController.cs index d16035b..2eb1111 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.Controllers/ChatController.cs +++ b/Source/Presentation/Do-Svyazi.User.Web.Controllers/ChatController.cs @@ -1,15 +1,21 @@ using Do_Svyazi.User.Application.CQRS.Chats.Commands; using Do_Svyazi.User.Application.CQRS.Chats.Queries; -using Do_Svyazi.User.Domain.Users; +using Do_Svyazi.User.Domain.Authenticate; using Do_Svyazi.User.Dtos.Chats; +using Do_Svyazi.User.Dtos.Users; using MediatR; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Do_Svyazi.User.Web.Controllers; -[Route("api/[controller]")] +[Authorize] [ApiController] +[Route("api/[controller]")] +[ProducesResponseType(StatusCodes.Status200OK)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status500InternalServerError)] public class ChatController : ControllerBase { private readonly IMediator _mediator; @@ -17,91 +23,89 @@ public class ChatController : ControllerBase public ChatController(IMediator mediator) => _mediator = mediator; [HttpGet(nameof(GetChats))] - [ProducesResponseType(StatusCodes.Status200OK)] + [Authorize(Roles = MessageIdentityRole.Admin)] public async Task>> GetChats(CancellationToken cancellationToken) { - var response = await _mediator.Send(new GetChats(), cancellationToken); + var response = await _mediator.Send(new GetChatsQuery(), cancellationToken); return Ok(response); } [HttpGet(nameof(GetChatById))] - [ProducesResponseType(StatusCodes.Status200OK)] public async Task> GetChatById( - [FromQuery] GetChatById getChatById, CancellationToken cancellationToken) + [FromQuery] GetChatByIdQuery getChatByIdQuery, CancellationToken cancellationToken) { - var response = await _mediator.Send(getChatById, cancellationToken); + var response = await _mediator.Send(getChatByIdQuery, cancellationToken); return Ok(response); } [HttpGet(nameof(GetUserIdsByChatId))] - [ProducesResponseType(StatusCodes.Status200OK)] public async Task>> GetUserIdsByChatId( - [FromQuery] GetUserIdsByChatId getUserIdsByChatId, CancellationToken cancellationToken) + [FromQuery] GetUserIdsByChatIdQuery getUserIdsByChatIdQuery, CancellationToken cancellationToken) { - var response = await _mediator.Send(getUserIdsByChatId, cancellationToken); + var response = await _mediator.Send(getUserIdsByChatIdQuery, cancellationToken); return Ok(response); } [HttpGet(nameof(GetUsersByChatId))] - [ProducesResponseType(StatusCodes.Status200OK)] - public async Task>> GetUsersByChatId( - [FromQuery] GetUsersByChatId getUsersByChatId, CancellationToken cancellationToken) + public async Task>> GetUsersByChatId( + [FromQuery] GetUsersByChatIdQuery getUsersByChatIdQuery, CancellationToken cancellationToken) { - var response = await _mediator.Send(getUsersByChatId, cancellationToken); + var response = await _mediator.Send(getUsersByChatIdQuery, cancellationToken); return Ok(response); } [HttpPost(nameof(AddChannel))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status201Created)] public async Task AddChannel( - AddChannel addChannelCommand, CancellationToken cancellationToken) + AddChannelCommand addChannelCommand, CancellationToken cancellationToken) { var response = await _mediator.Send(addChannelCommand, cancellationToken); - return Ok(response); + return Created(nameof(AddChannel), response); } [HttpPost(nameof(AddGroupChat))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status201Created)] public async Task AddGroupChat( - AddGroupChat addGroupChatCommand, CancellationToken cancellationToken) + AddGroupChatCommand addGroupChatCommand, CancellationToken cancellationToken) { var response = await _mediator.Send(addGroupChatCommand, cancellationToken); - return Ok(response); + return Created(nameof(AddGroupChat), response); } [HttpPost(nameof(AddPersonalChat))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status201Created)] public async Task AddPersonalChat( - AddPersonalChat addPersonalChatCommand, CancellationToken cancellationToken) + AddPersonalChatCommand addPersonalChatCommand, CancellationToken cancellationToken) { var response = await _mediator.Send(addPersonalChatCommand, cancellationToken); - return Ok(response); + return Created(nameof(AddPersonalChat), response); } [HttpPost(nameof(AddSavedMessages))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status201Created)] public async Task AddSavedMessages( - AddSavedMessages addSavedMessagesCommand, CancellationToken cancellationToken) + AddSavedMessagesCommand addSavedMessagesCommand, CancellationToken cancellationToken) { var response = await _mediator.Send(addSavedMessagesCommand, cancellationToken); - return Ok(response); + return Created(nameof(AddSavedMessages), response); } [HttpPost(nameof(AddUserToChat))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task AddUserToChat( - AddUserToChat addUserToChatCommand, CancellationToken cancellationToken) + AddUserToChatCommand addUserToChatCommand, CancellationToken cancellationToken) { - var response = await _mediator.Send(addUserToChatCommand, cancellationToken); - return Ok(response); + await _mediator.Send(addUserToChatCommand, cancellationToken); + return NoContent(); } [HttpDelete(nameof(DeleteUserFromChat))] - [ProducesResponseType(StatusCodes.Status200OK)] + [Authorize(Roles = MessageIdentityRole.Admin)] + [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task DeleteUserFromChat( - DeleteUserFromChat deleteUserFromChatCommand, CancellationToken cancellationToken) + DeleteUserFromChatCommand deleteUserFromChatCommand, CancellationToken cancellationToken) { - var response = await _mediator.Send(deleteUserFromChatCommand, cancellationToken); - return Ok(response); + await _mediator.Send(deleteUserFromChatCommand, cancellationToken); + return NoContent(); } } \ No newline at end of file diff --git a/Source/Presentation/Do-Svyazi.User.Web.Controllers/Helpers/AuthorizeAttribute.cs b/Source/Presentation/Do-Svyazi.User.Web.Controllers/Helpers/AuthorizeAttribute.cs new file mode 100644 index 0000000..3d52f92 --- /dev/null +++ b/Source/Presentation/Do-Svyazi.User.Web.Controllers/Helpers/AuthorizeAttribute.cs @@ -0,0 +1,21 @@ +// using Do_Svyazi.User.Domain.Authenticate; +// using Microsoft.AspNetCore.Mvc.Filters; +// +// namespace Do_Svyazi.User.Web.Controllers.Helpers; +// +// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +// public class AuthorizeAttribute : Attribute, IAuthorizationFilter +// { +// public AuthorizeAttribute() { } +// public AuthorizeAttribute(bool isEnabled) => IsEnabled = isEnabled; +// +// private bool IsEnabled { get; init; } +// +// public void OnAuthorization(AuthorizationFilterContext context) +// { +// if (!IsEnabled) return; +// +// if (context.HttpContext.Items["User"] is not MessageIdentityUser) +// throw new UnauthorizedAccessException(); +// } +// } \ No newline at end of file diff --git a/Source/Presentation/Do-Svyazi.User.Web.Controllers/Middlewares/AuthorizationMiddleware.cs b/Source/Presentation/Do-Svyazi.User.Web.Controllers/Middlewares/AuthorizationMiddleware.cs new file mode 100644 index 0000000..e7ce4d3 --- /dev/null +++ b/Source/Presentation/Do-Svyazi.User.Web.Controllers/Middlewares/AuthorizationMiddleware.cs @@ -0,0 +1,64 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Text; +using Do_Svyazi.User.Domain.Users; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; + +namespace Do_Svyazi.User.Web.Controllers.Middlewares; + +public class AuthorizationMiddleware +{ + private readonly RequestDelegate _next; + private readonly IConfiguration _configuration; + private readonly UserManager _userManager; + + public AuthorizationMiddleware( + RequestDelegate next, IConfiguration configuration, UserManager userManager) + { + _next = next; + _configuration = configuration; + _userManager = userManager; + } + + public async Task Invoke(HttpContext context) + { + var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); + + if (token != null) + await AttachUserToContext(context, token); + + await _next(context); + } + + private async Task AttachUserToContext(HttpContext context, string token) + { + try + { + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]); + tokenHandler.ValidateToken( + token, + new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateAudience = false, + ClockSkew = TimeSpan.Zero, + }, out SecurityToken validatedToken); + + var jwtToken = validatedToken as JwtSecurityToken; + string? userId = jwtToken?.Claims.First(x => x.Type == "jti").Value; + + var user = await _userManager.FindByIdAsync(userId); + context.Items["User"] = user; + } + catch + { + context.Response.StatusCode = 401; + await context.Response.WriteAsync("Wrong auth credentials"); + } + } +} \ No newline at end of file diff --git a/Source/Presentation/Do-Svyazi.User.Web.Controllers/Middlewares/ErrorHandlingMiddleware.cs b/Source/Presentation/Do-Svyazi.User.Web.Controllers/Middlewares/ErrorHandlingMiddleware.cs new file mode 100644 index 0000000..072b4f5 --- /dev/null +++ b/Source/Presentation/Do-Svyazi.User.Web.Controllers/Middlewares/ErrorHandlingMiddleware.cs @@ -0,0 +1,54 @@ +using Do_Svyazi.User.Domain.Exceptions; +using Microsoft.AspNetCore.Http; + +namespace Do_Svyazi.User.Web.Controllers.Middlewares; + +public class ErrorHandlingMiddleware +{ + private readonly RequestDelegate _next; + + public ErrorHandlingMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task Invoke(HttpContext context) + { + try + { + await _next(context); + } + catch (Do_Svyazi_User_BusinessLogicException e) + { + context.Response.StatusCode = 400; + await AttachErrorMessage(context, e); + } + catch (UnauthorizedAccessException e) + { + context.Response.StatusCode = 401; + await AttachErrorMessage(context, e); + } + catch (Do_Svyazi_User_NotFoundException e) + { + context.Response.StatusCode = 404; + await AttachErrorMessage(context, e); + } + catch (Exception e) + { + context.Response.StatusCode = 500; + await AttachErrorMessage(context, e); + } + } + + private async Task AttachErrorMessage(HttpContext context, Exception exception) + { + var message = new + { + message = exception.Message, + endpoint = $"{context.GetEndpoint()}", + stackTrace = exception.StackTrace, + }; + + await context.Response.WriteAsJsonAsync(message); + } +} \ No newline at end of file diff --git a/Source/Presentation/Do-Svyazi.User.Web.Controllers/RolesController.cs b/Source/Presentation/Do-Svyazi.User.Web.Controllers/RolesController.cs index 36c9696..7dac829 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.Controllers/RolesController.cs +++ b/Source/Presentation/Do-Svyazi.User.Web.Controllers/RolesController.cs @@ -2,13 +2,18 @@ using Do_Svyazi.User.Application.CQRS.Roles.Queries; using Do_Svyazi.User.Dtos.Roles; using MediatR; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Do_Svyazi.User.Web.Controllers; -[Route("api/[controller]")] +[Authorize] [ApiController] +[Route("api/[controller]")] +[ProducesResponseType(StatusCodes.Status200OK)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status500InternalServerError)] public class RolesController : ControllerBase { private readonly IMediator _mediator; @@ -16,29 +21,28 @@ public class RolesController : ControllerBase public RolesController(IMediator mediator) => _mediator = mediator; [HttpGet(nameof(GetRoleByUserId))] - [ProducesResponseType(StatusCodes.Status200OK)] public async Task> GetRoleByUserId( - [FromQuery] GetRoleByUserId getRoleByUserId, CancellationToken cancellationToken) + [FromQuery] GetRoleByUserIdQuery getRoleByUserIdQuery, CancellationToken cancellationToken) { - var response = await _mediator.Send(getRoleByUserId, cancellationToken); + var response = await _mediator.Send(getRoleByUserIdQuery, cancellationToken); return Ok(response); } [HttpPost(nameof(CreateRoleForChat))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task CreateRoleForChat( - CreateRoleForChat createRoleForChat, CancellationToken cancellationToken) + CreateRoleForChatCommand createRoleForChatCommand, CancellationToken cancellationToken) { - await _mediator.Send(createRoleForChat, cancellationToken); - return Ok(); + await _mediator.Send(createRoleForChatCommand, cancellationToken); + return NoContent(); } [HttpPost(nameof(ChangeRoleForUserById))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task ChangeRoleForUserById( - ChangeRoleForUserById changeRoleForUserById, CancellationToken cancellationToken) + ChangeRoleForUserByIdCommand changeRoleForUserByIdCommand, CancellationToken cancellationToken) { - await _mediator.Send(changeRoleForUserById, cancellationToken); - return Ok(); + await _mediator.Send(changeRoleForUserByIdCommand, cancellationToken); + return NoContent(); } } \ No newline at end of file diff --git a/Source/Presentation/Do-Svyazi.User.Web.Controllers/UserController.cs b/Source/Presentation/Do-Svyazi.User.Web.Controllers/UserController.cs index 23d530d..ca09146 100644 --- a/Source/Presentation/Do-Svyazi.User.Web.Controllers/UserController.cs +++ b/Source/Presentation/Do-Svyazi.User.Web.Controllers/UserController.cs @@ -1,16 +1,21 @@ using Do_Svyazi.User.Application.CQRS.Users.Commands; using Do_Svyazi.User.Application.CQRS.Users.Queries; -using Do_Svyazi.User.Domain.Users; +using Do_Svyazi.User.Domain.Authenticate; using Do_Svyazi.User.Dtos.Chats; using Do_Svyazi.User.Dtos.Users; using MediatR; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Do_Svyazi.User.Web.Controllers; -[Route("api/[controller]")] +[Authorize] [ApiController] +[Route("api/[controller]")] +[ProducesResponseType(StatusCodes.Status200OK)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status500InternalServerError)] public class UserController : ControllerBase { private readonly IMediator _mediator; @@ -18,79 +23,77 @@ public class UserController : ControllerBase public UserController(IMediator mediator) => _mediator = mediator; [HttpGet("GetAll")] - [ProducesResponseType(StatusCodes.Status200OK)] + [Authorize(Roles = MessageIdentityRole.Admin)] public async Task>> GetUsers(CancellationToken cancellationToken) { - var response = await _mediator.Send(new GetUsers(), cancellationToken); + var response = await _mediator.Send(new GetUsersQuery(), cancellationToken); return Ok(response); } [HttpGet(nameof(GetUser))] - [ProducesResponseType(StatusCodes.Status200OK)] - public async Task> GetUser( - [FromQuery] GetUser getUser, CancellationToken cancellationToken) + public async Task> GetUser( + [FromQuery] GetUserQuery getUserQuery, CancellationToken cancellationToken) { - var response = await _mediator.Send(getUser, cancellationToken); + var response = await _mediator.Send(getUserQuery, cancellationToken); return Ok(response); } [HttpGet(nameof(GetAllChatsByUserId))] - [ProducesResponseType(StatusCodes.Status200OK)] public async Task>> GetAllChatsByUserId( - [FromQuery] GetAllChatsByUserId getAllChatsByUserId, CancellationToken cancellationToken) + [FromQuery] GetAllChatsByUserIdQuery getAllChatsByUserIdQuery, CancellationToken cancellationToken) { - var response = await _mediator.Send(getAllChatsByUserId, cancellationToken); + var response = await _mediator.Send(getAllChatsByUserIdQuery, cancellationToken); return Ok(response); } [HttpGet(nameof(GetAllChatsIdsByUserId))] - [ProducesResponseType(StatusCodes.Status200OK)] public async Task>> GetAllChatsIdsByUserId( - [FromQuery] GetAllChatsIdsByUserId getAllChatsIdsByUserId, CancellationToken cancellationToken) + [FromQuery] GetAllChatsIdsByUserIdQuery getAllChatsIdsByUserIdQuery, CancellationToken cancellationToken) { - var response = await _mediator.Send(getAllChatsIdsByUserId, cancellationToken); + var response = await _mediator.Send(getAllChatsIdsByUserIdQuery, cancellationToken); return Ok(response); } [HttpPost(nameof(SetNickNameById))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task SetNickNameById( - SetUserNickNameById setUserNickNameById, CancellationToken cancellationToken) + SetUserNickNameByIdCommand setUserNickNameByIdCommand, CancellationToken cancellationToken) { - await _mediator.Send(setUserNickNameById, cancellationToken); - return Ok(); + await _mediator.Send(setUserNickNameByIdCommand, cancellationToken); + return NoContent(); } [HttpPost(nameof(DeleteUser))] - [ProducesResponseType(StatusCodes.Status200OK)] - public async Task DeleteUser(DeleteUser deleteUser, CancellationToken cancellationToken) + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task DeleteUser(DeleteUserCommand deleteUserCommand, CancellationToken cancellationToken) { - await _mediator.Send(deleteUser, cancellationToken); - return Ok(); + await _mediator.Send(deleteUserCommand, cancellationToken); + return NoContent(); } + [AllowAnonymous] [HttpPost(nameof(AddUser))] - [ProducesResponseType(StatusCodes.Status200OK)] - public async Task> AddUser(AddUser addUser, CancellationToken cancellationToken) + [ProducesResponseType(StatusCodes.Status201Created)] + public async Task> AddUser(AddUserCommand addUserCommand, CancellationToken cancellationToken) { - var response = await _mediator.Send(addUser, cancellationToken); - return Ok(response); + var response = await _mediator.Send(addUserCommand, cancellationToken); + return Created(nameof(AddUser), response); } [HttpPost(nameof(ChangeDescription))] - [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task ChangeDescription( - ChangeUserDescriptionById changeUserDescriptionById, CancellationToken cancellationToken) + ChangeUserDescriptionByIdCommand changeUserDescriptionByIdCommand, CancellationToken cancellationToken) { - await _mediator.Send(changeUserDescriptionById, cancellationToken); - return Ok(); + await _mediator.Send(changeUserDescriptionByIdCommand, cancellationToken); + return NoContent(); } [HttpPost(nameof(ChangeName))] - [ProducesResponseType(StatusCodes.Status200OK)] - public async Task ChangeName(ChangeUserNameById changeUserNameById, CancellationToken cancellationToken) + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task ChangeName(ChangeUserNameByIdCommand changeUserNameByIdCommand, CancellationToken cancellationToken) { - await _mediator.Send(changeUserNameById, cancellationToken); - return Ok(); + await _mediator.Send(changeUserNameByIdCommand, cancellationToken); + return NoContent(); } } \ No newline at end of file diff --git a/Source/Tests/CQRS.Tests/Extensions/MockExtensions.cs b/Source/Tests/CQRS.Tests/Extensions/MockExtensions.cs deleted file mode 100644 index 24b6d07..0000000 --- a/Source/Tests/CQRS.Tests/Extensions/MockExtensions.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Linq; -using Moq; - -namespace CQRS.Tests.Extensions; - -public static class MockExtensions -{ - private static void MockDbSet(Mock mock, T[] items) - { - IQueryable itemsQueryable = items.AsQueryable(); - - mock.As>() - .Setup(x => x.Provider) - .Returns(itemsQueryable.Provider); - - mock.As>() - .Setup(x => x.Expression) - .Returns(itemsQueryable.Expression); - - mock.As>() - .Setup(x => x.ElementType) - .Returns(itemsQueryable.ElementType); - - mock.As>() - .Setup(x => x.GetEnumerator()) - .Returns(itemsQueryable.GetEnumerator()); - } -} \ No newline at end of file diff --git a/Source/Tests/CQRS.Tests/UserTests.cs b/Source/Tests/CQRS.Tests/UserTests.cs deleted file mode 100644 index 396374f..0000000 --- a/Source/Tests/CQRS.Tests/UserTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using AutoFixture.Xunit2; -using Do_Svyazi.User.Application.CQRS.Users.Commands; -using Do_Svyazi.User.Application.CQRS.Users.Handlers; -using Do_Svyazi.User.DataAccess; -using Do_Svyazi.User.Domain.Users; -using EntityFrameworkCoreMock; -using FluentAssertions; -using Xunit; - -namespace CQRS.Tests; - -public class UserTests -{ - [Theory, AutoData] - public async Task AddUser_UserAdded([Greedy] MessengerUser user) - { - var dbContextMock = new DbContextMock(); - dbContextMock.CreateDbSetMock(x => x.Users, Array.Empty()); - - var usersCommandHandler = new UsersCommandHandler(dbContextMock.Object); - - var addUserCommand = new AddUser(user.Name, user.NickName, user.Description); - await usersCommandHandler.Handle(addUserCommand, CancellationToken.None); - - MessengerUser gainMessengerUser = dbContextMock.Object.Users.Single(); - - gainMessengerUser.Name.Should().Be(user.Name); - gainMessengerUser.NickName.Should().Be(user.NickName); - gainMessengerUser.Description.Should().Be(user.Description); - } - - [Theory, AutoData] - public async Task ChangeUserNameById_UserNameChanged( - [Greedy] MessengerUser user, - string newName) - { - var dbContextMock = new DbContextMock(); - dbContextMock.CreateDbSetMock(x => x.Users, new[] {user}); - - var usersCommandHandler = new UsersCommandHandler(dbContextMock.Object); - - var changeUserNameCommand = new ChangeUserNameById(user.Id, newName); - await usersCommandHandler.Handle(changeUserNameCommand, CancellationToken.None); - - MessengerUser gainMessengerUser = dbContextMock.Object.Users.Single(); - - gainMessengerUser.Name.Should().Be(newName); - } -} \ No newline at end of file diff --git a/Source/Tests/Integration.Tests/ChatAndUserInteraction.cs b/Source/Tests/Integration.Tests/ChatAndUserInteraction.cs new file mode 100644 index 0000000..a37c9f8 --- /dev/null +++ b/Source/Tests/Integration.Tests/ChatAndUserInteraction.cs @@ -0,0 +1,240 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using AutoMapper; +using Do_Svyazi.User.Application.CQRS.Authenticate.Commands; +using Do_Svyazi.User.Application.CQRS.Authenticate.Handlers; +using Do_Svyazi.User.Application.CQRS.Chats.Commands; +using Do_Svyazi.User.Application.CQRS.Chats.Handlers; +using Do_Svyazi.User.Application.CQRS.Chats.Queries; +using Do_Svyazi.User.Application.CQRS.Users.Handlers; +using Do_Svyazi.User.Application.CQRS.Users.Queries; +using Do_Svyazi.User.DataAccess; +using Do_Svyazi.User.Domain.Authenticate; +using Do_Svyazi.User.Domain.Users; +using Do_Svyazi.User.Dtos.Chats; +using Do_Svyazi.User.Dtos.Mapping; +using FluentAssertions; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using NUnit.Framework; + +namespace Integration.Tests; + +[TestFixture] +public class IntegrationTests : IDisposable +{ + private IMapper _mapper; + private DoSvaziDbContext _context; + private ApplicationDbContext _identityContext; + private UserManager _userManager; + private RoleManager _roleManager; + + [OneTimeSetUp] + public void Setup() + { + _mapper = new MapperConfiguration(c => + { + c.AddProfile(); + }).CreateMapper(); + + _context = new DoSvaziDbContext( + new DbContextOptionsBuilder() + .UseInMemoryDatabase("test_db") + .Options); + + _identityContext = new ApplicationDbContext( + new DbContextOptionsBuilder() + .UseInMemoryDatabase("user_identity_test_db") + .Options); + + _userManager = new UserManager( + new UserStore(_identityContext), null, + new PasswordHasher(), null, null, null, null, null, null); + + _roleManager = new RoleManager( + new RoleStore(_identityContext), null, null, null, null); + } + + [TearDown] + public void TearDown() + { + _context.Database.EnsureDeleted(); + _identityContext.Database.EnsureDeleted(); + } + + [Test] + public async Task AddUsersToChat_CheckUserHaveChat_CheckChatHaveUsers() + { + var chatsCommandHandler = new ChatsCommandHandler(_userManager, _context); + var authCommandHandler = new AuthenticateCommandHandler(_userManager, _roleManager); + var usersQueryHandler = new UsersQueryHandler(_userManager, _context, _mapper); + var chatsQueryHandler = new ChatsQueryHandler(_context, _mapper); + + RegisterModel userModel1 = CreateRegisterModel("name1", "nickname1", "email1", "phoneNumber1"); + RegisterModel userModel2 = CreateRegisterModel("name2", "nickname2", "email2", "phoneNumber2"); + + var userId1 = await authCommandHandler.Handle(new RegisterCommand(userModel1), CancellationToken.None); + var userId2 = await authCommandHandler.Handle(new RegisterCommand(userModel2), CancellationToken.None); + + Guid chatGroupId = await chatsCommandHandler.Handle(new AddGroupChatCommand(userId1, "chat1", "description1"), CancellationToken.None); + await chatsCommandHandler.Handle(new AddUserToChatCommand(userId2, chatGroupId), CancellationToken.None); + + var userChats1 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId1), CancellationToken.None); + var userChats2 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId2), CancellationToken.None); + MessengerChatDto chat = + await chatsQueryHandler.Handle(new GetChatByIdQuery(chatGroupId), CancellationToken.None); + + chat.Users.Should() + .Contain(userId1) + .And.Contain(userId2) + .And.HaveCount(2); + + userChats1.Should().Contain(chatGroupId).And.HaveCount(1); + userChats2.Should().Contain(chatGroupId).And.HaveCount(1); + } + + [Test] + public async Task DeleteUserFromChat_CheckUserNotHaveChat() + { + var chatsCommandHandler = new ChatsCommandHandler(_userManager, _context); + var authCommandHandler = new AuthenticateCommandHandler(_userManager, _roleManager); + var usersQueryHandler = new UsersQueryHandler(_userManager, _context, _mapper); + var chatsQueryHandler = new ChatsQueryHandler(_context, _mapper); + + RegisterModel userModel1 = CreateRegisterModel("name1", "nickname1", "email1", "phoneNumber1"); + RegisterModel userModel2 = CreateRegisterModel("name2", "nickname2", "email2", "phoneNumber2"); + RegisterModel userModel3 = CreateRegisterModel("name3", "nickname3", "email3", "phoneNumber3"); + + Guid userId1 = await authCommandHandler.Handle(new RegisterCommand(userModel1), CancellationToken.None); + Guid userId2 = await authCommandHandler.Handle(new RegisterCommand(userModel2), CancellationToken.None); + Guid userId3 = await authCommandHandler.Handle(new RegisterCommand(userModel3), CancellationToken.None); + + var addGroupChat = new AddGroupChatCommand(userId1, "chat1", "description1"); + Guid chatGroupId = await chatsCommandHandler.Handle(addGroupChat, CancellationToken.None); + + var addUserToChatCommand = new AddUserToChatCommand(userId2, chatGroupId); + await chatsCommandHandler.Handle(addUserToChatCommand, CancellationToken.None); + addUserToChatCommand = new AddUserToChatCommand(userId3, chatGroupId); + await chatsCommandHandler.Handle(addUserToChatCommand, CancellationToken.None); + + var userChats1 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId1), CancellationToken.None); + var userChats2 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId2), CancellationToken.None); + var userChats3 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId3), CancellationToken.None); + + userChats1.Should().Contain(chatGroupId).And.HaveCount(1); + userChats2.Should().Contain(chatGroupId).And.HaveCount(1); + userChats3.Should().Contain(chatGroupId).And.HaveCount(1); + + await chatsCommandHandler.Handle(new DeleteUserFromChatCommand(userId3, chatGroupId), CancellationToken.None); + userChats3 = await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId3), CancellationToken.None); + + MessengerChatDto chat = + await chatsQueryHandler.Handle(new GetChatByIdQuery(chatGroupId), CancellationToken.None); + + chat.Users.Should().NotContain(userId3).And.HaveCount(2); + userChats3.Should().NotContain(chatGroupId).And.HaveCount(0); + } + + [Test] + public async Task UserCreateFourChats() + { + var chatsCommandHandler = new ChatsCommandHandler(_userManager, _context); + var authCommandHandler = new AuthenticateCommandHandler(_userManager, _roleManager); + var usersQueryHandler = new UsersQueryHandler(_userManager, _context, _mapper); + var chatsQueryHandler = new ChatsQueryHandler(_context, _mapper); + + RegisterModel userModel1 = CreateRegisterModel("name1", "nickname1", "email1", "phoneNumber1"); + RegisterModel userModel2 = CreateRegisterModel("name2", "nickname2", "email2", "phoneNumber2"); + Guid userId1 = await authCommandHandler.Handle(new RegisterCommand(userModel1), CancellationToken.None); + Guid userId2 = await authCommandHandler.Handle(new RegisterCommand(userModel2), CancellationToken.None); + + var addGroupChat = new AddGroupChatCommand(userId1, "chat1", "description1"); + Guid chatGroupId1 = await chatsCommandHandler.Handle(addGroupChat, CancellationToken.None); + var userChats1 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId1), CancellationToken.None); + + userChats1.Should().HaveCount(1); + + var addSavedMessages = new AddSavedMessagesCommand(userId1, "chat2", "description2"); + Guid chatGroupId2 = await chatsCommandHandler.Handle(addSavedMessages, CancellationToken.None); + + userChats1 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId1), CancellationToken.None); + + userChats1.Should().HaveCount(2); + + var addChannel = new AddChannelCommand(userId1, "chat3", "description3"); + Guid chatGroupId3 = await chatsCommandHandler.Handle(addChannel, CancellationToken.None); + + userChats1 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId1), CancellationToken.None); + + userChats1.Should().HaveCount(3); + + var addPersonalChat = new AddPersonalChatCommand(userId1, userId2, "chat4", "description4"); + Guid chatGroupId4 = await chatsCommandHandler.Handle(addPersonalChat, CancellationToken.None); + + userChats1 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId1), CancellationToken.None); + var userChats2 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId2), CancellationToken.None); + + userChats1.Should().HaveCount(4); + userChats2.Should().HaveCount(1); + } + + + [Test] + public async Task CreatePersonalChat() + { + var chatsCommandHandler = new ChatsCommandHandler(_userManager, _context); + var authCommandHandler = new AuthenticateCommandHandler(_userManager, _roleManager); + var usersQueryHandler = new UsersQueryHandler(_userManager, _context, _mapper); + var chatsQueryHandler = new ChatsQueryHandler(_context, _mapper); + + RegisterModel userModel1 = CreateRegisterModel("name1", "nickname1", "email1", "phoneNumber1"); + RegisterModel userModel2 = CreateRegisterModel("name2", "nickname2", "email2", "phoneNumber2"); + Guid userId1 = await authCommandHandler.Handle(new RegisterCommand(userModel1), CancellationToken.None); + Guid userId2 = await authCommandHandler.Handle(new RegisterCommand(userModel2), CancellationToken.None); + + var addPersonalChat = new AddPersonalChatCommand(userId1, userId2, "chat1", "description1"); + Guid chatGroupId1 = await chatsCommandHandler.Handle(addPersonalChat, CancellationToken.None); + + var userChats1 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId1), CancellationToken.None); + var userChats2 = + await usersQueryHandler.Handle(new GetAllChatsIdsByUserIdQuery(userId2), CancellationToken.None); + + var getChatById = new GetChatByIdQuery(chatGroupId1); + var chat = await chatsQueryHandler.Handle(getChatById, CancellationToken.None); + + chat.Users.Should() + .Contain(userId1).And + .Contain(userId2).And + .HaveCount(2); + userChats1.Should().HaveCount(1); + userChats2.Should().HaveCount(1); + } + + public void Dispose() + { + _context.Dispose(); + _identityContext.Dispose(); + } + + private RegisterModel CreateRegisterModel(string userName, string name, string email, string phoneNumber) => new() + { + UserName = userName, + Name = name, + Email = email, + Password = $"Test??111{Guid.NewGuid()}", + PhoneNumber = phoneNumber, + }; +} \ No newline at end of file diff --git a/Source/Tests/Integration.Tests/IntegrationTests.cs b/Source/Tests/Integration.Tests/IntegrationTests.cs deleted file mode 100644 index e8c2ed1..0000000 --- a/Source/Tests/Integration.Tests/IntegrationTests.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using AutoMapper; -using Do_Svyazi.User.Application.CQRS.Chats.Commands; -using Do_Svyazi.User.Application.CQRS.Chats.Handlers; -using Do_Svyazi.User.Application.CQRS.Chats.Queries; -using Do_Svyazi.User.Application.CQRS.Users.Commands; -using Do_Svyazi.User.Application.CQRS.Users.Handlers; -using Do_Svyazi.User.Application.CQRS.Users.Queries; -using Do_Svyazi.User.DataAccess; -using Do_Svyazi.User.Domain.Users; -using Do_Svyazi.User.Dtos.Chats; -using Do_Svyazi.User.Dtos.Mapping; -using FluentAssertions; -using Microsoft.EntityFrameworkCore; -using NUnit.Framework; - -namespace Integration.Tests; - -[TestFixture] -public class IntegrationTests : IDisposable -{ - private DoSvaziDbContext _context; - - [SetUp] - public void Setup() - { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase("test_db") - .Options; - - _context = new DoSvaziDbContext(options); - } - - [TearDown] - public void TearDown() => _context.Database.EnsureDeleted(); - - [Test] - public async Task AddUsersToChat_CheckUserHaveChat_CheckChatHaveUsers() - { - var messengerUser1 = new MessengerUser("name1", "nickname1", "description1"); - var messengerUser2 = new MessengerUser("name2", "nickname2", "description2"); - - var mapper = GenerateMapper(); - var chatsCommandHandler = new ChatsCommandHandler(_context); - var usersCommandHandler = new UsersCommandHandler(_context); - var usersQueryHandler = new UsersQueryHandler(_context, mapper); - var chatsQueryHandler = new ChatsQueryHandler(_context, mapper); - - var addUser = new AddUser(messengerUser1.Name, messengerUser1.NickName, messengerUser1.Description); - Guid userId1 = await usersCommandHandler.Handle(addUser, CancellationToken.None); - - addUser = new AddUser(messengerUser2.Name, messengerUser2.NickName, messengerUser2.Description); - Guid userId2 = await usersCommandHandler.Handle(addUser, CancellationToken.None); - - var addGroupChat = new AddGroupChat(userId1, "chat1", "description1"); - Guid chatGroupId = await chatsCommandHandler.Handle(addGroupChat, CancellationToken.None); - - var addUserToChatCommand = new AddUserToChat(userId2, chatGroupId); - await chatsCommandHandler.Handle(addUserToChatCommand, CancellationToken.None); - - var getAllChatsIdsByUserId = new GetAllChatsIdsByUserId(userId1); - var userChats1 = await usersQueryHandler.Handle(getAllChatsIdsByUserId, CancellationToken.None); - - getAllChatsIdsByUserId = new GetAllChatsIdsByUserId(userId2); - var userChats2 = await usersQueryHandler.Handle(getAllChatsIdsByUserId, CancellationToken.None); - var getChatById = new GetChatById(chatGroupId); - MessengerChatDto chat = await chatsQueryHandler.Handle(getChatById, CancellationToken.None); - - chat.Users.Should().Contain(userId1) - .And.Contain(userId2) - .And.HaveCount(2); - userChats1.Should().Contain(chatGroupId).And.HaveCount(1); - userChats2.Should().Contain(chatGroupId).And.HaveCount(1); - } - - [Test] - public async Task DeleteUserFromChat_CheckUserNotHaveChat() - { - var messengerUser1 = new MessengerUser("name1", "nickname1", "description1"); - var messengerUser2 = new MessengerUser("name2", "nickname2", "description2"); - var messengerUser3 = new MessengerUser("name3", "nickname3", "description3"); - - var mapper = GenerateMapper(); - var chatsCommandHandler = new ChatsCommandHandler(_context); - var usersCommandHandler = new UsersCommandHandler(_context); - var usersQueryHandler = new UsersQueryHandler(_context, mapper); - var chatsQueryHandler = new ChatsQueryHandler(_context, mapper); - - var addUser = new AddUser(messengerUser1.Name, messengerUser1.NickName, messengerUser1.Description); - Guid userId1 = await usersCommandHandler.Handle(addUser, CancellationToken.None); - addUser = new AddUser(messengerUser2.Name, messengerUser2.NickName, messengerUser2.Description); - Guid userId2 = await usersCommandHandler.Handle(addUser, CancellationToken.None); - addUser = new AddUser(messengerUser3.Name, messengerUser3.NickName, messengerUser3.Description); - Guid userId3 = await usersCommandHandler.Handle(addUser, CancellationToken.None); - - var addGroupChat = new AddGroupChat(userId1, "chat1", "description1"); - Guid chatGroupId = await chatsCommandHandler.Handle(addGroupChat, CancellationToken.None); - - var addUserToChatCommand = new AddUserToChat(userId2, chatGroupId); - await chatsCommandHandler.Handle(addUserToChatCommand, CancellationToken.None); - addUserToChatCommand = new AddUserToChat(userId3, chatGroupId); - await chatsCommandHandler.Handle(addUserToChatCommand, CancellationToken.None); - - var getAllChatsIdsByUserId = new GetAllChatsIdsByUserId(userId1); - var userChats1 = await usersQueryHandler.Handle(getAllChatsIdsByUserId, CancellationToken.None); - - getAllChatsIdsByUserId = new GetAllChatsIdsByUserId(userId2); - var userChats2 = await usersQueryHandler.Handle(getAllChatsIdsByUserId, CancellationToken.None); - - getAllChatsIdsByUserId = new GetAllChatsIdsByUserId(userId3); - var userChats3 = await usersQueryHandler.Handle(getAllChatsIdsByUserId, CancellationToken.None); - - userChats1.Should().Contain(chatGroupId).And.HaveCount(1); - userChats2.Should().Contain(chatGroupId).And.HaveCount(1); - userChats3.Should().Contain(chatGroupId).And.HaveCount(1); - - var deleteUserFromChat = new DeleteUserFromChat(userId3, chatGroupId); - await chatsCommandHandler.Handle(deleteUserFromChat, CancellationToken.None); - getAllChatsIdsByUserId = new GetAllChatsIdsByUserId(userId3); - userChats3 = await usersQueryHandler.Handle(getAllChatsIdsByUserId, CancellationToken.None); - - var getChatById = new GetChatById(chatGroupId); - MessengerChatDto chat = await chatsQueryHandler.Handle(getChatById, CancellationToken.None); - - chat.Users.Should().NotContain(userId3).And.HaveCount(2); - userChats3.Should().NotContain(chatGroupId).And.HaveCount(0); - } - - public static IMapper GenerateMapper() - { - var mapperConfig = new MapperConfiguration(c => - { - c.AddProfile(); - }); - - return mapperConfig.CreateMapper(); - } - - public void Dispose() - { - _context.Dispose(); - } -} \ No newline at end of file diff --git a/Source/Tests/CQRS.Tests/ChatTests.cs b/Source/Tests/Unit.Tests/CQRS/ChatTests.cs similarity index 58% rename from Source/Tests/CQRS.Tests/ChatTests.cs rename to Source/Tests/Unit.Tests/CQRS/ChatTests.cs index e956eda..b611f47 100644 --- a/Source/Tests/CQRS.Tests/ChatTests.cs +++ b/Source/Tests/Unit.Tests/CQRS/ChatTests.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AutoFixture; @@ -10,26 +10,32 @@ using Do_Svyazi.User.Domain.Users; using EntityFrameworkCoreMock; using FluentAssertions; +using Microsoft.AspNetCore.Identity; +using Moq; using Xunit; +using static CQRS.Tests.Extensions.MockExtensions; -namespace CQRS.Tests; +namespace CQRS.Tests.CQRS; public class ChatTests { [Theory, AutoData] public async Task AddUserToChat_UserAdded( IFixture fixture, - [Greedy] MessengerUser user, + MessengerUser user, [Greedy] GroupChat chat) { - var dbContextMock = new DbContextMock(); + var users = new List {user}; + + var mockUserManager = MockUserManager, MessengerUser>(users); + mockUserManager.Setup( userManager => userManager.FindByIdAsync($"{user.Id}")).ReturnsAsync(user); + var dbContextMock = new DbContextMock(); dbContextMock.CreateDbSetMock(x => x.Chats, new[] {chat}); - dbContextMock.CreateDbSetMock(x => x.Users, new[] {user}); dbContextMock.CreateDbSetMock(x => x.ChatUsers); - var addUserToChatHandler = new ChatsCommandHandler(dbContextMock.Object); - var addUserToChatCommand = new AddUserToChat(user.Id, chat.Id); + var addUserToChatHandler = new ChatsCommandHandler(mockUserManager.Object, dbContextMock.Object); + var addUserToChatCommand = new AddUserToChatCommand(user.Id, chat.Id); // as soon as we have chat creator chat.Users.Should().HaveCount(1); @@ -38,35 +44,36 @@ public async Task AddUserToChat_UserAdded( ChatUser expectedChatUser = fixture.Build() .With(chatUser => chatUser.Chat, chat) - .With(chatUser => chatUser.User, user) .With(chatUser => chatUser.ChatId, chat.Id) .With(chatUser => chatUser.MessengerUserId, user.Id) .Create(); - chat.Users.Should().HaveCount(2); - chat.Users.Should().Contain(expectedChatUser); + chat.Users.Should().Contain(expectedChatUser).And.HaveCount(2); } [Theory, AutoData] public async Task DeleteUserFromChat_UsersListEmpty( - [Greedy] MessengerUser user, + MessengerUser user, [Greedy] GroupChat chat) { - var dbContextMock = new DbContextMock(); + var users = new List {user}; + + var mockUserManager = MockUserManager, MessengerUser>(users); + mockUserManager.Setup( userManager => userManager.FindByIdAsync($"{user.Id}")).ReturnsAsync(user); + var dbContextMock = new DbContextMock(); dbContextMock.CreateDbSetMock(x => x.Chats, new[] {chat}); - dbContextMock.CreateDbSetMock(x => x.Users, new[] {user}); dbContextMock.CreateDbSetMock(x => x.ChatUsers); - var chatsCommandHandler = new ChatsCommandHandler(dbContextMock.Object); + var chatsCommandHandler = new ChatsCommandHandler(mockUserManager.Object, dbContextMock.Object); - var addUserToChatCommand = new AddUserToChat(user.Id, chat.Id); + var addUserToChatCommand = new AddUserToChatCommand(user.Id, chat.Id); await chatsCommandHandler.Handle(addUserToChatCommand, CancellationToken.None); // as soon as we have chat creator chat.Users.Should().HaveCount(2); - var deleteUserFromChatCommand = new DeleteUserFromChat(user.Id, chat.Id); + var deleteUserFromChatCommand = new DeleteUserFromChatCommand(user.Id, chat.Id); await chatsCommandHandler.Handle(deleteUserFromChatCommand, CancellationToken.None); chat.Users.Should().HaveCount(1); diff --git a/Source/Tests/Unit.Tests/CQRS/UserTests.cs b/Source/Tests/Unit.Tests/CQRS/UserTests.cs new file mode 100644 index 0000000..77c1450 --- /dev/null +++ b/Source/Tests/Unit.Tests/CQRS/UserTests.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.Xunit2; +using Do_Svyazi.User.Application.CQRS.Authenticate.Commands; +using Do_Svyazi.User.Application.CQRS.Authenticate.Handlers; +using Do_Svyazi.User.Application.CQRS.Users.Commands; +using Do_Svyazi.User.Application.CQRS.Users.Handlers; +using Do_Svyazi.User.Domain.Authenticate; +using Do_Svyazi.User.Domain.Users; +using FluentAssertions; +using Microsoft.AspNetCore.Identity; +using Moq; +using Xunit; +using static CQRS.Tests.Extensions.MockExtensions; + +namespace CQRS.Tests.CQRS; + +public class UserTests +{ + [Theory, AutoData] + public async Task AddUser_UserAdded([Frozen] IFixture fixture, MessengerUser messengerUser) + { + var users = new List(); + + var mockUserManager = MockUserManager, MessengerUser>(users); + var mockRoleManager = MockRoleManager, MessageIdentityRole>(); + + var usersCommandHandler = new AuthenticateCommandHandler(mockUserManager.Object, mockRoleManager.Object); + + RegisterModel registerModel = fixture.Build() + .With(model => model.Email, messengerUser.Email) + .With(model => model.Name, messengerUser.UserName) + .With(model => model.UserName, messengerUser.UserName) + .With(model => model.PhoneNumber, messengerUser.PhoneNumber) + .Create(); + + var addUserCommand = new RegisterCommand(registerModel); + await usersCommandHandler.Handle(addUserCommand, CancellationToken.None); + + MessengerUser gainMessengerUser = mockUserManager.Object.Users.Single(); + + gainMessengerUser.UserName.Should().Be(registerModel.UserName); + gainMessengerUser.Name.Should().Be(registerModel.Name); + gainMessengerUser.Email.Should().Be(registerModel.Email); + gainMessengerUser.PhoneNumber.Should().Be(registerModel.PhoneNumber); + } + + [Theory, AutoData] + public async Task ChangeUserNameById_UserNameChanged(MessengerUser user, string newName) + { + var users = new List {user}; + + var mockUserManager = MockUserManager, MessengerUser>(users); + mockUserManager.Setup( userManager => userManager.FindByIdAsync($"{user.Id}")).ReturnsAsync(user); + + var usersCommandHandler = new UsersCommandHandler(mockUserManager.Object); + var changeUserNameCommand = new ChangeUserNameByIdCommand(user.Id, newName); + await usersCommandHandler.Handle(changeUserNameCommand, CancellationToken.None); + + MessengerUser gainMessengerUser = mockUserManager.Object.Users.Single(); + + gainMessengerUser.Name.Should().Be(newName); + } +} \ No newline at end of file diff --git a/Source/Tests/Unit.Tests/Extensions/MockExtensions.cs b/Source/Tests/Unit.Tests/Extensions/MockExtensions.cs new file mode 100644 index 0000000..1611c56 --- /dev/null +++ b/Source/Tests/Unit.Tests/Extensions/MockExtensions.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Identity; +using MockQueryable.Moq; +using Moq; + +namespace CQRS.Tests.Extensions; + +public static class MockExtensions +{ + public static void MockDbSet(Mock mock, T[] items) + { + IQueryable itemsQueryable = items.AsQueryable(); + + mock.As>() + .Setup(x => x.Provider) + .Returns(itemsQueryable.Provider); + + mock.As>() + .Setup(x => x.Expression) + .Returns(itemsQueryable.Expression); + + mock.As>() + .Setup(x => x.ElementType) + .Returns(itemsQueryable.ElementType); + + mock.As>() + .Setup(x => x.GetEnumerator()) + .Returns(itemsQueryable.GetEnumerator()); + } + + public static Mock MockUserManager(List? users = null) + where TOut : class + where T : UserManager + { + var mock = new Mock(new Mock>().Object, null, null, null, null, null, null, null, null); + mock.Object.PasswordValidators.Add(new PasswordValidator()); + + if (users != null) + { + mock.Setup(x => x.CreateAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(IdentityResult.Success) + .Callback((x, y) => users.Add(x)); + + mock.Setup(x => x.Users).Returns(users.AsQueryable().BuildMock()); + } + + + return mock; + } + + public static Mock MockRoleManager() + where TOut : class + where T : RoleManager + { + var mock = new Mock(new Mock>().Object, new RoleValidator[] { }, null, null, null); + + return mock; + } +} \ No newline at end of file diff --git a/Source/Tests/CQRS.Tests/CQRS.Tests.csproj b/Source/Tests/Unit.Tests/Unit.Tests.csproj similarity index 79% rename from Source/Tests/CQRS.Tests/CQRS.Tests.csproj rename to Source/Tests/Unit.Tests/Unit.Tests.csproj index ec4480b..d36c314 100644 --- a/Source/Tests/CQRS.Tests/CQRS.Tests.csproj +++ b/Source/Tests/Unit.Tests/Unit.Tests.csproj @@ -3,8 +3,9 @@ net6.0 enable - false + true + CQRS.Tests @@ -17,6 +18,8 @@ + + @@ -34,4 +37,10 @@ + + + ..\..\..\..\..\..\.nuget\packages\mockqueryable.moq\6.0.1\lib\net6.0\MockQueryable.Moq.dll + + +