예제 #1
0
        public User Authenticate(UserSignInDto model)
        {
            var  user            = _db.Users.SingleOrDefault(x => x.Username == model.Username);
            bool isValidPassword = BCrypt.Net.BCrypt.Verify(model.Password, user.Password);

            if (isValidPassword)
            {
                //generate Token
                var tokenHandler = new JwtSecurityTokenHandler();
                var secretBytes  = Encoding.UTF8.GetBytes(Utilities.SecretKey);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Username)
                    }),
                    Expires            = DateTime.Now.AddMinutes(30),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secretBytes), SecurityAlgorithms.HmacSha256)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);

                user.Token = tokenHandler.WriteToken(token);

                return(user);
            }

            return(null);
        }
        public async Task <IActionResult> LogIn(UserSignInDto model)
        {
            var user = await userManager.FindByNameAsync(model.UserName);

            if (user != null)
            {
                var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, false);

                if (result.Succeeded)
                {
                    var roles = await userManager.GetRolesAsync(user);

                    if (roles.Contains("Admin"))
                    {
                        return(RedirectToAction("Index", "Home", new { area = "Admin" }));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home", new { area = "Member" }));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Kullanıcı Adı veya Şifre Bulunamadı");
                }
            }
            return(View());
        }
        public async Task <IActionResult> LogIn(UserSignInDto model)
        {
            var user = await userManager.FindByNameAsync(model.UserName);

            if (user != null)
            {
                var result = await signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, false);

                if (result.Succeeded)
                {
                    var roles = await userManager.GetRolesAsync(user);

                    if (roles.Contains("Secretary"))
                    {
                        return(RedirectToAction("Index", "Profile"));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Profile"));
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Kullanıcı Adı veya Şifre Hatalı");
            }
            return(View(model));
        }
예제 #4
0
        public User Map(UserSignInDto source)
        {
            var target = new User();

            target.Email    = source.Email;
            target.Password = source.Password;
            return(target);
        }
예제 #5
0
        public IActionResult Authenticate(UserSignInDto model)
        {
            if (ModelState.IsValid)
            {
                var user = userRepo.Authenticate(model);
                return(Ok(user));
            }

            return(BadRequest(new { message = "NotValid" }));
        }
예제 #6
0
        public async Task <IActionResult> SignIn(UserSignInDto userSignInDto)
        {
            User user = await GetUser(userSignInDto.Email, userSignInDto.Password).ConfigureAwait(false);

            if (user == null)
            {
                return(NotFound());
            }
            await Authorize(user).ConfigureAwait(false);

            return(RedirectToRoute(nameof(UsersController.GetUser), new { id = user.UserId }));
        }
예제 #7
0
        public async Task <ActionResult <IResponse <object> > > SignInAsync(UserSignInDto dto)
        {
            var validationResponse = UserValidator.Validate(dto);

            if (!validationResponse.IsValid)
            {
                return(BadRequest(validationResponse));
            }

            var attemptCredentialsResponse = UserLogic.SignIn(UserMapper.Map(dto));

            if (!attemptCredentialsResponse.IsValid)
            {
                return(BadRequest(attemptCredentialsResponse));
            }

            if (attemptCredentialsResponse != null)
            {
                var claims = new List <Claim>
                {
                    new Claim(nameof(RequestContext.Email), attemptCredentialsResponse.Data.Email),
                    new Claim(nameof(RequestContext.UserId), attemptCredentialsResponse.Data.Id.ToString()),
                };

                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties
                {
                    AllowRefresh = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(30),
                    IsPersistent = true,
                    IssuedUtc    = DateTimeOffset.Now,
                    RedirectUri  = "User/SignIn"
                };

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);

                HttpContext.Response.Cookies.Append("account", JsonSerializer.Serialize(new { id = attemptCredentialsResponse.Data.Id, email = dto.Email }), new Microsoft.AspNetCore.Http.CookieOptions
                {
                    HttpOnly = false
                });
            }

            return(Ok(attemptCredentialsResponse.Data));
        }
예제 #8
0
        private void ValidateSignInModel(UserSignInDto model, User user)
        {
            byte[] md5Hash        = _md5.ComputeHash(Encoding.ASCII.GetBytes(model.Password));
            string hashedPassword = Encoding.ASCII.GetString(md5Hash);

            if (user == null)
            {
                throw new Exception("User does not exists");
            }

            if (user.Password != hashedPassword)
            {
                throw new Exception("Wrong Password");
            }
        }
예제 #9
0
        public async Task <LoginResultDto> LogInAsync(UserSignInDto userDto)
        {
            try
            {
                userDto.PasswordHash = GetPasswordHash(userDto.Password);

                var user = await _userAuthDalFacade.FindByEmailAsync(userDto.Email);

                if (user == null)
                {
                    return new LoginResultDto {
                               Success = false, Message = $"Пользователь {userDto.Email} не найден"
                    }
                }
                ;
                var passwordValid = userDto.PasswordHash == user.PasswordHash;
                if (!passwordValid)
                {
                    return new LoginResultDto {
                               Success = false, Message = $"Неправильный пароль"
                    }
                }
                ;

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserId", user.Id),
                        new Claim("ExpDate", DateTime.UtcNow.AddDays(7).ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appsettings.SecretKey)), SecurityAlgorithms.HmacSha256Signature)
                };

                var tokenHandler = new JwtSecurityTokenHandler();
                var secureToken  = tokenHandler.CreateToken(tokenDescriptor);
                var token        = tokenHandler.WriteToken(secureToken);

                return(new LoginResultDto {
                    Success = true, UserId = user.Id, Token = token
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #10
0
        public IResponse <string> Validate(UserSignInDto dto)
        {
            var response = new Response <string>();

            if (string.IsNullOrWhiteSpace(dto.Email))
            {
                response.Errors.Add("Email is required");
            }

            if (string.IsNullOrWhiteSpace(dto.Password))
            {
                response.Errors.Add("Password is required");
            }

            return(response);
        }
예제 #11
0
        private void Arrange()
        {
            _userValidator = new UserValidator();

            _userSignUpDto = new UserSignUpDto
            {
                Email           = "*****@*****.**",
                Password        = "******",
                ConfirmPassword = "******",
            };

            _userSignInDto = new UserSignInDto
            {
                Email    = "*****@*****.**",
                Password = "******"
            };
        }
예제 #12
0
        public async Task <IActionResult> SignIn([FromBody] UserSignInDto userCredentials)
        {
            if (userCredentials == null)
            {
                return(BadRequest("Invalid client request"));
            }
            var response = await _authenticationService.Authenticate(userCredentials);

            if (response == null)
            {
                return(Unauthorized());
            }
            else
            {
                return(Ok(response));
            }
        }
예제 #13
0
        public async Task <AuthenticationResponse> Authenticate(UserSignInDto userCredentials)
        {
            var user = await _repository.User.FindUser(userCredentials.Login);

            if (user == null || !BCrypt.Net.BCrypt.Verify(userCredentials.Password, user.Password) || user.Status == UserStatus.Inactive)
            {
                return(null);
            }
            var token    = GenerateToken(user);
            var response = new AuthenticationResponse
            {
                UserId = user.UserId,
                Token  = token
            };

            return(response);
        }
예제 #14
0
        public async Task <bool> AddSignInAsync(UserSignInDto user)
        {
            try
            {
                var appUser = new ApplicationUser
                {
                    Id       = user.UserId,
                    UserName = user.UserName,
                    Email    = user.UserEmail
                };

                await SignInManager.SignInAsync(appUser, user.IsPersistence, user.RememberBrowser);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #15
0
        public async Task <IActionResult> Login([FromBody] UserSignInDto userSignInDto)
        {
            var endPointDiscovery = await _discoveryCache.GetAsync();

            if (endPointDiscovery.IsError)
            {
                _logger.Log(LogLevel.Error, $"ErrorType: {endPointDiscovery.ErrorType} Error: {endPointDiscovery.Error}");
                throw new Exception("Something went wrong while connecting to the AuthServer Token Endpoint.");
            }

            var tokenResponse = await _httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = endPointDiscovery.TokenEndpoint,
                ClientId     = _configuration["Self:Id"],
                ClientSecret = _configuration["Self:Secret"],
                Scope        = "app.expensetracker.api.full openid profile offline_access",
                GrantType    = GrantTypes.Password,
                UserName     = userSignInDto.UserName,
                Password     = userSignInDto.Password
            });

            return(Ok(new { access_token = tokenResponse.AccessToken, refresh_token = tokenResponse.RefreshToken, expires_in = tokenResponse.ExpiresIn }));
        }
예제 #16
0
        public async Task <ActionResult> UserSignIn([FromBody] UserSignInDto userData)
        {
            var user = await _userManager.FindByEmailAsync(userData.email);

            if (user is null)
            {
                return(BadRequest($"User with e-mail address {userData.email} doesn't exist"));
            }

            var passwordValid = await _userManager.CheckPasswordAsync(user, userData.password);

            if (passwordValid)
            {
                var roles = await _userManager.GetRolesAsync(user);

                var jwtToken = GenerateJwt(user, roles);
                return(Ok(jwtToken));
            }
            else
            {
                return(BadRequest("Wrong password"));
            }
        }
예제 #17
0
        public UserWithTokenDto Authenticate(UserSignInDto model)
        {
            try
            {
                User user = _userRepository.GetByUsername(model.Username);
                ValidateSignInModel(model, user);

                byte[] key             = Encoding.ASCII.GetBytes(_tokenConfig.SecretKey);
                var    tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };

                var token = _tokenHandler.CreateToken(tokenDescriptor);

                return(new UserWithTokenDto
                {
                    Id = user.Id,
                    Username = user.Username,
                    Email = user.Email,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Age = user.Age,
                    Token = _tokenHandler.WriteToken(token)
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public UserWithTokenDto Authenticate([FromBody] UserSignInDto model)
 {
     return(_userService.Authenticate(model));
 }
        public async Task <AppHttpResponseMessageWrapper> SignInMemberAsync(UserSignInDto userInfo)
        {
            var response = await _httpClient.PostAsJsonAsync("api/account/signin/user", userInfo);

            return(new AppHttpResponseMessageWrapper(response));
        }
예제 #20
0
        public async Task <IActionResult> Login([FromBody] UserSignInDto userDto)
        {
            var result = await _userAuthService.LogInAsync(userDto);

            return(Json(result));
        }