Beispiel #1
0
        // returns true if all tests passed
        public static bool OutputTestResults(
        ExecutionResults failures, 
        Action<string> writeLine)
        {
            string executedTestsMessage = failures.TotalTestsRun.ToString()
            + " tests executed\n";

            if (failures.Failures.Any() == false) {
            writeLine(executedTestsMessage + "All tests passed!");
            return true;
            }

            var failureOutput = TestRunner.CalculateFailureString(failures.Failures);

            var consoleOutput = new System.Text.StringBuilder();
            consoleOutput.Append(executedTestsMessage);

            foreach(var failureLine in failureOutput) {
            consoleOutput.Append(failureLine.Subject + "\n" + failureLine.Body);
            }

            writeLine(consoleOutput.ToString());
            writeLine(failures.Failures.Count().ToString() + " test(s) failed\n");

            return false;
        }
 public virtual ActionResult ChangePassword(ChangePasswordViewModel model)
 {
     if (this.ModelState.IsValid)
     {
         var result = new ExecutionResults();
         var user   = new User()
         {
             UserID       = SecurityContextManager.CurrentIdentity.Ticket.UserSession.UserID,
             Name         = model.UserName,
             PasswordHash = model.ConfirmPassword
         };
         if (UserManager.UpdateUser(user, model.OldPassword, Request.UserHostAddress, result))
         {   //success
             if (this.IsJsonRequest())
             {
                 return(Json(new { success = true }));
             }
             else
             {
                 return(this.RedirectToAction(MVC.Account.ChangePasswordSuccess()));
             }
         }
         //failed business layer rules
         if (this.IsJsonRequest())
         {
             return(Json(new { success = false, message = result.ToHtmlString() }));
         }
         else
         {
             for (int e = 0; e < result.Messages.Count; e++)
             {
                 this.ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), result.Messages[e].Message);
             }
             return(this.View(model));
         }
     }
     if (this.IsJsonRequest())
     {
         return(Json(new { success = false, errors = this.ModelState.ToJson() }));
     }
     else
     {
         return(this.View(model)); //modelstate already populated
     }
 }
        public virtual ActionResult CheckAliasIsAvailable(string alias)
        {
            if (alias == SecurityContextManager.CurrentIdentity.Name)
            {
                return(Json(new { success = true, message = "This is your current sign in alias." }));
            }

            var result = new ExecutionResults();

            if (!UserManager.ValidateName(alias, result))
            {
                return(Json(new { success = false, message = result.ToHtmlString() }));
            }

            var user = UserManager.GetUserByName(alias);

            return(Json(new { success = (user == null), message = (User == null) ? "This name is available" : "This name is not available.  Choose another name." }));
        }
        public virtual ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                var result    = new ExecutionResults();
                var resetCode = UserManager.GenerateUserResetCode(model.UserName);
                if (!String.IsNullOrWhiteSpace(resetCode)) //user found
                {
                    //TODO: generate email body with reset code.
                }
                else
                {
                    //TODO: generate alternate body telling how to sign up.
                }
#warning TODO: send the reset code via email (or signup instructions if account does not exist) and then show a view with email confirmation.
                //TODO: send the email (whether user found or not!)
                //TODO: return an ActionResult if successful

                result.AppendError("The forgot password functionality is not yet implemented.");

                //failed business layer rules
                if (this.IsJsonRequest())
                {
                    return(Json(new { success = false, message = result.ToHtmlString() }));
                }
                else
                {
                    for (int e = 0; e < result.Messages.Count; e++)
                    {
                        this.ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), result.Messages[e].Message);
                    }
                    return(this.View(model));
                }
            }
            if (this.IsJsonRequest())
            {
                return(Json(new { success = false, errors = this.ModelState.ToJson() }));
            }
            else
            {
                return(this.View(model)); //modelstate already populated
            }
        }
        /// <summary>
        /// Base logic to register a full user, or a guest user.  Creates the appropriate records and the proper validation.
        /// </summary>
        /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>A boolean indicating success (true) or failure (false).</returns>
        protected virtual bool RegisterBase(User user, ExecutionResults result)
        {
            var password = user.PasswordHash;

            if (!ValidateName(user.Name, result) || !ValidatePassword(password, result))
            {
                return(false);
            }

            var existing = GetUserByName(user.Name);

            if (existing != null)
            {   //seed user table with deleted users with names you don't want users to have
                result.AppendError("The name you specified cannot be used.");
                return(false);
            }
            if (user.UserID.Equals(Guid.Empty))
            {
                user.UserID = Guid.NewGuid();
            }

            var hasher = HashManager.SelectProvider();
            var salt   = new UserSalt
            {
                PasswordSalt = hasher.GetSalt(),
                UserID       = user.UserID,
                HashGroup    = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum),
                HashName     = hasher.Name
            };

            user.PasswordHash = hasher.Hash(salt.PasswordSalt, password,
                                            salt.HashGroup + BaseHashIterations);
            using (var scope = new System.Transactions.TransactionScope())
            {
                //starts as a lightweight transaction
                SaveUser(user);
                //enlists in a full distributed transaction if users and salts have different connection strings
                SaveUserSalt(salt);
                scope.Complete();
            }
            return(true);
        }
Beispiel #6
0
        public Schedule Execute()
        {
            PrologMachine machine = Machine;

            if (!machine.CanRunToSuccess)
            {
                return(null);
            }

            ExecutionResults executionResults = machine.RunToSuccess();

            if (executionResults != ExecutionResults.Success)
            {
                return(null);
            }

            CodeTerm codeTerm = machine.QueryResults.Variables[0].CodeTerm;
            Schedule schedule = Schedule.Create(codeTerm);

            return(schedule);
        }
        public virtual ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var result = new ExecutionResults();
                var id     = UserManager.AuthenticateUser(model.UserName, model.Password,
                                                          model.RememberMe ? UserSessionDurationType.Extended : UserSessionDurationType.PublicComputer,
                                                          Request.UserHostAddress, result);
                if (id.IsAuthenticated && result.Success)
                {   //login successful
                    SecurityContextManager.CurrentUser = new UserPrincipal(id);
                    return(RedirectToLocal(returnUrl));
                }

                //failed business layer validations
                for (var e = result.Messages.Count - 1; e >= 0; e--)
                {
                    ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), result.Messages[e].Message);
                }
            }
            // failed data annotation validations
            return(View(model));
        }
 public virtual ActionResult Register(RegisterViewModel model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         var results  = new ExecutionResults();
         var user     = model.ToUser();
         var identity = UserManager.RegisterUser(user, UserSessionDurationType.Extended, Request.UserHostAddress, results);
         if (results.Success)
         {   //successful registration
             SecurityContextManager.CurrentUser = new UserPrincipal(identity);
             return(RedirectToLocal(returnUrl));
         }
         //failed business layer
         results.AppendError("Failed to complete registration.");
         for (var e = 0; e < results.Messages.Count; e++)
         {
             ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), results.Messages[e].Message);
         }
     }
     //failed data annotation validations
     model.Load();
     return(View(model));
 }
Beispiel #9
0
 /// <summary>
 /// Validates that the specified name meets minimum requirements.
 /// </summary>
 /// <param name="name">The desired name/alias.</param>
 /// <param name="result">Any error messages about the desired name.</param>
 /// <returns></returns>
 public static bool ValidateName(string name, ExecutionResults result)
 {
     return(Provider.ValidateName(name, result));
 }
Beispiel #10
0
        /// <summary>
        /// Authenticates a user with the requested rule options.  This internal method is called
        /// by the other public versions of the method.  Override in a derived class if you want
        /// to change the rule interpretations or add new rules.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <param name="duration"></param>
        /// <param name="ipAddress"></param>
        /// <param name="checkHistory"></param>
        /// <param name="allowUpdateHash"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        protected virtual UserIdentity AuthenticateUser(string name, string password,
            UserSessionDurationType duration, string ipAddress, bool checkHistory,
            bool allowUpdateHash, ExecutionResults result)
        {
            if (checkHistory)
            {
                var recentFailures = GetRecentFailedUserNameAuthenticationCount(name);
                if (recentFailures > AllowedFailuresPerPeriod)
                    return FailAuthenticateUser(name, ipAddress, result);
            }
            var user = GetUserByName(name);
            if (user == null)
                return FailAuthenticateUser(name, ipAddress, result);
            var salt = GetUserSalt(user.UserID);
            if (salt == null)
                return FailAuthenticateUser(name, ipAddress, result);

            //this should get a named hashProvider used to originally hash the password...
            //  fallback to 'default' provider in legacy case when we didn't store the name.
            var hasher = !string.IsNullOrEmpty(salt.HashName) ? HashManager.Providers[salt.HashName] : HashManager.DefaultProvider;
            var passwordHash = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);
            if (user.PasswordHash != passwordHash)
                return FailAuthenticateUser(name, ipAddress, result);
            var session = new UserSession
            {
                CreatedDate = DateTime.UtcNow,
                ExpirationDate = DateTime.UtcNow.AddMinutes(duration == UserSessionDurationType.PublicComputer ? PublicSessionDuration : ExtendedSessionDuration),
                UserID = user.UserID,
                RenewalToken = Guid.NewGuid()
            };
            var history = new AuthenticationHistory
            {
                CreatedDate = session.CreatedDate,
                IPAddress = ipAddress,
                IsAuthenticated = true,
                UserName = name,
                SessionID = session.SessionID,
                UserSession = session
            };
            using (var scope = new System.Transactions.TransactionScope())
            {
                if (allowUpdateHash && (hasher.IsObsolete || user.PasswordHashUpdatedDate < DateTime.UtcNow.AddMonths(-1)))
                {
                    //update hashes on regular basis, keeps the iterations in latest range for current users, and with a 'current' hash provider.
                    hasher = HashManager.SelectProvider();
                    salt.PasswordSalt = hasher.GetSalt();
                    salt.HashGroup = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum);
                    salt.HashName = hasher.Name;
                    user.PasswordHash = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);
                    user.PasswordHashUpdatedDate = DateTime.UtcNow;
                    //starts as a lightweight transaction
                    SaveUser(user);
                    //enlists in a full distributed transaction if users and salts have different connection strings
                    SaveUserSalt(salt);
                }
                //either continues distributed transaction if applicable,
                //  or creates a new lightweight transaction for these two commands
                SaveUserSession(session);
                InsertUserHistory(history);
                scope.Complete();
            }
            return new UserIdentity(history, Name);
        }
Beispiel #11
0
        /// <summary>
        /// Base logic to register a full user, or a guest user.  Creates the appropriate records and the proper validation.
        /// </summary>
        /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>A boolean indicating success (true) or failure (false).</returns>
        protected virtual bool RegisterBase(User user, ExecutionResults result)
        {
            var password = user.PasswordHash;
            if (!ValidateName(user.Name, result) || !ValidatePassword(password, result))
                return false;

            var existing = GetUserByName(user.Name);
            if (existing != null)
            {   //seed user table with deleted users with names you don't want users to have
                result.AppendError("The name you specified cannot be used.");
                return false;
            }
            if (user.UserID.Equals(Guid.Empty))
                user.UserID = Guid.NewGuid();

            var hasher = HashManager.SelectProvider();
            var salt = new UserSalt
            {
                PasswordSalt = hasher.GetSalt(),
                UserID = user.UserID,
                HashGroup = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum),
                HashName = hasher.Name
            };
            user.PasswordHash = hasher.Hash(salt.PasswordSalt, password,
                                                   salt.HashGroup + BaseHashIterations);
            using (var scope = new System.Transactions.TransactionScope())
            {
                //starts as a lightweight transaction
                SaveUser(user);
                //enlists in a full distributed transaction if users and salts have different connection strings
                SaveUserSalt(salt);
                scope.Complete();
            }
            return true;
        }
Beispiel #12
0
        /// <summary>
        /// Registers a new user.  The PasswordHash property should be the actual password.
        /// </summary>
        /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
        /// <param name="duration">The amount of time that the initial session will be valid.</param>
        /// <param name="ipAddress">The internet address where the user is connecting from.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>A boolean indicating success (true) or failure (false).</returns>
        public virtual UserIdentity RegisterUser(User user, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
        {
            var password = user.PasswordHash; //grab before it gets hashed.
            if (!RegisterBase(user, result))
                return new UserIdentity();

            return AuthenticateUser(name: user.Name, password: password, duration: duration,
                                    ipAddress: ipAddress, checkHistory: false, allowUpdateHash: false, result: result);
        }
Beispiel #13
0
 /// <summary>
 /// Validates that the specified name meets minimum requirements.
 /// </summary>
 /// <param name="name">The desired name/alias.</param>
 /// <param name="result">Any error messages about the desired name.</param>
 /// <returns></returns>
 public virtual bool ValidateName(string name, ExecutionResults result)
 {
     if (!NameRegex.IsMatch(name) && !EmailRegex.IsMatch(name))
     {
         //if this message is changed, do the same anywhere else it is used
         result.AppendError(
             "The name contains invalid characters.  The name must be an email address OR contain only letters, numbers, dashes, underscores, and spaces, are allowed.");
         return false;
     }
     return true;
 }
Beispiel #14
0
        public static bool FindAll(WamMachine machine, WamReferenceTarget[] arguments)
        {
            Debug.Assert(arguments.Length == 3);

            WamReferenceTarget arg0 = arguments[0].Dereference();
            WamReferenceTarget arg1 = arguments[1].Dereference();
            WamReferenceTarget arg2 = arguments[2].Dereference();

            WamVariable variable = arg0 as WamVariable;

            if (variable == null)
            {
                return(false);
            }

            WamCompoundTerm goal = arg1 as WamCompoundTerm;

            if (goal == null)
            {
                return(false);
            }

            WamVariable result = arg2 as WamVariable;

            if (result == null)
            {
                return(false);
            }

            WamInstructionStreamBuilder builder = new WamInstructionStreamBuilder();

            builder.Write(new WamInstruction(WamInstructionOpCodes.Allocate));
            for (int idx = 0; idx < goal.Functor.Arity; ++idx)
            {
                builder.Write(new WamInstruction(
                                  WamInstructionOpCodes.PutValue,
                                  goal.Children[idx],
                                  new WamInstructionRegister(WamInstructionRegisterTypes.Argument, (byte)idx)));
            }
            builder.Write(new WamInstruction(WamInstructionOpCodes.Call, goal.Functor));
            builder.Write(new WamInstruction(WamInstructionOpCodes.Success));

            machine.PushContext(builder.ToInstructionStream());

            List <WamReferenceTarget> values = new List <WamReferenceTarget>();

            try
            {
                ExecutionResults results = machine.RunToSuccess();
                while (results == ExecutionResults.Success)
                {
                    WamReferenceTarget value = variable.Clone();
                    values.Add(value);

                    results = machine.RunToSuccess();
                }
            }
            finally
            {
                machine.PopContext(true);
            }

            // Unbind the variable from the last results found by the goal.
            //
            variable.Unbind();

            // Unify the output variable with the list of values.
            //
            return(machine.Unify(result, WamReferenceTarget.Create(values)));
        }
 public void WhenGitHubFlowVersionIsExecutedWithToFileOptionSet()
 {
     _tempFile = Path.Combine(PathHelper.GetTempPath(), "ToFileTest.json");
     _result   = GitHubFlowVersionHelper.ExecuteIn(RepositoryPath, toFile: _tempFile);
 }
 /// <summary>
 /// Authenticates against the data store and returns a UserIdentity given 
 /// a user name, and password.
 /// </summary>
 /// <param name="name">The unique user name.</param>
 /// <param name="password">The matching password.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="duration">The amount of time that the issued token will be valid.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>
 /// A valid user instance.  If the user did not exist or the 
 /// credentials are incorrect then the IsAuthenticated flag
 /// will be false.  If the credentials were correct the 
 /// IsAuthenticated flag will be true.
 /// </returns>
 public static UserIdentity AuthenticateUser(string name, string password, UserSessionDurationType duration, string ipAddress,
                                               ExecutionResults result)
 {
     return Provider.AuthenticateUser(name, password, duration, ipAddress, result);
 }
 /// <summary>
 /// Authenticates against the data store and returns a UserIdentity given
 /// a token returned from a previous authentication.
 /// </summary>
 /// <param name="token">The unique token.</param>
 /// <param name="duration">The amount of time that the renewed token will be valid.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>
 /// A valid user identity instance.  If the token is incorrect or expired
 /// then the IsAuthenticated flag will be false.  Otherwise the identity
 /// will be authenticated.
 /// </returns>
 public static UserIdentity AuthenticateUser(string token, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
 {
     return Provider.AuthenticateUser(token, duration, ipAddress, result);
 }
Beispiel #18
0
 /// <summary>
 /// Registers a new user.  The PasswordHash property should be the actual password.
 /// </summary>
 /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
 /// <param name="duration">The amount of time that the initial session will be valid.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>A boolean indicating success (true) or failure (false).</returns>
 public abstract UserIdentity RegisterUser(User user, UserSessionDurationType duration, String ipAddress, ExecutionResults result);
Beispiel #19
0
 /// <summary>
 /// updates a user's name and/or password.
 /// </summary>
 /// <param name="item">The user details to be saved.  If Password is empty is it not changed.  If specified it should be the new raw password (not a hash).</param>
 /// <param name="currentPassword">The current raw password for the user used to authenticate that the change can be made, or the current resetcode last sent to this user.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>A boolean indicating success (true) or failure (false).</returns>
 public abstract bool UpdateUser(User item, String currentPassword, String ipAddress, ExecutionResults result);
Beispiel #20
0
 /// <summary>
 /// Authenticates against the data store and returns a UserIdentity given
 /// a token returned from a previous authentication.
 /// </summary>
 /// <param name="token">The unique token.</param>
 /// <param name="duration">The amount of time that the renewed token will be valid.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>
 /// A valid user identity instance.  If the token is incorrect or expired
 /// then the IsAuthenticated flag will be false.  Otherwise the identity
 /// will be authenticated.
 /// </returns>
 public abstract UserIdentity AuthenticateUser(string token, UserSessionDurationType duration, String ipAddress, ExecutionResults result);
Beispiel #21
0
 /// <summary>
 /// Authenticates against the data store and returns a UserIdentity given
 /// a user name, and password.
 /// </summary>
 /// <param name="name">The unique user name.</param>
 /// <param name="password">The matching password.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="duration">The amount of time that the issued token will be valid.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>
 /// A valid user instance.  If the user did not exist or the
 /// credentials are incorrect then the IsAuthenticated flag
 /// will be false.  If the credentials were correct the
 /// IsAuthenticated flag will be true.
 /// </returns>
 public abstract UserIdentity AuthenticateUser(string name, string password, UserSessionDurationType duration, string ipAddress,
                                               ExecutionResults result);
Beispiel #22
0
        private IEnumerable <IExecutionResults> PerformTests(IEnumerable <IBenchmarkTest> tests)
        {
            foreach (var test in tests.Select(t => new HostedBenchmarkTest(t, _logger)))
            {
                var localTest = test;
                var result    = new ExecutionResults {
                    Name     = test.Name,
                    TypeName = test.TypeName,
                    Category = test.Category
                };

                var resultStatus = ResultStatus.Indeterminate;

                try
                {
                    _logger.WriteEntry(string.Format("{0}.{1}: Setup", test.TypeName, test.Name),
                                       LogLevel.Setup);

                    test.Setup();


                    var executionCount    = test.ExecutionCount + 1;
                    var localResultStatus = resultStatus;
                    var parallelOptions   = new ParallelOptions();

                    if (!test.RunInParallel)
                    {
                        //ignore parallelism.
                        parallelOptions.MaxDegreeOfParallelism = 1;
                    }

                    Parallel.For(0, executionCount, parallelOptions, indexer =>
                    {
                        var testPass = ExecuteTest(indexer, localTest);
                        if (!localTest.ThrewException && indexer <= 0)
                        {
                            return;
                        }

                        localResultStatus = (ResultStatus)
                                            Math.Max(
                            (int)localTest.GetResult(),
                            (int)localResultStatus
                            );

                        result.AddTestPass(testPass);
                    });

                    resultStatus = localResultStatus;

                    _logger.WriteEntry(string.Format("{0}: Teardown", test.Name),
                                       LogLevel.Teardown);

                    test.Teardown();
                }
                catch (SetupException setupException)
                {
                    _logger.WriteEntry(string.Format("{0}: Setup Exception\r\n{1}", test.Name, setupException),
                                       LogLevel.Exception | LogLevel.Setup);

                    result.SetupException = setupException;

                    result.ResultText = "Test threw an exception during Setup.";
                    resultStatus      = ResultStatus.Failed;
                }
                catch (TeardownException teardownException)
                {
                    _logger.WriteEntry(string.Format("{0}: Teardown Exception\r\n{1}", test.Name, teardownException),
                                       LogLevel.Exception | LogLevel.Teardown);

                    result.TeardownException = teardownException;

                    result.ResultText = "Test threw an exception during Teardown.";
                    resultStatus      = ResultStatus.Failed;
                }

                SetStatus(result, resultStatus, test.Warn, test.Fail);


                yield return(result);
            }
        }
Beispiel #23
0
 /// <summary>
 /// Authenticates against the data store and returns a UserIdentity given
 /// a token returned from a previous authentication.
 /// </summary>
 /// <param name="token">The unique token.</param>
 /// <param name="duration">The amount of time that the renewed token will be valid.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>
 /// A valid user identity instance.  If the token is incorrect or expired
 /// then the IsAuthenticated flag will be false.  Otherwise the identity
 /// will be authenticated.
 /// </returns>
 public static UserIdentity AuthenticateUser(string token, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
 {
     return(Provider.AuthenticateUser(token, duration, ipAddress, result));
 }
 /// <summary>
 /// Invalidates a session token so it can no longer be used.
 /// </summary>
 /// <param name="token"></param>
 /// <param name="ipAddress"></param>
 /// <param name="result"></param>
 public static void InvalidateSession(string token, String ipAddress, ExecutionResults result)
 {
     Provider.InvalidateSession(token, ipAddress, result);
 }
Beispiel #25
0
 /// <summary>
 /// Registers a new user.  The PasswordHash property should be the actual password.
 /// </summary>
 /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
 /// <param name="duration">The amount of time that the initial session will be valid.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>A boolean indicating success (true) or failure (false).</returns>
 public static UserIdentity RegisterUser(User user, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
 {
     return(Provider.RegisterUser(user, duration, ipAddress, result));
 }
 /// <summary>
 /// Registers a new user.  The PasswordHash property should be the actual password.
 /// </summary>
 /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
 /// <param name="duration">The amount of time that the initial session will be valid.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>A boolean indicating success (true) or failure (false).</returns>
 public static UserIdentity RegisterUser(User user, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
 {
     return Provider.RegisterUser(user, duration, ipAddress, result);
 }
 public void WhenGitHubFlowVersionIsExecuted()
 {
     _result = GitHubFlowVersionHelper.ExecuteIn(RepositoryPath);
 }
 /// <summary>
 /// updates a user's name and/or password.
 /// </summary>
 /// <param name="item">The user details to be saved.  If Password is empty is it not changed.  If specified it should be the new raw password (not a hash).</param>
 /// <param name="currentPassword">The current raw password for the user used to authenticate that the change can be made.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>A boolean indicating success (true) or failure (false).</returns>
 public static bool UpdateUser(User item, String currentPassword, String ipAddress, ExecutionResults result)
 {
     return Provider.UpdateUser(item, currentPassword, ipAddress, result);
 }
 public override bool UpdateUser(Security.User item, string currentPassword, string ipAddress, ExecutionResults result)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Validates that the specified name meets minimum requirements.
 /// </summary>
 /// <param name="name">The desired name/alias.</param>
 /// <param name="result">Any error messages about the desired name.</param>
 /// <returns></returns>
 public static bool ValidateName(string name, ExecutionResults result)
 {
     return Provider.ValidateName(name, result);
 }
Beispiel #31
0
 /// <summary>
 /// updates a user's name and/or password.
 /// </summary>
 /// <param name="item">The user details to be saved.  If Password is empty is it not changed.  If specified it should be the new raw password (not a hash).</param>
 /// <param name="currentPassword">The current raw password for the user used to authenticate that the change can be made, or the current resetcode last sent to this user.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>A boolean indicating success (true) or failure (false).</returns>
 public virtual bool UpdateUser(User item, String currentPassword, String ipAddress, ExecutionResults result)
 {
     if (item.UserID.Equals(Guid.Empty))
         throw new ArgumentException("The user identity must be specified.");
     var user = GetUserByID(item.UserID);
     var salt = GetUserSalt(item.UserID);
     if (user == null || salt == null)
     {
         result.AppendError("The specified user identity does not exist.");
         return false;
     }
     if (salt.ResetCode == currentPassword)
     {
         if (salt.ResetCodeExpiration < DateTime.UtcNow)
         {
             result.AppendError(
                 user.IsGuest
                 ? "Your account verification code has expired.  Request a password reset to complete your registration."
                 : "Your password reset code has expired.  Request a new one to be sent to you, and then use it immediately.");
             return false;
         }
         salt.ResetCode = null;
         salt.ResetCodeExpiration = DateTime.UtcNow;
     }
     else
     {
         var rememberMe = !SecurityContextManager.IsAnonymous &&
                           SecurityContextManager.CurrentUser.Identity.Ticket.UserSession.ExpirationDate >
                           DateTime.UtcNow.AddMinutes(PublicSessionDuration);
         if (!AuthenticateUser(name: item.Name, password: currentPassword, ipAddress: ipAddress,
                               duration: rememberMe ? UserSessionDurationType.Extended : UserSessionDurationType.PublicComputer,
                               allowUpdateHash: false, checkHistory: false, result: result).IsAuthenticated)
         {
             result.AppendError("Cannot change password due to authentication error with current password.");
             return false;
         }
     }
     if (user.Name != item.Name)
     {   //user is changing their sign in name.  Make sure the new name is available.
         var nameExisting = GetUserByName(item.Name);
         if (nameExisting != null)
         {
             result.AppendError("The name you specified cannot be used.");
             return false;
         }
         user.Name = item.Name;
     }
     if (!String.IsNullOrEmpty(item.PasswordHash))
     {
         var password = item.PasswordHash;
         //update hashes on regular basis, keeps the iterations in latest range for current users, and with a 'current' hash provider.
         HashProvider hasher = HashManager.SelectProvider();
         salt.PasswordSalt = hasher.GetSalt();
         salt.HashGroup = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum);
         salt.HashName = hasher.Name;
         user.PasswordHash = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);
         user.PasswordUpdatedDate = DateTime.UtcNow;
     }
     using (var scope = new System.Transactions.TransactionScope())
     {
         //starts as a lightweight transaction
         SaveUser(user);
         //enlists in a full distributed transaction if users and salts have different connection strings
         SaveUserSalt(salt);
         scope.Complete();
     }
     return true;
 }
 /// <summary>
 /// Validates that a password meets minimum requirements.
 /// </summary>
 /// <param name="password"></param>
 /// <param name="results"></param>
 /// <returns></returns>
 public static bool ValidatePassword(string password, ExecutionResults results)
 {
     return Provider.ValidatePassword(password, results);
 }
Beispiel #33
0
 /// <summary>
 /// Validates that a password meets minimum requirements.
 /// </summary>
 /// <param name="password"></param>
 /// <param name="results"></param>
 /// <returns></returns>
 public virtual bool ValidatePassword(string password, ExecutionResults results)
 {
     if (!PasswordRegex.IsMatch(password))
     {
         results.AppendError(PasswordErrorMessage);
         return false;
     }
     return true;
 }
Beispiel #34
0
        private cs.UserIdentity AuthenticateUser(string name, string password,
                                                 UserSessionDurationType duration, string ipAddress, bool checkHistory,
                                                 bool allowUpdateHash, ExecutionResults result)
        {
            if (checkHistory)
            {
                var recentFailures = GetRecentFailedUserNameAuthenticationCount(name);
                if (recentFailures > AllowedFailuresPerPeriod)
                {
                    return(FailAuthenticateUser(name, ipAddress, result));
                }
            }
            User user = GetUserByName(name);

            if (user == null)
            {
                return(FailAuthenticateUser(name, ipAddress, result));
            }
            UserSalt salt = GetUserSalt(user.UserID);

            if (salt == null)
            {
                return(FailAuthenticateUser(name, ipAddress, result));
            }

            //this should get a named hashProvider used to originally hash the password...
            //  fallback to 'default' provider in legacy case when we didn't store the name.
            HashProvider hasher       = !string.IsNullOrEmpty(salt.HashName) ? HashManager.Providers[salt.HashName] : HashManager.DefaultProvider;
            var          passwordHash = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);

            if (user.PasswordHash != passwordHash)
            {
                return(FailAuthenticateUser(name, ipAddress, result));
            }
            var session = new UserSession
            {
                CreatedDate    = DateTime.UtcNow,
                ExpirationDate = DateTime.UtcNow.AddMinutes(duration == UserSessionDurationType.PublicComputer ? PublicSessionDuration : ExtendedSessionDuration),
                UserID         = user.UserID,
                RenewalToken   = Guid.NewGuid()
            };
            var history = new AuthenticationHistory
            {
                IPAddress       = ipAddress,
                IsAuthenticated = true,
                UserName        = name,
                UserSession     = session
            };

            using (var scope = new System.Transactions.TransactionScope())
            {
                if (allowUpdateHash && (hasher.IsObsolete || user.PasswordHashUpdatedDate < DateTime.UtcNow.AddMonths(-1)))
                {
                    //update hashes on regular basis, keeps the iterations in latest range for current users, and with a 'current' hash provider.
                    hasher                       = HashManager.SelectProvider();
                    salt.PasswordSalt            = hasher.GetSalt();
                    salt.HashGroup               = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum);
                    salt.HashName                = hasher.Name;
                    user.PasswordHash            = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);
                    user.PasswordHashUpdatedDate = DateTime.UtcNow;
                    //starts as a lightweight transaction
                    SaveUser(user);
                    //enlists in a full distributed transaction if users and salts have different connection strings
                    SaveUserSalt(salt);
                }
                //either continues distributed transaction if applicable,
                //  or creates a new lightweight transaction for these two commands
                SaveUserSession(session);
                InsertUserHistory(history);
            }
            return(new cs.UserIdentity(history, this.Name));
        }
Beispiel #35
0
 /// <summary>
 /// Returns a failed authentication attempt, an anonymous user identity.
 /// </summary>
 /// <param name="name">The user name.</param>
 /// <param name="ipAddress">The IP address the user was coming from.</param>
 /// <param name="result">A container for error messages.</param>
 /// <returns></returns>
 protected UserIdentity FailAuthenticateUser(string name, string ipAddress, ExecutionResults result)
 {
     result.AppendError(LoginCredentialsFailureMessage);
     InsertUserHistory(new AuthenticationHistory
         {
             CreatedDate = DateTime.UtcNow,
             UserName = name,
             IPAddress = ipAddress,
             IsAuthenticated = false
         });
     return new UserIdentity();
 }
Beispiel #36
0
        /// <summary>
        /// Authenticates against the data store and returns a UserIdentity given
        /// a token returned from a previous authentication.
        /// </summary>
        /// <param name="token">The unique token.</param>
        /// <param name="duration">The amount of time that the renewed token will be valid.</param>
        /// <param name="ipAddress">The internet address where the user is connecting from.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>
        /// A valid user identity instance.  If the token is incorrect or expired
        /// then the IsAuthenticated flag will be false.  Otherwise the identity
        /// will be authenticated.
        /// </returns>
        public override UserIdentity AuthenticateUser(string token, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
        {
            String errorMsg = "Authentication token invalid.";
            Guid   renewalToken;

            if (!Guid.TryParse(token, out renewalToken))
            {
                result.AppendError(errorMsg);
                return(new cs.UserIdentity());
            }
            UserSession session = GetUserSession(renewalToken);

            if (session == null)
            {
                result.AppendError(errorMsg);
                return(new cs.UserIdentity());
            }
            AuthenticationHistory history = GetSessionAuthenticationHistory(session);

            if (history == null)
            {
                result.AppendError(errorMsg);
                return(new cs.UserIdentity());
            }
            else if (history.IPAddress != ipAddress)
            {                                  //coming from a new IPAddress, token was stolen or user is coming from a new dynamic IP address (new internet connection?)
                result.AppendError(errorMsg);
                return(new cs.UserIdentity()); //force new login with password (essentially approves this new IP address)
                //WARN: is this a valid check?  Can an imposter just fake the source IP?  Could a legitimate user hop IP Addresses during a single session?
            }

            session.RenewedDate    = DateTime.UtcNow;
            session.ExpirationDate = DateTime.UtcNow.AddMinutes(duration == UserSessionDurationType.PublicComputer ? PublicSessionDuration : ExtendedSessionDuration);
            SaveUserSession(session);
            history.UserSession = session;
            return(new UserIdentity(history, this.Name));
        }
Beispiel #37
0
 /// <summary>
 /// Validates that a password meets minimum requirements.
 /// </summary>
 /// <param name="password"></param>
 /// <param name="results"></param>
 /// <returns></returns>
 public static bool ValidatePassword(string password, ExecutionResults results)
 {
     return(Provider.ValidatePassword(password, results));
 }
Beispiel #38
0
        /// <summary>
        /// Registers a new user.  The PasswordHash property should be the actual password.
        /// </summary>
        /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
        /// <param name="duration">The amount of time that the initial session will be valid.</param>
        /// <param name="ipAddress">The internet address where the user is connecting from.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>A boolean indicating success (true) or failure (false).</returns>
        public override UserIdentity RegisterUser(User user, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
        {
            string password = user.PasswordHash;

            if (!ValidateName(user.Name, result) || !ValidatePassword(password, result))
            {
                return(new cs.UserIdentity());
            }

            var existing = GetUserByName(user.Name);

            if (existing != null)
            {   //seed user table with deleted users with names you don't want users to have
                result.AppendError("The name you specified cannot be used.");
                return(new cs.UserIdentity());
            }
            if (user.UserID.Equals(Guid.Empty))
            {
                user.UserID = Guid.NewGuid();
            }

            HashProvider hasher = HashManager.SelectProvider();
            var          salt   = new UserSalt
            {
                PasswordSalt = hasher.GetSalt(),
                UserID       = user.UserID,
                HashGroup    = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum),
                HashName     = hasher.Name
            };

            user.PasswordHash = hasher.Hash(salt.PasswordSalt, password,
                                            salt.HashGroup + BaseHashIterations);
            using (var scope = new System.Transactions.TransactionScope())
            {
                //starts as a lightweight transaction
                SaveUser(user);
                //enlists in a full distributed transaction if users and salts have different connection strings
                SaveUserSalt(salt);
            }
            return(AuthenticateUser(name: user.Name, password: password, duration: duration,
                                    ipAddress: ipAddress, checkHistory: false, allowUpdateHash: false, result: result));
        }
Beispiel #39
0
 /// <summary>
 /// Authenticates against the data store and returns a UserIdentity given
 /// a user name, and password.
 /// </summary>
 /// <param name="name">The unique user name.</param>
 /// <param name="password">The matching password.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="duration">The amount of time that the issued token will be valid.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>
 /// A valid user instance.  If the user did not exist or the
 /// credentials are incorrect then the IsAuthenticated flag
 /// will be false.  If the credentials were correct the
 /// IsAuthenticated flag will be true.
 /// </returns>
 public static UserIdentity AuthenticateUser(string name, string password, UserSessionDurationType duration, string ipAddress,
                                             ExecutionResults result)
 {
     return(Provider.AuthenticateUser(name, password, duration, ipAddress, result));
 }
Beispiel #40
0
        /// <summary>
        /// updates a user's name and/or password.
        /// </summary>
        /// <param name="item">The user details to be saved.  If Password is empty is it not changed.  If specified it should be the new raw password (not a hash).</param>
        /// <param name="currentPassword">The current raw password for the user used to authenticate that the change can be made, or the current resetcode last sent to this user.</param>
        /// <param name="ipAddress">The internet address where the user is connecting from.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>A boolean indicating success (true) or failure (false).</returns>
        public override bool UpdateUser(User item, String currentPassword, String ipAddress, ExecutionResults result)
        {
            if (item.UserID.Equals(Guid.Empty))
            {
                throw new ArgumentException("The user identity must be specified.");
            }
            var user = GetUserByID(item.UserID);
            var salt = GetUserSalt(item.UserID);

            if (user == null || salt == null)
            {
                result.AppendError("The specified user identity does not exist.");
                return(false);
            }
            if (salt.ResetCode == currentPassword)
            {
                if (salt.ResetCodeExpiration < DateTime.UtcNow)
                {
                    result.AppendError(
                        "Your password reset code has expired.  Request a new one to be sent to you, and then use it immediately.");
                    return(false);
                }
                salt.ResetCode           = null;
                salt.ResetCodeExpiration = DateTime.UtcNow;
            }
            else
            {
                var rememberMe = !cs.SecurityContextManager.IsAnonymous &&
                                 cs.SecurityContextManager.CurrentUser.Identity.Ticket.UserSession.ExpirationDate >
                                 DateTime.UtcNow.AddMinutes(PublicSessionDuration);
                if (!AuthenticateUser(name: item.Name, password: currentPassword, ipAddress: ipAddress,
                                      duration: rememberMe ? UserSessionDurationType.Extended : UserSessionDurationType.PublicComputer,
                                      allowUpdateHash: false, checkHistory: false, result: result).IsAuthenticated)
                {
                    result.AppendError("Cannot change password due to authentication error with current password.");
                    return(false);
                }
            }
            if (user.Name != item.Name)
            {   //user is changing their sign in name.  Make sure the new name is available.
                var nameExisting = GetUserByName(item.Name);
                if (nameExisting != null)
                {
                    result.AppendError("The name you specified cannot be used.");
                    return(false);
                }
                user.Name = item.Name;
            }
            if (!String.IsNullOrEmpty(item.PasswordHash))
            {
                var password = item.PasswordHash;
                //update hashes on regular basis, keeps the iterations in latest range for current users, and with a 'current' hash provider.
                HashProvider hasher = HashManager.SelectProvider();
                salt.PasswordSalt        = hasher.GetSalt();
                salt.HashGroup           = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum);
                salt.HashName            = hasher.Name;
                user.PasswordHash        = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);
                user.PasswordUpdatedDate = DateTime.UtcNow;
            }
            using (var scope = new System.Transactions.TransactionScope())
            {
                //starts as a lightweight transaction
                SaveUser(user);
                //enlists in a full distributed transaction if users and salts have different connection strings
                SaveUserSalt(salt);
            }
            return(true);
        }
Beispiel #41
0
 /// <summary>
 /// Invalidates a session token so it can no longer be used.
 /// </summary>
 /// <param name="token"></param>
 /// <param name="ipAddress"></param>
 /// <param name="result"></param>
 public static void InvalidateSession(string token, String ipAddress, ExecutionResults result)
 {
     Provider.InvalidateSession(token, ipAddress, result);
 }
 /// <summary>
 /// Sends a password reset notification to the specified user.
 /// </summary>
 /// <param name="userName">The user to notify.</param>
 /// <param name="result">
 /// A placeholder for errors in the system, such as email not available now.
 /// Do not notify caller if the user does not exist, for security reasons.</param>
 /// <remarks>
 /// 
 /// </remarks>
 public virtual bool NotifyPasswordReset(String userName, ExecutionResults result)
 {
     //Either configure the Azure implementation, or create your own.
     result.AppendError("The forgot password functionality is not yet implemented.");
     return false;
 }
Beispiel #43
0
 /// <summary>
 /// updates a user's name and/or password.
 /// </summary>
 /// <param name="item">The user details to be saved.  If Password is empty is it not changed.  If specified it should be the new raw password (not a hash).</param>
 /// <param name="currentPassword">The current raw password for the user used to authenticate that the change can be made.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>A boolean indicating success (true) or failure (false).</returns>
 public static bool UpdateUser(User item, String currentPassword, String ipAddress, ExecutionResults result)
 {
     return(Provider.UpdateUser(item, currentPassword, ipAddress, result));
 }
 public PrologResult(ExecutionResults initialStatus)
 {
     status = initialStatus;
 }
        private void ProcessResults(ExecutionResults results)
        {
            Synchronize();

            switch (results)
            {
                case ExecutionResults.Success:
                    {
                        UpdateQueryResults();
                        RaiseExecutionComplete(new PrologQueryEventArgs(QueryResults));
                    }
                    break;

                case ExecutionResults.Failure:
                    {
                        RaiseExecutionComplete(new PrologQueryEventArgs(null));
                    }
                    break;

                case ExecutionResults.None:
                case ExecutionResults.Backtrack:
                    {
                        RaiseExecutionSuspended();
                    }
                    break;

                default:
                    throw new InvalidOperationException(string.Format("Unknown results {0}.", results));
            }
        }
Beispiel #46
0
        private ExecutionResults ExecuteCommand(string command, string paramters)
        {
            mStandardOut = mStandardErr = "";
              ExecutionResults results = new ExecutionResults();
              results.mResult = false;
              results.mStderr = "";
              results.mStdout = "";
              results.mCommand = command + " " + paramters;

              try
              {
            ProcessStartInfo pinfo = new ProcessStartInfo(command, paramters);
            pinfo.RedirectStandardError = true;
            pinfo.RedirectStandardOutput = true;
            pinfo.WindowStyle = ProcessWindowStyle.Hidden;
            pinfo.UseShellExecute = false;
            pinfo.CreateNoWindow = true;
            Process proc = Process.Start(pinfo);
            while (!proc.StandardOutput.EndOfStream)
            {
              mStandardOut = mStandardOut + proc.StandardOutput.ReadLine();
            }
            while (!proc.StandardError.EndOfStream)
            {
              mStandardErr = mStandardErr + proc.StandardError.ReadLine();
            }
            results.mStderr = mStandardErr;
            results.mStdout = mStandardOut;
            results.mResult = true;
              }
              catch (System.ComponentModel.Win32Exception e)
              {
            results.mStderr = e.Message;
              }

              return results;
        }
Beispiel #47
0
 /// <summary>
 /// Authenticates against the data store and returns a UserIdentity given 
 /// a user name, and password.
 /// </summary>
 /// <param name="name">The unique user name.</param>
 /// <param name="password">The matching password.</param>
 /// <param name="ipAddress">The internet address where the user is connecting from.</param>
 /// <param name="duration">The amount of time that the issued token will be valid.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>
 /// A valid user instance.  If the user did not exist or the 
 /// credentials are incorrect then the IsAuthenticated flag
 /// will be false.  If the credentials were correct the 
 /// IsAuthenticated flag will be true.
 /// </returns>
 public virtual UserIdentity AuthenticateUser(
     string name, string password, UserSessionDurationType duration,
     string ipAddress, ExecutionResults result)
 {
     return AuthenticateUser(name: name, password: password, duration: duration,
         ipAddress: ipAddress, checkHistory: true, allowUpdateHash: true, result: result);
 }
 public override Security.UserIdentity AuthenticateUser(string token, Security.UserSessionDurationType duration, string ipAddress, ExecutionResults result)
 {
     throw new NotImplementedException();
 }
Beispiel #49
0
        /// <summary>
        /// Authenticates against the data store and returns a UserIdentity given
        /// a token returned from a previous authentication.
        /// </summary>
        /// <param name="token">The unique token.</param>
        /// <param name="duration">The amount of time that the renewed token will be valid.</param>
        /// <param name="ipAddress">The internet address where the user is connecting from.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>
        /// A valid user identity instance.  If the token is incorrect or expired
        /// then the IsAuthenticated flag will be false.  Otherwise the identity
        /// will be authenticated.
        /// </returns>
        public virtual UserIdentity AuthenticateUser(string token, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
        {
            const string errorMsg = "Authentication token invalid.";
            Guid renewalToken;
            if (!Guid.TryParse(token, out renewalToken))
            {
                result.AppendError(errorMsg);
                return new UserIdentity();
            }
            var session = GetUserSession(renewalToken);
            if (session == null)
            {
                result.AppendError(errorMsg);
                return new UserIdentity();
            }
            var history = GetSessionAuthenticationHistory(session);
            if (history == null)
            {
                result.AppendError(errorMsg);
                return new UserIdentity();
            }
            if (history.IPAddress != ipAddress)
            {	//coming from a new IPAddress, token was stolen or user is coming from a new dynamic IP address (new internet connection?)
                result.AppendError(errorMsg);
                return new UserIdentity(); //force new login with password (essentially approves this new IP address)
                //WARN: is this a valid check?  Can an imposter just fake the source IP?  Could a legitimate user hop IP Addresses during a single session?
            }

            if ((DateTime.UtcNow - session.RenewedDate).Duration() > TimeSpan.FromMinutes(1))
            {   //reduce the number of writes.  Only need to know within a minute how many active users there are.  There may be many json requests for a single page in a minute.
                session.RenewedDate = DateTime.UtcNow;
                session.ExpirationDate = DateTime.UtcNow.AddMinutes(duration == UserSessionDurationType.PublicComputer ? PublicSessionDuration : ExtendedSessionDuration);
                SaveUserSession(session);
            }
            history.UserSession = session;
            return new UserIdentity(history, Name);
        }
Beispiel #50
0
 /// <summary>
 /// Registers a new guest user.  The user is being created by another user
 /// that is inviting this user to join.
 /// </summary>
 /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
 /// <param name="result">A ExecutionResults instance to add applicable
 /// warning and error messages to.</param>
 /// <returns>The guest password good for 14 days, or another configurable number of days.  
 /// After that initial period the user can request a password reset when joining.</returns>
 public virtual String RegisterGuestUser(User user, ExecutionResults result)
 {
     user.IsGuest = true;
     return !RegisterBase(user, result) ? null
         : GenerateUserResetCode(user.Name, TimeSpan.FromDays(GuestUserExpirationDays));
 }
 /// <summary>
 /// Deconstructs context.
 /// </summary>
 /// <param name="executionResult">Last execution result.</param>
 /// <param name="executionContext">Current execution context.</param>
 public void Deconstruct(out IExecutionResult executionResult, out TestFlowExecutionContext executionContext)
 {
     executionResult  = ExecutionResults.LastOrDefault();
     executionContext = this;
 }
 public override Security.UserIdentity RegisterUser(Security.User user, Security.UserSessionDurationType duration, string ipAddress, ExecutionResults result)
 {
     throw new NotImplementedException();
 }