public async Task <ActionResult <UserRoleDto> > Login(UserAuthenticationDto dto)
        {
            var user = await userManager.FindByNameAsync(dto.Username);

            if (user == null)
            {
                return(BadRequest(new { message = "User does not exist." }));
            }

            var result = await signInManager.CheckPasswordSignInAsync(user, dto.Password, true);

            if (!result.Succeeded)
            {
                return(BadRequest(new { message = "Invalid Password" }));
            }

            await signInManager.SignInAsync(user, false, "Password");

            var roles = await userManager.GetRolesAsync(user);

            return(Ok(new UserRoleDto
            {
                Username = user.UserName,
                UserRoles = roles,
            }));
        }
Пример #2
0
        /// <inheritdoc />
        public async Task <Result <UserAuthenticationResponseDto, string> > LoginAsync(string username, string password, string apiKey)
        {
            var userAuthentication = new UserAuthenticationDto
            {
                GrantType = "password",
                Username  = username,
                Password  = password
            };

            var url = _configuration.ApiBaseUrl + "/tokens";

            try
            {
                var user = await url.PostJsonAsync(userAuthentication).ReceiveJson <UserAuthenticationResponseDto>();

                return(new Result <UserAuthenticationResponseDto, string>(user));
            }
            catch (FlurlHttpException ex)
            {
                try
                {
                    var dopplerError = await ex.GetResponseJsonAsync <DopplerErrorDto>();

                    return(new Result <UserAuthenticationResponseDto, string>(dopplerError.Detail));
                }
                catch
                {
                    return(new Result <UserAuthenticationResponseDto, string>(ex.Message));
                }
            }
            catch (Exception ex)
            {
                return(new Result <UserAuthenticationResponseDto, string>(ex.Message));
            }
        }
Пример #3
0
        public IActionResult Authenticate([FromBody] UserAuthenticationDto userDto)
        {
            var user = _userLogic.Authenticate(userDto.Username, userDto.Password);

            if (user == 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 Claim[]
                {
                    new Claim(ClaimTypes.Name, user.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);

            return(Ok(new
            {
                user.Id,
                user.Username,
                user.FirstName,
                user.LastName,
                user.Email,
                Token = tokenString
            }));
        }
Пример #4
0
        public async Task <IActionResult> Login([FromBody] UserAuthenticationDto userAuthentication)
        {
            if (!await _userService.Validate(userAuthentication, ModelState))
            {
                return(Unauthorized());
            }

            return(Ok(new { Token = _userService.CreateToken().Result }));
        }
Пример #5
0
        public async Task <IActionResult> Authenticate([FromBody] UserAuthenticationDto user)
        {
            if (!await _authenticationService.ValidateUser(user))
            {
                _logger.LogWarning($"{nameof(Authenticate)}: Authentication failed. Wrong user name or password.");
                return(Unauthorized());
            }

            return(Ok(new { Token = await _authenticationService.CreateToken() }));
        }
Пример #6
0
        public IActionResult Authenticate([FromBody] UserAuthenticationDto model)
        {
            var user = _userRepo.Authenticate(model.Username, model.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
            return(Ok(user));
        }
Пример #7
0
        public IActionResult Authenticate([FromBody] UserAuthenticationDto userAuthenticationDto)
        {
            var userAuth = _userService.Authenticate(userAuthenticationDto);

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

            return(Ok(userAuth));
        }
Пример #8
0
        /// <summary>
        /// </summary>
        public bool Authenticate(UserAuthenticationDto auth)
        {
            if (string.IsNullOrEmpty(auth.username) || (string.IsNullOrEmpty(auth.username) || string.IsNullOrEmpty(auth.email)))
            {
                return(false);
            }
            User user = context.Users
                        .Single(u => string.IsNullOrEmpty(u.username) ? u.username == auth.username : u.email == auth.email);

            return(dot_social.Utils.ComparePasswords(auth.password, user.password, user.salt));
        }
Пример #9
0
        public async Task <bool> Validate(UserAuthenticationDto userAuthentication, ModelStateDictionary modelState)
        {
            _user = await _userManager.FindByEmailAsync(userAuthentication.Email);

            if (_user != null && await _userManager.CheckPasswordAsync(_user, userAuthentication.Password))
            {
                return(true);
            }

            modelState.TryAddModelError("wrongCredentials", "Wrong email or password");
            _logger.Log(LogLevel.Error, "Auth failed! Wrong email or password");
            return(false);
        }
        async Task <Result> IAuthenticationApplicationService.Login(UserAuthenticationDto userAuthenticationDto)
        {
            var user = await _userRepository.GetUserBy(userAuthenticationDto.Email);

            if (user == null)
            {
                return(Result.Error(HttpStatusCode.Unauthorized, Resource.Unauthorized));
            }

            return(_passwordHasher.Check(user.Password, userAuthenticationDto.Password) ?
                   Result.Ok(GenerateToken(user)) :
                   Result.Error(HttpStatusCode.Unauthorized, Resource.Unauthorized));
        }
Пример #11
0
 public ActionResult Login(UserAuthenticationDto userAuthenticationDto)
 {
     if (ModelState.IsValid)
     {
         if (GetService().Login(userAuthenticationDto) != null)
         {
             GetTempDataManager().SetTempData(TempDataConstants.MESSAGE, Message.CreateSuccessMessage(MessageKeyConstants.INFO_LOGIN_SUCCESSFUL_MESSAGE));
             return(RedirectToAction(WebConstants.VIEW_INDEX, WebConstants.CONTROLLER_HOME));
         }
         GetTempDataManager().SetTempData(TempDataConstants.MESSAGE, Message.CreateErrorMessage(MessageKeyConstants.INFO_LOGIN_FAILURE_MESSAGE));
     }
     return(View("Index", userAuthenticationDto));
 }
Пример #12
0
        public ActionResult <InterfaceUtilizador> Authenticate([Bind] UserAuthenticationDto userDto)
        {
            lock (_system)
            {
                InterfaceUtilizador user = null;
                int    typeOfUser        = _system.TypeUser(userDto.email);
                string token             = CalculateHash.GetHashString(userDto.email + DateTime.Now);
                if (typeOfUser != -1)
                {
                    switch (typeOfUser)
                    {
                    case 0:
                    {
                        user = (Cliente)_system.Authenticate(userDto.email, userDto.password, token);
                        break;
                    }

                    case 1:
                    {
                        user = (Instrutor)_system.Authenticate(userDto.email, userDto.password, token);
                        break;
                    }

                    case 2:
                    {
                        user = (Rececionista)_system.Authenticate(userDto.email, userDto.password, token);
                        break;
                    }
                    }
                }

                if (user == null || typeOfUser == -1)
                {
                    return(Unauthorized(new
                    {
                        message = "Credentials are wrong..."
                    }));
                }

                StringBuilder a = new StringBuilder()
                                  .Append("{")
                                  .Append("\"token\":\"")
                                  .Append(token)
                                  .Append("\",\"user\":")
                                  .Append(JsonSerializer.Serialize(user, user.GetType()))
                                  .Append("}");

                return(Ok(a.ToString()));
            }
        }
Пример #13
0
        public async Task <IActionResult> Register([FromBody] SaveUserDto userDto)
        {
            var result = await _userService.Register(userDto);

            if (!result.IsSuccess)
            {
                return(BadRequest(result));
            }

            UserAuthenticationDto ObjToken = new UserAuthenticationDto
            {
                Token = result.Response
            };

            return(Ok(ObjToken));
        }
Пример #14
0
        public UserAuthenticationGetDto Authenticate(UserAuthenticationDto userAuthenticationDto)
        {
            var username = userAuthenticationDto.Username;
            var password = userAuthenticationDto.Password;

            var user = _context.Users.SingleOrDefault(x => x.Username == username);

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

            var passwordHash = new PasswordHash(user.PasswordSalt, user.PasswordHash);

            if (!passwordHash.Verify(password))
            {
                return(null);
            }

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

            var token = tokenHandler.CreateToken(tokenDescriptor);

            _context.Tokens.Add(new Token {
                Value = tokenHandler.WriteToken(token), UserId = user.Id
            });
            _context.SaveChanges();

            var userToReturn = new UserAuthenticationGetDto
            {
                UserId = user.Id,
                Token  = tokenHandler.WriteToken(token)
            };

            return(userToReturn);
        }
Пример #15
0
        public UserAuthenticationDto Login(UserAuthenticationDto userAuthenticationDto)
        {
            UserAuthenticationDto userAuthenticationToLoginDto = _userAuthenticationDao.Find(new UserFilterDto()
            {
                Email = userAuthenticationDto.Email
            });

            if (userAuthenticationToLoginDto == null)
            {
                return(null);
            }
            if (!PasswordUtils.Verify(userAuthenticationToLoginDto.Password, userAuthenticationDto.Password))
            {
                return(null);
            }
            SessionProvider.GetInstance().AddSession(new UserSession(userAuthenticationToLoginDto));
            return(userAuthenticationToLoginDto);
        }
Пример #16
0
        public IActionResult Authenticate([FromBody] UserAuthenticationDto userDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new
                                  { Message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage) }));
            }

            try
            {
                var user = _authenticationService.Authenticate(userDto.Email, userDto.Password);

                if (user == 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 Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Id.ToString()),
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                                SecurityAlgorithms.HmacSha256Signature),
                    Audience = "auth"
                };
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return(Ok(new UserAuthenticatedDto()
                {
                    Id = user.Id,
                    Token = tokenString
                }));
            }
            catch (Exception e)
            {
                return(BadRequest(new MessageObj(e.Message)));
            }
        }
Пример #17
0
        public async Task <IActionResult> Login([FromBody] UserAuthenticationDto userAuthentication)
        {
            try
            {
                var user = await _authenticationManager.ValidateUser(userAuthentication);

                if (!user)
                {
                    _logger.LogWarn($"{nameof(Login)}: Authentication failed. Wrong username or password.");
                    return(Unauthorized());
                }

                return(Ok(new { Token = await _authenticationManager.CreateToken() }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(StatusCode(500));
            }
        }
Пример #18
0
        public async Task <IActionResult> Token([FromForm] UserAuthenticationDto userAthenticationDto)
        {
            var userToken = await _accountService.GenerateToken(userAthenticationDto.UserName, userAthenticationDto.Password);

            return(Ok(new { access_token = userToken }));
        }
 public LoginPostLogicValidation(UserAuthenticationDto userAuthenticationDto)
 {
     _userAuthenticationDto          = userAuthenticationDto;
     _userAuthenticationDtoValidator = new UserAuthenticationDtoValidator();
 }
Пример #20
0
 public UserSession(UserAuthenticationDto userAuthenticationDto)
     : base(SESSION_NAME)
 {
     UserAuthenticationDto = userAuthenticationDto;
 }
        public async Task <bool> ValidateUser(UserAuthenticationDto userAuthentication)
        {
            _user = await _userManager.FindByNameAsync(userAuthentication.UserName);

            return(_user != null && await _userManager.CheckPasswordAsync(_user, userAuthentication.Password));
        }