Exemplo n.º 1
0
        public async Task <JsonWebToken> SignIn(string email, string password)
        {
            var user = await GetUser(email);

            if (user == null)
            {
                throw new ServiceException(ErrorCodes.InvalidCredentials, "Invalid credentials");
            }

            if (!user.ValidatePassword(password, _passwordHasher))
            {
                throw new ServiceException(ErrorCodes.InvalidCredentials, "Invalid credentials");
            }

            var jwt = _jwtHandler.Create(user.Email, user.Role);

            var refreshTokenFromDb = await GetRefreshTokenByEmail(user.Email);

            if (refreshTokenFromDb == null)
            {
                var refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString())
                                   .Replace("+", string.Empty)
                                   .Replace("=", string.Empty)
                                   .Replace("/", string.Empty);
                jwt.RefreshToken = refreshToken;

                await AddRefreshToken(new RefreshToken { Email = email, Token = refreshToken });
            }
            else
            {
                jwt.RefreshToken = refreshTokenFromDb.Token;
            }

            return(jwt);
        }
Exemplo n.º 2
0
        public JsonWebToken SignIn(string username, string password)
        {
            var user = UserQueries.Login(username, password);

            if (user == null)
            {
                throw new AuthenticationException("Invalid credentials.");
            }
            var jwt          = _jwtHandler.Create(user);
            var refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString())
                               .Replace("+", string.Empty)
                               .Replace("=", string.Empty)
                               .Replace("/", string.Empty);

            jwt.RefreshToken = refreshToken;

            TokenQueries.SaveRefreshToken(new RefreshToken
            {
                Username = user.UserName,
                UserId   = user.Id,
                Token    = refreshToken
            }
                                          );

            return(jwt);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Вход.
        /// </summary>
        public TokenViewModel SignInAsync(SignInViewModel model)
        {
            var(user, isSuccess) = _userService.TryToSignInAsync(model.Email, model.Password);
            if (!isSuccess)
            {
                throw new Exception("Invalid credentials.");
            }

            var jwt          = _jwtHandler.Create(model.Email);
            var refreshToken = _passwordHasher.HashPassword(model, Guid.NewGuid().ToString())
                               .Replace("+", string.Empty)
                               .Replace("=", string.Empty)
                               .Replace("/", string.Empty);

            jwt.RefreshToken = refreshToken;
            _refreshTokens.Add(new RefreshToken {
                Username = model.Email, Token = refreshToken
            });

            var tokenViewModel = new TokenViewModel
            {
                JsonWebToken = jwt,
                UserId       = user.Id,
                Role         = user.UserRole,
                FullName     = (user.LastName) +
                               (user.FirstName == String.Empty ? String.Empty : $" {user.FirstName}") +
                               (user.MiddleName == String.Empty ? String.Empty : $" {user.MiddleName}")
            };

            return(tokenViewModel);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="user"></param>
        public async Task <JsonWebToken> SignUp(CreateUser user)
        {
            user.Email = string.IsNullOrEmpty(user.Email) ? "" : user.Email.ToLower();
            var existingUser = (await _userRepository.Get(x => x.Email == user.Email)).FirstOrDefault();

            if (existingUser != null)
            {
                throw new ApplicationException("This email address is already in use by another account");
            }
            try
            {
                var userModel = new User()
                {
                    Id            = ObjectId.GenerateNewId().ToString(),
                    UId           = Guid.NewGuid(),
                    Email         = user.Email,
                    PasswordHash  = _encryptPassword.CreateHash(user.Password),
                    UserType      = user.UserRole.ToString(),
                    FirstName     = user.FirstName,
                    LastName      = user.LastName,
                    TermsAccepted = user.TermsConditionsAccepted,
                    CreatedOn     = DateTime.UtcNow,
                    IsDeleted     = false
                };
                await _userRepository.Add(userModel);

                var jsonWebToken = _jwtHandler.Create(userModel.Id, user.UserRole.ToString(), true);
                jsonWebToken.Username = user.Email;
                return(jsonWebToken);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Register error - " + ex.Message);
            }
        }
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="user"></param>
        public async Task <AuthenticationResult> SignUp(CreateUser user)
        {
            user.Email = string.IsNullOrEmpty(user.Email) ? "" : user.Email.ToLower();
            var existingUser = (await _userRepository.Get(x => x.Email == user.Email)).FirstOrDefault();

            if (existingUser != null)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Message = "This email address is already in use by another account",
                });
            }
            try
            {
                var userModel = new User()
                {
                    Id           = ObjectId.GenerateNewId().ToString(),
                    Email        = user.Email,
                    PasswordHash = _encryptPassword.CreateHash(user.Password),
                    Name         = user.Name,
                    ProfilePhoto = "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTJ-mXuETtV9PelHdVOYG7yMwKVZpW1NGNpFwND484eFIxU8IBe",
                    CreatedOn    = DateTime.UtcNow,
                    IsDeleted    = false
                };
                await _userRepository.Add(userModel);

                var jsonWebToken = _jwtHandler.Create(userModel.Id);

                var userProfile = new UserView
                {
                    Id           = userModel.Id,
                    Name         = userModel.Name,
                    ProfilePhoto = userModel.ProfilePhoto
                };

                return(new AuthenticationResult
                {
                    Success = true,
                    Token = jsonWebToken,
                    User = userProfile
                });
            }
            catch (Exception ex)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Message = "Register error - " + ex.Message,
                });
            }
        }
Exemplo n.º 6
0
        public AuthDto Login(AuthCommand command)
        {
            var user = _userRepository.GetByLogin(command.Login);

            if (user == null)
            {
                _notificationProvider.AddValidationError("User", "Usuário ou senha inválido");
                return(null);
            }

            if (!_encrypterService.Compare(command.Password, user.Salt, user.HashPassword))
            {
                _notificationProvider.AddValidationError("User", "Usuário ou senha inválido");
                return(null);
            }

            if (user.IsDeleted)
            {
                _notificationProvider.AddValidationError("User", "Usuário inválido");
                return(null);
            }

            var jwtToken = _jwt.Create(user.Login, user.Name);

            return(new AuthDto(jwtToken.Token));
        }
Exemplo n.º 7
0
        public async Task <IdentityToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null)
            {
                throw new Exception("Refresh token was not found.");
            }
            if (refreshToken.Revoked)
            {
                throw new Exception($"Refresh token was revoked");
            }
            var account = await _accountRepository.GetAsync(refreshToken.UserId);

            if (account == null)
            {
                throw new Exception($"Account was not found.");
            }
            var jwt = _jwtHandler.Create(account.Username, account.Role, account.Id);



            return(new IdentityToken
            {
                AccessToken = jwt.AccessToken,
                Expires = jwt.Expires,
                RefreshToken = refreshToken.Token,
                Role = account.Role,
                UserId = account.Id
            });
        }
Exemplo n.º 8
0
        public async Task <IdentityToken> LoginAsync(string username, string password)
        {
            var account = await _accountRepository.GetAsync(username);

            if (account == null)
            {
                throw new Exception("Invalid credentials");
            }
            var hash = _encrypter.GetHash(password, account.Salt);

            if (account.Password != hash)
            {
                throw new Exception("Invalid credentials");
            }
            var token        = Guid.NewGuid().ToString("N");
            var refreshToken = new RefreshToken(account, token);
            var jwt          = _jwtHandler.Create(account.Username, account.Role, account.Id);

            await _refreshTokenRepository.CreateAsync(refreshToken);

            return(new IdentityToken
            {
                AccessToken = jwt.AccessToken,
                Expires = jwt.Expires,
                RefreshToken = token,
                Role = account.Role,
                UserId = account.Id
            });
        }
Exemplo n.º 9
0
        public async Task <object> auth(Usuarios usuario)
        {
            Usuarios _usuario = await _ctx.Usuarios.FirstOrDefaultAsync(u => u.Correo == usuario.Correo && u.Contrasena == usuario.Contrasena);

            if (_usuario != null)
            {
                if (_usuario.Estatus)
                {
                    var token = _jwt.Create(usuario.Correo);
                    _usuario.Token = token.AccessToken;

                    if (await _ctx.SaveChangesAsync() > 0)
                    {
                        _manager.Activate(_usuario.Token);

                        return(new
                        {
                            _usuario.Correo,
                            _usuario.Usuario,
                            _usuario.Contrasena,
                            _usuario.Sexo,
                            _usuario.FechaCreacion,
                            _usuario.Token
                        });
                    }
                }
                return(null);
            }
            return(null);
        }
Exemplo n.º 10
0
        public LoginResultDto Execute(LoginDto dto)
        {
            User           user   = unit.User.GetByEmailIncludingRoles(dto.Email);
            LoginResultDto result = new LoginResultDto();

            if (user == null)
            {
                result.Message = Messages.UserNotExist;
            }
            else if (!user.ValidatePassword(dto.Password, _encrypter))
            {
                result.Message = Messages.InvalidPassword;
            }
            else if (user.Status != Enums.EntityStatus.Active.ToInt())
            {
                result.Message = Messages.UserNotActivated;
            }
            else if (user.UserRole == null || !user.UserRole.Any(p => p.RoleId == Roles.Admin.ToInt()))
            {
                result.Message = Messages.AccessDenied;
            }
            else
            {
                result.Object       = DtoBuilder.CreateLoginDto(user);
                result.Object.Token = _jwtHandler.Create(user.Id);
                result.Status       = true;
            }
            return(result);
        }
Exemplo n.º 11
0
        public async Task <JsonWebToken> LoginAsync(string idToken)
        {
            GoogleJsonWebSignature.Payload validPayload;

            try
            {
                validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken);
            }
            catch (Exception)
            {
                throw new AuthException("invalid_id_token_1");
            }

            if (validPayload == null)
            {
                throw new AuthException("invalid_id_token_2");
            }

            if (validPayload.HostedDomain != "skolakrizik.cz")
            {
                throw new AuthException("email_not_in_domain");
            }

            return(_jwtHandler.Create(validPayload.Email));
        }
Exemplo n.º 12
0
        public JsonWebToken SignIn(string username, string password)
        {
            var user = GetUser(username);

            if (!_encryptionManager.Compare(password, user.Password))
            {
                throw new Exception("Invalid credentials");
            }

            var jwt     = _jwtHandler.Create(user.ID);
            var refresh = GetOrAddRefreshToken(user.ID);

            jwt.RefreshToken = refresh.Token;

            return(jwt);
        }
Exemplo n.º 13
0
        public async Task <BaseResponse <JsonWebToken> > Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var email = request.EmailAddress.Trim().ToLowerInvariant();

            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(new BaseResponse <JsonWebToken>(false, "Email address is incorrect"));
            }

            // if (!await _userManager.IsEmailConfirmedAsync(user))
            // {
            //    return new BaseResponse<JsonWebToken>(false, "User has not confirmed email. Please confirm email.");
            // }

            var result = await _signInManager.PasswordSignInAsync(user, request.Password, false, false);

            if (!result.Succeeded)
            {
                // if (result.IsLockedOut)
                // {
                //    return new BaseResponse<JsonWebToken>(false, "Your profile has been locked. Please initiate a password reset to unlock your profile.");
                // }
                // else
                // {
                //    int maxAttempts = _userManager.Options.Lockout.MaxFailedAccessAttempts;
                //    int failedAttempts = await _userManager.GetAccessFailedCountAsync(user);
                //    return new BaseResponse<JsonWebToken>(false, $"Invalid credentials supplied. You have {maxAttempts - failedAttempts} attempts left.");
                // }

                return(new BaseResponse <JsonWebToken>(false, $"Invalid credentials supplied. Email or password is incorrect"));
            }

            List <Claim> claims = new List <Claim>();
            //get role claims here
            var roleNames = await _userManager.GetRolesAsync(user);

            var roles = _roleManager.Roles.Where(x => roleNames.Contains(x.Name)).ToList();

            foreach (ApplicationRole role in roles)
            {
                var roleClaims = await _roleManager.GetClaimsAsync(role);

                claims.AddRange(roleClaims);
            }

            // await _userManager.ResetAccessFailedCountAsync(user);
            //generate token
            var tokenResult = _jwtHandler.Create(
                user.Id,
                user.Email,
                $"{user.FirstName} {user.LastName}",
                user.UserType,
                claims, GetAuthorizationCode(user.UserType),
                true
                );

            return(new BaseResponse <JsonWebToken>(true, "Login successful", tokenResult));
        }
Exemplo n.º 14
0
        public async Task <UserModel> LoginAsync(string email, string password)
        {
            if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(password))
            {
                throw new CardException("Invalid Credentials", $"Invalid credentials.");
            }

            User entity = await _repository.GetByEmailAsync(email);

            if (entity == null)
            {
                throw new CardException("Invalid Credentials", $"Invalid credentials.");
            }
            if (!entity.ValidatePassword(password, _encrypter))
            {
                throw new CardException("Invalid Credentials", $"Invalid credentials.");
            }

            var jwtWebToken = _jwtHandler.Create(entity.Id);
            var model       = _mapper.Map <UserModel>(entity);

            model.Token   = jwtWebToken.Token;
            model.Expires = jwtWebToken.Expires;
            return(model);
        }
Exemplo n.º 15
0
        public async Task <ResponseModel> LoginUser(LoginModel loginModel)
        {
            ResponseModel result = new ResponseModel();

            User user = null;

            if (!string.IsNullOrWhiteSpace(loginModel.Email))
            {
                user = _userRepo.GetUserByEmailAsync(loginModel.Email, true);
            }

            if (user == null)
            {
                result.Error  = ErrorMessageCode.USER_NOT_FOUND;
                result.Status = HttpStatusCode.NotFound;
                return(result);
            }

            if (user.IsDeactivate)
            {
                result.Error  = ErrorMessageCode.USER_IS_DEACTIVATE;
                result.Status = HttpStatusCode.Forbidden;
                return(result);
            }

            try
            {
                var passcode    = UtilCommon.GeneratePasscode(loginModel.PassCode, user.Salt);
                var expireToken = 1;
                if (passcode.Equals(user.PassCode))
                {
                    result.Status = System.Net.HttpStatusCode.OK;
                    LoginApiModel data = new LoginApiModel();
                    data.IsFirstLogin = user.IsFirstLogin;
                    data.Token        = _jwtHandler.Create(user.Id.ToString(), expireToken, user.Role);
                    data.Avatar       = UtilCommon.GetDisplayImageUrl(user.Avatar);
                    data.FullName     = user.FullName;
                    data.Role         = user.Role;
                    data.UserId       = user.Id;
                    result.Data       = data;
                    await _userRepo.UpdateAsync(user);

                    return(result);
                }
                else
                {
                    result.Error  = ErrorMessageCode.PASSWORD_INCORRECT;
                    result.Status = System.Net.HttpStatusCode.NotFound;
                    var date = DateTime.UtcNow;
                    return(result);
                }
            }
            catch (Exception ex)
            {
                result.Error  = ex.ToString();
                result.Status = System.Net.HttpStatusCode.NotImplemented;
                return(result);
            }
        }
Exemplo n.º 16
0
 public IActionResult SignIn([FromBody] SignIn request)
 {
     if (string.IsNullOrWhiteSpace(request.Username) && request.Username != "ajeet" && request.Password != "secret")
     {
         return(Unauthorized());
     }
     return(Ok(_jwtHandler.Create(request.Username)));
 }
Exemplo n.º 17
0
        public async Task <IActionResult> AuthenticationToken(string pin)
        {
            //find it based on pin
            string verificationProfileId;

            try
            {
                verificationProfileId = await _persistantStorageService.GetSpeakerVerificationProfileByPinAsync(pin);
            }
            catch
            {
                //throw new InvalidOperationException("No valid speaker profile matching PIN.");
                return(StatusCode(400, "No valid speaker profile matching PIN."));
            }


            using (var memoryStream = new MemoryStream())
            {
                try
                {
                    await Request.Body.CopyToAsync(memoryStream);

                    byte[] waveBytes = memoryStream.ToArray();

                    VerificationResult result = await _speakerRecognitionClient.VerifyAsync(verificationProfileId, waveBytes);

                    if (result.Result == "Accept")
                    {
                        var user = await _persistantStorageService.GetUserByVerificationProfileId(verificationProfileId);

                        if (user == null)
                        {
                            return(StatusCode(500, "Invalid verification profile provided."));
                        }

                        var claims = new Dictionary <string, string>
                        {
                            { OpenIdConnectConstants.Claims.Subject, user.UserPrinipleName }
                        };

                        return(Json(new { result = result.Result, jwt = _jwtHandler.Create(claims) }));
                    }
                    else
                    {
                        return(Json(new { result = result.Result }));
                    }
                }
                catch (HttpException e)
                {
                    return(StatusCode(e.StatusCode, e.Message));
                }
                catch (Exception e)
                {
                    return(StatusCode(500, e.ToString()));
                }
            }
        }
        public async Task <JsonWebToken> LoginAsync(string name, string password)
        {
            var user = await _repository.GetAsync(name);

            if (user == null || !user.ValidatePassword(password))
            {
                return(null);
            }
            return(_jwtHandler.Create(user.Id));
        }
Exemplo n.º 19
0
        public async Task <AuthTokenDto> AuthenticateAsync(string username, string password)
        {
            var user = await _userService.ReadByUsernameAsync(username);

            if (user != null && username == user.Username && password == user.Password)
            {
                return(_jwtHandler.Create(username));
            }

            return(null);
        }
Exemplo n.º 20
0
        public async Task <JsonWebToken> CreateTokenAsync(string username)
        {
            var user = await _context.Users.SingleOrDefaultAsync(u => u.Username == username);

            var claims = new Dictionary <string, string>
            {
                ["custom"] = "value"
            };

            return(_jwtHandler.Create(user.Id, user.Username, user.Role, claims));
        }
Exemplo n.º 21
0
        public JsonWebToken SignIn(string username, string password)
        {
            var user = GetUser(username);

            if (user == null)
            {
                throw new Exception("Invalid credentials.");
            }
            var jwt          = _jwtHandler.Create(user.UserName);
            var refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString())
                               .Replace("+", string.Empty)
                               .Replace("=", string.Empty)
                               .Replace("/", string.Empty);

            jwt.RefreshToken = refreshToken;
            _refreshTokens.Add(new RefreshToken {
                Username = username, Token = refreshToken
            });

            return(jwt);
        }
Exemplo n.º 22
0
        public async Task <CustomJsonWebToken> LoginAsync(string email, string password)
        {
            var user = await repository.FindAsync(u => u.Email.Equals(email)) ??
                       throw new CustomException("invalid_credentials", $"Invalid credentials");

            if (!user.ValidPassword(password))
            {
                throw new CustomException("invalid_credentials", $"Invalid credentials");
            }

            return(jwtHandler.Create(user.Id));
        }
Exemplo n.º 23
0
        public async Task <JsonWebToken> LoginAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email) ??
                       throw new ActioException("invalid_credentials", $"Invalid credentials.");

            if (!user.ValidatePassword(password, _encrypter))
            {
                throw new ActioException("invalid_credentials", $"Invalid credentials.");
            }

            return(_jwtHandler.Create(user.Id));
        }
        public async Task <JsonWebToken> LoginAsync(string email, string password)
        {
            var user = await _repository.GetAsync(email);

            if (user == null || !user.ValidatePassword(password, _encrypter))
            {
                throw new SchoolException("invalid_credentials",
                                          $"Invalid username or password.");
            }


            return(_jwtHandler.Create(user.UserGuid));
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Login([FromBody] UserLogin user)
        {
            var userLogged = await authRepository.LoginAsync(user.Email, user.Password);

            if (userLogged == null)
            {
                return(Unauthorized(authRepository.ObterErros()));
            }

            var token = jwtHandler.Create(userLogged);

            return(Ok(token));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Login([FromBody] User user)
        {
            var userFromRepo = await authRepository.Login(user.Name, user.Password);

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

            userFromRepo.Password = "";

            return(Ok(jwtHandler.Create(userFromRepo)));
        }
Exemplo n.º 27
0
        public async Task <JsonWebToken> LoginAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null)
            {
                throw new HttpResponseException(StatusCodes.Status401Unauthorized, "Invalid credentials");
            }
            if (!user.ValidatePassword(password, _encrypter))
            {
                throw new HttpResponseException(StatusCodes.Status401Unauthorized, "Invalid credentials");
            }
            var jwt = _jwtHandler.Create(user.Id);
            await _refreshTokenRepository.AddAsync(new RefreshToken()
            {
                UserId  = user.Id,
                Token   = jwt.RefreshToken.Value,
                Expires = (new DateTime(1970, 1, 1)).AddSeconds(jwt.RefreshToken.Expires)
            });

            return(jwt);
        }
        public JsonWebToken SignIn(string username, string password)
        {
            var user = GetUser(username);

            if (user == null)
            {
                throw new Exception("Invalid credentials.");
            }
            if (user.Password != password)
            {
                throw new Exception("Wrong password.");
            }
            var jwt          = _jwtHandler.Create(user.Id.ToString());
            var refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString())
                               .Replace("+", string.Empty)
                               .Replace("=", string.Empty)
                               .Replace("/", string.Empty);

            jwt.RefreshToken = refreshToken;
            Task.Run(() => InsertAccessTokenDB(jwt, username));
            return(jwt);
        }
        public async Task <JsonWebToken> SignIn(string username, string password)
        {
            var user = await _userManager.FindByNameAsync(username);

            if (user != null)
            {
                var signInResult = await _signInManager.CheckPasswordSignInAsync(user, password, false);

                if (signInResult.Succeeded)
                {
                    var jwt          = _jwtHandler.Create(user);
                    var refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString())
                                       .Replace("+", string.Empty)
                                       .Replace("=", string.Empty)
                                       .Replace("/", string.Empty);
                    jwt.RefreshToken  = refreshToken;
                    user.RefreshToken = refreshToken;
                    _repository.UpdateRefreshToken(user);
                    return(jwt);
                }
            }
            return(null);
        }
Exemplo n.º 30
0
        public async Task <JsonWebToken> SignIn(string username, string password)
        {
            var user = await _userManager.FindByNameAsync(username);

            if (user != null)
            {
                if (await _userManager.CheckPasswordAsync(user, password))
                {
                    return(await _jwtHandler.Create(user, _userManager));
                }
            }

            throw new UserException("Username or password not correct.");
        }