public async void Register_WithUniqueEmail_Ok()
        {
            // Arrange
            var client   = _server.Instance.CreateClient();
            var loginReq = new RegisterRequestDTO
            {
                ConfirmPassword = "******",
                Password        = "******",
                Email           = "*****@*****.**",
                UserName        = "******"
            };

            // Act
            var content = new StringContent(JsonConvert.SerializeObject(loginReq), Encoding.UTF8, "application/json");

            var response = await client.PostAsync("api/auth/register", content);

            var stream = await response.Content.ReadAsStreamAsync();

            TokenResponseDTO data = null;

            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                data = JsonConvert.DeserializeObject <TokenResponseDTO>(await reader.ReadToEndAsync());
            }

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(data.AccessToken);
            Assert.NotNull(data.RefreshToken);
        }
        public void TestCheckWithDuplicateEmail()
        {
            // Arrange
            var registerRequest = new RegisterRequestDTO
            {
                UserName           = "******",
                FirstName          = "New",
                LastName           = "User",
                DateOfBirth        = new DateTime(),
                PhoneNumber        = "123459",
                Email              = "*****@*****.**",
                MedicalInformation = "N/A",
                BankAccount        = "84903",
                Password           = "******"
            };

            var duplicateRegisterRequest = new RegisterRequestDTO
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            // Act
            _ = _userController.Register(registerRequest);
            var checkUserResponse = _userController.CheckUser(duplicateRegisterRequest);

            // Assert
            Assert.That(checkUserResponse, Is.InstanceOf <ConflictResult>());
        }
        public IActionResult Register([FromBody] RegisterRequestDTO dto)
        {
            RegisterResponse response = new RegisterResponse();

            var userExists = uow.User.FindByEmail(dto.Email);

            if (userExists.Success)
            {
                return(NotFound(response, userExists.Message));
            }

            var user = mapper.Map <User>(dto);

            var userCreated = uow.User.Register(user);

            if (!userCreated.Success)
            {
                return(NotFound(response, userCreated.Message));
            }

            if (!uow.Commit())
            {
                return(NotFound(response));
            }

            response.Id = userCreated.Data;

            return(Ok(response));
        }
Example #4
0
 public async Task <IActionResult> PortalUserRegister([FromBody] RegisterRequestDTO model)
 {
     return(Ok(await _databaseTutorUOW.UserRepository.Register(new RequestDTO <RegisterRequestDTO>()
     {
         Data = model
     })));
 }
Example #5
0
        public async Task <IActionResult> Register([FromBody] RegisterRequestDTO model)
        {
            _logger.LogDebug("Register invoked");
            var userExistsWithTheGivenEmail = await _userService.GetUserByEmail(model.Email);

            if (userExistsWithTheGivenEmail != null)
            {
                _logger.LogDebug("Register failed");
                return(BadRequest("The user with the given email already exists."));
            }

            // Create an appropriate mapper going from DTO to Entity
            var userEntity = new UserEntity
            {
                Email    = model.Email,
                UserName = model.UserName,
                Password = HashPassword(model.Password),
                // Hard coded role
                Role = Role.User
            };

            var user = await _userService.Create(userEntity);

            var(token, validFor) = _jwtHandler.CreateRefreshToken();
            var refreshToken = await _refreshTokenService.Create(token, validFor, user);

            var tokens = CreateTokensResponse(user.UserName, user.Email, user.Role.ToString(), refreshToken.Token);

            _logger.LogDebug("Register successful");
            return(Ok(tokens));
        }
        public ActionResult <RegisterResponseDTO> Register(RegisterRequestDTO registerRequest)
        {
            // Checking if the non nullable fields (as per business rules) are not empty/null
            if (string.IsNullOrEmpty(registerRequest.UserName) || string.IsNullOrEmpty(registerRequest.Email) ||
                string.IsNullOrEmpty(registerRequest.PhoneNumber) || string.IsNullOrEmpty(registerRequest.Password))
            {
                return(new BadRequestResult());
            }

            User user;

            if (TryCreateUser(registerRequest.UserName, registerRequest.FirstName, registerRequest.LastName, registerRequest.DateOfBirth, registerRequest.PhoneNumber,
                              registerRequest.Email, registerRequest.MedicalInformation, registerRequest.BankAccount, registerRequest.Password, out user))
            {
                return(new RegisterResponseDTO
                {
                    UserName = user.UserName,
                    Token = CreateToken(user.Id)
                });
            }
            else
            {
                return(new ConflictResult());
            }
        }
Example #7
0
        public async Task <bool> RegisterAsync(RegisterRequestDTO loginRequest, IOutputPort <RegisterResponseDTO> outputPort)
        {
            try
            {
                _logger.LogInformation("Creating user for request {@request}", loginRequest);
                var result = await _userRepository.CreateUserAsync(new User(loginRequest.FirstName, loginRequest.LastName, loginRequest.Email, loginRequest.Username), loginRequest.Password);

                _logger.LogInformation("User repository returned {@response}", result);

                if (result)
                {
                    outputPort.CreateResponse(new RegisterResponseDTO(true));
                }

                else
                {
                    outputPort.CreateResponse(new RegisterResponseDTO(false, new ErrorResponse(new List <Error> {
                        new Error(GlobalErrorCodes.InternalServer, "Cannot create new user")
                    })));
                }

                return(result);
            }

            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                outputPort.CreateResponse(new RegisterResponseDTO(false, new ErrorResponse(new List <Error> {
                    GlobalErrors.UnexpectedError
                })));
                return(false);
            }
        }
        public void TestRegistration()
        {
            // Arrange
            var login = new LoginDto
            {
                UserName = "******",
                Password = "******"
            };

            var registrationRequest = new RegisterRequestDTO
            {
                UserName           = "******",
                FirstName          = "New",
                LastName           = "User",
                DateOfBirth        = new DateTime(),
                PhoneNumber        = "123459",
                Email              = "*****@*****.**",
                MedicalInformation = "N/A",
                BankAccount        = "84903",
                Password           = "******"
            };

            var newLogin = new LoginDto
            {
                UserName = "******",
                Password = "******"
            };

            // Act
            var initialLoginResponse = _userController.Login(login);

            // Assert
            Assert.IsNull(initialLoginResponse.Value);

            // Act
            var registrationResponse = _userController.Register(registrationRequest);

            // Assert
            Assert.IsNotNull(registrationResponse.Value);
            Assert.False(string.IsNullOrEmpty(registrationResponse.Value.UserName));
            Assert.False(string.IsNullOrEmpty(registrationResponse.Value.Token));

            // Act
            ActionResult <LoggedInDto> finalLoginResponse = _userController.Login(newLogin);

            // Assert
            Assert.IsNotNull(finalLoginResponse.Value);
            Assert.IsFalse(string.IsNullOrEmpty(finalLoginResponse.Value.UserName));
            Assert.IsFalse(string.IsNullOrEmpty(finalLoginResponse.Value.Token));

            Assert.AreEqual(finalLoginResponse.Value.UserName, registrationResponse.Value.UserName);
        }
Example #9
0
        public void IfUsernameIsTaken_ReturnBadRequest()
        {
            var user = new RegisterRequestDTO {
                Username = "******",
                Password = "******",
                ClientId = "Test"
            };

            var controller = new AuthController(_authService);
            var result     = controller.Register(user) as ObjectResult;

            Assert.Equal(400, result?.StatusCode);
            Assert.Equal("The user with the given username already exists.", result?.Value);
        }
        public void TestCheckWithValidUserAndEmail()
        {
            // Arrange
            var registerRequest = new RegisterRequestDTO
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            // Act
            ActionResult checkUserResponse = _userController.CheckUser(registerRequest);

            // Assert
            Assert.That(checkUserResponse, Is.InstanceOf <OkResult>());
        }
        public void IfUsernameIsTaken_ReturnNull()
        {
            // Arrange
            var user = new RegisterRequestDTO
            {
                Username = "******",
                Password = "******",
                ClientId = "Test"
            };

            // Act
            var result = _authService.Register(user);

            // Assert
            Assert.Null(result);
        }
        public ActionResult CheckUser(RegisterRequestDTO registerRequest)
        {
            // Check if username is already used (must be unique as per entity schema)
            if (_database.User.FirstOrDefault(u => u.UserName.ToLower() == registerRequest.UserName.ToLower()) != null)
            {
                return(new BadRequestResult());
            }

            // Check if email is already used (must be unique as per entity schema)
            if (_database.User.FirstOrDefault(u => u.Email.ToLower() == registerRequest.Email.ToLower()) != null)
            {
                return(new ConflictResult());
            }

            return(new OkResult());
        }
        public void IfUsernameIsntTaken_CompleteRegistration_ReturnAccessToken()
        {
            // Arrange
            var user = new RegisterRequestDTO
            {
                Username = "******",
                Password = "******",
                ClientId = "Test"
            };

            // Act
            var result = _authService.Register(user);

            // Assert
            Assert.NotNull(result);
            Assert.NotNull(result.AccessToken);
            Assert.Equal(2, _dbContext.Users.ToListAsync().Result.Count);
        }
Example #14
0
        public async Task <IActionResult> Register(RegisterRequestDTO model)
        {
            try
            {
                var user = new UserModel {
                    UserName          = model.Username,
                    Email             = model.Email,
                    DefaultCurrencyID = (int)CommonCurrencies.Tenge
                };
                var id = await _accountService.RegisterAsync(user, model.Password);

                return(Created("", id));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #15
0
        public async Task <IHttpActionResult> Register(RegisterRequestDTO model)
        {
            try
            {
                if (model == null)
                {
                    return(BadRequest("You've sent an empty model"));
                }

                var user = new ApplicationUser {
                    UserName = model.Username, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Заполняем базовые категории
                    using (_context)
                    {
                        var userInDb = _context.Users.Single(t => t.UserName == user.UserName);
                        foreach (Category ct in _context.Categories.Where(c => (c.CreatedBy == null) || (c.CreatedBy.Contains("SYS"))).ToList())
                        {
                            userInDb.Categories.Add(ct);
                        }
                        _context.SaveChanges();
                    }
                }
                else
                {
                    string _errors = "";
                    foreach (var error in result.Errors)
                    {
                        _errors = $"{_errors}{error};";
                    }
                    throw new Exception(_errors);
                }
                return(Created("", user.Id));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #16
0
        public void IfUsernameIsntTaken_CompleteRegistration()
        {
            var user = new RegisterRequestDTO {
                Username = "******", Password = "******", ClientId = "Test"
            };
            var controller = new AuthController(_authService);

            var result = (controller.Register(user) as ObjectResult)?.Value as AuthResponseDTO;
            var token  = new JwtSecurityTokenHandler().ReadJwtToken(result?.AccessToken);

            var username = token.Claims.FirstOrDefault(claim => claim.Type == "username")?.Value;
            var clientId = token.Claims.FirstOrDefault(claim => claim.Type == "clientId")?.Value;
            var role     = token.Claims.FirstOrDefault(claim => claim.Type == "roles")?.Value;

            Assert.NotNull(result);
            Assert.Equal(user.Username, username);
            Assert.Equal(user.ClientId, clientId);
            Assert.Equal(Role.User.ToString(), role);
        }
        public void TestRegistrationWithDuplicatePhoneNumber()
        {
            // Arrange
            var registerRequest = new RegisterRequestDTO
            {
                UserName           = "******",
                FirstName          = "New",
                LastName           = "User",
                DateOfBirth        = new DateTime(),
                PhoneNumber        = "123459",
                Email              = "*****@*****.**",
                MedicalInformation = "N/A",
                BankAccount        = "84903",
                Password           = "******"
            };

            var duplicateRegisterRequest = new RegisterRequestDTO
            {
                UserName           = "******",
                FirstName          = "New",
                LastName           = "User",
                DateOfBirth        = new DateTime(),
                PhoneNumber        = "123459",
                Email              = "*****@*****.**",
                MedicalInformation = "N/A",
                BankAccount        = "84903",
                Password           = "******"
            };

            // Act
            var registrationOneResponse = _userController.Register(registerRequest);

            // Assert
            Assert.IsNotNull(registrationOneResponse.Value);
            Assert.False(string.IsNullOrEmpty(registrationOneResponse.Value.UserName));
            Assert.False(string.IsNullOrEmpty(registrationOneResponse.Value.Token));

            // Act
            var registrationTwoResponse = _userController.Register(duplicateRegisterRequest);

            // Assert
            Assert.That(registrationTwoResponse.Result, Is.InstanceOf <ConflictResult>());
        }
Example #18
0
        public async Task <ActionResult> Register([FromBody] RegisterRequestDTO request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Request"));
            }

            Dictionary <bool, string> dic = await _authService.Register(request);

            if (dic.ContainsKey(true))
            {
                return(Ok(new { status = 200, msg = "success" }));
            }
            else if (dic.ContainsKey(false))
            {
                return(Ok(new { status = 200, msg = "failure", errormessage = dic[false] }));
            }

            return(BadRequest("Invalid Request"));
        }
        public async void Register_WithEmailThatIsInUse_BadRequest()
        {
            // Arrange
            var client   = _server.Instance.CreateClient();
            var loginReq = new RegisterRequestDTO
            {
                ConfirmPassword = "******",
                Password        = "******",
                Email           = "*****@*****.**",
                UserName        = "******"
            };

            var content = new StringContent(JsonConvert.SerializeObject(loginReq), Encoding.UTF8, "application/json");

            // Act
            var response = await client.PostAsync("api/auth/register", content);

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
Example #20
0
        public async Task <RegisterResultDTO> Register(RegisterRequestDTO item)
        {
            var result = new RegisterResultDTO {
                Successful = false
            };
            var request = new HttpRequestMessage(HttpMethod.Post, this.UrlApi + "Register");

            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var content = new StringContent(JsonConvert.SerializeObject(item), Encoding.UTF8, "application/json");

            request.Content = content;
            //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var response = await _httpClient.SendAsync(request, CancellationToken.None);

            string str = await response.Content.ReadAsStringAsync();

            result = JsonConvert.DeserializeObject <RegisterResultDTO>(str);
            return(result);
        }
        public async Task <Dictionary <bool, string> > Register(RegisterRequestDTO request)
        {
            var user = new ResultUser {
                UserName = request.UserName, Email = request.Email
            };
            var result = await UserManager.CreateAsync(user, request.Password);

            if (result.Succeeded)
            {
                return(new Dictionary <bool, string> {
                    { true, "success" }
                });
            }
            else
            {
                return(new Dictionary <bool, string> {
                    { false, result.Errors.FirstOrDefault().Description }
                });
            }
            //result.Errors.
        }
        public IObservable <bool> Register(string username, string email, string password, string confirmPassword)
        {
            var registerDto = new RegisterRequestDTO
            {
                Email           = email,
                UserName        = username,
                Password        = password,
                ConfirmPassword = confirmPassword
            };

            return(_authApi.GetClient().Register(registerDto).Select(response =>
            {
                var res = response;
                var handler = new JwtSecurityTokenHandler();
                var token = handler.ReadJwtToken(response.AccessToken);
                _runtimeContext.AccessToken = response.AccessToken;
                _runtimeContext.RefreshToken = response.RefreshToken;
                _runtimeContext.UserName = token.Payload.FirstOrDefault(x => x.Key == "username").Value.ToString();
                _runtimeContext.Role = token.Claims.FirstOrDefault(x => x.Type == "roles").Value.ToString();
                _runtimeContext.Email = email;
                return true;
            }));
        }
Example #23
0
 public AuthResponseDTO Register(RegisterRequestDTO registerDto) =>
 _userRepository.Register(registerDto.Username, registerDto.Password) == null ? null :
 new AuthResponseDTO
 {
     AccessToken = _jwtHandler.CreateJwt(registerDto.ClientId, registerDto.Username, Role.User.ToString())
 };