Exemple #1
0
        /// <summary>
        /// Returns the user profile. An admin can get any user's profile.
        /// </summary>
        /// <param name="token">AuthenticatedToken of the logged on user.</param>
        /// <param name="logOnName">LogOnName of the user whose profile is requested.</param>
        /// <returns>ZentityUser instance filled with properties.</returns>
        /// <remarks>This method is expected to be called for the scenario where the administrator is requesting profile of a user.
        /// This method works when the AuthenticatedToken belongs to the administrator, or when the token
        /// belongs to the user whose logon name is passed as the second parameter.</remarks>
        public static ZentityUserProfile GetUserProfile(AuthenticatedToken token, string logOnName)
        {
            #region Input Validation
            ValidateToken(token);
            #endregion

            try
            {
                //// The token must be of the user who is updating the logon name or it must be an admin's token.
                if (!string.Equals(token.IdentityName, logOnName, StringComparison.OrdinalIgnoreCase) &&
                    !DataAccessLayer.IsAdmin(token.IdentityName))
                {
                    return(null);
                }

                ZentityUser user = new ZentityUser(logOnName, token);
                user.FillUserProperties();
                return(user.Profile);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #2
0
        /// <summary>
        /// Updates log on name of the current logged on user.
        /// </summary>
        /// <param name="token">AuthenticatedToken of the logged on user.</param>
        /// <param name="currentLogOn">Current logon name of the user whose logon name is to be updated.</param>
        /// <param name="newLogOn">New log on name.</param>
        /// <returns>True if operation succeeds.</returns>
        /// <remarks>An administrator can update any user's log on name. Other users can update only their own logon name.
        /// Hence for non-admin users the current log on must match the logged on user's log on name.</remarks>
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to System.IdentityModel, Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// <code>
        /// //Get authentication provider from factory
        /// IAuthenticationProvider provider = AuthenticationProviderFactory.CreateAuthenticationProvider(&quot;ZentityAuthenticationProvider&quot;);
        /// //Login as admin
        /// AuthenticatedToken adminToken = provider.Authenticate(new UserNameSecurityToken(&quot;Administrator&quot;, &quot;XXXX&quot;));//Supply correct password
        /// //Administrator changes Jimmy's log on name.
        /// bool updated = ZentityUserManager.UpdateLogOnName(adminToken, &quot;Jimmy&quot;, &quot;Jimmy12&quot;);
        /// if (updated)
        /// {
        ///     Console.WriteLine(&quot;Updated log on name successfully&quot;);
        /// }
        /// else
        /// {
        ///     Console.WriteLine(&quot;Could not update log on name.&quot;);
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="Zentity.Security.AuthenticationProvider.ZentityAuthenticationProvider"/>
        public static bool UpdateLogOnName(AuthenticatedToken token, string currentLogOn, string newLogOn)
        {
            #region Input Validation
            ValidateToken(token);
            ValidateParameters("currentLogOn", currentLogOn, "newLogOn", newLogOn);
            #endregion

            try
            {
                //// The token must be of the user who is updating the logon name or it must be an admin's token.
                if (!string.Equals(token.IdentityName, currentLogOn, StringComparison.OrdinalIgnoreCase) &&
                    !DataAccessLayer.IsAdmin(token.IdentityName))
                {
                    return(false);
                }

                ZentityUser user    = new ZentityUser(currentLogOn, token);
                bool        success = user.UpdateLogOnName(newLogOn);
                return(success);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
        /// <summary>
        /// Initializes a new instance of the ZentityUserAdmin class
        /// only if the credentials are correct and the user is set as an admin user
        /// </summary>
        /// <param name="adminUserName">LogOnName of an admin user</param>
        /// <param name="adminPassword">Password of the admin user</param>
        /// <remarks>
        /// The Zentity installation provides a built in administrator account, whose credentials are as
        /// provided in the code below.
        /// It is highly recommended that the admin password should be changed soon after installing Zentity,
        /// and at least one alternate admin account should be created.
        /// </remarks>
        /// <example>
        /// <code>
        /// //The ZentityUserAdmin constructor initializes an instance only when valid credentials
        ///    //for a user with admin rights are provided.
        ///    //Otherwise the constructor throws AuthenticationException.
        ///    try
        ///    {
        ///        ZentityUserAdmin admin = new ZentityUserAdmin(&quot;Administrator&quot;, &quot;XXXX&quot;);//Supply correct password
        ///        Console.WriteLine(&quot;Administrator logged in.&quot;);
        ///    }
        ///    //AuthenticationException might be thrown in case of errors in connecting to the authentication store
        ///    //or if admin credentials are incorrect.
        ///    catch (AuthenticationException ex)
        ///    {
        ///        Console.WriteLine(ex.Message);
        ///        //In case of database errors the AuthenticationException object will wrap the sql exception.
        ///        if (ex.InnerException != null)
        ///        {
        ///            Console.WriteLine(ex.InnerException.Message);
        ///        }
        ///    }
        ///
        /// </code>
        /// </example>
        public ZentityUserAdmin(string adminUserName, string adminPassword)
        {
            #region Input Validation
            if (string.IsNullOrEmpty(adminUserName))
            {
                throw new ArgumentNullException("adminUserName");
            }

            if (string.IsNullOrEmpty(adminPassword))
            {
                throw new ArgumentNullException("adminPassword");
            }
            #endregion

            try
            {
                ZentityUser user = new ZentityUser(adminUserName, adminPassword);
                if (user.VerifyPassword())
                {
                    if (!DataAccessLayer.IsAdmin(adminUserName))
                    {
                        throw new AuthenticationException(ConstantStrings.AdminAuthenticationExceptionMessage);
                    }
                }
                else
                {
                    throw new AuthenticationException(ConstantStrings.AdminAuthenticationExceptionMessage);
                }
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #4
0
        /// <summary>
        /// Returns number of days remaining for password expiry for the user represented by logOnName.
        /// </summary>
        /// <param name="token">AuthenticatedToken of the logged on user, typically an admin.</param>
        /// <param name="logOnName">LogOnName of the user whose information is requested.</param>
        /// <returns>Remaining days, if operation succeeds, null otherwise.</returns>
        /// <remarks>Call this method when an admin wants information for a user. For a user requesting his information,
        /// call the overload with just AuthenticatedToken parameter.</remarks>
        public static int?GetRemainingDaysToPasswordExpiry(AuthenticatedToken token, string logOnName)
        {
            //// Input Validation
            ValidateToken(token);
            ValidateParameters("logOnName", logOnName);

            try
            {
                //// The token must be of the user who is updating the logon name or it must be an admin's token.
                if (!string.Equals(token.IdentityName, logOnName, StringComparison.OrdinalIgnoreCase) &&
                    !DataAccessLayer.IsAdmin(token.IdentityName))
                {
                    return(null);
                }

                ZentityUser user          = new ZentityUser(logOnName, token);
                int?        remainingDays = user.GetRemainingDaysToPasswordExpiry();
                return(remainingDays);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #5
0
        /// <summary>
        /// Unregisters a user. An admin can unregister any user, while a user can request unregistration for himself.
        /// </summary>
        /// <param name="token">Authenticated token of the logged on user.</param>
        /// <param name="logOnName">LogOn name of the user whose account is to be unregistered.</param>
        /// <returns>True if unregister operation completes successfully.</returns>
        /// <remarks>This method succeeds for any user's logon name when an admin token is passed.
        /// When a user token is passed, the logon name must be of the same user. Or else call the overload with just
        /// AuthenticatedToken parameter for unregistering a user. </remarks>
        public static bool Unregister(AuthenticatedToken token, string logOnName)
        {
            #region Input Validation
            ValidateToken(token);
            ValidateParameters("logOnName", logOnName);
            #endregion

            try
            {
                //// The token must be of the admin or the user who wants to unregister.
                if (!string.Equals(token.IdentityName, logOnName, StringComparison.OrdinalIgnoreCase) &&
                    !DataAccessLayer.IsAdmin(token.IdentityName))
                {
                    return(false);
                }

                ZentityUser user    = new ZentityUser(logOnName, token);
                bool        success = user.Unregister();
                return(success);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #6
0
        /// <summary>
        /// Registers a new user to Zentity.
        /// Set all required properties of ZentityUser instance and then call Register to
        /// create the user account
        /// </summary>
        /// <param name="newUser">ZentityUser instance with all mandatory properties filled in</param>
        /// <returns>True if user account created successfully</returns>
        /// <exception cref="System.ArgumentException">Thrown when ZentityUser object is not filled in with all required property values.</exception>
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the authentication database script (present in Program Files\Zentity 1.0\Scripts folder)</item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// <code>
        /// try
        ///    {
        ///        ZentityUser newUser = new ZentityUser();
        ///        //Set the mandatory properties of the ZentityUser object.
        ///        newUser.FirstName = &quot;John&quot;;
        ///        newUser.Email = &quot;[email protected]&quot;;
        ///        newUser.LogOnName = &quot;JohnDE&quot;;
        ///        newUser.SetPassword(&quot;john@123&quot;); //In case of a UI accepting user inputs this call would be newUser.SetPassword(passwordBox1.Password)
        ///        newUser.SetSecurityQuestion(&quot;What is a bit?&quot;);
        ///        newUser.SetAnswer(&quot;0 or 1&quot;);
        ///        //Optional properties - the user can be registered with or without setting these properties.
        ///        newUser.MiddleName = &quot;D&quot;;
        ///        newUser.LastName = &quot;Erickson&quot;;
        ///        newUser.City = &quot;New York&quot;;
        ///        newUser.State = &quot;New York State&quot;;
        ///        newUser.Country = &quot;USA&quot;;
        ///        bool registered = ZentityUserManager.Register(newUser);
        ///        if (registered)
        ///        {
        ///            Console.WriteLine(&quot;User John registered successfully&quot;);
        ///        }
        ///        else
        ///        {
        ///            //false value might mean the logon name is already in use.
        ///            Console.WriteLine(@&quot;User John could not be registered. The logon name chosen might be already in use.
        ///    Try choosing a different logon name.&quot;);
        ///        }
        ///    }
        ///    //AuthenticationException might be thrown in case of errors in connecting to the authentication store
        ///    //or if admin credentials are incorrect.
        ///    catch (AuthenticationException ex)
        ///    {
        ///        Console.WriteLine(ex.Message);
        ///        //In case of database errors the AuthenticationException object will wrap the sql exception.
        ///        if (ex.InnerException != null)
        ///        {
        ///            Console.WriteLine(ex.InnerException.Message);
        ///        }
        ///    }
        /// </code>
        /// </example>
        public static bool Register(ZentityUser newUser)
        {
            #region Input Validation
            if (newUser == null)
            {
                throw new ArgumentNullException("newUser");
            }
            #endregion

            return(newUser.Register());
        }
Exemple #7
0
        /// <summary>
        /// Updates a user profile. Create a ZentityUser instance, set login name
        /// and password to correct values. Then set the properties which need modification
        /// Then call UpdateProfile()
        /// </summary>
        /// <param name="user">ZentityUser object filled in with logon name, password and
        /// properties which are to be updated</param>
        /// <returns>True if user profile is updated successfully</returns>
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to System.IdentityModel, Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// <code>
        /// ZentityUser john = ZentityUserManager.GetUserProfile(&quot;JohnDE&quot;, &quot;john@123&quot;);
        /// john.LogOnName = &quot;JohnDE&quot;;
        /// john.SetPassword(&quot;john@123&quot;);
        /// //Update security question and email
        /// john.SetSecurityQuestion(&quot;Define Bit&quot;);
        /// john.Email = &quot;[email protected]&quot;;
        /// bool updated = ZentityUserManager.UpdateProfile(john);
        /// </code>
        /// </example>
        public static bool UpdateProfile(ZentityUser user)
        {
            #region Validation
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            #endregion

            return(user.UpdateProfile());
        }
Exemple #8
0
        /// <summary>
        /// Retrieves user information from database and returns collection of
        /// Zentity user objects
        /// </summary>
        /// <param name="startIndex">Set this to proper value for paged retrieval of users. </param>
        /// <param name="endIndex">Set this to proper value for paged retrieval of users. </param>
        /// <returns>Collection of users</returns>
        internal static IEnumerable <ZentityUser> GetUsers(int startIndex, int endIndex)
        {
            #region Parameter validation
            if (startIndex <= 0 || endIndex == 0)
            {
                throw new ArgumentException(ConstantStrings.IndexValuesExceptionMessage);
            }
            if (startIndex > endIndex && endIndex != -1)
            {
                throw new ArgumentException(ConstantStrings.IndexValuesExceptionMessage);
            }
            #endregion

            //Call SP GetPagedUserRecords
            try
            {
                Collection <ZentityUser> pagedUsers = new Collection <ZentityUser>();
                //Execute stored procedure GetUserInfo
                using (SqlConnection conn = new SqlConnection(_connectionString))
                {
                    Dictionary <string, string> parameters = new Dictionary <string, string>(2);
                    parameters.Add("StartIndex", startIndex.ToString());
                    parameters.Add("EndIndex", endIndex.ToString());
                    using (SqlCommand cmd = new SqlCommand(_executeGetPagedUserRecordsFunction, conn))
                    {
                        cmd.CommandType = CommandType.Text;
                        SetCommandParameters(cmd, parameters);

                        //Execute stored procedure
                        conn.Open();
                        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                        while (reader.Read())
                        {
                            ZentityUser user = new ZentityUser();
                            //Read the records one by one and create a Zentity user instance
                            //Fill in list of users
                            SetUserProperties(user, reader, true);
                            pagedUsers.Add(user);
                        }
                        conn.Close();
                    }
                }
                return(pagedUsers.AsEnumerable());
            }
            catch (SqlNullValueException ex)
            {
                throw new AuthenticationException(ConstantStrings.DatabaseExceptionMessage, ex);
            }
            catch (SqlException ex)
            {
                throw new AuthenticationException(ConstantStrings.DatabaseExceptionMessage, ex);
            }
        }
Exemple #9
0
        /// <summary>
        /// Generates a new password for the user in case he forgets the password
        /// </summary>
        /// <param name="logOnName">Login name of the user</param>
        /// <param name="securityQuestion">Security question selected by the user</param>
        /// <param name="answer">User's answer to the security question</param>
        /// <returns>New password generated for the user</returns>
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// <code>
        /// try
        ///    {
        ///        //For getting a new password you need to provide the security question and answer
        ///        //entered at the time of registration.
        ///        string newSystemGeneratedPassword = ZentityUserManager.ForgotPassword(&quot;JohnDE&quot;, &quot;What is a bit?&quot;, &quot;0 or 1&quot;);
        ///        if (!string.IsNullOrEmpty(newSystemGeneratedPassword))
        ///        {
        ///            Console.WriteLine(&quot;New password generated is {0}&quot;, newSystemGeneratedPassword);
        ///            //Try logging in using new password - refer to ZentityAuthenticationProvider.Authenticate() method documentation
        ///        }
        ///        else
        ///        {
        ///            //LogOn name might not be updated if the new logon chosen is already in use.
        ///            Console.WriteLine(&quot;Errors in getting a new password. Security question / answer might be incorrect.&quot;);
        ///        }
        ///    }
        ///    catch (AuthenticationException ex)
        ///    {
        ///        Console.WriteLine(ex.Message);
        ///        //In case of database errors the AuthenticationException object will wrap the sql exception.
        ///        if (ex.InnerException != null)
        ///        {
        ///            Console.WriteLine(ex.InnerException.Message);
        ///        }
        ///    }
        ///
        /// </code>
        /// </example>
        public static string ForgotPassword(string logOnName, string securityQuestion, string answer)
        {
            #region Input Validation
            ValidateParameters("logOnName", logOnName, "securityQuestion", securityQuestion, "answer", answer);
            #endregion

            try
            {
                string newPassword = ZentityUser.ForgotPassword(logOnName, securityQuestion, answer);
                return(newPassword);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #10
0
        /// <summary>
        /// Retrieves user information for the given user
        /// </summary>
        /// <param name="logOnName">LogOn Name of the user whose information is to be retrieved</param>
        /// <param name="password">User password</param>
        /// <returns>ZentityUser instance in which property values are filled in from database</returns>
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// <code>
        /// try
        ///    {
        ///        ZentityUser user = ZentityUserManager.GetUserProfile(&quot;JohnDE&quot;, &quot;john@123&quot;);
        ///        //The ZentityUser instance returned contains all property values filled in from the authentication store.
        ///        if (user != null)
        ///        {
        ///            Console.WriteLine(&quot;Email : {0}&quot;, user.Email);
        ///            //Display remaining properties.
        ///        }
        ///    }
        ///    catch (AuthenticationException ex)
        ///    {
        ///        Console.WriteLine(ex.Message);
        ///        //In case of database errors the AuthenticationException object will wrap the sql exception.
        ///        if (ex.InnerException != null)
        ///        {
        ///            Console.WriteLine(ex.InnerException.Message);
        ///        }
        ///    }
        ///
        /// </code>
        /// </example>
        public static ZentityUserProfile GetUserProfile(string logOnName, string password)
        {
            #region Input Validation
            ValidateParameters("logOnName", logOnName, "password", password);
            #endregion

            try
            {
                ZentityUser user = new ZentityUser(logOnName, password);
                user.FillUserProperties();
                return(user.Profile);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #11
0
        /// <summary>
        /// Updates a user logon name.
        /// </summary>
        /// <param name="currentLogOn">Current log on name</param>
        /// <param name="newLogOn">New log on name</param>
        /// <param name="password">User Password</param>
        /// <returns>True if user logon name is updated successfully</returns>
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// <code>
        /// try
        ///    {
        ///        bool isLogOnUpdated = ZentityUserManager.UpdateLogOnName(&quot;JohnDE&quot;, &quot;john&quot;, &quot;john@123&quot;);
        ///        if (isLogOnUpdated)
        ///        {
        ///            Console.WriteLine(&quot;LogOn updated&quot;);
        ///        }
        ///        else
        ///        {
        ///            //LogOn name might not be updated if the new logon chosen is already in use.
        ///            Console.WriteLine(&quot;Errors in updating logon. The logon name might be in use. Try choosing a different logon name.&quot;);
        ///        }
        ///    }
        ///    catch (AuthenticationException ex)
        ///    {
        ///        Console.WriteLine(ex.Message);
        ///        //In case of database errors the AuthenticationException object will wrap the sql exception.
        ///        if (ex.InnerException != null)
        ///        {
        ///            Console.WriteLine(ex.InnerException.Message);
        ///        }
        ///    }
        ///
        /// </code>
        /// </example>
        public static bool UpdateLogOnName(string currentLogOn, string newLogOn, string password)
        {
            #region Input Validation
            ValidateParameters("currentLogOn", currentLogOn, "newLogOn", newLogOn, "password", password);
            #endregion

            try
            {
                ZentityUser user    = new ZentityUser(currentLogOn, password);
                bool        success = user.UpdateLogOnName(newLogOn);
                return(success);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #12
0
        /// <summary>
        /// Changes user password if the current password is verified to be correct
        /// </summary>
        /// <param name="logOnName">LogOn name of the user</param>
        /// <param name="currentPassword">Current password</param>
        /// <param name="newPassword">New password</param>
        /// <returns>True if user password is changed successfully</returns>'
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// <code>
        /// try
        ///    {
        ///        bool passwordChanged = ZentityUserManager.ChangePassword(&quot;JohnDE&quot;, &quot;john@123&quot;, &quot;john@12345&quot;);
        ///        if (passwordChanged)
        ///        {
        ///            Console.WriteLine(&quot;Password changed&quot;);
        ///        }
        ///        else
        ///        {
        ///            //LogOn name might not be updated if the new logon chosen is already in use.
        ///            Console.WriteLine(&quot;Errors in changing password. Current credentials may be incorrect.&quot;);
        ///        }
        ///    }
        ///    catch (AuthenticationException ex)
        ///    {
        ///        Console.WriteLine(ex.Message);
        ///        //In case of database errors the AuthenticationException object will wrap the sql exception.
        ///        if (ex.InnerException != null)
        ///        {
        ///            Console.WriteLine(ex.InnerException.Message);
        ///        }
        ///    }
        ///
        /// </code>
        /// </example>
        public static bool ChangePassword(string logOnName, string currentPassword, string newPassword)
        {
            #region Input Validation
            ValidateParameters("logOnName", logOnName, "currentPassword", currentPassword, "newPassword", newPassword);
            #endregion

            try
            {
                ZentityUser user    = new ZentityUser(logOnName, currentPassword);
                bool        success = user.ChangePassword(newPassword);
                return(success);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #13
0
        /// <summary>
        /// Returns number of days remaining before the password expires.
        /// </summary>
        /// <param name="logOnName">Logon name of the user</param>
        /// <param name="password">User password</param>
        /// <returns>Remaining days for password expiry. </returns>
        /// <remarks>Useful for displaying warning to the user that he needs to change his password in n days</remarks>
        /// <example>
        /// Pre-requisites for running this code sample
        /// <list type="bullet">
        /// <item>Refer to the sample application configuration file given in help, and create a similar one for your application.</item>
        /// <item>Add reference to Zentity.Security.Authentication.dll and Zentity.Security.AuthenticationProvider.dll </item>
        /// <item>Run the sample for registering new users to create the user accounts in the authentication database.</item>
        /// <item>Then run this sample, replacing inputs with valid values</item>
        /// </list>
        /// For a complete sample please refer to ZentityUser.GetRemainingDaysToPasswordExpiry() documentation
        /// <code>
        /// try
        ///    {
        ///        //This method returns the number of days remaining for password expiry of the user, as per the
        ///        //password policy.
        ///        //Typically useful for showing reminder message to the user when he logs in.
        ///        int? remainingDays = ZentityUserManager.GetRemainingDaysToPasswordExpiry(&quot;JohnDE&quot;, &quot;john@123&quot;);
        ///        Console.WriteLine(&quot;Your password expires in {0} days&quot;, remainingDays);
        ///    }
        ///    catch (AuthenticationException ex)
        ///    {
        ///        Console.WriteLine(ex.Message);
        ///        //In case of database errors the AuthenticationException object will wrap the sql exception.
        ///        if (ex.InnerException != null)
        ///        {
        ///            Console.WriteLine(ex.InnerException.Message);
        ///        }
        ///    }
        /// </code>
        /// </example>
        /// <seealso cref="ZentityUser.GetRemainingDaysToPasswordExpiry"/>
        public static int?GetRemainingDaysToPasswordExpiry(string logOnName, string password)
        {
            #region Input Validation
            ValidateParameters("logOnName", logOnName, "password", password);
            #endregion

            try
            {
                ZentityUser user          = new ZentityUser(logOnName, password);
                int?        remainingDays = user.GetRemainingDaysToPasswordExpiry();
                return(remainingDays);
            }
            catch (TypeInitializationException ex)
            {
                //// thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #14
0
        /// <summary>
        /// Retrieves user information from database and returns ZentityUser object
        /// filled in with property values
        /// </summary>
        /// <param name="logOnName">LogOn name of the user</param>
        /// <returns>ZentityUser object filled with property values stored in the database</returns>
        internal static ZentityUser GetUser(string logOnName)
        {
            #region Parameter validation
            if (string.IsNullOrEmpty(logOnName))
            {
                throw new ArgumentNullException("logOnName");
            }
            #endregion
            ZentityUser user = new ZentityUser();
            try
            {
                //Execute stored procedure GetUserInfo
                using (SqlConnection conn = new SqlConnection(_connectionString))
                {
                    Dictionary <string, string> parameters = new Dictionary <string, string>(1);
                    parameters.Add("LogOnName", logOnName);
                    using (SqlCommand cmd = new SqlCommand(_executeGetUserInfoFunction, conn))
                    {
                        cmd.CommandType = CommandType.Text;
                        SetCommandParameters(cmd, parameters);

                        //Execute stored procedure
                        conn.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            SetUserProperties(user, reader, false);
                        }
                        conn.Close();
                    }
                }
                return(user);
            }
            catch (SqlNullValueException ex)
            {
                throw new AuthenticationException(ConstantStrings.DatabaseExceptionMessage, ex);
            }
            catch (SqlException ex)
            {
                throw new AuthenticationException(ConstantStrings.DatabaseExceptionMessage, ex);
            }
        }
Exemple #15
0
        /// <summary>
        /// Registers new user account to the database.
        /// </summary>
        /// <param name="newUser">Zentity user object with all required properties set to proper values</param>
        /// <returns>True if user registration is successful</returns>
        internal static bool RegisterUser(ZentityUser newUser)
        {
            //// Parameter Validation
            if (newUser == null)
            {
                throw new ArgumentNullException("newUser");
            }

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("RegisterUser", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        //// Set mandatory properties
                        SetCommandParameter(cmd, "FirstName", newUser.Profile.FirstName);
                        SetCommandParameter(cmd, "Email", newUser.Profile.Email);
                        SetCommandParameter(cmd, "LogOnName", newUser.Profile.LogOnName);
                        SetCommandParameter(cmd, "Password", newUser.Password);
                        SetCommandParameter(cmd, "AccountStatus", newUser.Profile.AccountStatus);
                        SetCommandParameter(cmd, "SecurityQuestion", newUser.Profile.SecurityQuestion);
                        SetCommandParameter(cmd, "Answer", newUser.Profile.Answer);

                        //// Set optional properties
                        SetCommandParameter(cmd, "MiddleName", newUser.Profile.MiddleName);
                        SetCommandParameter(cmd, "LastName", newUser.Profile.LastName);
                        SetCommandParameter(cmd, "City", newUser.Profile.City);
                        SetCommandParameter(cmd, "State", newUser.Profile.State);
                        SetCommandParameter(cmd, "Country", newUser.Profile.Country);

                        return(ExecuteNonQuery(conn, cmd));
                    }
                }
            }
            catch (SqlException ex)
            {
                throw new AuthenticationException(ConstantStrings.DatabaseExceptionMessage, ex);
            }
        }
Exemple #16
0
        /// <summary>
        /// Authenticates a user based on the UserNameSecurityToken passed
        /// </summary>
        /// <param name="credentialToken">This parameter is expected to be a UserNameSecurityToken</param>
        /// <returns>AuthenticatedToken instance for the user if authentication succeeds, null otherwise</returns>
        public AuthenticatedToken Authenticate(SecurityToken credentialToken)
        {
            #region Input validation
            // Validate input
            if (credentialToken == null)
            {
                throw new ArgumentNullException("credentialToken");
            }

            UserNameSecurityToken credential = credentialToken as UserNameSecurityToken;
            if (credential == null)
            {
                throw new ArgumentException(ConstantStrings.InvalidTokenTypeMessage, "credentialToken");
            }
            #endregion

            try
            {
                // Authenticate user
                if (!string.IsNullOrEmpty(credential.UserName) && !string.IsNullOrEmpty(credential.Password))
                {
                    ZentityUser user          = new ZentityUser(credential.UserName, credential.Password);
                    bool        authenticated = user.VerifyPassword();
                    if (authenticated)
                    {
                        ZentityAuthenticatedToken token = new ZentityAuthenticatedToken(credential.UserName.ToString());
                        return(token);
                    }
                }

                // If username/password are not provided, or are invalid, return a null token.
                return(null);
            }
            catch (TypeInitializationException ex)
            {
                // thrown in case of incorrect application configuration
                throw new AuthenticationException(ConstantStrings.TypeInitializationExceptionMessage, ex);
            }
        }
Exemple #17
0
        /// <summary>
        /// Updates a user profile to database.
        /// </summary>
        /// <param name="user">ZentityUser object with property values to be modified set to new values</param>
        /// <returns>True if profile is updated in the database</returns>
        internal static bool UpdateProfile(ZentityUser user)
        {
            //// Parameter Validation
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("UpdateProfile", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        //// Set command parameters for changed properties
                        SetCommandParameter(cmd, "FirstName", user.Profile.FirstName);
                        SetCommandParameter(cmd, "MiddleName", user.Profile.MiddleName);
                        SetCommandParameter(cmd, "LastName", user.Profile.LastName);
                        SetCommandParameter(cmd, "Email", user.Profile.Email);
                        SetCommandParameter(cmd, "City", user.Profile.City);
                        SetCommandParameter(cmd, "State", user.Profile.State);
                        SetCommandParameter(cmd, "Country", user.Profile.Country);
                        SetCommandParameter(cmd, "SecurityQuestion", user.Profile.SecurityQuestion);
                        SetCommandParameter(cmd, "Answer", user.Profile.Answer);

                        //// Add logon name
                        SetCommandParameter(cmd, "LogOnName", user.LogOnName);

                        return(ExecuteNonQuery(conn, cmd));
                    }
                }
            }
            catch (SqlException ex)
            {
                throw new AuthenticationException(ConstantStrings.DatabaseExceptionMessage, ex);
            }
        }
Exemple #18
0
        private static void SetUserProperties(ZentityUser user, SqlDataReader reader, bool readLogOnName)
        {
            #region Parameter validation
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (reader.IsClosed)
            {
                throw new ArgumentException(ConstantStrings.ReaderClosedExceptionMessage);
            }
            #endregion

            user.SetUserId(reader.GetGuid(0));
            user.FirstName = reader.GetString(1);
            //For nullable columns GetString() throws exception in case the record does not have the value filled
            object value = reader.GetValue(2);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.MiddleName = value.ToString();
            }
            value = reader.GetValue(3);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.LastName = value.ToString();
            }
            user.Email = reader.GetString(4);
            value      = reader.GetValue(5);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.City = value.ToString();
            }
            value = reader.GetValue(6);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.State = value.ToString();
            }
            value = reader.GetValue(7);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.Country = value.ToString();
            }
            int i = 8;
            if (readLogOnName)
            {
                user.LogOnName = reader.GetString(8);
                i = 9;
            }
            value = reader.GetValue(i++);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.SetAccountStatus(value.ToString());
            }
            value = reader.GetValue(i++);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.SetDateCreated(Convert.ToDateTime(value));
            }
            value = reader.GetValue(i++);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.SetDateModified(Convert.ToDateTime(value));
            }
            value = reader.GetValue(i++);
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                user.SetPasswordCreationDate(Convert.ToDateTime(value));
            }
        }