Ejemplo n.º 1
0
        public async Task <IActionResult> Login(LoginViewModel loginViewModel)
        {
            try
            {
                var response = await _accountBl.Login(loginViewModel.UserName, loginViewModel.Password);

                if (response != null && response.IsActive && !response.IsDeleted)
                {
                    response.Token = _tokenGenerator.GenerateJwtToken(
                        _appConfiguration.JwtAuthorizationSettings.SecretKey,
                        _appConfiguration.JwtAuthorizationSettings.Issuer,
                        _appConfiguration.JwtAuthorizationSettings.Audience,
                        new List <Claim>
                    {
                        new Claim(ClaimTypes.Email, Convert.ToString(loginViewModel.UserName)),
                        new Claim("UserId", Convert.ToString(response.Id)),
                    },
                        _appConfiguration.JwtAuthorizationSettings.ExpirationTimeInMinute);

                    if (loginViewModel.RememberMe)
                    {
                        var refreshToken = _tokenGenerator.GenerateJwtToken(_appConfiguration.JwtRefreshTokenSettings.SecretKey,
                                                                            _appConfiguration.JwtRefreshTokenSettings.Issuer,
                                                                            _appConfiguration.JwtRefreshTokenSettings.Audience,
                                                                            new List <Claim>
                        {
                            new Claim(ClaimTypes.Email, Convert.ToString(loginViewModel.UserName)),
                            new Claim("UserId", Convert.ToString(response.Id)),
                        },
                                                                            _appConfiguration.JwtRefreshTokenSettings.ExpirationTimeInMinute);
                        if (await _accountBl.SaveRefreshToken(refreshToken, response.Id.ToString(), response.UserNo))
                        {
                            response.RefreshToken = refreshToken;
                        }
                    }
                    return(Ok(response));
                }
                else
                {
                    HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    return(StatusCode((int)HttpStatusCode.Forbidden));
                }
            }
            catch (Exception exception)
            {
                return(InternalServerError(exception));
            }
        }
Ejemplo n.º 2
0
        public async Task <RegisterResponseModel> Register(
            RegisterModel validModel,
            UserManager <Entities.UserDb.User> userManager,
            SignInManager <Entities.UserDb.User> signInManager,
            IConfiguration configuration)
        {
            var newUser = _mapper.Map <Entities.UserDb.User>(validModel);

            var result = await userManager.CreateAsync(newUser, validModel.Password);

            //Sign in and generate token if register is succesful
            if (result.Succeeded)
            {
                var user = await userManager.FindByEmailAsync(validModel.Email);

                AddedToOrderDb(user.Id);

                await userManager.AddToRoleAsync(user, validModel.RoleName);

                await signInManager.SignInAsync(user, false);

                var token = await _tokenGenerator.GenerateJwtToken(validModel.Email, user, configuration);

                RegisterResponseModel model = new RegisterResponseModel {
                    UserId = user.Id,
                    Token  = token
                };

                return(model);
            }
            throw new ApplicationException("UNKNOWN_ERROR");
        }
Ejemplo n.º 3
0
        public async Task <object> Login(LoginModel model,
                                         UserManager <Entities.UserDb.User> userManager,
                                         SignInManager <Entities.UserDb.User> signInManager,
                                         IConfiguration configuration)
        {
            var userName = await userManager.FindByEmailAsync(model.Email);

            var result = await signInManager.PasswordSignInAsync(userName.UserName, model.Password, false, false);

            if (result.Succeeded)
            {
                var appUser = userManager.Users.SingleOrDefault(r => r.Email == model.Email);
                var token   = await _tokenGenerator.GenerateJwtToken(model.Email, appUser, configuration);

                var userId        = (await userManager.FindByEmailAsync(model.Email)).Id;
                var roleName      = (await userManager.GetRolesAsync(appUser)).SingleOrDefault();
                var modelResponse = new LoginResponseModel
                {
                    UserId   = userId,
                    Token    = token,
                    RoleName = roleName
                };

                return(modelResponse);
            }

            throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Send Forgot Password Email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public async Task <bool> SendForgotPasswordEmail(string email)
        {
            UsersDTO user     = new UsersDTO();
            bool     result   = false;
            bool     response = true;

            if (response)
            {
                user = await GetUserDetailsByUsername(email);

                if (user != null)
                {
                    IList <Claim> claims = GetPasswordClaims(_mapper.Map <Users>(user));
                    var           token  = _tokenGenerator.GenerateJwtToken(
                        _appConfiguration.JwtForgotPasswordSettings.SecretKey,
                        _appConfiguration.JwtForgotPasswordSettings.Issuer,
                        _appConfiguration.JwtForgotPasswordSettings.Audience,
                        claims,
                        _appConfiguration.JwtForgotPasswordSettings.ExpirationTimeInMinute
                        );

                    result = true;
                }
            }
            return(result);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Login(LoginDto model)
        {
            if (_authentication.ValidateCredentials(model.Login, model.Password))
            {
                var appUser = await _userManager.FindByNameAsync(model.Login);

                if (appUser == null)
                {
                    appUser = new User
                    {
                        UserName = model.Login,
                        Roles    = new List <Role>()
                    };
                    var result = await _userManager.CreateAsync(appUser);

                    if (result != IdentityResult.Success)
                    {
                        BadRequest("Can't create user!");
                    }
                }

                return(Ok(_tokenGenerator.GenerateJwtToken(appUser)));
            }

            return(BadRequest("Wrong login or password"));
        }
Ejemplo n.º 6
0
        public async Task <ApiResponse> Login([FromBody] LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new ApiException(ModelState.AllErrors(), StatusCodes.Status401Unauthorized);
            }

            var result = await _signInManager.PasswordSignInAsync(model.Email,
                                                                  model.Password,
                                                                  model.RememberLogin,
                                                                  false);

            if (!result.Succeeded)
            {
                ModelState.AddModelError(string.Empty, "Invalid email or password");

                throw new ApiException(ModelState.AllErrors(), StatusCodes.Status401Unauthorized);
            }


            var user = await _userManager.FindByNameAsync(model.Email);

            var token        = _tokenGenerator.GenerateJwtToken(user.AppUserId);
            var refreshToken = _tokenGenerator.GenerateRefreshToken();

            user.RefreshTokens.Add(refreshToken);
            _dbContext.Set <AuthUser>().Update(user);
            await _dbContext.SaveChangesAsync();

            var refreshTokenByteArray = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(refreshToken));

            try
            {
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return(new ApiResponse(new
                {
                    token = jwtToken,
                    expires = token.ValidTo,
                    refreshToken = Convert.ToBase64String(refreshTokenByteArray)
                }));
            }
            catch (Exception ex)
            {
                throw new ApiException(ex);
            }
        }
Ejemplo n.º 7
0
        public async Task <TokenModel> Handle(SignInModel request, CancellationToken cancellationToken)
        {
            var result = await _authDataManager.SignIn(request.Mail);

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

            var claims = new Claim[]
            {
                new Claim(BSConstants.UserId, result.Id.ToString())
            };
            string jwt = await _tokenGenerator.GenerateJwtToken(claims, _jwtSecrets.TokenSecrete, DateTime.Now.AddDays(1));

            var token = new TokenModel
            {
                Token = jwt
            };

            return(token);
        }