Exemple #1
0
        /// <summary>
        /// Attempts to register a new user. Only the username is validated, it is expected that other fields have already been validated!
        /// </summary>
        /// <param name="signupParams"></param>
        /// <returns></returns>
        public RegisteredUser RegisterUser(WebSignupParameters signupParams)
        {
            RegisteredUser newUserRecord = null;

            if (FindUserByUsername(signupParams.Username) != null)
            {
                //BAD! Another conflicting user exists!
                throw new SecurityException("A user with the same username already exists!");
            }
            using (var db = new DatabaseAccessService().OpenOrCreateDefault())
            {
                var registeredUsers = db.GetCollection <RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey);
                //Calculate cryptographic info
                var cryptoConf        = PasswordCryptoConfiguration.CreateDefault();
                var pwSalt            = AuthCryptoHelper.GetRandomSalt(64);
                var encryptedPassword = AuthCryptoHelper.CalculateUserPasswordHash(signupParams.Password, pwSalt, cryptoConf);
                //Create user
                newUserRecord = new RegisteredUser
                {
                    Identifier = Guid.NewGuid(),
                    Username   = signupParams.Username,
                    CryptoSalt = pwSalt,
                    PasswordCryptoConfiguration = cryptoConf,
                    PasswordKey = encryptedPassword,
                };
                //Add the user to the database
                registeredUsers.Insert(newUserRecord);

                //Index database
                registeredUsers.EnsureIndex(x => x.Identifier);
            }
            return(newUserRecord);
        }
        public static byte[] CalculateUserPasswordHash(string password, byte[] salt, PasswordCryptoConfiguration cryptoConf)
        {
            var passwordBytes = Encoding.UTF8.GetBytes(password);

            return(CalculatePasswordHash(passwordBytes, salt, cryptoConf.Iterations, cryptoConf.Length));
        }