Beispiel #1
0
        public async Task <ServiceResponse <GetUserDto> > AuthenticateUser(AuthenticateUserDto authUser)
        {
            ServiceResponse <GetUserDto> serviceResponse = new ServiceResponse <GetUserDto>();

            try
            {
                User user = await(from u in _context.Users
                                  where u.Name == authUser.Email
                                  select u).FirstOrDefaultAsync();

                //if (user == null || !BC.Verify(authUser.Password, user.Password))
                if (user == null || !customPasswordHasher.VerifyPassword(user.PasswordHash, authUser.Password))
                {
                    serviceResponse.Data    = null;
                    serviceResponse.Success = false;
                    serviceResponse.Message = "Wrong user and/or password";
                }
                else
                {
                    serviceResponse.Data    = _mapper.Map <GetUserDto>(user);
                    serviceResponse.Message = "JWT Token goes here!";
                }
            }
            catch (System.Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.Message;
            }
            return(serviceResponse);
        }
Beispiel #2
0
        public IActionResult Authenticate([FromBody] AuthenticateModel authenticateModel)
        {
            AuthenticateUserDto authenticateUserDto =
                _usersService.Authenticate(authenticateModel.Email, authenticateModel.Password);

            if (authenticateUserDto == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, authenticateUserDto.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };
            SecurityToken token       = tokenHandler.CreateToken(tokenDescriptor);
            string        tokenString = tokenHandler.WriteToken(token);

            return(Ok(new
            {
                authenticateUserDto.Id,
                authenticateUserDto.Email,
                authenticateUserDto.FirstName,
                authenticateUserDto.LastName,
                Token = tokenString
            }));
        }
        public async Task <IActionResult> AuthenticateUser([FromBody] AuthenticateUserDto user)
        {
            var authUser = await _userRepository.AuthenticateUserAsync(user.Username, user.Password);

            if (authUser == null)
            {
                return(BadRequest(new
                {
                    message = "Username or Password is incorrect"
                }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_config["JwtSettings:Secret"]);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, authUser.Id.ToString()),
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            authUser.Token = tokenString;

            var userToReturn = _mapper.Map <UserForAuthenticationDto> (authUser);

            return(Ok(userToReturn));
        }
Beispiel #4
0
        public AuthenticatedUserDto AuthenticateUser(AuthenticateUserDto authenticateUser)
        {
            if (authenticateUser == null)
            {
                return(new AuthenticatedUserDto($"{nameof(authenticateUser)} not found."));
            }

            if (string.IsNullOrEmpty(authenticateUser.Email))
            {
                return(new AuthenticatedUserDto("Email is required."));
            }

            if (string.IsNullOrEmpty(authenticateUser.Password))
            {
                return(new AuthenticatedUserDto("Password is required."));
            }

            string passwordDecrypt = this.EncryptionService.Decrypt(authenticateUser.Password);

            UserSystemDto userSystem = this.UserService.Find(authenticateUser.Email, passwordDecrypt);

            if (userSystem == null)
            {
                return(new AuthenticatedUserDto("The email and/or password entered is invalid. Please try again."));
            }

            return(new AuthenticatedUserDto(userSystem));
        }
Beispiel #5
0
        public async Task <IActionResult> AuthenticateUser([FromBody] AuthenticateUserDto authUser)
        {
            ServiceResponse <GetUserDto> response = await _userService.AuthenticateUser(authUser);

            if (response.Data == null)
            {
                return(Unauthorized(response));
            }
            else
            {
                ServiceResponse <JwtTokens> respjwtTokens = new ServiceResponse <JwtTokens>();

                _jwtAuthManager.RemoveRefreshTokenByUserName(authUser.Email);
                var claims = new[]
                {
                    new Claim("Email", authUser.Email),
                    new Claim("Role", "role"),
                    new Claim("Activated", response.Data.Status == UserStatus.Disabled ? "False": "True")
                };
                var jwtResult = _jwtAuthManager.GenerateTokens(authUser.Email, claims, DateTime.Now);
                _logger.LogInformation($"User [{authUser.Email}] logged in the system.");
                JwtTokens jwtTokens = new JwtTokens();
                jwtTokens.AccessToken  = jwtResult.AccessToken.ToString();
                jwtTokens.RefreshToken = jwtResult.RefreshToken.TokenString;
                respjwtTokens.Data     = jwtTokens;
                respjwtTokens.Message  = "Validated";
                return(Ok(jwtResult));
            }
        }
Beispiel #6
0
 public IActionResult Authenticate([FromBody] AuthenticateUserDto authenticateUserDto) =>
 _mapper.Map <User>(authenticateUserDto)
 .Map(_userService.Authenticate)
 .Map(x => AllOk(new KeyDto()
 {
     Key = x.Key
 }))
 .Reduce(AuthenticationErrorHandler, err => err is AuthenticationError)
 .Reduce(InternalServisErrorHandler);
        public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticateUserDto credentials)
        {
            if (await userService.AuthenticateUserAsync(credentials))
            {
                return(Ok(jwtService.GenerateToken(credentials.UserName, Roles.Admin)));
            }

            return(BadRequest(ValidationResultFactory(nameof(credentials), credentials, UserControllerResources.AuthenticationFailed)));
        }
Beispiel #8
0
        public IActionResult Authenticate([FromBody] AuthenticateUserDto authenticateUserDto)
        {
            var token = _userService.Authenticate(authenticateUserDto.Username, authenticateUserDto.Password);

            if (token == null)
            {
                return(BadRequest(new { message = "Username of password incorrect" }));
            }

            return(Ok(new { Token = token }));
        }
Beispiel #9
0
        public async Task <IActionResult> Login(AuthenticateUserDto request)
        {
            ServiceResponse <string> response = await _authRepo.Login(
                request.Email, request.Password);

            if (!response.Success)
            {
                return(BadRequest(response));
            }
            return(Ok(response));
        }
        public async Task <ActionResult> Authenticate(AuthenticateUserDto authenticationUserDto)
        {
            try
            {
                string token = await _business.Authenticate(authenticationUserDto);

                return(Ok(token));
            }
            catch (AuthenticationFailedException exception)
            {
                return(Unauthorized(exception.Message));
            }
        }
        public async Task <IActionResult> Login(AuthenticateUserDto apiRequest)
        {
            var result = await _signInManager.PasswordSignInAsync(
                apiRequest.UserName,
                apiRequest.Password,
                true,
                true);

            if (result.Succeeded)
            {
                return(Ok());
            }

            return(BadRequest());
        }
Beispiel #12
0
        public IActionResult Authentication([FromBody] AuthenticateUserDto userAuthentication)
        {
            if (userAuthentication == null)
            {
                return(this.BadRequest(this.NotificationFactory.Error($"{nameof(userAuthentication)} not found.")));
            }

            AuthenticatedUserDto authenticatedUserDto = this.AuthenticationService.AuthenticateUser(userAuthentication);


            if (!authenticatedUserDto.Authenticated)
            {
                return(this.BadRequest(this.NotificationFactory.Error(authenticatedUserDto.Error)));
            }

            return(this.Ok(this.NotificationFactory.Success(authenticatedUserDto.UserSystem)));
        }
Beispiel #13
0
        public IActionResult Authenticate([FromBody] AuthenticateUserDto userLoginDTO)
        {
            return(_mapper.Map <User>(userLoginDTO) //form AuthUserDto to User
                   .Map(_userService.Authenticate)
                   .Map(_mapper.Map <UserDto>)
                   .Map(InsertToken)
                   .Map(_userService.AddAuthenticatedUser)
                   .Map(x => AllOk(new KeyDto()
            {
                Key = x.Key
            }))
                   .Reduce(AuthenticationErrorHandler, err => err is AuthenticationError)
                   .Reduce(InternalServisErrorHandler));

            //KeyDto keyData = _mapper.Map<KeyDto>(userData);
            //return Ok(keyData);
        }
        public Task <string> Authenticate(AuthenticateUserDto authenticationUserDto)
        {
            User user = null;

            try
            {
                user = _repository.GetAll().Where(user => user.Mail == authenticationUserDto.Mail).Include(user => user.RoleNavigation).Single();
            }
            finally
            {
                if (user == null || !_passwordHasher.Check(authenticationUserDto.Password, user.HashedPassword))
                {
                    throw new AuthenticationFailedException();
                }
            }

            string token = _jwtGenerator.GenerateToken(user.Id, user.RoleNavigation.Name);

            return(Task.FromResult(token));
        }
Beispiel #15
0
        public async Task <IActionResult> AuthenticateUser(AuthenticateUserDto userDto)
        {
            try
            {
                var authenticationResult = await userService.AuthenticateUser(userDto);

                return(Ok(authenticationResult));
            }
            catch (System.Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError,
                                  new ResponseDto <UserDto>
                {
                    Errors = new List <ErrorDto>
                    {
                        new ErrorDto
                        {
                            ErrorCode = 1, ErrorMessage = ex.Message
                        }
                    }
                }));
            }
        }
        public async Task <IActionResult> AuthenticateUser([FromBody] AuthenticateUserDto user)
        {
            if (user == null)
            {
                return(BadRequest("The body is empty."));
            }

            var filter = Builders <BsonDocument> .Filter.Eq("Email", user.Email);

            var query_res = await userCollection.Find(filter).FirstOrDefaultAsync();

            if (query_res == null)
            {
                return(BadRequest(user.Email + " is not a user."));
            }

            if (HashString(user.Password) == query_res["Password"])
            {
                return(Ok(query_res["_id"].ToString()));
            }

            return(BadRequest("Incorrect password."));
        }
Beispiel #17
0
    public async Task <ResponseDto <UserDto> > AuthenticateUser(AuthenticateUserDto userDto)
    {
        var userEntity = await userRepository.GetUserByEmail(userDto.Email);

        if (userEntity != null)
        {
            userEntity.LastLogin = DateTime.Now;
        }
        var updatedUserEntity = await userRepository.UpdateUser(userEntity);

        if (updatedUserEntity != null)
        {
            return(new ResponseDto <UserDto> {
                Results = new UserDto {
                    Email = updatedUserEntity.Email,
                    Id = updatedUserEntity.Id,
                    FullName = updatedUserEntity.FullName,
                    ActivationId = updatedUserEntity.ActivationId,
                    LastLogin = updatedUserEntity.LastLogin
                }
            });
        }
        return(null);
    }
        public async Task <bool> AuthenticateUserAsync(AuthenticateUserDto credentials)
        {
            var user = await userRepository.GetByUserName(credentials.UserName);

            return(user != null && encypterService.GetHash(credentials.Password, user.Salt) == user.Password ? true : false);
        }