/// <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); } }
/// <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("ZentityAuthenticationProvider"); /// //Login as admin /// AuthenticatedToken adminToken = provider.Authenticate(new UserNameSecurityToken("Administrator", "XXXX"));//Supply correct password /// //Administrator changes Jimmy's log on name. /// bool updated = ZentityUserManager.UpdateLogOnName(adminToken, "Jimmy", "Jimmy12"); /// if (updated) /// { /// Console.WriteLine("Updated log on name successfully"); /// } /// else /// { /// Console.WriteLine("Could not update log on name."); /// } /// </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("Administrator", "XXXX");//Supply correct password /// Console.WriteLine("Administrator logged in."); /// } /// //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); } }
/// <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); } }
/// <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); } }
/// <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 = "John"; /// newUser.Email = "[email protected]"; /// newUser.LogOnName = "JohnDE"; /// newUser.SetPassword("john@123"); //In case of a UI accepting user inputs this call would be newUser.SetPassword(passwordBox1.Password) /// newUser.SetSecurityQuestion("What is a bit?"); /// newUser.SetAnswer("0 or 1"); /// //Optional properties - the user can be registered with or without setting these properties. /// newUser.MiddleName = "D"; /// newUser.LastName = "Erickson"; /// newUser.City = "New York"; /// newUser.State = "New York State"; /// newUser.Country = "USA"; /// bool registered = ZentityUserManager.Register(newUser); /// if (registered) /// { /// Console.WriteLine("User John registered successfully"); /// } /// else /// { /// //false value might mean the logon name is already in use. /// Console.WriteLine(@"User John could not be registered. The logon name chosen might be already in use. /// Try choosing a different logon name."); /// } /// } /// //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()); }
/// <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("JohnDE", "john@123"); /// john.LogOnName = "JohnDE"; /// john.SetPassword("john@123"); /// //Update security question and email /// john.SetSecurityQuestion("Define Bit"); /// john.Email = "[email protected]"; /// 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()); }
/// <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); } }
/// <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("JohnDE", "What is a bit?", "0 or 1"); /// if (!string.IsNullOrEmpty(newSystemGeneratedPassword)) /// { /// Console.WriteLine("New password generated is {0}", 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("Errors in getting a new password. Security question / answer might be 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 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); } }
/// <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("JohnDE", "john@123"); /// //The ZentityUser instance returned contains all property values filled in from the authentication store. /// if (user != null) /// { /// Console.WriteLine("Email : {0}", 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); } }
/// <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("JohnDE", "john", "john@123"); /// if (isLogOnUpdated) /// { /// Console.WriteLine("LogOn updated"); /// } /// else /// { /// //LogOn name might not be updated if the new logon chosen is already in use. /// Console.WriteLine("Errors in updating logon. The logon name might be in use. Try choosing a different logon name."); /// } /// } /// 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); } }
/// <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("JohnDE", "john@123", "john@12345"); /// if (passwordChanged) /// { /// Console.WriteLine("Password changed"); /// } /// else /// { /// //LogOn name might not be updated if the new logon chosen is already in use. /// Console.WriteLine("Errors in changing password. Current credentials may be 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 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); } }
/// <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("JohnDE", "john@123"); /// Console.WriteLine("Your password expires in {0} days", 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); } }
/// <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); } }
/// <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); } }
/// <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); } }
/// <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); } }
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)); } }