예제 #1
0
        public async Task <Results <RefreshTokenContract> > Login(PandaUserLoginContract account)
        {
            var refreshTokenIsNullOrEmpty = await _userLogic.RefreshTokenIsNullOrEmpty(account.Email);

            if (!refreshTokenIsNullOrEmpty)
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("User still loged in."));
            }

            var signInResult = await _userLogic.Login(account);

            if (signInResult.IsError())
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(signInResult.Errors.ToArray()));
            }
            account.Id = signInResult.Data.Id;

            var token        = _jwtTokenService.GenerateToken(account.Email, account.Id.ToString());
            var refreshToken = _jwtTokenService.GenerateRefreshToken();
            var tokenData    = new RefreshTokenContract {
                RefreshToken = refreshToken, Token = token
            };

            var refreshTokenResult = await _userLogic.UpdateRefreshTokenToUser(account.Email, refreshToken);

            if (refreshTokenResult.IsError())
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(refreshTokenResult.Errors.ToArray()));
            }
            return(PandaResponse.CreateSuccessResponse(tokenData));
        }
        public ActionResult LoginAdmin()
        {
            var key = _config.GetSection("AppSettings:EncryptionKey").Value;
            // Roles = CUSTOMER,ADMIN
            var token = _jwtTokenService.GenerateToken(1, 1, "ADMIN", key);

            return(Ok(token));
        }
        public async Task <ServiceResponseData <TokenData> > LoginAsync(LoginModel loginModel)
        {
            var responseData = new ServiceResponseData <TokenData>();

            try
            {
                var user = await _userManager.FindByNameAsync(loginModel.UserName);

                if (user == null)
                {
                    throw new Exception("Invalid username");
                }

                var isValidPassword = await _userManager.CheckPasswordAsync(user, loginModel.Password);

                if (!isValidPassword)
                {
                    throw new Exception("Invalid password");
                }
                responseData = await _jwtTokenService.GenerateToken(user);
            }
            catch (Exception ex)
            {
                responseData.ErrorMessage = ex.ProcessException(_errorService);
                responseData.IsSuccess    = false;
            }

            return(await Task.FromResult(responseData));
        }
예제 #4
0
        public async Task <IActionResult> Login(UserLoginDto userLoginDto)
        {
            var user = await _userManager.FindByNameAsync(userLoginDto.Username);

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

            var result = await _signInManager.CheckPasswordSignInAsync(user, userLoginDto.Password, false);

            if (result.Succeeded)
            {
                var userApp = _mapper.Map <UserDetailDto>(user);

                return(Ok(new
                {
                    token = await _jwtTokenService.GenerateToken(user),
                    user = userApp
                }));
            }
            else
            {
                return(Unauthorized());
            }
        }
예제 #5
0
        public async Task <IActionResult> Login([FromBody] LoginDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = await _authenticationService.PasswordSignInAsync(model.UserName, model.Password, true);

            if (result.Succeeded)
            {
                var token = _jwtTokenService.GenerateToken(result.UserIdentity, result.Roles);

                return(Ok(token));
            }

            if (result.IsLockedOut)
            {
                return(BadRequest($"User account locked out, max failed access attemps are {_identityOptions.Value.Lockout.MaxFailedAccessAttempts}"));
            }
            else if (result.IsNotAllowed)
            {
                return(BadRequest("User account is not allowed, make sure your account have been verified"));
            }
            else if (result.RequiresTwoFactor)
            {
                return(BadRequest("Two Factor Login is required"));
            }

            return(BadRequest("User Name or Password does not match"));
        }
예제 #6
0
        public async Task <IActionResult> SignIn([FromBody] GenericUserContract account)
        {
            GenericUser accountData = await _accountFacade.SignIn(account);

            var response = LinqExtensions.CreateErrorResponse <RefreshTokenContract>("Unauthorized");

            if (accountData != null)
            {
                var token        = _jwtTokenService.GenerateToken(accountData.Email, accountData.Id.ToString());
                var refreshToken = _jwtTokenService.GenerateRefreshToken();
                var tokenData    = new RefreshTokenContract {
                    RefreshToken = refreshToken, Token = token
                };
                response = LinqExtensions.CreateSuccessResponse(tokenData);
            }
            return(Ok(response));
        }
예제 #7
0
        public async Task <IActionResult> GenerateTokenAsync([FromBody] LoginViewModel user)
        {
            var userId = await _usersService.ValidateUserAsync(user.Email, user.Password);

            if (userId > 0)
            {
                return(Ok(_jwtTokenService.GenerateToken(userId, 60)));
            }
            return(BadRequest("Could not find user with these email/password"));
        }
예제 #8
0
        public async Task <ActionResult> Login([FromBody] LoginModel model)
        {
            var user = await _userRepository.GetByUsernameAndPassword(model.Username, model.Password);

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

            return(Ok(new { Token = _tokenService.GenerateToken(user), _tokenService.Descriptor.Expires }));
        }
예제 #9
0
        public async Task <Tuple <string, User, ApiResponse> > TokenGenerate(string emailId, string password)
        {
            var result = await _userService.GetUserByEmailAndPassword(emailId.Trim(), new Security().Encrypt(password.Trim()));

            //Authenticate User, Check if it’s a registered user in Database
            if (!result.Status)
            {
                return(new Tuple <string, User, ApiResponse>(null, result.Data, result));
            }

            if (password == new Security().Decrypt(result.Data.Password))
            {
                var token = _jwtTokenService.GenerateToken(result.Data.EmailAddress, Guid.NewGuid().ToString());

                result.Data.Password = null;
                return(new Tuple <string, User, ApiResponse>(token, result.Data, result));
            }
            else
            {
                return(new Tuple <string, User, ApiResponse>(null, result.Data, result));
            }
        }
예제 #10
0
        public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticateModel model)
        {
            var user = await userService.AuthenticateAsync(model.Username, model.Password);

            if (user == null)
            {
                return(BadRequest(new Errors(ControllerMessage.AuthenticateError)));
            }

            var tokenString = jwtTokenService.GenerateToken(user.UserId.ToString());

            return(Ok(new { Token = tokenString }));
        }
예제 #11
0
        public async Task <IActionResult> TokenAsync(AuthorizationDto authData)
        {
            var isAuthorized = await _authService.AuthorizeAsync(authData.Username, authData.Password);

            if (!isAuthorized)
            {
                return(Unauthorized());
            }

            var token = _jwtTokenService.GenerateToken(authData.Username);

            return(Ok(token));
        }
예제 #12
0
        public async Task <TokenViewModel> Login(UserCredentials credentials)
        {
            var appUser = await _userManager.FindByNameAsync(credentials.Username);

            var isPasswordCorrect = await _userManager.CheckPasswordAsync(appUser, credentials.Password);

            if (isPasswordCorrect)
            {
                var token = _tokenService.GenerateToken(appUser);
                return(new TokenViewModel(token));
            }

            throw InvalidCredentialsExceptions();
        }
예제 #13
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto model)
        {
            var user = await _userService.Authenticate(model.Username, model.Password);

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

            var userAuthenticated = _jwtTokenService.GenerateToken(user);


            return(Ok(userAuthenticated));
        }
예제 #14
0
        public async Task <TokenModel> Login(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                throw new UnauthorizedAccessException("Required parameter is null or empty");
            }

            var account = await _accountService.GetAccountAsync(username.ToLower(), password);

            if (account == null)
            {
                throw new UnauthorizedAccessException("User with this name and password not found");
            }

            return(_tokenService.GenerateToken(account.Username));
        }
예제 #15
0
        public async Task <IActionResult> CreateAsync(NewUserDto authData)
        {
            var user = await _userService.GetAsync(authData.Username);

            if (user != null)
            {
                return(BadRequest($"{authData.Username} был создан ранее."));
            }

            var result = await _userService.CreateAsync(authData);

            await _authService.CreatePasswordAsync(authData.Username, authData.Password);

            var token = _jwtTokenService.GenerateToken(result.Username);

            return(Ok(token));
        }
        public ActionResult Login([FromBody] LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid input"));
            }

            CustomerModel customer = _customerService.SignIn(model.Email, model.Password);

            if (customer == null)
            {
                return(Unauthorized());
            }

            JWTToken token = _jwtTokenService.GenerateToken(customer);

            return(Ok(token));
        }
예제 #17
0
        public async Task <IActionResult> Login(UserLoginRequest userLoginRequest)
        {
            var userLoggedInResult = await _authService.Login(userLoginRequest);

            if (userLoggedInResult.ResponseStatus == ResponseStatus.Succeeded)
            {
                var token = _jwtTokenService.GenerateToken(userLoggedInResult);

                return(Ok(new
                {
                    userLoggedInResult.Data,
                    userLoggedInResult.ResponseStatus,
                    Token = token,
                    userLoggedInResult.Error
                }));
            }

            return(StatusCode((int)userLoggedInResult.Error.HttpStatusCode, userLoggedInResult));
        }
예제 #18
0
        public async Task <IActionResult> LoginUser([FromBody] LoginUserRequest loginUserRequest)
        {
            _logger.LogDebug($"Attempting to log in user: {loginUserRequest.Email}");

            var user = await _db.Users
                       .IgnoreQueryFilters()
                       .FirstOrDefaultAsync(u => u.Email == loginUserRequest.Email);

            //need to match password here too once password has been added

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

            var jwtToken = _jwtTokenService.GenerateToken(user.Id);

            return(Ok(jwtToken));
        }
예제 #19
0
        public async Task <LoginResult> Login(LoginQuery loginQuery)
        {
            var loginResult = new LoginResult();

            var user = await _userService.GetUser(loginQuery.Email, loginQuery.Password);

            if (user != null)
            {
                loginResult.IsValidUser = true;
                loginResult.UserId      = user.Id;
                loginResult.FullName    = $"{user.FirstName} {user.LastName}";
                loginResult.Token       = _jwtTokenService.GenerateToken(user.Email, user.UserType);

                //move this to a queue
                await _cacheProvider.SetCache($"User_{user.Email}", user);
            }

            return(loginResult);
        }
예제 #20
0
        public async Task <IActionResult> Login(SigninViewModel input)
        {
            var user = await _userService.GetUserByEmail(input.Email);

            if (user == null)
            {
                return(BadRequest(new { error = "", error_description = "Usuario não existe" }));
            }

            if (!user.IsActive)
            {
                return(BadRequest(new { error = "", error_description = "Usuario não esta ativo" }));
            }

            if (!await _userService.DoLogin(user.Email, input.Password))
            {
                return(BadRequest(new { error = "", error_description = "Email ou senha inválida" }));
            }

            string token = _jwtTokenService.GenerateToken(user);

            return(Ok(new { token }));
        }
예제 #21
0
        public async Task <Response> SendMagicLinkEmailAsync(string emailTo)
        {
            var apiKey = _configuration.GetSection("SendGridApiKey")?.Value;

            if (apiKey == null)
            {
                throw new Exception("Can't find SendGridApiKey value in configuration.");
            }

            var client = new SendGridClient(apiKey);

            var token = _jwtTokenService.GenerateToken(emailTo);

            var msg = new SendGridMessage();

            msg.SetFrom("*****@*****.**");
            msg.AddTo(emailTo);
            msg.SetSubject("Login Magic Link for 9Cat.world");
            msg.AddContent(MimeType.Text, $"Hello! You can login to 9Cat.world with {emailTo}. Your token is: {token} and is valid for 30 days.");

            var result = await client.SendEmailAsync(msg);

            return(result);
        }
예제 #22
0
        public async Task <IActionResult> SignIn([FromBody] SignInModelRq signInModelRq)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = await _authService.SignInAsync(signInModelRq.UserName, signInModelRq.Password, true);

            if (result.Succeeded)
            {
                GrantedPermission grantedPermission = await _permissionService.GetGrantedPermission(result.UserIdentity.Id, result.Roles.ToList());

                List <Claim> additionClaims = new List <Claim>();
                //additionClaims.Add(new Claim("permission", JsonConvert.SerializeObject(grantedPermission)));
                UserModel infoUser = await _userService.GetUserById(result.UserIdentity.Id);

                additionClaims.Add(new Claim("userInfo", JsonConvert.SerializeObject(infoUser)));
                var token = _jwtTokenService.GenerateToken(result.UserIdentity, result.Roles, additionClaims);
                return(Ok(token));
            }

            if (result.IsLockedOut)
            {
                return(BadRequest($"User account locked out, max failed access attemps are {_identityOptions.Value.Lockout.MaxFailedAccessAttempts}"));
            }
            else if (result.IsNotAllowed)
            {
                return(BadRequest("User account is not allowed, make sure your account have been verified"));
            }
            else if (result.RequiresTwoFactor)
            {
                return(BadRequest("Two Factor Login is required"));
            }

            return(BadRequest("User Name or Password does not match"));
        }
        public async Task <IActionResult> GenerateToken()
        {
            var token = await _jwtTokenService.GenerateToken();

            return(Ok(token));
        }
예제 #24
0
        public IActionResult GenerateToken()
        {
            var token = _jwtTokenService.GenerateToken();

            return(Ok(token));
        }