Beispiel #1
0
        public ActionResult <UserAuthenticatedDto> Login([FromBody] UserLoginDto userInDto)
        {
            if ((string.IsNullOrEmpty(userInDto.Email) && string.IsNullOrEmpty(userInDto.UserName)) || string.IsNullOrEmpty(userInDto.Password))
            {
                return(BadRequest(new Message("Username (and Email) or Password is empty.")));
            }

            User user = null;

            if (!string.IsNullOrEmpty(userInDto.Email) && !string.IsNullOrEmpty(userInDto.UserName))
            {
                user = _userRepository.Where(u => u.Email == userInDto.Email && u.UserName == userInDto.UserName).FirstOrDefault();
            }
            else if (!string.IsNullOrEmpty(userInDto.Email))
            {
                user = _userRepository.Where(u => u.Email == userInDto.Email).FirstOrDefault();
            }
            else if (!string.IsNullOrEmpty(userInDto.UserName))
            {
                user = _userRepository.Where(u => u.UserName == userInDto.UserName).FirstOrDefault();
            }

            // Check if user exists
            if (user == null)
            {
                return(BadRequest(new Message("User not found. Please check your email and/or username.")));
            }

            if (!UserHelpers.VerifyPasswordHash(userInDto.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(BadRequest(new Message("Password is incorrect.")));
            }

            var userOutDto = _mapper.Map <UserAuthenticatedDto>(user);

            userOutDto.Token = UserHelpers.GenerateToken(user, _tokenSettings);

            return(userOutDto);
        }