public static void Main(string[] args) { try { // We use the default SHA-256 & 4 byte length SaltedHash demo = new SaltedHash(); // We have a password, which will generate a Hash and Salt string Password = "******"; string Hash; string Salt; demo.GetHashAndSaltString(Password, out Hash, out Salt); Console.WriteLine("Password = {0} , Hash = {1} , Salt = {2}", Password, Hash, Salt); // Password validation // // We need to pass both the earlier calculated Hash and Salt (we need to store this somewhere safe between sessions) // First check if a wrong password passes string WrongPassword = "******"; Console.WriteLine("Verifying {0} = {1}", WrongPassword, demo.VerifyHashString(WrongPassword, Hash, Salt)); // Check if the correct password passes Console.WriteLine("Verifying {0} = {1}", Password, demo.VerifyHashString(Password, Hash, Salt)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return; } }
public bool IsValidLogin(String userName, String password) { try { bool PasswordMatch = false; /*_________________________________________________________________________ * Compare the user's hash and salt with the password entered. * _________________________________________________________________________*/ SystemUser systemUser = GetSystemUser(userName); if (systemUser != null && systemUser.Hash != null && systemUser.Salt != null) { SaltedHash SH = new SaltedHash(); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); string dbHash = encoding.GetString(systemUser.Hash); string dbSalt = encoding.GetString(systemUser.Salt); PasswordMatch = SH.VerifyHashString(password, dbHash, dbSalt); } else { PasswordMatch = false; } return(PasswordMatch); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(false); } }
public static string GeneratePassword(int numberOfCharacters) { try { char[] chars = new char[62]; chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); byte[] data = new byte[1]; /*__________________________________________________________________________________________ * RNGCryptoServiceProvider * Implements a cryptographic Random Number Generator (RNG) using the implementation * provided by the cryptographic service provider (CSP). * __________________________________________________________________________________________*/ RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); data = new byte[numberOfCharacters]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(numberOfCharacters); foreach (byte b in data) { result.Append(chars[b % (chars.Length)]); } return(result.ToString()); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
/// <summary> /// Given a data block this routine returns both a Hash and a Salt /// </summary> /// <param name="Data"> /// A <see cref="System.Byte"/>byte array containing the data from which to derive the salt /// </param> /// <param name="Hash"> /// A <see cref="System.Byte"/>byte array which will contain the hash calculated /// </param> /// <param name="Salt"> /// A <see cref="System.Byte"/>byte array which will contain the salt generated /// </param> public void GetHashAndSalt(byte[] Data, out byte[] Hash, out byte[] Salt) { try { // Allocate memory for the salt Salt = new byte[SalthLength]; // Strong runtime pseudo-random number generator, on Windows uses CryptAPI // on Unix /dev/urandom RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); // Create a random salt random.GetNonZeroBytes(Salt); // Compute hash value of our data with the salt. Hash = ComputeHash(Data, Salt); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); Salt = null; Hash = null; return; } }
public System.Web.Http.Results.OkNegotiatedContentResult <List <SettingsModel> > GetSettingsAll() { try { SqlDataReader reader = null; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spGetSettingsAll"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; myConnection.Open(); reader = sqlCmd.ExecuteReader(); List <SettingsModel> settingList = new List <SettingsModel>(); SettingsModel setting = null; while (reader.Read()) { setting = new SettingsModel(); setting.SettingId = reader.GetInt32(0); setting.Settingkey = reader.GetString(1); setting.SettingValue = reader.GetString(2); settingList.Add(setting); } myConnection.Close(); return(Ok(content: settingList)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
/// <summary> /// This routine verifies whether the data generates the same hash as we had stored previously /// </summary> /// <param name="Data">The data to verify </param> /// <param name="Hash">The hash we had stored previously</param> /// <param name="Salt">The salt we had stored previously</param> /// <returns>True on a succesfull match</returns> public bool VerifyHash(byte[] Data, byte[] Hash, byte[] Salt) { try { byte[] NewHash = ComputeHash(Data, Salt); // No easy array comparison in C# -- we do the legwork if (NewHash.Length != Hash.Length) { return(false); } for (int Lp = 0; Lp < Hash.Length; Lp++) { if (!Hash[Lp].Equals(NewHash[Lp])) { return(false); } } return(true); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(false); } }
public System.Web.Http.Results.OkNegotiatedContentResult <List <RestaurantMenuModel> > GetRestaurantMenuItems([FromBody] RestaurantMenuItemParameterModel restaurantMenuItemParameterModel) { try { SqlDataReader reader = null; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spGetRestaurantMenuItems"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Restaurant_Id"; parameter.SqlDbType = SqlDbType.Int; parameter.Direction = ParameterDirection.Input; parameter.Size = 4; parameter.Value = restaurantMenuItemParameterModel.RestaurantId; sqlCmd.Parameters.Add(parameter); myConnection.Open(); reader = sqlCmd.ExecuteReader(); int restaurantMenuIdOrdinal = reader.GetOrdinal("Restaurant_Menu_Id"); int restaurantIdOrdinal = reader.GetOrdinal("Restaurant_Id"); int restaurantMenuCategoryIdOrdinal = reader.GetOrdinal("Restaurant_Menu_Category_Id"); int menuCategoryOrdinal = reader.GetOrdinal("Restaurant_Menu_Category"); int menuItemOrdinal = reader.GetOrdinal("Menu_Item"); int menuCostOrdinal = reader.GetOrdinal("Menu_Cost"); int sortIndexOrdinal = reader.GetOrdinal("Sort_Index"); int endDateOrdinal = reader.GetOrdinal("End_Date"); List <RestaurantMenuModel> restaurantMenuModelList = new List <RestaurantMenuModel>(); RestaurantMenuModel restaurantMenuModel = null; while (reader.Read()) { restaurantMenuModel = new RestaurantMenuModel(); restaurantMenuModel.RestaurantMenuId = reader.GetInt32(restaurantMenuIdOrdinal); restaurantMenuModel.RestaurantId = reader.GetInt32(restaurantIdOrdinal); restaurantMenuModel.RestaurantMenuCategoryId = reader.GetInt32(restaurantMenuCategoryIdOrdinal); restaurantMenuModel.MenuCategory = reader.GetString(menuCategoryOrdinal); restaurantMenuModel.MenuItem = reader.GetString(menuItemOrdinal); restaurantMenuModel.MenuCost = reader.GetDecimal(menuCostOrdinal); restaurantMenuModel.SortIndex = reader.GetInt32(sortIndexOrdinal); restaurantMenuModel.EndDate = (reader.IsDBNull(endDateOrdinal) ? (DateTime?)null : (DateTime?)reader.GetDateTime(endDateOrdinal)); restaurantMenuModelList.Add(restaurantMenuModel); } myConnection.Close(); return(Ok(content: restaurantMenuModelList)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
public System.Web.Http.Results.OkNegotiatedContentResult <SystemUserModel> GetUserRole([FromBody] LoginIdModel loginIdModel) { try { SqlDataReader reader = null; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spGetUserRole"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Login_Id"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Direction = ParameterDirection.Input; parameter.Size = 50; parameter.Value = loginIdModel.LoginId; sqlCmd.Parameters.Add(parameter); myConnection.Open(); reader = sqlCmd.ExecuteReader(); int systemUserIdOrdinal = reader.GetOrdinal("System_User_Id"); int firstNameOrdinal = reader.GetOrdinal("First_Name"); int lastNameOrdinal = reader.GetOrdinal("Last_Name"); int emailAddressOrdinal = reader.GetOrdinal("Email_Address"); int loginIdOrdinal = reader.GetOrdinal("Login_Id"); int roleOrdinal = reader.GetOrdinal("Role"); int endDateOrdinal = reader.GetOrdinal("End_Date"); SystemUserModel systemUserModel = new SystemUserModel(); if (reader.Read()) { systemUserModel.SystemUserId = reader.GetInt32(systemUserIdOrdinal); systemUserModel.FirstName = reader.GetString(firstNameOrdinal); systemUserModel.LastName = reader.GetString(lastNameOrdinal); systemUserModel.EmailAddress = reader.GetString(emailAddressOrdinal); systemUserModel.LoginId = reader.GetString(loginIdOrdinal); systemUserModel.Role = reader.GetString(roleOrdinal); systemUserModel.EndDate = (reader.IsDBNull(endDateOrdinal) ? (DateTime?)null : (DateTime?)reader.GetDateTime(endDateOrdinal)); } myConnection.Close(); return(Ok(content: systemUserModel)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
public TemporaryPasswordModel GetTemporaryPasswordByLoginId(LoginRequest login) { try { SqlDataReader reader = null; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spGetTemporaryPasswordByLogin"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Login_Id"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Input; parameter.Value = login.Username; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Temporary_Password"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Input; parameter.Value = login.Password; sqlCmd.Parameters.Add(parameter); myConnection.Open(); reader = sqlCmd.ExecuteReader(); TemporaryPasswordModel temporaryPasswordModel = new TemporaryPasswordModel(); int temporaryPasswordIdOrdinal = reader.GetOrdinal("Temporary_Password_Id"); int loginIdOrdinal = reader.GetOrdinal("Login_Id"); int temporaryPasswordOrdinal = reader.GetOrdinal("Temporary_Password"); int createdDateOrdinal = reader.GetOrdinal("Created_Date"); if (reader.Read()) { temporaryPasswordModel.TemporaryPasswordId = reader.GetInt32(temporaryPasswordIdOrdinal); temporaryPasswordModel.LoginId = reader.GetString(loginIdOrdinal); temporaryPasswordModel.TemporaryPassword = reader.GetString(temporaryPasswordOrdinal); temporaryPasswordModel.CreatedDate = reader.GetDateTime(createdDateOrdinal); } myConnection.Close(); return(temporaryPasswordModel); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
/// <summary> /// The constructor takes a HashAlgorithm as a parameter. /// </summary> /// <param name="HashAlgorithm"> /// A <see cref="HashAlgorithm"/> HashAlgorihm which is derived from HashAlgorithm. C# provides /// the following classes: SHA1Managed,SHA256Managed, SHA384Managed, SHA512Managed and MD5CryptoServiceProvider /// </param> public SaltedHash(HashAlgorithm HashAlgorithm, int theSaltLength) { try { HashProvider = HashAlgorithm; SalthLength = theSaltLength; } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return; } }
/// <summary> /// This routine provides a wrapper around VerifyHash converting the strings containing the /// data, hash and salt into byte arrays before calling VerifyHash. /// </summary> /// <param name="Data">A UTF-8 encoded string containing the data to verify</param> /// <param name="Hash">A base-64 encoded string containing the previously stored hash</param> /// <param name="Salt">A base-64 encoded string containing the previously stored salt</param> /// <returns></returns> public bool VerifyHashString(string Data, string Hash, string Salt) { try { byte[] HashToVerify = Convert.FromBase64String(Hash); byte[] SaltToVerify = Convert.FromBase64String(Salt); byte[] DataToVerify = Encoding.UTF8.GetBytes(Data); return(VerifyHash(DataToVerify, HashToVerify, SaltToVerify)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(false); } }
public virtual byte[] ReadBytes(DbDataReader dataReader, int ordinalPosition) { try { Byte[] bytes = new Byte[(int)(dataReader.GetBytes(ordinalPosition, 0, null, 0, Int32.MaxValue))]; dataReader.GetBytes(ordinalPosition, 0, bytes, 0, bytes.Length); return(bytes); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
private String GetRole(String username) { try { RestaurantController restaurantController = new RestaurantController(); LoginIdModel loginIdModel = new Restaurants.Models.LoginIdModel(); loginIdModel.LoginId = username; return(restaurantController.GetUserRole(loginIdModel).Content.Role); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(""); } }
private Int32 GetSystemUserIdFromLogin(String loginId) { SystemUserModel systemUserModel = new SystemUserModel(); try { SqlDataReader reader = null; Int32 systemUserId = 0; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spGetSystemUserIdFromLogin"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Login_Id"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Direction = ParameterDirection.Input; parameter.Size = 50; parameter.Value = loginId; sqlCmd.Parameters.Add(parameter); myConnection.Open(); reader = sqlCmd.ExecuteReader(); int systemUserIdOrdinal = reader.GetOrdinal("System_User_Id"); if (reader.Read()) { systemUserId = reader.GetInt32(systemUserIdOrdinal); } myConnection.Close(); return(systemUserId); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(-1); } }
/// <summary> /// The actual hash calculation is shared by both GetHashAndSalt and the VerifyHash functions /// </summary> /// <param name="Data">A byte array of the Data to Hash</param> /// <param name="Salt">A byte array of the Salt to add to the Hash</param> /// <returns>A byte array with the calculated hash</returns> private byte[] ComputeHash(byte[] Data, byte[] Salt) { try { // Allocate memory to store both the Data and Salt together byte[] DataAndSalt = new byte[Data.Length + SalthLength]; // Copy both the data and salt into the new array Array.Copy(Data, DataAndSalt, Data.Length); Array.Copy(Salt, 0, DataAndSalt, Data.Length, SalthLength); // Calculate the hash // Compute hash value of our plain text with appended salt. return(HashProvider.ComputeHash(DataAndSalt)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
/// <summary> /// The routine provides a wrapper around the GetHashAndSalt function providing conversion /// from the required byte arrays to strings. Both the Hash and Salt are returned as Base-64 encoded strings. /// </summary> /// <param name="Data"> /// A <see cref="System.String"/> string containing the data to hash /// </param> /// <param name="Hash"> /// A <see cref="System.String"/> base64 encoded string containing the generated hash /// </param> /// <param name="Salt"> /// A <see cref="System.String"/> base64 encoded string containing the generated salt /// </param> public void GetHashAndSaltString(string Data, out string Hash, out string Salt) { try { byte[] HashOut; byte[] SaltOut; // Obtain the Hash and Salt for the given string GetHashAndSalt(Encoding.UTF8.GetBytes(Data), out HashOut, out SaltOut); // Transform the byte[] to Base-64 encoded strings Hash = Convert.ToBase64String(HashOut); Salt = Convert.ToBase64String(SaltOut); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); Salt = null; Hash = null; return; } }
private Boolean IsTemporaryPassword(ChangePasswordModel changePasswordModel) { try { Boolean isTemporaryPassword = false; LoginController loginController = new LoginController(); LoginRequest login = new LoginRequest(); login.Username = changePasswordModel.LoginId; login.Password = changePasswordModel.OldPassword; TemporaryPasswordModel temporaryPasswordModel = loginController.GetTemporaryPasswordByLoginId(login); if (temporaryPasswordModel != null && temporaryPasswordModel.LoginId != null) { isTemporaryPassword = true; } return(isTemporaryPassword); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(false); } }
public void SaveTemporaryPassword(String loginId, String temporaryPassword) { try { SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spSaveTemporaryPassword"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Login_Id"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Direction = ParameterDirection.Input; parameter.Size = 50; parameter.Value = loginId; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Temporary_Password"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Direction = ParameterDirection.Input; parameter.Size = 50; parameter.Value = temporaryPassword; sqlCmd.Parameters.Add(parameter); myConnection.Open(); sqlCmd.ExecuteNonQuery(); myConnection.Close(); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return; } }
public IHttpActionResult Authenticate(LoginRequest login) { LoginReturnModel loginReturnModel = new LoginReturnModel(); try { Int32 systemUserId = 0; String role = ""; var loginResponse = new LoginResponse { }; LoginRequest loginrequest = new LoginRequest { }; loginrequest.Username = login.Username.ToLower(); loginrequest.Password = login.Password; // If this is a temporary password, return the temporary login info. TemporaryPasswordModel temporaryPasswordModel = new TemporaryPasswordModel(); temporaryPasswordModel = GetTemporaryPasswordByLoginId(login); if (temporaryPasswordModel != null && temporaryPasswordModel.LoginId != null && temporaryPasswordModel.TemporaryPassword != null) { return(Ok <TemporaryPasswordModel>(temporaryPasswordModel)); } //IHttpActionResult response; HttpResponseMessage responseMsg = new HttpResponseMessage(); bool isUsernamePasswordValid = false; isUsernamePasswordValid = IsValidLogin(loginrequest.Username, loginrequest.Password); systemUserId = GetSystemUserIdFromLogin(loginrequest.Username); role = GetRole(loginrequest.Username); // if credentials are valid if (isUsernamePasswordValid) { //return the token string token = createToken(loginrequest.Username); loginReturnModel.Code = "success"; loginReturnModel.Message = "The login was successful"; loginReturnModel.Token = token; loginReturnModel.SystemUserId = systemUserId; loginReturnModel.Role = role; return(Ok <LoginReturnModel>(loginReturnModel)); } else { loginReturnModel.Code = "error"; loginReturnModel.Message = "The login was unsuccessful"; loginReturnModel.Token = ""; loginReturnModel.SystemUserId = -1; loginReturnModel.Role = ""; return(Ok <LoginReturnModel>(loginReturnModel)); } } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); loginReturnModel.Code = "error"; loginReturnModel.Message = "The login was unsuccessful"; loginReturnModel.Token = ""; return(Ok <LoginReturnModel>(loginReturnModel)); } }
public void SendEmail([FromBody] EmailModel emailModel) { try { String smtpServerName = ""; int smtpPort = 0; Boolean smtpSSL = false; Boolean smtpIgnoreBadCertificate = false; Boolean smtpAllowInsecure = false; String smtpUserName = ""; String smtpPassword = ""; List <SettingsModel> settingsList = GetSettingsAll().Content; if (settingsList != null && settingsList.Count > 0) { foreach (SettingsModel setting in settingsList) { switch (setting.Settingkey) { case "SMTP_Server_Name": smtpServerName = setting.SettingValue; break; case "SMTP_Port": _ = int.TryParse(setting.SettingValue, out smtpPort); break; case "SMTP_SSL": smtpSSL = (setting.SettingValue == "true") ? true : false; break; case "SMTP_Ignore_Bad_Certificate": smtpIgnoreBadCertificate = (setting.SettingValue == "true") ? true : false; break; case "SMTP_Allow_Insecure": smtpAllowInsecure = (setting.SettingValue == "true") ? true : false; break; case "SMTP_UserName": smtpUserName = setting.SettingValue; break; case "SMTP_Password": smtpPassword = setting.SettingValue; break; } } } SmtpClient smtpClient = new SmtpClient(smtpServerName, smtpPort); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword); // smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = smtpSSL; MailMessage mail = new MailMessage(); mail.IsBodyHtml = true; //Setting From , To and CC mail.From = new MailAddress(emailModel.EmailFrom, emailModel.EmailFrom); mail.To.Add(new MailAddress(emailModel.EmailTo)); //mail.CC.Add(new MailAddress("*****@*****.**")); mail.Subject = emailModel.EmailSubject; mail.Body = emailModel.EmailBody; smtpClient.Send(mail); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return; } }
public System.Web.Http.Results.OkNegotiatedContentResult <ForgotPasswordReturnModel> ForgotPassword([FromBody] ForgotPasswordModel forgotPasswordModel) { ForgotPasswordReturnModel forgotPasswordReturnModel = new ForgotPasswordReturnModel(); try { // Generate a temporary password String temporaryPassword = GeneratePassword(8); // Save the temporary password in the db TemporaryPasswordModel temporaryPasswordModel = new TemporaryPasswordModel(); temporaryPasswordModel.LoginId = forgotPasswordModel.LoginId; temporaryPasswordModel.TemporaryPassword = temporaryPassword; temporaryPasswordModel.CreatedDate = DateTime.Now.AddDays(1); RestaurantController restaurantController = new RestaurantController(); restaurantController.SaveTemporaryPassword(forgotPasswordModel.LoginId, temporaryPassword); // Get the users first and last name for the email String emailTo = ""; String firstName = ""; String lastName = ""; SystemUser systemUser = GetSystemUser(forgotPasswordModel.LoginId); if (systemUser != null) { emailTo = systemUser.EmailAddress; firstName = systemUser.FirstName; lastName = systemUser.LastName; // Send an email to the user EmailModel emailModel = new EmailModel(); emailModel.EmailFrom = "*****@*****.**"; emailModel.EmailTo = emailTo; emailModel.EmailSubject = "Restaurants - Temporary password for " + firstName + " " + lastName; emailModel.EmailBody = "<html><body><table> " + "<tr><td>Name:</td><td>" + firstName + " " + lastName + "</td><td> </td></tr>" + "<tr><td>Temporary Password:</td><td>" + temporaryPassword + "</td><td> </td></tr>" + "<tr><td colspan='3'> </td></tr>" + "<tr><td colspan='3'>Your request for a tempory password has been processed.<br />This password will allow you to reset your lost password and is valid for 24 hours.</td></tr>" + "<tr><td colspan='3'> </td></tr>" + "<tr><td colspan='3'>Please log in to <a href='https://restaurants.nicholssoftware.com/passwordreset'>https://restaurants.nicholssoftware.com/passwordreset</a> using your temporary password and update your login information.</td></tr>" + "</table></body></html>"; restaurantController.SendEmail(emailModel); } forgotPasswordReturnModel.Code = "success"; forgotPasswordReturnModel.Message = "The forgot password generation was successful"; forgotPasswordReturnModel.TemporaryPassword = temporaryPassword; return(Ok(content: forgotPasswordReturnModel)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); forgotPasswordReturnModel.Code = "error"; forgotPasswordReturnModel.Message = "The forgot password generation was unsuccessful"; forgotPasswordReturnModel.TemporaryPassword = ""; return(Ok(content: forgotPasswordReturnModel)); } }
public System.Web.Http.Results.OkNegotiatedContentResult <ReturnCodeModel> SaveRestaurantMenuCategory([FromBody] RestaurantMenuCategoryModel restaurantMenuCategory) { try { Int32 recordId = 0; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spSaveRestaurantMenuCategory"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Restaurant_Menu_Category_Id"; parameter.SqlDbType = SqlDbType.Int; parameter.Size = 4; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurantMenuCategory.RestaurantMenuCategoryId; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Restaurant_Id"; parameter.SqlDbType = SqlDbType.Int; parameter.Size = 4; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurantMenuCategory.RestaurantId; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Restaurant_Menu_Category"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 150; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurantMenuCategory.RestaurantMenuCategory; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Sort_Index"; parameter.SqlDbType = SqlDbType.Int; parameter.Size = 4; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurantMenuCategory.SortIndex; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@End_Date"; parameter.SqlDbType = SqlDbType.DateTime; parameter.Size = 8; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurantMenuCategory.EndDate; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Return_Id"; parameter.SqlDbType = SqlDbType.Int; parameter.Size = 4; parameter.Direction = ParameterDirection.Output; sqlCmd.Parameters.Add(parameter); myConnection.Open(); sqlCmd.ExecuteNonQuery(); recordId = (Int32)parameter.Value; myConnection.Close(); ReturnCodeModel returnCodeModel = new ReturnCodeModel(); returnCodeModel.RecordId = recordId; returnCodeModel.ReturnCode = "success"; returnCodeModel.Message = "The record has been saved successfully"; return(Ok(content: returnCodeModel)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
public System.Web.Http.Results.OkNegotiatedContentResult <ReturnCodeModel> SaveRestaurant([FromBody] RestaurantModel restaurant) { try { Int32 recordId = 0; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spSaveRestaurant"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Restaurant_Id"; parameter.SqlDbType = SqlDbType.Int; parameter.Size = 4; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.RestaurantId; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Restaurant_Name"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 100; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.RestaurantName; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Address"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.Address; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@City"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.City; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@State"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.State; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Zip_Code"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 20; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.ZipCode; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Email_Address"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.EmailAddress; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Restaurant_Image_URL"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 1000; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.RestaurantImageURL; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Sales_Tax_Percent"; parameter.SqlDbType = SqlDbType.Decimal; parameter.Size = 10; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.SalesTaxPercentage; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@End_Date"; parameter.SqlDbType = SqlDbType.DateTime; parameter.Size = 8; parameter.Direction = ParameterDirection.Input; parameter.Value = restaurant.EndDate; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Return_Id"; parameter.SqlDbType = SqlDbType.Int; parameter.Size = 4; parameter.Direction = ParameterDirection.Output; sqlCmd.Parameters.Add(parameter); myConnection.Open(); sqlCmd.ExecuteNonQuery(); recordId = (Int32)parameter.Value; myConnection.Close(); ReturnCodeModel returnCodeModel = new ReturnCodeModel(); returnCodeModel.RecordId = recordId; returnCodeModel.ReturnCode = "success"; returnCodeModel.Message = "The record has been saved successfully"; return(Ok(content: returnCodeModel)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
public System.Web.Http.Results.OkNegotiatedContentResult <ResponseModel> ChangePassword([FromBody] ChangePasswordModel changePasswordModel) { try { SaltedHash SH = new SaltedHash(); string strHash = ""; string strSalt = ""; byte[] hash = null; byte[] salt = null; ResponseModel response = new ResponseModel(); // See if this is a temporary password if (IsTemporaryPassword(changePasswordModel) == true) { // Dont check for a valid login } else if (IsValidLogin(changePasswordModel.LoginId, changePasswordModel.OldPassword) == false) { response.Code = "error"; response.Message = "Invalid Login or Password"; return(Ok(content: response)); } SH.GetHashAndSaltString(changePasswordModel.NewPassword, out strHash, out strSalt); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); hash = encoding.GetBytes(strHash); salt = encoding.GetBytes(strSalt); SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spChangePassword"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Login_Id"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Direction = ParameterDirection.Input; parameter.Size = 50; parameter.Value = changePasswordModel.LoginId; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Hash"; parameter.SqlDbType = SqlDbType.VarBinary; parameter.Direction = ParameterDirection.Input; parameter.Size = 250; parameter.Value = hash; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Salt"; parameter.SqlDbType = SqlDbType.VarBinary; parameter.Direction = ParameterDirection.Input; parameter.Size = 250; parameter.Value = salt; sqlCmd.Parameters.Add(parameter); parameter = new SqlParameter(); parameter.ParameterName = "@Results"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Size = 50; parameter.Direction = ParameterDirection.Output; sqlCmd.Parameters.Add(parameter); myConnection.Open(); sqlCmd.ExecuteNonQuery(); if (parameter.Value.ToString().Equals("0")) { response.Code = "success"; response.Message = "Your Password Has Been Changed Successfully"; } else { response.Code = "error"; response.Message = "Invalid Login or Password"; } myConnection.Close(); return(Ok(content: response)); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
public SystemUser GetSystemUser(String userName) { try { SqlDataReader reader = null; SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"]; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "spGetSystemUsersByLogin"; sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Connection = myConnection; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@Login_Id"; parameter.SqlDbType = SqlDbType.VarChar; parameter.Direction = ParameterDirection.Input; parameter.Value = userName; sqlCmd.Parameters.Add(parameter); myConnection.Open(); reader = sqlCmd.ExecuteReader(); int systemUserIdOrdinal = reader.GetOrdinal("System_User_Id"); int firstNameOrdinal = reader.GetOrdinal("First_Name"); int lastNameOrdinal = reader.GetOrdinal("Last_Name"); int emailAddressOrdinal = reader.GetOrdinal("Email_Address"); int loginIdOrdinal = reader.GetOrdinal("Login_Id"); int hashOrdinal = reader.GetOrdinal("Hash"); int saltOrdinal = reader.GetOrdinal("Salt"); int endDateOrdinal = reader.GetOrdinal("End_Date"); List <SystemUser> systemUserList = new List <SystemUser>(); SystemUser systemUser = null; while (reader.Read()) { systemUser = new SystemUser(); systemUser.SystemUserId = reader.GetInt32(systemUserIdOrdinal); systemUser.FirstName = reader.GetString(firstNameOrdinal); systemUser.LastName = reader.GetString(lastNameOrdinal); systemUser.EmailAddress = reader.GetString(emailAddressOrdinal); systemUser.LoginId = reader.GetString(loginIdOrdinal); systemUser.Hash = reader.IsDBNull(hashOrdinal) ? null : ReadBytes(reader, hashOrdinal); systemUser.Salt = reader.IsDBNull(saltOrdinal) ? null : ReadBytes(reader, saltOrdinal); systemUser.EndDate = reader.IsDBNull(endDateOrdinal) ? (DateTime?)null : (DateTime?)reader.GetDateTime(endDateOrdinal); systemUserList.Add(systemUser); } myConnection.Close(); if (systemUserList != null && systemUserList.Count > 0) { return(systemUserList[0]); } else { return(null); } } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpStatusCode statusCode; string token; String tokenIssuer = ""; String tokenAudience = ""; //determine whether a jwt exists or not if (!TryRetrieveToken(request, out token)) { statusCode = HttpStatusCode.Unauthorized; //allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute return(base.SendAsync(request, cancellationToken)); } try { string sec = ""; if (ConfigurationManager.AppSettings["TokenSecret"] != null) { sec = ConfigurationManager.AppSettings["TokenSecret"].ToString(); } if (ConfigurationManager.AppSettings["TokenIssuer"] != null && ConfigurationManager.AppSettings["TokenAudience"] != null) { tokenIssuer = ConfigurationManager.AppSettings["TokenIssuer"].ToString(); tokenAudience = ConfigurationManager.AppSettings["TokenAudience"].ToString(); } var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); SecurityToken securityToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = tokenAudience, ValidIssuer = tokenIssuer, ValidateLifetime = true, ValidateIssuerSigningKey = true, LifetimeValidator = this.LifetimeValidator, IssuerSigningKey = securityKey }; //extract and assign the user of the jwt Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken); HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken); return(base.SendAsync(request, cancellationToken)); } catch (SecurityTokenValidationException ex) { statusCode = HttpStatusCode.Unauthorized; ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); } catch (Exception ex) { statusCode = HttpStatusCode.InternalServerError; ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); } return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode) { })); }
private string createToken(string username) { try { //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token DateTime issuedAt = DateTime.UtcNow; //Set issued at date DateTime expires = DateTime.UtcNow.AddDays(7); //set the time when it expires String tokenIssuer = ""; String tokenAudience = ""; var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }); string sec = ""; if (ConfigurationManager.AppSettings["TokenSecret"] != null) { sec = ConfigurationManager.AppSettings["TokenSecret"].ToString(); } var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); if (ConfigurationManager.AppSettings["TokenIssuer"] != null && ConfigurationManager.AppSettings["TokenAudience"] != null) { tokenIssuer = ConfigurationManager.AppSettings["TokenIssuer"].ToString(); tokenAudience = ConfigurationManager.AppSettings["TokenAudience"].ToString(); } //create the jwt var token = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken( issuer: tokenIssuer, audience: tokenAudience, subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); SystemUser systemUser = GetSystemUser(username); if (systemUser != null) { token.Payload["FirstName"] = systemUser.FirstName; token.Payload["LastName"] = systemUser.LastName; token.Payload["EmailAddress"] = systemUser.EmailAddress; token.Payload["EndDate"] = systemUser.EndDate; } var tokenString = tokenHandler.WriteToken(token); return(tokenString); } catch (Exception ex) { ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name); return(null); } }