示例#1
0
        public AuditInterceptor(IUserAuth userAuth, IRepository<Audit> auditRepository)
        {
            Check.Require(userAuth != null, "User Authorization Context is Required");

            UserAuth = userAuth;
            AuditRepository = auditRepository;
        }
        /// <summary>
        /// Creates the required missing tables or DB schema 
        /// </summary>
        public static void AssignRoles(this IAuthRepository UserAuthRepo, IUserAuth userAuth,
            ICollection<string> roles = null, ICollection<string> permissions = null)
        {
            var managesRoles = UserAuthRepo as IManageRoles;
            if (managesRoles != null)
            {
                managesRoles.AssignRoles(userAuth.Id.ToString(), roles, permissions);
            }
            else
            {
                if (!roles.IsEmpty())
                {
                    foreach (var missingRole in roles.Where(x => !userAuth.Roles.Contains(x)))
                    {
                        userAuth.Roles.Add(missingRole);
                    }
                }

                if (!permissions.IsEmpty())
                {
                    foreach (var missingPermission in permissions.Where(x => !userAuth.Permissions.Contains(x)))
                    {
                        userAuth.Permissions.Add(missingPermission);
                    }
                }

                UserAuthRepo.SaveUserAuth(userAuth);
            }
        }
        public IUserAuth CreateUserAuth(IUserAuth newUser, string password)
        {
            ValidateNewUser(newUser, password);

            AssertNoExistingUser(newUser);

            var saltedHash = new SaltedHash();
            string salt;
            string hash;
            saltedHash.GetHashAndSaltString(password, out hash, out salt);
            var digestHelper = new DigestAuthFunctions();
            newUser.DigestHa1Hash = digestHelper.CreateHa1(newUser.UserName, DigestAuthProvider.Realm, password);
            newUser.PasswordHash = hash;
            newUser.Salt = salt;
            newUser.CreatedDate = DateTime.UtcNow;
            newUser.ModifiedDate = newUser.CreatedDate;

            using (var session = _documentStore.OpenSession())
            {
                session.Store(newUser);
                session.SaveChanges();
            }

            return newUser;
        }
 public static ICollection<string> GetPermissions(this IAuthRepository UserAuthRepo, IUserAuth userAuth)
 {
     var managesRoles = UserAuthRepo as IManageRoles;
     return managesRoles != null 
         ? managesRoles.GetPermissions(userAuth.Id.ToString()) 
         : userAuth.Permissions;
 }
 private static void CreateUser(IUserAuthRepository userRepo, IUserAuth user, string password)
 {
     string hash;
     string salt;
     new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
     user.Salt = salt;
     user.PasswordHash = hash;
     userRepo.CreateUserAuth(user, password);
 }
        public static void PopulateSession(this IAuthSession session, IUserAuth userAuth, List<IAuthTokens> authTokens)
        {
            if (userAuth == null)
                return;

            var originalId = session.Id;
            session.PopulateWith(userAuth);
            session.Id = originalId;
            session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
            session.ProviderOAuthAccess = authTokens;
        }
 public static ICollection<string> GetRoles(this IAuthRepository UserAuthRepo, IUserAuth userAuth)
 {
     var managesRoles = UserAuthRepo as IManageRoles;
     if (managesRoles != null)
     {
         return managesRoles.GetRoles(userAuth.Id.ToString());
     }
     else
     {
         return userAuth.Roles;
     }
 }
        private void ValidateNewUserWithoutPassword(IUserAuth newUser)
        {
            newUser.ThrowIfNull("newUser");

            if (newUser.UserName.IsNullOrEmpty() && newUser.Email.IsNullOrEmpty())
                throw new ArgumentNullException("UserName or Email is required");

            if (!newUser.UserName.IsNullOrEmpty())
            {
                if (!ValidUserNameRegEx.IsMatch(newUser.UserName))
                    throw new ArgumentException("UserName contains invalid characters", "UserName");
            }
        }
 private void AssertNoExistingUser(IUserAuth newUser, IUserAuth exceptForExistingUser = null)
 {
     if (newUser.UserName != null)
     {
         var existingUser = GetUserAuthByUserName(newUser.UserName);
         if (existingUser != null
             && (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
             throw new ArgumentException("User {0} already exists".Fmt(newUser.UserName));
     }
     if (newUser.Email != null)
     {
         var existingUser = GetUserAuthByUserName(newUser.Email);
         if (existingUser != null
             && (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
             throw new ArgumentException("Email {0} already exists".Fmt(newUser.Email));
     }
 }
示例#10
0
        public void Setup()
        {
            _userBLL = MockRepository.GenerateStub<IUserBLL>();
            _userAuth = MockRepository.GenerateStub<IUserAuth>();
            _delegateBLL = new DelegateBLL(_userAuth, _userBLL);
            _roleProvider = MockRepository.GenerateStub<RoleProvider>();
            _userAuth.RoleProvider = _roleProvider;

            _currentUser.UserName = "******";
            _userBLL.Expect(a => a.GetUser()).Return(_currentUser).Repeat.Any();

            for (int i = 0; i < 3; i++)
            {
                _users.Add(CreateValidEntities.User(i+3));
                //_users[i].Delegate = _users[0];
            }
        }
        public bool TryAuthenticate(string userName, string password, out IUserAuth userAuth)
        {
            userAuth = GetUserAuthByUserName(userName);
            if (userAuth == null)
                return false;

            if (HostContext.Resolve<IHashProvider>().VerifyHashString(password, userAuth.PasswordHash, userAuth.Salt))
            {
                this.RecordSuccessfulLogin(userAuth);

                return true;
            }

            this.RecordInvalidLoginAttempt(userAuth);

            userAuth = null;
            return false;
        }
        public IUserAuth CreateUserAuth(IUserAuth newUser, string password)
        {
            ValidateNewUser(newUser, password);

            AssertNoExistingUser(newUser);

            var saltedHash = new SaltedHash();
            string salt;
            string hash;
            saltedHash.GetHashAndSaltString(password, out hash, out salt);

            newUser.PasswordHash = hash;
            newUser.Salt = salt;
            newUser.CreatedDate = DateTime.UtcNow;
            newUser.ModifiedDate = newUser.CreatedDate;

            Session.Save(new UserAuthNHibernate(newUser));
            return newUser;
        }
        public static void UnAssignRoles(this IAuthRepository UserAuthRepo, IUserAuth userAuth,
            ICollection<string> roles = null, ICollection<string> permissions = null)
        {
            var managesRoles = UserAuthRepo as IManageRoles;
            if (managesRoles != null)
            {
                managesRoles.UnAssignRoles(userAuth.Id.ToString(), roles, permissions);
            }
            else
            {
                roles.Each(x => userAuth.Roles.Remove(x));
                permissions.Each(x => userAuth.Permissions.Remove(x));

                if (roles != null || permissions != null)
                {
                    UserAuthRepo.SaveUserAuth(userAuth);
                }
            }
        }
示例#14
0
        public IUserAuth CreateUserAuth(IUserAuth newUser, string password)
        {
            UserEntry user = newUser as UserEntry;

            ValidateNewUser(user, password);
            AssertNoExistingUser(user);

            var saltedHash = HostContext.Resolve<IHashProvider>();
            string salt;
            string hash;
            saltedHash.GetHashAndSaltString(password, out hash, out salt);

            user.PartitionKey = Guid.NewGuid().ToString();
            user.RowKey = newUser.UserName;
            user.RowKey = TableEntityHelper.RemoveDiacritics(user.RowKey);
            user.RowKey = TableEntityHelper.ToAzureKeyString(user.RowKey);

            //user.Id = 0;
            user.PasswordHash = hash;
            user.Salt = salt;
            var digestHelper = new DigestAuthFunctions();
            user.DigestHa1Hash = digestHelper.CreateHa1(user.UserName, DigestAuthProvider.Realm, password);
            user.CreatedDate = DateTime.UtcNow;
            user.ModifiedDate = user.CreatedDate;

            //var userId = user.Id.ToString(CultureInfo.InvariantCulture);
            //if (!newUser.UserName.IsNullOrEmpty())
            //{
            //    redis.SetEntryInHash(IndexUserNameToUserId, newUser.UserName, userId);
            //}
            //if (!newUser.Email.IsNullOrEmpty())
            //{
            //    redis.SetEntryInHash(IndexEmailToUserId, newUser.Email, userId);
            //}
            SaveUserAuth(user);

            return user;
        }
示例#15
0
 internal virtual bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null)
 {
     return(userAuth?.LockedDate != null);
 }
示例#16
0
        public bool TryAuthenticate(Dictionary <string, string> digestHeaders, string privateKey, int nonceTimeOut, string sequence, out IUserAuth userAuth)
        {
            //userId = null;
            userAuth = GetUserAuthByUserName(digestHeaders["username"]);
            if (userAuth == null)
            {
                return(false);
            }

            if (userAuth.VerifyDigestAuth(digestHeaders, privateKey, nonceTimeOut, sequence))
            {
                this.RecordSuccessfulLogin(userAuth);

                return(true);
            }

            this.RecordInvalidLoginAttempt(userAuth);

            userAuth = null;
            return(false);
        }
示例#17
0
 protected virtual void AssertNotLocked(IUserAuth userAuth)
 {
     if (userAuth.LockedDate != null)
         throw new AuthenticationException("This account has been locked");
 }
示例#18
0
 private async Task LoadUserAuthAsync(IAuthSession session, IUserAuth userAuth, CancellationToken token = default)
 {
     await session.PopulateSessionAsync(userAuth, this, token).ConfigAwait();
 }
示例#19
0
        public virtual async Task <IUserAuth> UpdateUserAuthAsync(IUserAuth existingUser, IUserAuth newUser, CancellationToken token = default)
        {
            newUser.ValidateNewUser();

            await using var redis = await factory.GetClientAsync(token).ConfigAwait();
            await AssertNoExistingUserAsync(redis, newUser, existingUser, token).ConfigAwait();

            newUser.Id            = existingUser.Id;
            newUser.PasswordHash  = existingUser.PasswordHash;
            newUser.Salt          = existingUser.Salt;
            newUser.DigestHa1Hash = existingUser.DigestHa1Hash;
            newUser.CreatedDate   = existingUser.CreatedDate;
            newUser.ModifiedDate  = DateTime.UtcNow;

            await redis.StoreAsync(newUser, token).ConfigAwait();

            return(newUser);
        }
 public static IUserAuth CreateUserAuth(this IAuthRepository authRepo, IUserAuth newUser, string password)
 {
     return ((IUserAuthRepository)authRepo).CreateUserAuth(newUser, password);
 }
示例#21
0
 public UserController(IUserAuth users)
 {
     this.users = users;
 }
示例#22
0
 public IUserAuth UpdateUserAuth(IUserAuth existingUser, IUserAuth newUser)
 {
     SaveUserAuth(newUser);
     return(newUser);
 }
        public IUserAuth UpdateUserAuth(IUserAuth existingUser, IUserAuth newUser, string password)
        {
            ValidateNewUser(newUser, password);

            AssertNoExistingUser(newUser, existingUser);

            var hash = existingUser.PasswordHash;
            var salt = existingUser.Salt;
            if (password != null)
            {
                var saltedHash = HostContext.Resolve<IHashProvider>();
                saltedHash.GetHashAndSaltString(password, out hash, out salt);
            }

            newUser.Id = existingUser.Id;
            newUser.PasswordHash = hash;
            newUser.Salt = salt;
            newUser.CreatedDate = existingUser.CreatedDate;
            newUser.ModifiedDate = DateTime.UtcNow;

            var nhSession = GetCurrentSessionFn(sessionFactory);
            nhSession.Save(new UserAuthNHibernate(newUser));

            return newUser;
        }
示例#24
0
 public Handler(IUserAuth userAuth, IConnectionString connection)
 {
     _connection = connection;
     _userAuth   = userAuth;
 }
示例#25
0
 private static void AssertNoExistingUser(IMongoDatabase mongoDatabase, IUserAuth newUser, IUserAuth exceptForExistingUser = null)
 {
     if (newUser.UserName != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.UserName);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException(string.Format(ErrorMessages.UserAlreadyExistsTemplate1, newUser.UserName));
         }
     }
     if (newUser.Email != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.Email);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException(string.Format(ErrorMessages.EmailAlreadyExistsTemplate1, newUser.Email));
         }
     }
 }
        public bool TryAuthenticate(Dictionary <string, string> digestHeaders, string PrivateKey, int NonceTimeOut, string sequence, out IUserAuth userAuth)
        {
            //userId = null;
            userAuth = GetUserAuthByUserName(digestHeaders["username"]);
            if (userAuth == null)
            {
                return(false);
            }

            var digestHelper = new DigestAuthFunctions();

            if (digestHelper.ValidateResponse(digestHeaders, PrivateKey, NonceTimeOut, userAuth.DigestHa1Hash, sequence))
            {
                //userId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
                return(true);
            }
            userAuth = null;
            return(false);
        }
 private static void AssertNoExistingUser(MongoDatabase mongoDatabase, IUserAuth newUser, IUserAuth exceptForExistingUser = null)
 {
     if (newUser.UserName != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.UserName);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException("User {0} already exists".Fmt(newUser.UserName));
         }
     }
     if (newUser.Email != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.Email);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException("Email {0} already exists".Fmt(newUser.Email));
         }
     }
 }
示例#28
0
        public static void PopulatePasswordHashes(this IUserAuth newUser, string password, IUserAuth existingUser = null)
        {
            if (newUser == null)
            {
                throw new ArgumentNullException(nameof(newUser));
            }

            var hash = existingUser?.PasswordHash;
            var salt = existingUser?.Salt;

            if (password != null)
            {
                var passwordHasher = !HostContext.Config.UseSaltedHash
                    ? HostContext.TryResolve <IPasswordHasher>()
                    : null;

                if (passwordHasher != null)
                {
                    salt = null; // IPasswordHasher stores its Salt in PasswordHash
                    hash = passwordHasher.HashPassword(password);
                }
                else
                {
                    var hashProvider = HostContext.Resolve <IHashProvider>();
                    hashProvider.GetHashAndSaltString(password, out hash, out salt);
                }
            }

            newUser.PasswordHash = hash;
            newUser.Salt         = salt;

            newUser.PopulateDigestAuthHash(password, existingUser);
        }
 public static IUserAuth UpdateUserAuth(this IAuthRepository authRepo, IUserAuth existingUser, IUserAuth newUser, string password)
 {
     return authRepo.AssertUserAuthRepository().UpdateUserAuth(existingUser, newUser, password);
 }
示例#30
0
 public static IUserAuth CreateUserAuth(this IAuthRepository authRepo, IUserAuth newUser, string password) =>
 authRepo.AssertUserAuthRepository().CreateUserAuth(newUser, password);
示例#31
0
 public static void RecordSuccessfulLogin(this IUserAuthRepository repo, IUserAuth userAuth)
 {
     repo.RecordSuccessfulLogin(userAuth, rehashPassword: false, password: null);
 }
示例#32
0
 public static IUserAuth UpdateUserAuth(this IAuthRepository authRepo, IUserAuth existingUser, IUserAuth newUser, string password) =>
 authRepo.AssertUserAuthRepository().UpdateUserAuth(existingUser, newUser, password);
示例#33
0
        private static void PopulateDigestAuthHash(this IUserAuth newUser, string password, IUserAuth existingUser = null)
        {
            var createDigestAuthHashes = HostContext.GetPlugin <AuthFeature>()?.CreateDigestAuthHashes;

            if (createDigestAuthHashes == true)
            {
                if (existingUser == null)
                {
                    var digestHelper = new DigestAuthFunctions();
                    newUser.DigestHa1Hash = digestHelper.CreateHa1(newUser.UserName, DigestAuthProvider.Realm, password);
                }
                else
                {
                    newUser.DigestHa1Hash = existingUser.DigestHa1Hash;

                    // If either one changes the digest hash has to be recalculated
                    if (password != null || existingUser.UserName != newUser.UserName)
                    {
                        newUser.DigestHa1Hash = new DigestAuthFunctions().CreateHa1(newUser.UserName, DigestAuthProvider.Realm, password);
                    }
                }
            }
            else if (createDigestAuthHashes == false)
            {
                newUser.DigestHa1Hash = null;
            }
        }
示例#34
0
 public static ICollection <string> GetPermissions(this IAuthRepository UserAuthRepo, IUserAuth userAuth)
 {
     return(UserAuthRepo is IManageRoles managesRoles
         ? managesRoles.GetPermissions(userAuth.Id.ToString())
         : userAuth.Permissions);
 }
示例#35
0
        private async Task AssertNoExistingUserAsync(IRedisClientFacadeAsync redis, IUserAuth newUser, IUserAuth exceptForExistingUser = null, CancellationToken token = default)
        {
            if (newUser.UserName != null)
            {
                var existingUser = await GetUserAuthByUserNameAsync(redis, newUser.UserName, token).ConfigAwait();

                if (existingUser != null &&
                    (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
                {
                    throw new ArgumentException(ErrorMessages.UserAlreadyExistsFmt.LocalizeFmt(newUser.UserName.SafeInput()));
                }
            }
            if (newUser.Email != null)
            {
                var existingUser = await GetUserAuthByUserNameAsync(redis, newUser.Email, token).ConfigAwait();

                if (existingUser != null &&
                    (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
                {
                    throw new ArgumentException(ErrorMessages.EmailAlreadyExistsFmt.LocalizeFmt(newUser.Email.SafeInput()));
                }
            }
        }
 public override IUserAuth CreateUserAuth(IUserAuth newUser, string password)
 {
     return(userAuth);
 }
示例#37
0
        public virtual async Task <IUserAuth> UpdateUserAuthAsync(IUserAuth existingUser, IUserAuth newUser, string password, CancellationToken token = default)
        {
            newUser.ValidateNewUser(password);

            await using var redis = await factory.GetClientAsync(token).ConfigAwait();
            await AssertNoExistingUserAsync(redis, newUser, existingUser, token).ConfigAwait();

            if (existingUser.UserName != newUser.UserName && existingUser.UserName != null)
            {
                await redis.RemoveEntryFromHashAsync(IndexUserNameToUserId, existingUser.UserName, token).ConfigAwait();
            }
            if (existingUser.Email != newUser.Email && existingUser.Email != null)
            {
                await redis.RemoveEntryFromHashAsync(IndexEmailToUserId, existingUser.Email, token).ConfigAwait();
            }

            newUser.Id = existingUser.Id;
            newUser.PopulatePasswordHashes(password, existingUser);
            newUser.CreatedDate  = existingUser.CreatedDate;
            newUser.ModifiedDate = DateTime.UtcNow;

            var userId = newUser.Id.ToString(CultureInfo.InvariantCulture);

            if (!newUser.UserName.IsNullOrEmpty())
            {
                await redis.SetEntryInHashAsync(IndexUserNameToUserId, newUser.UserName, userId, token).ConfigAwait();
            }
            if (!newUser.Email.IsNullOrEmpty())
            {
                await redis.SetEntryInHashAsync(IndexEmailToUserId, newUser.Email, userId, token).ConfigAwait();
            }

            await redis.StoreAsync(newUser, token).ConfigAwait();

            return(newUser);
        }
示例#38
0
 private void SaveUser(IUserAuth userAuth)
 {
     if (userAuth.Id == default(int))
         userAuth.Id = IncUserAuthCounter();
     var usersCollection = mongoDatabase.GetCollection<UserAuth>(UserAuthCol);
     usersCollection.ReplaceOne(u => u.Id == userAuth.Id, (UserAuth)userAuth, 
         new UpdateOptions() {IsUpsert = true});
 }
示例#39
0
 private static void AssertNoExistingUser(IMongoDatabase mongoDatabase, IUserAuth newUser, IUserAuth exceptForExistingUser = null)
 {
     if (newUser.UserName != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.UserName);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException(ErrorMessages.UserAlreadyExistsFmt.LocalizeFmt(newUser.UserName.SafeInput()));
         }
     }
     if (newUser.Email != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.Email);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException(ErrorMessages.EmailAlreadyExistsFmt.LocalizeFmt(newUser.Email.SafeInput()));
         }
     }
 }
示例#40
0
        public IUserAuth UpdateUserAuth(IUserAuth existingUser, IUserAuth newUser, string password)
        {
            newUser.ValidateNewUser(password);

            AssertNoExistingUser(mongoDatabase, newUser, existingUser);

            var hash = existingUser.PasswordHash;
            var salt = existingUser.Salt;
            if (password != null)
            {
                var saltedHash = HostContext.Resolve<IHashProvider>();
                saltedHash.GetHashAndSaltString(password, out hash, out salt);
            }
            // If either one changes the digest hash has to be recalculated
            var digestHash = existingUser.DigestHa1Hash;
            if (password != null || existingUser.UserName != newUser.UserName)
            {
                var digestHelper = new DigestAuthFunctions();
                digestHash = digestHelper.CreateHa1(newUser.UserName, DigestAuthProvider.Realm, password);
            }
            newUser.Id = existingUser.Id;
            newUser.PasswordHash = hash;
            newUser.Salt = salt;
            newUser.DigestHa1Hash = digestHash;
            newUser.CreatedDate = existingUser.CreatedDate;
            newUser.ModifiedDate = DateTime.UtcNow;
            SaveUser(newUser);

            return newUser;
        }
示例#41
0
 private void LoadUserAuth(IAuthSession session, IUserAuth userAuth)
 {
     session.PopulateSession(userAuth, this);
 }
示例#42
0
        public bool TryAuthenticate(Dictionary<string, string> digestHeaders, string privateKey, int nonceTimeOut, string sequence, out IUserAuth userAuth)
        {
            //userId = null;
            userAuth = GetUserAuthByUserName(digestHeaders["username"]);
            if (userAuth == null)
                return false;

            var digestHelper = new DigestAuthFunctions();
            if (digestHelper.ValidateResponse(digestHeaders, privateKey, nonceTimeOut, userAuth.DigestHa1Hash, sequence))
            {
                this.RecordSuccessfulLogin(userAuth);

                return true;
            }

            this.RecordInvalidLoginAttempt(userAuth);

            userAuth = null;
            return false;
        }
示例#43
0
 public Handler(IUserAuth userAuth)
 {
     _userAuth = userAuth;
 }
示例#44
0
        public void SaveUserAuth(IUserAuth userAuth)
        {
            userAuth.ModifiedDate = DateTime.UtcNow;
            if (userAuth.CreatedDate == default(DateTime))
                userAuth.CreatedDate = userAuth.ModifiedDate;

            SaveUser(userAuth);
        }
 public static IUserAuth CreateUserAuth(this IAuthRepository authRepo, IUserAuth newUser, string password)
 {
     return authRepo.AssertUserAuthRepository().CreateUserAuth(newUser, password);
 }
        protected virtual bool EmailAlreadyExists(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens = null)
        {
            if (tokens != null && tokens.Email != null)
            {
                var userWithEmail = authRepo.GetUserAuthByUserName(tokens.Email);
                if (userWithEmail == null) 
                    return false;

                var isAnotherUser = userAuth == null || (userAuth.Id != userWithEmail.Id);
                return isAnotherUser;
            }
            return false;
        }
示例#47
0
        public static bool VerifyPassword(this IUserAuth userAuth, string providedPassword, out bool needsRehash)
        {
            needsRehash = false;
            if (userAuth == null)
            {
                throw new ArgumentNullException(nameof(userAuth));
            }

            if (userAuth.PasswordHash == null)
            {
                return(false);
            }

            var passwordHasher = HostContext.TryResolve <IPasswordHasher>();

            var usedOriginalSaltedHash = userAuth.Salt != null;

            if (usedOriginalSaltedHash)
            {
                var oldSaltedHashProvider = HostContext.Resolve <IHashProvider>();
                if (oldSaltedHashProvider.VerifyHashString(providedPassword, userAuth.PasswordHash, userAuth.Salt))
                {
                    needsRehash = !HostContext.Config.UseSaltedHash;
                    return(true);
                }

                return(false);
            }

            if (passwordHasher == null)
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("Found newer PasswordHash without Salt but no registered IPasswordHasher to verify it");
                }

                return(false);
            }

            if (passwordHasher.VerifyPassword(userAuth.PasswordHash, providedPassword, out needsRehash))
            {
                needsRehash = HostContext.Config.UseSaltedHash;
                return(true);
            }

            if (HostContext.Config.FallbackPasswordHashers.Count > 0)
            {
                var decodedHashedPassword = Convert.FromBase64String(userAuth.PasswordHash);
                if (decodedHashedPassword.Length == 0)
                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug("userAuth.PasswordHash is empty");
                    }

                    return(false);
                }

                var formatMarker = decodedHashedPassword[0];

                foreach (var oldPasswordHasher in HostContext.Config.FallbackPasswordHashers)
                {
                    if (oldPasswordHasher.Version == formatMarker)
                    {
                        if (oldPasswordHasher.VerifyPassword(userAuth.PasswordHash, providedPassword, out _))
                        {
                            needsRehash = true;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
示例#48
0
 private void LoadUserAuth(IAuthSession session, IUserAuth userAuth)
 {
     session.PopulateSession(userAuth,
                             GetUserAuthDetails(session.UserAuthId).ConvertAll(x => (IAuthTokens)x));
 }
示例#49
0
 public override IUserAuth CreateUserAuth(IUserAuth newUser, string password) => userAuth;
示例#50
0
 public bool TryAuthenticate(Dictionary <string, string> digestHeaders, string privateKey, int nonceTimeOut, string sequence,
                             out IUserAuth userAuth)
 {
     throw new NotImplementedException();
 }
示例#51
0
 private static void AssertNoExistingUser(IMongoDatabase mongoDatabase, IUserAuth newUser, IUserAuth exceptForExistingUser = null)
 {
     if (newUser.UserName != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.UserName);
         if (existingUser != null
             && (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
             throw new ArgumentException(string.Format(ErrorMessages.UserAlreadyExistsTemplate1, newUser.UserName));
     }
     if (newUser.Email != null)
     {
         var existingUser = GetUserAuthByUserName(mongoDatabase, newUser.Email);
         if (existingUser != null
             && (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
             throw new ArgumentException(string.Format(ErrorMessages.EmailAlreadyExistsTemplate1, newUser.Email));
     }
 }
示例#52
0
 public override async Task <IUserAuth> CreateUserAuthAsync(IUserAuth newUser, string password, CancellationToken token = default)
 => CreateUserAuth(newUser, password);
示例#53
0
        public IUserAuth UpdateUserAuth(IUserAuth existingUser, IUserAuth newUser)
        {
            newUser.ValidateNewUser();

            AssertNoExistingUser(mongoDatabase, newUser);

            newUser.Id = existingUser.Id;
            newUser.PasswordHash = existingUser.PasswordHash;
            newUser.Salt = existingUser.Salt;
            newUser.DigestHa1Hash = existingUser.DigestHa1Hash;
            newUser.CreatedDate = existingUser.CreatedDate;
            newUser.ModifiedDate = DateTime.UtcNow;
            SaveUser(newUser);

            return newUser;
        }
示例#54
0
 public override bool TryAuthenticate(string userName, string password, out IUserAuth userAuth)
 {
     userAuth = this.userAuth;
     return(true);
 }
示例#55
0
 private void LoadUserAuth(IAuthSession session, IUserAuth userAuth)
 {
     session.PopulateSession(userAuth,
         GetUserAuthDetails(session.UserAuthId).ConvertAll(x => (IAuthTokens)x));
 }
        public static void AssertEqual(IUserAuth userAuth, Register request)
		{
			Assert.That(userAuth, Is.Not.Null);
			Assert.That(userAuth.UserName, Is.EqualTo(request.UserName));
			Assert.That(userAuth.Email, Is.EqualTo(request.Email));
			Assert.That(userAuth.DisplayName, Is.EqualTo(request.DisplayName));
			Assert.That(userAuth.FirstName, Is.EqualTo(request.FirstName));
			Assert.That(userAuth.LastName, Is.EqualTo(request.LastName));
		}
示例#57
0
        public IUserAuth CreateUserAuth(IUserAuth newUser, string password)
        {
            newUser.ValidateNewUser(password);

            AssertNoExistingUser(mongoDatabase, newUser);

            var saltedHash = HostContext.Resolve<IHashProvider>();
            string salt;
            string hash;
            saltedHash.GetHashAndSaltString(password, out hash, out salt);
            var digestHelper = new DigestAuthFunctions();
            newUser.DigestHa1Hash = digestHelper.CreateHa1(newUser.UserName, DigestAuthProvider.Realm, password);
            newUser.PasswordHash = hash;
            newUser.Salt = salt;
            newUser.CreatedDate = DateTime.UtcNow;
            newUser.ModifiedDate = newUser.CreatedDate;

            SaveUser(newUser);
            return newUser;
        }
示例#58
0
 protected virtual void AssertNoExistingUser(IDbConnection db, IUserAuth newUser, IUserAuth exceptForExistingUser = null)
 {
     if (newUser.UserName != null)
     {
         var existingUser = GetUserAuthByUserName(db, newUser.UserName);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException(string.Format(ErrorMessages.UserAlreadyExistsTemplate1, newUser.UserName));
         }
     }
     if (newUser.Email != null)
     {
         var existingUser = GetUserAuthByUserName(db, newUser.Email);
         if (existingUser != null &&
             (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
         {
             throw new ArgumentException(string.Format(ErrorMessages.EmailAlreadyExistsTemplate1, newUser.Email));
         }
     }
 }
 protected virtual bool IsAccountLocked(IAuthRepository authRepo, IUserAuth userAuth, IAuthTokens tokens=null)
 {
     if (userAuth == null) return false;
     return userAuth.LockedDate != null;
 }
示例#60
0
        public virtual bool TryAuthenticate(Dictionary <string, string> digestHeaders, string privateKey, int nonceTimeOut, string sequence, out IUserAuth userAuth)
        {
            userAuth = GetUserAuthByUserName(digestHeaders["username"]);
            if (userAuth == null)
            {
                return(false);
            }

            var digestHelper = new DigestAuthFunctions();

            if (digestHelper.ValidateResponse(digestHeaders, privateKey, nonceTimeOut, userAuth.DigestHa1Hash, sequence))
            {
                this.RecordSuccessfulLogin(userAuth);
                return(true);
            }

            this.RecordInvalidLoginAttempt(userAuth);

            userAuth = null;
            return(false);
        }