public string EncodeCredentials(string userId, string password) { string encoded = string.Empty; encoded = RijndaelCrypt.Encrypt(password, AppIdentifier()); return(encoded); }
public async Task <IActionResult> Forgot(Forgot model) { if (ModelState.IsValid) { var customer = this._context.Customers.Include(i => i.CustomerClass).Include(i => i.User).Where(c => c.User.UserName == model.Email).FirstOrDefault(); if (customer != null) { model.Customer = customer; var rg = new RijndaelCrypt(); model.Url = Url.Action("ResetPwd", new { u = rg.Encrypt(customer.User.UserName) }); var htmlToConvert = await RenderViewAsync("MailForgotPwd", model, true); var msg = EmailUtil.sendNotificationEmail(_smtp, customer.Email, "เปลี่ยนรหัสผ่าน", htmlToConvert.ToString()); ViewData["Message"] = "ระบบกำลังส่่งการกำหนดรหัสผ่านใหม่ไปยังอีเมลของท่าน"; return(View(model)); } ViewData["ErrorMessage"] = "ไม่พบอีเมลในระบบ"; } else { ViewData["ErrorMessage"] = "โปรดระบุอีเมล"; } return(View(model)); }
public ActionResult ResetPassword(ResetNewPasswordViewModel _passwordInfo) { try { if (!ModelState.IsValid) { return(View()); } AuthenticatedUser _authUser; using (AuthRepository Repo = new AuthRepository()) { _authUser = Repo.GetAuthenticatedUserById(CurrentUser.EmployeeInfoId); } if (_authUser.IsFirstTimeLogin == false) { return(RedirectToAction("GeneralInfo", "Profile")); } if (RijndaelCrypt.DecryptPassword(_authUser.PasswordHash, _authUser.Salt) == _passwordInfo.NewPassword) { TempData["Msg"] = AlertMessageProvider.FailureMessage("New password should not be same as current password."); return(View()); } var _accountInfo = new AccountInfo(); _accountInfo.Id = CurrentUser.AccountId; _accountInfo.Salt = RandomPassword.Generate(18, 20); _accountInfo.PasswordHash = RijndaelCrypt.EncryptPassword(_passwordInfo.NewPassword, _accountInfo.Salt); _accountInfo.IsFirstTimeLogin = false; using (AccountRepository Repo = new AccountRepository()) { Repo.ChangeNewPassword(_accountInfo); } var ctx = Request.GetOwinContext(); var authManager = ctx.Authentication; authManager.SignOut("ApplicationCookie"); TempData["Msg"] = "<span style='color:green; text-align:center;'>Password has been reset successfully.</span>"; return(RedirectToAction("Login", "Auth", new { area = "" })); } catch (Exception ex) { TempData["Msg"] = AlertMessageProvider.FailureMessage(ex.ToString()); return(View()); } }
public ActionResult ResetPassword(ResetNewPasswordViewModel passwordInfo) { try { if (TempData["AccountId"] == null) { return(RedirectToAction("Login", "Auth")); } if (!ModelState.IsValid) { return(View()); } int _accountId = (int)TempData["AccountId"]; var _accountInfo = new AccountInfo(); _accountInfo.Id = _accountId; _accountInfo.Salt = RandomPassword.Generate(18, 20); _accountInfo.PasswordHash = RijndaelCrypt.EncryptPassword(passwordInfo.NewPassword, _accountInfo.Salt); _accountInfo.IsFirstTimeLogin = false; using (AccountRepository Repo = new AccountRepository()) { Repo.ChangeNewPassword(_accountInfo); } using (AccountConfirmationRepository Repo = new AccountConfirmationRepository()) { AccountConfirmationInfo _accountConfirmation = null; _accountConfirmation = Repo.GetAccountConfirmationByAccountId(_accountId); if (_accountConfirmation != null) { Repo.DeleteAccountConfirmation(_accountConfirmation.Id); } } TempData["Msg"] = "<span style='color:green; text-align:center;'>Password has been reset successfully.</span>"; return(RedirectToAction("Login", "Auth")); } catch (Exception ex) { TempData["Msg"] = "<span style='color:red; text-align:center;'>" + ex.Message.ToString() + ".</span>"; return(View()); } }
public static TemporaryFile SecureFileUncrypt(this ICakeContext context, FilePath file, string secret) { string extension = file.GetExtension(); if (extension == "enc") { extension = file.GetFilenameWithoutExtension().GetExtension(); } var f = new TemporaryFile(extension); RijndaelCrypt.Decrypt(file.FullPath, f.Path, secret); return(f); }
public ActionResult ChangePassword(ChangePasswordViewModel passwordInfo) { try { if (!ModelState.IsValid) { return(View()); } var _account = new AccountInfo(); using (AccountRepository Repo = new AccountRepository()) { _account = Repo.GetEmployeeAccountById(CurrentUser.AccountId); } string decryptedPassword = RijndaelCrypt.DecryptPassword(_account.PasswordHash, _account.Salt); if (decryptedPassword != passwordInfo.CurrentPassword) { TempData["Msg"] = AlertMessageProvider.FailureMessage("Current password is invalid."); return(View()); } if (decryptedPassword == passwordInfo.NewPassword) { TempData["Msg"] = AlertMessageProvider.FailureMessage("New password should not be same as current password."); return(View()); } _account.Salt = RandomPassword.Generate(18, 20); _account.PasswordHash = RijndaelCrypt.EncryptPassword(passwordInfo.NewPassword, _account.Salt); using (AccountRepository Repo = new AccountRepository()) { Repo.ChangeNewPassword(_account); } TempData["Msg"] = AlertMessageProvider.SuccessMessage("Password changed successfully."); return(View()); } catch (Exception ex) { return(View("Error", new HandleErrorInfo(ex, "Auth", "ChangePassword"))); } }
/// <summary> /// 加密数据 /// </summary> /// <param name="encryptString"></param> /// <returns></returns> public static string EncryptData(string encryptString) { if (string.IsNullOrEmpty(encryptString)) { throw new ArgumentNullException("EncryptDBConnString()方法,参数encryptString值为空"); } string key = GetEncryptKey(); if (string.IsNullOrEmpty(key)) { throw new Exception("配置中未读取到客户密钥串"); } return(RijndaelCrypt.Encrypt(encryptString, key)); }
public async Task <dynamic> Register(string data) { string url = $"{baseUrl}/Register"; var result = await _httpService.PostApiResult(url, KeyValuePair.Create(Rsa.PublicKey, RijndaelCrypt.EncryptString(data, Client.ServerKey, Client.ServerIV))); if (result.All(char.IsDigit)) { return(JsonConvert.DeserializeObject <AuthorizeResultEnum>(result)); } else { Client.AccessToken = RijndaelCrypt.DecryptString(JsonConvert.DeserializeObject <string>(result), Client.ServerKey, Client.ServerIV); } return(AuthorizeResultEnum.Ok); }
// GET: Auth/Verify public ActionResult Verify(string t) { try { AccountConfirmationInfo _accountConfirmation = null; string _token = RijndaelCrypt.DecryptString(t); using (AccountConfirmationRepository Repo = new AccountConfirmationRepository()) { _accountConfirmation = Repo.GetAccountConfirmationByToken(_token); } if (_accountConfirmation == null) { TempData["Msg"] = "Link has been already used or invalid."; return(View()); // invalid token } byte[] data = Convert.FromBase64String(_token); DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0)); if (when < DateTime.UtcNow.AddHours(-24)) { TempData["Msg"] = "Link has been expired."; return(View()); // expired token } else { TempData["AccountId"] = _accountConfirmation.AccountId; TempData["IsVerified"] = true; return(RedirectToAction("ResetPassword")); // valid token } } catch (Exception ex) { TempData["Msg"] = "<span style='color:red; text-align:center;'>" + ex.Message.ToString() + ".</span>"; return(View()); } }
public IActionResult ResetPwd(string u) { var rg = new RijndaelCrypt(); var uname = rg.Decrypt(u); var user = this._context.Users.Include(i => i.UserRole).Where(w => w.UserName == uname).FirstOrDefault(); if (user != null) { if (user != null && user.Status == UserStatusType.Active) { this._loginServices.Login(user, true); return(RedirectToAction("ResetPwd", "Customer")); } } ViewData["ErrorMessage"] = "พบข้อผิดพลาด"; return(RedirectToAction("Login", "Accounts")); }
private void btnDecode_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(rtxtEncryString.Text)) { MessageBox.Show("加密串不能为空"); return; } if (string.IsNullOrEmpty(txtSecretKey.Text)) { MessageBox.Show("密钥不能为空"); return; } string str = RijndaelCrypt.Decrypt(rtxtEncryString.Text.Trim(), txtSecretKey.Text.Trim()); rtxtString.Text = str; }
private void btnEncrypt_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(rtxtString.Text)) { MessageBox.Show("字符串不能为空"); return; } if (string.IsNullOrEmpty(txtSecretKey.Text)) { MessageBox.Show("密钥不能为空"); return; } string encryptString = RijndaelCrypt.Encrypt(rtxtString.Text.Trim(), txtSecretKey.Text.Trim()); rtxtEncryString.Text = encryptString; }
public FileStreamResult SaveGallery() { string txt = ""; using (AccountRepository Repo = new AccountRepository()) { foreach (var item in Repo.GetAccounts()) { txt += item.CompanyEmail + Environment.NewLine; txt += RijndaelCrypt.DecryptPassword(item.PasswordHash, item.Salt) + Environment.NewLine; txt += item.RoleName + Environment.NewLine + "---------" + Environment.NewLine + Environment.NewLine; } } var byteArray = Encoding.ASCII.GetBytes(txt); var stream = new MemoryStream(byteArray); return(File(stream, "text/plain", "saved_data.txt")); }
private TaskEntity InsertTask() { TaskEntity taskEntity = new TaskEntity(); taskEntity.TaskID = Guid.NewGuid().ToString("N"); taskEntity.DataType = DataTypes.Sale; taskEntity.Cron = "0 3 * * * ? *"; taskEntity.DataHandler = "Transfer8Pro.DAO.DataHandlers.SqlServer_DataHandler"; string connStr = @"server=192.168.0.14;database=Smart_NewBookDB;uid=sa;pwd=sa.;min pool size=10;max pool size=300;Connection Timeout=10;"; string encryptKey = Common.GetEncryptKey(); taskEntity.DBConnectString_Hashed = RijndaelCrypt.Encrypt(connStr, encryptKey); taskEntity.SQL = "SELECT * FROM dbo.T8_BookInfo WHERE SalesDateTime>=@StartTime AND SalesDateTime<=@EndTime"; taskEntity.TaskName = "天销售数据" + DateTime.Now.ToLongTimeString(); //taskEntity.Enabled = true; taskEntity.IsDelete = false; taskEntity.TaskStatus = TaskStatus.RUN; taskEntity.CreateTime = DateTime.Now; return(taskEntity); }
private void EncryptPassword() { if (txtInput.Text.Length == 0) { return; } EncryptionElement element = comboApplicationId.SelectedItem as EncryptionElement; try { if (element != null) { txtOutPut.Text = checkDecrypt.Checked ? RijndaelCrypt.Decrypt(txtInput.Text, element.ApplicationId) : RijndaelCrypt.Encrypt(txtInput.Text, element.ApplicationId); } txtOutPut.BackColor = SystemColors.Control; txtOutPut.ForeColor = SystemColors.WindowText; } catch (Exception ex) { txtOutPut.Text = ex.Message; txtOutPut.BackColor = Color.Red; txtOutPut.ForeColor = Color.White; } }
public static string Encode(string userId, string password) { return(RijndaelCrypt.Encrypt(password, AppIdentifier)); }
public string DecodeCredentials(string cipher) { return(RijndaelCrypt.Decrypt(cipher, AppIdentifier())); }
public ActionResult Login(LoginViewModel loginInfo) { try { if (!ModelState.IsValid) { return(View()); } loginInfo.CompanyEmail = loginInfo.CompanyEmail.ToLower(); AuthenticatedUser _authUser; using (AuthRepository Repo = new AuthRepository()) { _authUser = Repo.IsAccountExist(loginInfo); } if (_authUser != null) { if (RijndaelCrypt.DecryptPassword(_authUser.PasswordHash, _authUser.Salt) == loginInfo.Password) { if (_authUser.IsActive == true) { using (AccountRepository Repo = new AccountRepository()) { var _userAccount = new AccountInfo(); _userAccount.Id = _authUser.AccountId; _userAccount.LastLoginIp = Request.UserHostAddress.ToString(); _userAccount.LastLoginDate = DateTime.Now; Repo.UpdateAccountOnLogin(_userAccount); } string _mode = _authUser.Role == "SuperAdmin" ? "Admin" : "Employee"; var _identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, _authUser.FirstName + " " + _authUser.LastName), new Claim(ClaimTypes.Email, _authUser.CompanyEmail), new Claim(ClaimTypes.Role, _authUser.Role), new Claim(ClaimTypes.NameIdentifier, _authUser.AccountId.ToString()), new Claim("EmployeeInfoId", _authUser.EmployeeInfoId.ToString()), new Claim("LastLoginDate", _authUser.LastLoginDate.ToString()), new Claim("LastLoginIp", _authUser.LastLoginIp), new Claim("Mode", _mode) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var authManager = ctx.Authentication; authManager.SignIn(new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow.AddMinutes(30), AllowRefresh = true, IsPersistent = false }, _identity); if (_authUser.IsCheckListCompleted == false) { if (_authUser.IsFirstTimeLogin == true) { return(RedirectToAction("ResetPassword", "Account", new { Area = "EmployeeReg" })); } return(RedirectToAction("PersonalInfo", "Profile", new { Area = "EmployeeReg" })); } return(Redirect(GetRedirectUrl(loginInfo.ReturnUrl, _authUser.Role))); } else { TempData["Msg"] = "<span style='color:red; text-align:center;'>Your account is deactive, you can't access online services.</span>"; return(View()); } } } TempData["Msg"] = "<span style='color:red; text-align:center;'>Invalid Username/Password.</span>"; return(View()); } catch (Exception ex) { TempData["Msg"] = "<span style='color:red; text-align:center;'>" + ex.Message.ToString() + ".</span>"; return(View()); } }
public ActionResult ForgotPassword(ForgotPasswordViewModel forgotInfo) { try { if (!ModelState.IsValid) { return(View()); } AccountInfo _account = null; string _token; using (AccountRepository Repo = new AccountRepository()) { _account = Repo.GetEmployeeAccountByCompanyEmail(forgotInfo.CompanyEmail); } if (_account == null) { TempData["Msg"] = "<span style='color:red; text-align:center;'>Account does not associate with this email.</span>"; return(RedirectToAction("ForgotPassword", "Auth")); } if (_account.IsFirstTimeLogin == true) { TempData["Msg"] = "<span style='color:red; text-align:center;'>You cannot reset password right now, please check your account creation email.</span>"; return(RedirectToAction("ForgotPassword", "Auth")); } byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary()); byte[] key = Guid.NewGuid().ToByteArray(); _token = Convert.ToBase64String(time.Concat(key).ToArray()); using (AccountConfirmationRepository Repo = new AccountConfirmationRepository()) { AccountConfirmationInfo _accountConfirmation = null; _accountConfirmation = Repo.GetAccountConfirmationByAccountId(_account.Id); if (_accountConfirmation != null) { Repo.DeleteAccountConfirmation(_accountConfirmation.Id); } _accountConfirmation = new AccountConfirmationInfo(); _accountConfirmation.Token = _token; _accountConfirmation.AccountId = _account.Id; Repo.SaveAccountConfirmation(_accountConfirmation); } List <string> To = new List <string>() { _account.CompanyEmail }; string Subject = "Password Reset Link"; var resetPasswordUrl = Url.Action("Verify", "Auth", new { t = RijndaelCrypt.EncryptString(_token) }, protocol: Request.Url.Scheme); var forgotPasswordUrl = Url.Action("ForgotPassword", "Auth", null, protocol: Request.Url.Scheme); string Body = "Dear " + _account.EmployeeFullName + ", <br/><br/>" + "We heard that you lost your LPS online account password. Sorry about that! <br/><br/>" + "But don’t worry! You can use the following link within the next day to reset your password: <br/><br/>" + "<a href='" + resetPasswordUrl + "' target='_blank'>" + resetPasswordUrl + "</a> <br/><br/>" + "If you don’t use this link within 24 hours, it will expire. To get a new password reset link, visit<br/>" + "<a href='" + forgotPasswordUrl + "' target='_blank'>" + forgotPasswordUrl + " </a> <br/><br/>" + "Thanks,<br/>" + "Logic Powered Solutions"; bool result = EmailSender.Send(Subject, Body, To); if (result) { TempData["Msg"] = "<span style='color:green; text-align:center;'>Request launched, for further processing please check your email.</span>"; } else { TempData["Msg"] = "<span style='color:red; text-align:center;'>Something went wrong! email not sent, please try again later.</span>"; } return(RedirectToAction("ForgotPassword", "Auth")); } catch (Exception ex) { TempData["Msg"] = "<span style='color:red; text-align:center;'>" + ex.Message.ToString() + ".</span>"; return(View()); } }
public ActionResult ResendEmail(int id) { try { AccountInfo _accountInfo = null; using (AccountRepository Repo = new AccountRepository()) { _accountInfo = Repo.GetAccountByid(id); } if (_accountInfo == null) { TempData["Msg"] = AlertMessageProvider.FailureMessage("Something went wrong! email not sent, please try again later."); return(RedirectToAction("Manage", "Account")); } if (_accountInfo.IsCheckListCompleted == true) { TempData["Msg"] = AlertMessageProvider.FailureMessage("This account has been already activated."); return(RedirectToAction("Manage", "Account")); } List <string> To = new List <string>() { _accountInfo.CompanyEmail }; string Subject = "LPS Online Account Information"; var LoginUrl = Url.Action("Login", "Auth", new { Area = "" }, protocol: Request.Url.Scheme); string Body = "Dear Employee, <br/><br/>" + "Your account has been created.<br/>" + "Please ensure to save the username and password written below:<br/><br/>" + "Username: <b>" + _accountInfo.CompanyEmail + "</b><br/>" + "Password: <b>" + RijndaelCrypt.DecryptPassword(_accountInfo.PasswordHash, _accountInfo.Salt) + "</b><br/><br/>" + "<a href='" + LoginUrl + "' target='_blank'>" + LoginUrl + "</a><br/>" + "You can login to your account to use LPS online services.<br/><br/>" + "Thanks,<br/>" + "<b>Logic Powered Solutions</b>"; bool result = EmailSender.Send(Subject, Body, To); if (result) { TempData["Msg"] = AlertMessageProvider.SuccessMessage("Email has been sent to employee successfully."); } else { TempData["Msg"] = AlertMessageProvider.FailureMessage("Something went wrong! email not sent, please try again later."); } return(RedirectToAction("Manage")); } catch (Exception ex) { return(View("Error", new HandleErrorInfo(ex, "Account", "ResendEmail"))); } }
public ActionResult Create(AccountInfo accountInfo) { try { if (ModelState.IsValid) { var _employeeInfo = new Model.EmployeeInfo(); _employeeInfo.CreatedByAccountId = CurrentUser.AccountId; _employeeInfo.CreatedDate = DateTime.Now; int employeeInfoId; int accountId; string saltValue = RandomPassword.Generate(18, 20); string password = RijndaelCrypt.EncryptPassword(RandomPassword.Generate(), saltValue); accountInfo.CompanyEmail = accountInfo.CompanyEmail.ToLower(); accountInfo.PasswordHash = password; accountInfo.Salt = saltValue; accountInfo.LastLoginDate = DateTime.Now; accountInfo.LastLoginIp = ""; accountInfo.IsActive = true; accountInfo.IsFirstTimeLogin = true; using (var transaction = new System.Transactions.TransactionScope()) { using (AccountRepository Repo = new AccountRepository()) { if (Repo.IsEmailExist(accountInfo.CompanyEmail) == true) { TempData["Msg"] = AlertMessageProvider.FailureMessage("Email already exist."); return(View()); } int roleId = Repo.GetRoleIdByName("Anonymous"); accountInfo.RoleId = roleId; accountId = Repo.CreateAccount(accountInfo); } using (AccountCheckListRepository Repo = new AccountCheckListRepository()) { var _accountCheckList = new AccountCheckListInfo(accountId); Repo.SaveAccountCheckList(_accountCheckList); } using (EmployeeRepository Repo = new EmployeeRepository()) { _employeeInfo.AccountId = accountId; employeeInfoId = Repo.SaveEmployeeInfo(_employeeInfo); } using (LeaveAllowedRepository Repo = new LeaveAllowedRepository()) { LeaveAllowedInfo _leaveAllowed = new LeaveAllowedInfo(0, 0, employeeInfoId, CurrentUser.AccountId); Repo.SaveLeaveAllowed(_leaveAllowed); } using (SalaryRepository Repo = new SalaryRepository()) { var _salaryInfo = new SalaryInfo(CurrentUser.AccountId, employeeInfoId); Repo.SaveSalary(_salaryInfo); } using (FamilyMemberRepository Repo = new FamilyMemberRepository()) { var _familyMember = new FamilyMemberInfo { Name = "Self", Relation = "Selef", EmployeeInfoId = employeeInfoId }; Repo.SaveFamilyMember(_familyMember); } transaction.Complete(); } List <string> To = new List <string>() { accountInfo.CompanyEmail }; string Subject = "LPS Online Account Information"; var LoginUrl = Url.Action("Login", "Auth", new { Area = "" }, protocol: Request.Url.Scheme); string Body = "Dear Employee, <br/><br/>" + "Your account has been created.<br/>" + "Please ensure to save the username and password written below:<br/><br/>" + "Username: <b>" + accountInfo.CompanyEmail + "</b><br/>" + "Password: <b>" + RijndaelCrypt.DecryptPassword(accountInfo.PasswordHash, accountInfo.Salt) + "</b><br/><br/>" + "<a href='" + LoginUrl + "' target='_blank'>" + LoginUrl + "</a><br/>" + "You can login to your account to use LPS online services.<br/><br/>" + "Thanks,<br/>" + "<b>Logic Powered Solutions</b>"; bool result = EmailSender.Send(Subject, Body, To); if (result) { TempData["Msg"] = AlertMessageProvider.SuccessMessage("Account created, email has been sent to employee successfully."); } else { TempData["Msg"] = AlertMessageProvider.FailureMessage("Something went wrong! email not sent, please try again later."); } return(RedirectToAction("Manage", "Account")); } return(View()); } catch (Exception ex) { return(View("Error", new HandleErrorInfo(ex, "Account", "Create"))); } }
public static void SecureFileCrypt(this ICakeContext context, FilePath file, FilePath encryptedFile, string secret) { RijndaelCrypt.Encrypt(file.FullPath, encryptedFile.FullPath, secret); }
public async Task <IActionResult> SSO(SSODTO model) { if (string.IsNullOrEmpty(model.u)) { model.u = model.UserName; } if (string.IsNullOrEmpty(model.p)) { model.p = model.Password; } if (string.IsNullOrEmpty(model.p)) { model.p = model.u; } if (!string.IsNullOrEmpty(model.u) && !string.IsNullOrEmpty(model.p)) { var rg = new RijndaelCrypt(); var u = rg.Decrypt(model.u); var p = rg.Decrypt(model.p); var f = ""; if (!string.IsNullOrEmpty(model.f)) { f = rg.Decrypt(model.f); } if (!string.IsNullOrEmpty(model.facebookFlag)) { f = model.facebookFlag; } var user = this._context.Users.Include(w => w.UserRole).Where(w => w.UserName == u).FirstOrDefault(); /*create customer imobile*/ _logger.LogWarning(DateUtil.Now() + ""); _logger.LogWarning("SSO"); _logger.LogWarning(JsonConvert.SerializeObject(model)); model.u = u; if (user == null) { await this.Repair(u, p, f, "loginForStatus"); user = this._context.Users.Include(u2 => u2.UserRole).Where(u2 => u2.UserName == u).FirstOrDefault(); } if (user != null) { if (user.Status != UserStatusType.InActive) { var customer = this._context.Customers.Where(w => w.UserID == user.ID).FirstOrDefault(); if (customer == null) { ViewData["ErrorMessage"] = "ไม่พบข้อมูลผู้ใช้"; _logger.LogWarning(ViewData["ErrorMessage"].ToString()); return(RedirectToAction("Login", "Accounts", new { message = ViewData["ErrorMessage"] })); } f = customer.FacebookFlag; var valid = false; if (!string.IsNullOrEmpty(f) && f.ToLower() == "y") { valid = true; } else { if (customer.BCryptPwd == p) { valid = true; } if (!valid) { if (!string.IsNullOrEmpty(user.Password)) { string paintTextPassword = DataEncryptor.Decrypt(user.Password); string passworeInDB = p; if (!valid) { if (!string.IsNullOrEmpty(paintTextPassword) && !string.IsNullOrEmpty(passworeInDB)) { try { if (BCrypt.Net.BCrypt.Verify(paintTextPassword, passworeInDB)) { valid = true; } } catch { } } } } } if (!valid) { if (!string.IsNullOrEmpty(user.Password)) { string desPassword = DataEncryptor.Decrypt(user.Password); if (p == desPassword) { valid = true; } } } } if (valid) { this._loginServices.Login(user, true); GetCustomerClass(customer); customer.FirstLogedIn = true; this._context.SaveChanges(); return(RedirectToAction("Privilege", "Home", new { /*poppromo = 1 */ })); } } else { ViewData["ErrorMessage"] = "ถูกระงับการเป็นสมาชิก"; _logger.LogWarning(ViewData["ErrorMessage"].ToString()); return(RedirectToAction("Login", "Accounts", new { message = ViewData["ErrorMessage"] })); } } } ViewData["ErrorMessage"] = "รหัสผู้ใช้ หรือ รหัสผ่านไม่ถูกต้อง"; _logger.LogWarning(ViewData["ErrorMessage"].ToString()); return(RedirectToAction("Login", "Accounts", new { message = ViewData["ErrorMessage"] })); }
public async Task <IActionResult> Register(CustomerDTO model, bool repair = false) { if (ModelState.IsValid) { if (!repair) { if (string.IsNullOrEmpty(model.username)) { model.username = model.email; } if (!model.isDhiMember) { model.citizenId = null; } if (this.isExistIDCard(model)) { var rg = new RijndaelCrypt(); model.ShowIdcardDupPopup = true; var ducus = this._context.Customers.Include(i => i.User).Where(c => c.IDCard == model.citizenId & (model.ID > 0 ? c.ID != model.ID : true)); model.dupEmail = new List <string>(); model.dupFBID = new List <string>(); foreach (var cus in ducus) { if (string.IsNullOrEmpty(cus.FacebookID)) { model.dupEmail.Add(cus.User.UserName); } else { model.dupFBID.Add(cus.User.UserName); } model.dupIdcard = model.citizenId; } ModelState.AddModelError("citizenId", "รหัสบัตรประชาชนซ้ำในระบบ"); } if (this.isExistEmail(model)) { ModelState.AddModelError("email", "อีเมลซ้ำในระบบ"); } if (this.isExistUserName(model)) { ModelState.AddModelError("email", "รหัสผู้ใช้งานซ้ำในระบบ"); } //if (this.isExistMobileNo(model)) // ModelState.AddModelError("moblieNo", "เบอร์โทรศัพท์ซ้ำในระบบ"); //if (this.isExistName(model)) //{ // ModelState.AddModelError("firstName", "ชื่อนามสกุลซ้ำในระบบ"); // ModelState.AddModelError("lastName", "ชื่อนามสกุลซ้ำในระบบ"); //} if (!string.IsNullOrEmpty(model.friendCode) && !this.isExistFriendCode(model)) { ModelState.AddModelError("friendCode", "ไม่พบข้อมูล friend Code"); } } if (ModelState.IsValid) { if (model.valid) { model.password = DataEncryptor.Decrypt(model.pEncyprt); var customer = new Customer(); customer.Create_On = DateUtil.Now(); customer.ChannelUpdate = CustomerChanal.TIP; customer = CustomerBinding.Binding(customer, model); GetCustomerClass(customer); customer.Create_On = DateUtil.Now(); customer.Create_By = customer.User.UserName; customer.Update_On = DateUtil.Now(); customer.Update_By = customer.User.UserName; customer.Success = false; var regs = this.GetPointCondition(customer, TransacionTypeID.Register); foreach (var item in regs) { if (item.Point.Value > 0) { var point = this.GetCustomerPoint(item, customer, item.Point.Value, (int)TransacionTypeID.Register, CustomerChanal.TIP, "tipsociety-register"); customer.CustomerPoints.Add(point); } } var friendpoint = 0; Customer friend = null; if (!string.IsNullOrEmpty(customer.FriendCode)) { var invites = this.GetPointCondition(customer, TransacionTypeID.InviteFriend); foreach (var item in invites) { var p = this.GetPoint(item, customer); if (p > 0) { var point = this.GetCustomerPoint(item, customer, p, (int)TransacionTypeID.InviteFriend, CustomerChanal.TIP, "tipsociety-register"); friend = this._context.Customers.Where(w => w.RefCode == customer.FriendCode).FirstOrDefault(); if (friend != null) { friendpoint = p; point.CustomerID = friend.ID; this._context.CustomerPoints.Add(point); } } } } this._context.Customers.Add(customer); this._context.SaveChanges(); this._context.Entry(customer).GetDatabaseValues(); customer.RefCode = CustomerBinding.GetRefCode(customer); this._context.Users.Attach(customer.User); this._context.Entry(customer.User).Property(u => u.Email).IsModified = true; this._context.Entry(customer.User).Property(u => u.PhoneNumber).IsModified = true; this._context.Update(customer); this._context.SaveChanges(); AddConsent(model); if (_conf.SendEmail == true && friend != null && friendpoint > 0) { await MailInviteFriend(friend.Email, friend, customer, friendpoint); } try { if (!repair) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(_mobile.Url + "/rewardpoint/customerprofile/register"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var rg = new RijndaelCrypt(); model.username = rg.Encrypt(model.username); model.password = rg.Encrypt(model.password); model.status = customer.Status.toStatusNameEn(); StringContent content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content); if (response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.OK) { customer.Success = true; this._context.SaveChanges(); } else { _logger.LogWarning(JsonConvert.SerializeObject(model)); _logger.LogWarning(await response.Content.ReadAsStringAsync()); } } } } catch { } if (_conf.SendEmail == true) { await MailActivateAcc(customer.Email, customer.ID); } //if (_conf.SendSMS == true) // SendSMS(customer.ID); return(await Login(new Login() { UserName = model.email, Password = model.password }, true)); } else { model.pEncyprt = DataEncryptor.Encrypt(model.password); } model.valid = true; } } return(View(model)); }
public async Task <IActionResult> Terminate(string code) { var acccode = this._context.AccountCodes.Where(w => w.Code == code && w.Status == StatusType.Active).FirstOrDefault(); if (acccode != null) { var customer = _context.Customers.Where(w => w.ID == acccode.CustomerID).FirstOrDefault(); if (customer != null) { var redeems = this._context.Redeems.Where(w => w.CustomerID == customer.ID); var mobile = this._context.MobilePoints.Where(w => w.CustomerID == customer.ID); var classchages = this._context.CustomerClassChanges.Where(w => w.CustomerID == customer.ID); var adjusts = this._context.PointAdjusts.Where(w => w.CustomerID == customer.ID); var points = this._context.CustomerPoints.Where(w => w.CustomerID == customer.ID); var tempcus = JsonConvert.SerializeObject(customer, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var tcus = new TerminateCustomer(); tcus = JsonConvert.DeserializeObject <TerminateCustomer>(tempcus); tcus.ID = 0; tcus.CustomerID = customer.ID; this._context.TerminateCustomers.Add(tcus); foreach (var item in redeems) { var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var t = new TerminateRedeem(); t = JsonConvert.DeserializeObject <TerminateRedeem>(temp); t.ID = 0; this._context.TerminateRedeems.Add(t); } foreach (var item in points) { var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var t = new TerminateCustomerPoint(); t = JsonConvert.DeserializeObject <TerminateCustomerPoint>(temp); t.ID = 0; this._context.TerminateCustomerPoints.Add(t); } foreach (var item in mobile) { var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var t = new TerminateMobilePoint(); t = JsonConvert.DeserializeObject <TerminateMobilePoint>(temp); t.ID = 0; this._context.TerminateMobilePoints.Add(t); } foreach (var item in classchages) { var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var t = new TerminateCustomerClassChange(); t = JsonConvert.DeserializeObject <TerminateCustomerClassChange>(temp); t.ID = 0; this._context.TerminateCustomerClassChanges.Add(t); } foreach (var item in adjusts) { var temp = JsonConvert.SerializeObject(item, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var t = new TerminatePointAdjust(); t = JsonConvert.DeserializeObject <TerminatePointAdjust>(temp); t.ID = 0; this._context.TerminatePointAdjusts.Add(t); } var user = this._context.Users.Where(w => w.ID == customer.UserID).FirstOrDefault(); if (user != null) { var rg = new RijndaelCrypt(); var u = rg.Encrypt(user.UserName); var p = rg.Encrypt(DataEncryptor.Decrypt(user.Password)); var flag = rg.Encrypt(customer.FacebookFlag); var tempuser = JsonConvert.SerializeObject(user, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var tuser = new TerminateUser(); tuser = JsonConvert.DeserializeObject <TerminateUser>(tempuser); tuser.ID = 0; tuser.CustomerID = customer.ID; this._context.TerminateUsers.Add(tuser); this._context.CustomerPoints.RemoveRange(points); this._context.MobilePoints.RemoveRange(mobile); this._context.CustomerClassChanges.RemoveRange(classchages); this._context.PointAdjusts.RemoveRange(adjusts); this._context.Redeems.RemoveRange(redeems); this._context.Customers.Remove(customer); this._context.Users.Remove(user); acccode.Status = StatusType.InActive; this._context.SaveChanges(); /*delete customer imobile*/ using (var client = new HttpClient()) { client.BaseAddress = new Uri(_mobile.Url + "/rewardpoint/customerprofile/delete"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var model = new { u = u, p = p, flag = flag }; StringContent content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content); if (response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.OK) { customer.Success = true; this._context.SaveChanges(); } } } } } this._loginServices.Logout(); return(View()); }
public async Task <IActionResult> Login(Login model, bool registed = false) { model.UserName = model.UserName.Trim(); model.Password = model.Password.Trim(); ModelState.Remove(""); if (ModelState.IsValid) { // Login statement here var user = this._context.Users.Include(u => u.UserRole).Where(u => u.UserName == model.UserName).FirstOrDefault(); if (user == null) { /*create customer imobile*/ if (user == null) { await this.Repair(model.UserName, model.Password, null, bcrypt : BCrypt.Net.BCrypt.HashPassword(model.Password)); user = this._context.Users.Include(u2 => u2.UserRole).Where(u2 => u2.UserName == model.UserName).FirstOrDefault(); } } if (user != null) { if (registed) { if (user != null && user.Status == UserStatusType.Active) { this._loginServices.Login(user, model.RememberMe); var customer = this._context.Customers.Where(w => w.UserID == user.ID).FirstOrDefault(); if (customer != null) { customer.FirstLogedIn = true; this._context.SaveChanges(); } return(RedirectToAction("RegisterCompleted", new { Email = model.UserName })); } } else { if (user.Status != UserStatusType.InActive) { if (user.UserRole != null && user.UserRole.RoleName == RoleName.Member) { var customer = this._context.Customers.Where(w => w.UserID == user.ID).FirstOrDefault(); if (customer == null) { ViewData["ErrorMessage"] = "ไม่พบข้อมูลผู้ใช้"; return(View(model)); } if (customer.FirstLogedIn == false && customer.Channel == CustomerChanal.TipInsure) { var rg = new RijndaelCrypt(); return(RedirectToAction("ResetPwd", "Accounts", new { u = rg.Encrypt(customer.User.UserName) })); } if (!string.IsNullOrEmpty(user.Password)) { string desPassword = DataEncryptor.Decrypt(user.Password); if (model.Password == desPassword) { this._loginServices.Login(user, model.RememberMe); GetCustomerClass(customer); customer.FirstLogedIn = true; var conditions = this.GetPointCondition(customer, TransacionTypeID.Login); foreach (var con in conditions) { } this._context.SaveChanges(); return(RedirectToAction("Info", "Customer")); } } if (!string.IsNullOrEmpty(customer.BCryptPwd)) { string paintTextPassword = model.Password; string passworeInDB = customer.BCryptPwd; if (!string.IsNullOrEmpty(paintTextPassword) && !string.IsNullOrEmpty(passworeInDB)) { if (BCrypt.Net.BCrypt.Verify(paintTextPassword, passworeInDB)) { user.Password = DataEncryptor.Encrypt(model.Password); customer.Syned = true; this._context.Users.Update(user); this._loginServices.Login(user, model.RememberMe); GetCustomerClass(customer); customer.FirstLogedIn = true; this._context.SaveChanges(); return(RedirectToAction("Info", "Customer")); } } } } else if (user.UserRole.RoleName == RoleName.Merchant) { string desPassword = DataEncryptor.Decrypt(user.Password); if (model.Password == desPassword) { this._loginServices.Login(user, model.RememberMe); return(RedirectToAction("Index", "MerchantU")); } } else { string desPassword = DataEncryptor.Decrypt(user.Password); if (model.Password == desPassword) { this._loginServices.Login(user, model.RememberMe); return(RedirectToAction("Index", "Admin")); } } } else { ViewData["ErrorMessage"] = "ถูกระงับการเป็นสมาชิก"; return(View(model)); } } } } ViewData["ErrorMessage"] = "รหัสผู้ใช้ หรือ รหัสผ่านไม่ถูกต้อง"; return(View(model)); }
public static string Decode(string cipher) { return(RijndaelCrypt.Decrypt(cipher, AppIdentifier)); }