public async void USER_AUTHENTICATE_SUCCESSFULLY(string userEmail)
        {
            // Arrange
            var userDetails = new Mock <IGetUserLoginAuthenticate>();
            AuthenticateUser         getUserDetails  = new AuthenticateUser(userDetails.Object);
            UserLoginRequestMessages userInfo        = new UserLoginRequestMessages();
            UserLoginRequestDTO      userInformation = new UserLoginRequestDTO();

            userInfo.UserEmail        = userEmail;
            userInformation.UserEmail = userEmail;
            var UserResponse = new UserInformation();

            UserResponse.FirstName   = "CJay2";
            UserResponse.LastName    = "BJay1";
            UserResponse.PhoneNumber = "2222222222";
            UserResponse.UserEmail   = userEmail;
            UserResponse.UserStatus  = "FullAccess";
            UserResponse.UserType    = "Acitved";
            userDetails.Setup(user => user.GetUserAuthenticate(userInformation)).ReturnsAsync(UserResponse);

            // Act
            var actualUser = await getUserDetails.AuthenticateUserAsync(userInfo);

            // Assert
            Assert.Equal(UserResponse.UserEmail, actualUser.UserEmail);
            //Assert.Equal(UserResponse.FirstName, actualUser.FirstName);
            //Assert.Equal(UserResponse.LastName, actualUser.LastName);
            //Assert.Equal(UserResponse.PhoneNumber, actualUser.PhoneNumber);
            //Assert.Equal(UserResponse.UserStatus, actualUser.UserStatus);
            //Assert.Equal(UserResponse.UserType, actualUser.UserType);
        }
Ejemplo n.º 2
0
        public async Task <ActionResult <UserLoginResponseDTO> > Login(UserLoginRequestDTO user)
        {
            var userResult = await Service.Login(user);

            if (userResult == null) //User login failed
            {
                return(StatusCode(403, new { message = "نام کاربری اشتباه وارد شده" }));
            }
            else if (userResult.IsActive == false)
            {
                return(StatusCode(403, new { message = "کاربر غیر فعال شده است" }));
            }
            else if (userResult.Password != user.Password)
            {
                return(StatusCode(403, new { message = "رمز عبور اشتباه است" }));
            }
            else
            {
                var tokenString = GenerateToken(userResult);
                return(Ok(new UserLoginResponseDTO()
                {
                    AccessToken = tokenString,
                    RefreshToken = string.Empty,
                }));
            }
        }
Ejemplo n.º 3
0
        public async Task <ActionResult <UserDTO> > CreateUser([FromBody] UserLoginRequestDTO dto, CancellationToken ct)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            if (!await _userSvc.CheckUsernameAvailableAsync(dto.Username, ct))
            {
                var modelErrors = new ModelStateDictionary();
                modelErrors.AddModelError("details", "That username is already in use.");
                return(Conflict(modelErrors));
            }

            if (Validators.CheckForbiddenName(dto.Username))
            {
                var modelErrors = new ModelStateDictionary();
                modelErrors.AddModelError("details", "That username is forbidden or reserved for system use.");
                return(Conflict(modelErrors));
            }

            var obj = _mapper.Map <User>(dto);

            obj.Id   = Guid.NewGuid();
            obj.Salt = PasswordUtils.GenerateSalt();
            obj.Hash = PasswordUtils.GenerateHash(dto.Password, obj.Salt);
            obj      = await _userSvc.AddUserAsync(obj, ct);

            return(CreatedAtAction(nameof(GetUser), new { id = obj.Id }, _mapper.Map <UserDTO>(obj)));
        }
Ejemplo n.º 4
0
        public async Task <List <UserInformation> > GetAllUserInformations(UserLoginRequestDTO UserEmail)
        {
            List <UserInformation> UserInfo = new List <UserInformation>();
            GetQueryByProperties   getQuery = new GetQueryByProperties();
            string query    = getQuery.GetDetailQuery("AuthenticateUser", "LoginAuthenticate");
            string newQuery = query.Replace("{useremail}", "");

            using (SqlCommand cmd = new SqlCommand(newQuery, conn))
            {
                cmd.CommandType = CommandType.Text;
                conn.Open();

                using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
                {
                    while (reader.Read())
                    {
                        UserInfo.Add(
                            new UserInformation
                        {
                            UserId      = Convert.ToInt32(reader["UserId"]),
                            UserEmail   = reader["UserEmail"].ToString(),
                            FirstName   = reader["firstName"].ToString(),
                            LastName    = reader["lastName"].ToString(),
                            UserType    = ((UserIdDeleted)Convert.ToInt16(reader["IsDeleted"])).ToString(),
                            UserStatus  = reader["StatusCode"].ToString(),
                            PhoneNumber = reader["PhoneNumber"].ToString(),
                        }
                            );
                    }
                    conn.Close();
                    return(UserInfo);
                }
            }
        }
Ejemplo n.º 5
0
        public async Task <ActionResult <UserLoginResponseDTO> > AuthenticateUser([FromBody] UserLoginRequestDTO dto, CancellationToken ct)
        {
            // Find user
            var user = await _userSvc.GetUserAsync(dto.Username, ct : ct);

            if (user == null)
            {
                var modelErrors = new ModelStateDictionary();
                modelErrors.AddModelError("details", "Bad username or password.");
                return(Unauthorized(modelErrors));
            }

            // Confirm password
            if (!user.CheckPassword(dto.Password))
            {
                var modelErrors = new ModelStateDictionary();
                modelErrors.AddModelError("details", "Bad username or password.");
                return(Unauthorized(modelErrors));
            }

            // Generate token, Return result
            var result = _mapper.Map <UserLoginResponseDTO>(user);

            result.Token = await _userSvc.GenerateAdminTokenAsync(user, ct);

            return(Ok(result));
        }
Ejemplo n.º 6
0
        public IActionResult Authentificate(UserLoginRequestDTO user)
        {
            var result = _userService.Authenticate(user);

            if (result == null)
            {
                return(BadRequest(new { Message = "Username or Password is invalid!" }));
            }
            return(Ok(result));
        }
Ejemplo n.º 7
0
        public async Task Authenticate(UserLoginRequestDTO userDto)
        {
            User user = await _userManager.FindByNameAsync(userDto.Username);

            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                throw new EntityInvalidationException("The account needs to be registered first with the received code in email");
            }
            else
            {
                await _signInManager.PasswordSignInAsync(userDto.Username, userDto.Password, userDto.RememberMe, lockoutOnFailure : false);
            }
        }
Ejemplo n.º 8
0
        public UserResponseDTO Authenticate(UserLoginRequestDTO model)
        {
            User user = _userRepository.GetByUsernameAndPassword(model.Username, model.Password);

            if (user == null)
            {
                return(null);
            }

            var token = GenerateUserJWTToken(user);

            return(new UserResponseDTO(user, token));
        }
Ejemplo n.º 9
0
        public async Task <ActionResult> Authenticate([FromBody] UserLoginRequestDTO userDto)
        {
            try
            {
                await _userService.Authenticate(userDto);

                return(Ok());
            }

            catch (ApplicationException ex)
            {
                return(NotFound(ex.Message));
            }
        }
Ejemplo n.º 10
0
        public async Task <List <UserInformation> > GetUserInformation(UserLoginRequestMessages user)
        {
            var config = new MapperConfiguration(cfg =>
                                                 cfg.CreateMap <UserLoginRequestMessages, UserLoginRequestDTO>()
                                                 );
            BusinessLoginUserResponse userResponse   = new BusinessLoginUserResponse();
            UserLoginRequestDTO       requestMessage = new UserLoginRequestDTO();
            var userInfo = await userAuthenticate.GetAllUserInformations(requestMessage);

            //List<UserInformation> userInfo = await DAOServiceManager.GetInstance().GetUserInformationAll().GetAllUserInformations(requestMessage);

            if (userInfo != null)
            {
                return(userInfo);
            }
            return(null);
        }
Ejemplo n.º 11
0
 public async Task<UserInformation> AuthenticateUserAsync(UserLoginRequestMessages user)
 {
     var config = new MapperConfiguration(cfg =>
         cfg.CreateMap<UserLoginRequestMessages, UserLoginRequestDTO>()
     );
     BusinessLoginUserResponse userResponse = new BusinessLoginUserResponse();
     UserLoginRequestDTO requestMessage = new UserLoginRequestDTO();
     requestMessage = config.CreateMapper().Map<UserLoginRequestDTO>(user);
     var userInfo = await userAuthenticate.GetUserAuthenticate(requestMessage);
     /*var userInfo = await DAOServiceManager.GetInstance().GetAuthenticateUserByEmail()
         .GetUserAuthenticate(requestMessage);*/
     if (userInfo != null)
     {
         return userInfo;
     }
     return null;
 }
Ejemplo n.º 12
0
 public async Task Authenticate(UserLoginRequestDTO adminDto)
 {
     // check if it's really admin
     await _signInManager.PasswordSignInAsync(adminDto.Username, adminDto.Password, adminDto.RememberMe, lockoutOnFailure : false);
 }
Ejemplo n.º 13
0
 public async Task <User> Login(UserLoginRequestDTO loginRequestDTO)
 {
     return(await Repository.Login(loginRequestDTO));
 }
Ejemplo n.º 14
0
        public async Task <User> Login(UserLoginRequestDTO loginRequestDTO)
        {
            var query = "select * from Users where username=@username and password =@password";

            return((await SqlServerDbConnection.QueryAsync <User>(query, new { username = loginRequestDTO.UserName, password = loginRequestDTO.Password })).FirstOrDefault());
        }
        public async Task <ActionResult> Login([FromBody] UserLoginRequestDTO userLoginRequestDTO,
                                               [FromServices] SigningConfigurations signingConfigurations,
                                               [FromServices] TokenConfigurations tokenConfigurations)
        {
            try
            {
                bool credentialsIsValid = false;
                if (userLoginRequestDTO != null && !string.IsNullOrEmpty(userLoginRequestDTO.Email))
                {
                    User userLogin = _userManager.FindByEmailAsync(userLoginRequestDTO.Email).Result;

                    IEnumerable <Address> address = userLogin.Addresses;

                    if (userLogin != null)
                    {
                        var result = await _signInManager.PasswordSignInAsync(userLoginRequestDTO.Email, userLoginRequestDTO.Password, false, true);

                        if (result.Succeeded)
                        {
                            credentialsIsValid = _userManager.IsInRoleAsync(userLogin, userLoginRequestDTO.Role).Result;
                        }

                        if (credentialsIsValid)
                        {
                            ClaimsIdentity identity = new ClaimsIdentity(
                                new GenericIdentity(userLoginRequestDTO.Email, "Login"),
                                new[] {
                                new Claim("Id", userLogin.Id.ToString()),
                                new Claim("EstablishmentId", userLogin.EstablishmentId.ToString()),
                                new Claim("UserName", userLogin.UserName),
                                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                                new Claim(JwtRegisteredClaimNames.UniqueName, userLoginRequestDTO.Email)
                            }
                                );

                            var roles = _userManager.GetRolesAsync(userLogin).Result;

                            foreach (string role in roles)
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Role, role));
                            }

                            DateTime creationDate   = DateTime.Now;
                            DateTime expirationDate = creationDate +
                                                      TimeSpan.FromSeconds(tokenConfigurations.Seconds);

                            UserLoginResponseDTO userLoginResponseDTO = new UserLoginResponseDTO
                            {
                                User           = _mapper.Map <UserResponseDTO>(userLogin),
                                Token          = new AuthToken().GemerateToken(signingConfigurations, tokenConfigurations, identity, creationDate, expirationDate),
                                CreationDate   = creationDate,
                                ExpirationDate = expirationDate
                            };

                            return(Ok(userLoginResponseDTO));
                        }
                    }
                    return(NotFound());
                }
                return(BadRequest("Unable to login."));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }