示例#1
0
        public async Task <IActionResult> SignIn([FromBody] SignInRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var account = _mapper.Map <Account>(request);
                account = await _accountRepository.SignInAsync(account);

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

                return(Ok(_tokenHelper.GenerateToken(account)));
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Exception", e.Message);
            }

            return(BadRequest(ModelState));
        }
示例#2
0
        public AuthorizeModel Login(UserLoginModel userLogin)
        {
            var user = _userRepository.GetUserByEmail(userLogin.Email);

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

            (_, string checkedPassword) = _hashHelper.Hash(userLogin.Password, user.Salt);

            if (user.Password != checkedPassword)
            {
                throw new Exception("Invalid Credentials");
            }

            var mappedUser = new AuthorizeModel
            {
                Id    = user.Id,
                Email = user.Email,
            };

            mappedUser.Token = _tokenHelper.GenerateToken(user.Email, user.Id, user.Role);

            return(mappedUser);
        }
示例#3
0
        public object Login(UserLoginRequest request)
        {
            var user = repository.GetByEmail(request.Email);

            if (user == null || !BCrypt.Net.BCrypt.Verify(request.Password, user.Password))
            {
                return(null);
            }
            string token = tokenHelper.GenerateToken(user);

            return(response.Response(user, token));
        }
示例#4
0
        public LoginResult Login(LoginRequest request)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var lowerLogin = request.Login.ToLower();

            var user = _dataProvider.Get <UserDb>(i => i.Login == lowerLogin).SingleOrDefault();

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

            var varify = BCrypt.Net.BCrypt.Verify(request.Password, user.Password);

            if (!varify)
            {
                return(null);
            }

            var token = _tokenHelper.GenerateToken(user.Id);

            return(new LoginResult {
                Token = token
            });
        }
示例#5
0
        /// <summary>
        /// Authenticate the user in the system and generate the access-key (token)
        /// </summary>
        /// <param name="request">Request data</param>
        /// <param name="details">Indicates whether to return user details</param>
        /// <param name="cancellationToken">A System.Threading.CancellationToken to observe while waiting for the task to complete</param>
        protected async Task <IActionResult> AuthenticateAsync(AuthenticateRequest request, bool details, CancellationToken cancellationToken = default)
        {
            if (!AppKey.HasValue || !AppAccess.HasValue)
            {
                return(Unauthorized(_localizer["SCOPE_NOT_DEFINED"].Value));
            }

            AuthenticateResult <UserDto> authResult = await _appService.AuthenticateAsync(AppKey.Value, AppAccess.Value, request.Login, request.Password, cancellationToken);

            if (authResult.Success)
            {
                SimpleUserResponse   userDetail = null;
                IEnumerable <string> roles      = null;
                if (details)
                {
                    userDetail = new SimpleUserResponse(authResult.User.Id)
                    {
                        Name  = new FullNameResponse(authResult.User.Name.FirstName, authResult.User.Name.LastName),
                        Email = authResult.User.Email
                    };
                    roles = authResult.User.Roles?.Select(r => r.Name);
                }

                string token = _tokenHelper.GenerateToken(authResult.User, request.Login, out DateTime? expiresIn);

                AuthenticateResponse result = new AuthenticateResponse(token, expiresIn, roles, userDetail);
                return(Ok(result));
            }

            return(Unauthorized(authResult.ErrorsMessage));
        }
示例#6
0
        public AuthorizeModel Register(RegisterViewModel registerViewModel)
        {
            if (!new EmailAddressAttribute().IsValid(registerViewModel.UserName))
            {
                throw new Exception("Invalid E-mail");
            }

            if (!_passwordHelper.GetPasswordRegex(registerViewModel.Password))
            {
                throw new Exception("Invalid Credentials");
            }

            var user = _userRepository.GetUserByUserName(registerViewModel.UserName);

            if (user != null)
            {
                throw new Exception("User already exists");
            }

            if (registerViewModel.Password != registerViewModel.ConfirmPassword)
            {
                throw new Exception("Invalid Credentials");
            }

            (string salt, string hashedPassword) = _hashHelper.Hash(registerViewModel.Password);

            var createdUser = new User
            {
                UserName  = registerViewModel.UserName,
                FirstName = registerViewModel.FirstName,
                LastName  = registerViewModel.LastName,
                Password  = hashedPassword,
                Salt      = salt,
                Balance   = 1000,
                Role      = Role.Player
            };

            _userRepository.Create(createdUser);

            var model = new AuthorizeModel {
                Id = createdUser.Id, UserName = createdUser.UserName
            };

            model.Token = _tokenHelper.GenerateToken(createdUser.UserName, createdUser.Id, createdUser.Role);

            return(model);
        }
        public async Task <IActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(ApiResponse(ModelState));
            }

            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password,
                                                                  model.RememberMe, true);

            if (result.Succeeded)
            {
                // Create Succeeded login event log
                await _activityLog.AddActivityLog(ActivityLogType.Login, UserId);

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

                var tokenResponse = _tokenHelper.GenerateToken(user);
                return(ApiResponse(tokenResponse));
            }

            if (result.IsLockedOut)
            {
                // Create IsLockedOut login event log
                await _activityLog.AddActivityLog(ActivityLogType.IsAccountLockedOut, UserId);

                AddError("This user is temporarily blocked");
                return(ApiResponse());
            }

            // Create Invalid login event log
            await _activityLog.AddActivityLog(ActivityLogType.InvalidLogin, UserId);

            AddError("Incorrect user or password");
            return(ApiResponse());
        }
示例#8
0
        public async Task <Response <LoginUserResult> > LoginAsync(LoginUserRequest loginRequest)
        {
            if (!await _users.ExistsAsync(loginRequest.Username))
            {
                return(Failure <LoginUserResult>("User with such username does not exist"));
            }

            var user = await _users.GetAsync(loginRequest.Username);

            if (user.Password != loginRequest.Password)
            {
                return(Failure <LoginUserResult>("Incorrect password"));
            }

            var loginResult = _mapper.Map <LoginUserResult>(user);

            loginResult.Token = _tokenHelper.GenerateToken(user);
            return(Success(loginResult));
        }
示例#9
0
        public async Task <AuthenticateUserResponse> Login(LoginRequest request)
        {
            _logger.LogInformation($"Login attempt for {request.Username}");

            // Get the user that owns this email address, if any.
            var matchedEmail = await _context
                               .UserEmails
                               .Include(x => x.User)
                               .OrderByDescending(x => x.Created)
                               .FirstOrDefaultAsync(x => x.Email == request.Username);

            if (matchedEmail == null)
            {
                return new AuthenticateUserResponse
                       {
                           Message      = "Invalid Username/Password",
                           Success      = false,
                           ResponseCode = 404
                       }
            }
            ;

            // Validate it's the latest validated email.
            var emails = await _context
                         .UserEmails
                         .Where(x => x.User == matchedEmail.User && x.ValidatedDate.HasValue)
                         .OrderByDescending(x => x.ValidatedDate)
                         .ToListAsync();

            if (emails != null && emails.FirstOrDefault()?.Email != request.Username)
            {
                return new AuthenticateUserResponse
                       {
                           Message      = "Email is obsolete",
                           ResponseCode = 401,
                           Success      = false
                       }
            }
            ;

            // Encrypt the incoming password so we can check against the hashed one in database.
            var encryptedPassword =
                EncryptionHelper.GenerateSaltedHash(request.Password, matchedEmail.User.Id.ToString());

            var user = await _context
                       .Users
                       .Where(x => x.Id == matchedEmail.User.Id &&
                              x.Password == encryptedPassword)
                       .SingleOrDefaultAsync();

            _logger.LogInformation($"Login Success for {request.Username}");


            var userDetails = await _mediator.Send(new GetUserByIdQuery { Id = user.Id });

            var token = _tokenHelper.GenerateToken(userDetails.Data);

            return(new AuthenticateUserResponse
            {
                Firstname = user.Firstname,
                Id = user.Id,
                Surname = user.Surname,
                Token = token,
                Message = "Login Success",
                Success = true,
                ResponseCode = 200,
            });
        }