/// <summary> /// 用户注册 /// </summary> /// <returns></returns> public Result <dynamic> Register(MemberRegisterRequest ent) { #region 数据验证 var result = new Result <dynamic>(); if (ent.mobile_phone.IsNullOrEmpty()) { result.Message = "用户手机号码不能为空"; return(result); } if (ent.display_name.IsNullOrEmpty()) { result.Message = "用户昵称不能为空"; return(result); } var exists = MemberRepository.Exists(ent.mobile_phone); if (exists.HasValue) { if (exists.Value) { result.Message = "存在相同的手机号码"; } } else { result.Message = "查询数据库异常"; } if (!string.IsNullOrEmpty(result.Message)) { result.Code = ResultCode.Error; return(result); } var smsService = new SmsService(); var sms = smsService.VerifySmsCode(ent.mobile_phone, 1, ent.mobile_code); if (sms.Code != ResultCode.Success) { return(sms); } #endregion MemberModel entity = new MemberModel() { MobilePhone = ent.mobile_phone, Portrait = string.Empty, EncryptedPwd = SecurityHelper.Encrypt(ent.pass_word), DisplayName = ent.display_name, Gender = ent.gender, LocationArea = ent.location_area, Birthday = ent.birthday, AccountBalance = 0, AmountTotal = 0, AmountWithdrawn = 0, TotalScore = 0, TotalWithdrawScore = 0, JpushId = string.Empty, OpenidWxMp = string.Empty, OpenidWxOpen = string.Empty, Status = 0, CreateTime = DateTime.Now, UpdateTime = DateTime.Now }; var member = MemberRepository.Add(entity); if (member.Id > 0) { string token = Guid.NewGuid().ToString().Replace("-", "").ToLower(); var cache = new RedisCacheHelper <Model.Member>(); cache.Set(token, new Model.Member() { id = entity.Id, display_name = entity.DisplayName }, TimeSpan.FromDays(5)); result.Message = "注册成功"; result.Code = ResultCode.Success; result.Data = new MemberLoginResponse { id = member.Id, mobile = member.MobilePhone, portrait = member.Portrait, display_name = member.DisplayName, gender = member.Gender, location_area = member.LocationArea, birthday = member.Birthday, account_balance = member.AccountBalance, amount_total = member.AmountTotal, amount_withdrawn = member.AmountWithdrawn, total_score = member.TotalScore, total_withdraw_score = member.TotalWithdrawScore, token = token }; } else { result.Code = ResultCode.Error; result.Message = "数据库操作异常"; } return(result); }
/// <summary> /// 对字符串进行 MD5 加密(32Bit) /// </summary> /// <param name="self"> 字符串本身 </param> /// <param name="encoding">编码,为 null 时取默认值</param> /// <returns> 加密后的哈希值 </returns> public static string ToMd5On32Bit(this string self, Encoding encoding = null) { return(SecurityHelper.Md5Encrypt(self, encoding)); }
public string GenerateRefreshToken() { return(Convert.ToBase64String(SecurityHelper.GetRandomBytes())); }
public SetupModule() { var configuration = Nancy.TinyIoc.TinyIoCContainer.Current.Resolve <ServantConfiguration>(); var host = Nancy.TinyIoc.TinyIoCContainer.Current.Resolve <IHost>(); Get["/setup/confirm/"] = _ => { string url = Request.Query.Url; Model.Url = url; return(View["confirm", Model]); }; Get["/setup/restartservant/"] = _ => { new System.Threading.Thread(() => { host.Kill(); host.Start(); }).Start(); return(true); }; if (!configuration.SetupCompleted) { Get["/setup/1/"] = _ => { Model.Configuration = configuration; Model.AcceptTerms = false; Model.AutoSendCrashReport = true; Model.OriginalServantUrl = configuration.ServantUrl; return(View["1", Model]); }; Post["/setup/1/"] = _ => { var formSettings = this.Bind <ServantConfiguration>(); var originalInputtedServantUrl = formSettings.ServantUrl; if (BindingHelper.SafeFinializeBinding(formSettings.ServantUrl) == null) { AddPropertyError("servanturl", "URL is invalid."); } else { formSettings.ServantUrl = BindingHelper.FinializeBinding(formSettings.ServantUrl); } var validationResult = this.Validate(formSettings); var acceptTerms = (bool)Request.Form.AcceptTerms; AddValidationErrors(validationResult); if (!acceptTerms) { AddPropertyError("acceptterms", "You must agree and accept."); } if (string.IsNullOrWhiteSpace(formSettings.Password)) { AddPropertyError("password", "Password cannot be empty."); } if (!HasErrors) { formSettings.Password = SecurityHelper.HashPassword(formSettings.Password); formSettings.SetupCompleted = true; formSettings.AutoSendCrashReport = (bool)Request.Form.AutoSendCrashReport; Helpers.ConfigurationHelper.UpdateConfiguration(formSettings); if (!configuration.EnableErrorMonitoring && formSettings.EnableErrorMonitoring) { host.StartLogParsing(); } var isHttps = formSettings.ServantUrl.StartsWith("https://"); if (isHttps) { var port = new Uri(formSettings.ServantUrl).Port; host.RemoveCertificateBinding(port); host.AddCertificateBinding(port); } return(Response.AsRedirect("/setup/confirm/?url=" + HttpUtility.UrlEncode(formSettings.ServantUrl))); } formSettings.ServantUrl = originalInputtedServantUrl; Model.OriginalServantUrl = configuration.ServantUrl; Model.Settings = formSettings; Model.AcceptTerms = Request.Form.AcceptTerms; return(View["1", Model]); }; } }
public UserController(IMembershipService membershipService, IUnityContainer unityContainer, Site currentSite, SecurityHelper securityHelper) { _unityContainer = unityContainer; _currentSite = currentSite; _securityHelper = securityHelper; FormsService = new FormsAuthenticationService(); MembershipService = membershipService; }
private async Task SetConfig() { Config config = new Config { AppRoot = $"{Request.PathBase}/", ApiUrl = _appSettings.ApiUrl }; if (_appSettings.Impersonate && _env.IsDevelopment()) { config.User = _appSettings.User; config.User.Name = $"{_appSettings.User.RestOfName} {_appSettings.User.Surname}"; var claims = new List <Claim> { new Claim(Constants.Sub, _appSettings.User.Inumber), new Claim(Constants.Email, _appSettings.User.Email), new Claim(Constants.RestOfName, _appSettings.User.RestOfName), new Claim(Constants.Surname, _appSettings.User.Surname) }; // the claims in our app settings need to be BYU-I roles claims.AddRange(config.User.ByuiRoles.Select(r => new Claim(Constants.Role, r))); // get a JWT with the stuff we impersonated config.AuthToken = OAuthClient.GetJwt(claims); // now make the roles in our user Application roles config.User.Roles = SecurityHelper.ConvertByuiRolesToApplicationRoles(config.User.ByuiRoles); } else if (User.Identity.IsAuthenticated) { config.AuthToken = await HttpContext.GetTokenAsync("access_token"); // need these as the real BYU-Idaho roles for our claims, but then we'll convert them to application roles for the User in the config object List <string> byuiRoles = User.Claims.FirstOrDefault(c => c.Type == Constants.Role)?.Value.Split(',').Select(r => r.Trim()).ToList(); config.User = new User { Name = $"{User.Claims.FirstOrDefault(c => c.Type == Constants.RestOfName)?.Value} {User.Claims.FirstOrDefault(c => c.Type == Constants.Surname)?.Value}", Email = User.Claims.FirstOrDefault(c => c.Type == Constants.Email)?.Value, Roles = SecurityHelper.ConvertByuiRolesToApplicationRoles(byuiRoles) }; if (_env.IsDevelopment()) { // if it is development, create a jwt to pass to the api var claims = User.Claims.Where(c => c.Type != Constants.Role).ToList(); if (byuiRoles?.Any() == true) { claims.AddRange(byuiRoles.Select(r => new Claim(Constants.Role, r))); } config.Token = config.AuthToken; config.AuthToken = OAuthClient.GetJwt(claims); } } // if the user isn't logged in, we need to get our token to use to make our anonymous api calls if (_appSettings.AllowAnonymous && config.AuthToken == null) { config.AuthToken = await _oAuthClient.GetAccessTokenAsync(); } ViewData["Config"] = JsonConvert.SerializeObject(config, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); }
private void BindPaymentInfo(Order order) { if (order == null) { return; } string cardTypeDecrypted = SecurityHelper.Decrypt(order.CardType); if (!String.IsNullOrEmpty(cardTypeDecrypted)) { this.lblCardType.Text = Server.HtmlEncode(cardTypeDecrypted); } else { pnlCartType.Visible = false; } string cardNameDecrypted = SecurityHelper.Decrypt(order.CardName); if (!String.IsNullOrEmpty(cardNameDecrypted)) { this.lblCardName.Text = Server.HtmlEncode(cardNameDecrypted); } else { pnlCardName.Visible = false; } if (order.AllowStoringCreditCardNumber) { string cardNumberDecrypted = SecurityHelper.Decrypt(order.CardNumber); if (!String.IsNullOrEmpty(cardNumberDecrypted)) { this.lblCardNumber.Text = Server.HtmlEncode(cardNumberDecrypted); } else { pnlCardNumber.Visible = false; } } else { string maskedCreditCardNumberDecrypted = SecurityHelper.Decrypt(order.MaskedCreditCardNumber); if (!String.IsNullOrEmpty(maskedCreditCardNumberDecrypted)) { this.lblCardNumber.Text = Server.HtmlEncode(maskedCreditCardNumberDecrypted); } else { pnlCardNumber.Visible = false; } } if (order.AllowStoringCreditCardNumber) { string cardCVV2Decrypted = SecurityHelper.Decrypt(order.CardCVV2); this.lblCardCVV2.Text = Server.HtmlEncode(cardCVV2Decrypted); } else { pnlCardCVV2.Visible = false; } string cardExpirationMonthDecrypted = SecurityHelper.Decrypt(order.CardExpirationMonth); if (!String.IsNullOrEmpty(cardExpirationMonthDecrypted) && cardExpirationMonthDecrypted != "0") { this.lblCardExpirationMonth.Text = cardExpirationMonthDecrypted; } else { pnlCardExpiryMonth.Visible = false; } string cardExpirationYearDecrypted = SecurityHelper.Decrypt(order.CardExpirationYear); if (!String.IsNullOrEmpty(cardExpirationYearDecrypted) && cardExpirationYearDecrypted != "0") { this.lblCardExpirationYear.Text = cardExpirationYearDecrypted; } else { pnlCardExpiryYear.Visible = false; } this.lblPONumber.Text = Server.HtmlEncode(order.PurchaseOrderNumber); this.lblPaymentMethodName.Text = Server.HtmlEncode(order.PaymentMethodName); this.lblPaymentStatus.Text = PaymentStatusManager.GetPaymentStatusName(order.PaymentStatusID); this.btnCapture.Visible = OrderManager.CanCapture(order); this.btnMarkAsPaid.Visible = OrderManager.CanMarkOrderAsPaid(order); }
/// <summary> /// 修改用户信息 /// </summary> /// <param name="user"></param> /// <returns></returns> public JsonNetResult Save(UserModel user) { if (!this.Validate(user)) { return(JsonNet(new ResponseResult(false, "The required attributes of user are not filled.", ErrorCodes.RequireField))); } var service = new UserService(); if (string.IsNullOrEmpty(user.Id)) { var validationUser = service.GetByAccount(user.Account, user.Id); if (validationUser != null) { return(JsonNet(new ResponseResult(false, "账号重复了!"))); } } service.Save(new UserEntity { Id = user.Id, Name = user.Name, Account = user.Account, Password = string.IsNullOrEmpty(user.Password) ? string.Empty : SecurityHelper.HashPassword(user.Password), Title = user.Title, UnitId = user.UnitId, IsChangePassword = true }); return(JsonNet(new ResponseResult())); }
public SimpleAjaxResult Save() { try { var serialNo = SerialNoHelper.Create(); if (Amount < 0) { return(new SimpleAjaxResult(Localize("invalidAmount"))); } TransactionHelper.BeginTransaction(); var account1 = AccountService.GetByName(AccountName); if (account1 == null || (account1.State != AccountStates.Normal && account1.State != AccountStates.Invalid)) { return(new SimpleAjaxResult(string.Format(Localize("accountNonFound"), AccountName))); } var account2 = AccountService.GetByName(AccountNameTo); if (account2 == null || (account2.State != AccountStates.Normal && account2.State != AccountStates.Invalid)) { return(new SimpleAjaxResult(string.Format(Localize("accountNonFound"), AccountNameTo))); } var accountType = AccountTypeService.GetById(account1.AccountTypeId); if (accountType == null || !accountType.IsRecharging) { return(new SimpleAjaxResult(string.Format(Localize("accountCannotRecharging"), AccountName))); } accountType = AccountTypeService.GetById(account2.AccountTypeId); if (accountType == null || !accountType.IsRecharging) { return(new SimpleAjaxResult(string.Format(Localize("accountCannotRecharging"), AccountNameTo))); } if (Amount == 0) { Amount = account1.Amount; } if (account1.Amount < Amount) { return(new SimpleAjaxResult(Localize("invalidAmount"))); } var passSvc = UnityContainer.Resolve <IPasswordService>(HostSite.PasswordType); var password = passSvc.Decrypto(Password); if (User.SaltAndHash(password, account1.PasswordSalt) != account1.Password) { return(new SimpleAjaxResult(Localize("invalidPassword", "ÃÜÂë´íÎó"))); } account1.Amount -= Amount; account2.Amount += Amount; AccountService.Update(account1); AccountService.Update(account2); // transfer in DealLog dealLog = new DealLog(serialNo); dealLog.Account = account1; dealLog.Addin = account1.AccountId; dealLog.Amount = Amount; dealLog.DealType = DealTypes.TransferOut; DealLogService.Create(dealLog); // transfer out dealLog = new DealLog(serialNo); dealLog.Account = account2; dealLog.Addin = account2.AccountId; dealLog.Amount = -Amount; dealLog.DealType = DealTypes.TransferIn; DealLogService.Create(dealLog); Logger.LogWithSerialNo(LogTypes.AccountTransfer, serialNo, account1.AccountId, account1.Name, account2.Name, Amount); var r = new DataAjaxResult(); if (!string.IsNullOrWhiteSpace(HostSite.TicketTemplateOfTransfer)) { r.Data1 = MessageFormator.FormatTickForTransfer(HostSite.TicketTemplateOfTransfer, serialNo, account1, account1.OwnerId.HasValue ? MembershipService.GetUserById(account1.OwnerId.Value) : null, AccountTypeService.GetById(account1.AccountTypeId), account2, account2.OwnerId.HasValue ? MembershipService.GetUserById(account2.OwnerId.Value) : null, AccountTypeService.GetById(account2.AccountTypeId), SecurityHelper.GetCurrentUser().CurrentUser ); PrintTicketService.Create(new PrintTicket(LogTypes.AccountTransfer, serialNo, r.Data1.ToString(), account1)); } return(TransactionHelper.CommitAndReturn(r)); } catch (System.Exception ex) { Logger.Error(LogTypes.AccountTransfer, ex); return(new SimpleAjaxResult(Localize("SystemError"))); } }
protected void Page_Load(object sender, EventArgs e) { SetupControl(); userID = ValidationHelper.GetInteger(SessionHelper.GetValue("UserPasswordRequestID"), 0); hash = QueryHelper.GetString("hash", string.Empty); time = QueryHelper.GetString("datetime", string.Empty); policyReq = QueryHelper.GetInteger("policyreq", 0); pwdExp = QueryHelper.GetInteger("exp", 0); returnUrl = QueryHelper.GetString("returnurl", null); btnReset.Text = GetString("general.reset"); rfvConfirmPassword.Text = GetString("general.requiresvalue"); siteName = SiteContext.CurrentSiteName; // Get interval from settings interval = SettingsKeyInfoProvider.GetDoubleValue(siteName + ".CMSResetPasswordInterval"); // Prepare failed message string invalidRequestMessage = DataHelper.GetNotEmpty(InvalidRequestText, String.Format(ResHelper.GetString("membership.passwresetfailed"), ResolveUrl("~/cmspages/logon.aspx?forgottenpassword=1"))); // Reset password cancelation if (QueryHelper.GetBoolean("cancel", false)) { // Get user info UserInfo ui = UserInfoProvider.GetUserInfoWithSettings("UserPasswordRequestHash = '" + SecurityHelper.GetSafeQueryString(hash, true) + "'"); if (ui != null) { ui.UserPasswordRequestHash = null; UserInfoProvider.SetUserInfo(ui); SessionHelper.Remove("UserPasswordRequestID"); ShowInformation(GetString("membership.passwresetcancelled")); } else { ShowError(invalidRequestMessage); } pnlReset.Visible = false; return; } // Reset password request if (!URLHelper.IsPostback()) { if (policyReq > 0) { ShowInformation(GetString("passwordpolicy.policynotmet") + "<br />" + passStrength.GetPasswordPolicyHint()); } // Prepare query string query = "UserPasswordRequestHash = '" + SecurityHelper.GetSafeQueryString(hash, true) + "'"; if (userID > 0) { query = SqlHelper.AddWhereCondition(query, "UserID = " + userID, "OR"); } // Get user info UserInfo ui = UserInfoProvider.GetUserInfoWithSettings(query); // Validate request ResetPasswordResultEnum result = AuthenticationHelper.ValidateResetPassword(ui, hash, time, interval, "Reset password control"); // Prepare messages string timeExceededMessage = DataHelper.GetNotEmpty(ExceededIntervalText, String.Format(ResHelper.GetString("membership.passwreqinterval"), ResolveUrl("~/cmspages/logon.aspx?forgottenpassword=1"))); string resultMessage = string.Empty; // Check result switch (result) { case ResetPasswordResultEnum.Success: // Save user is to session SessionHelper.SetValue("UserPasswordRequestID", ui.UserID); // Delete it from user info ui.UserPasswordRequestHash = null; UserInfoProvider.SetUserInfo(ui); break; case ResetPasswordResultEnum.TimeExceeded: resultMessage = timeExceededMessage; break; default: resultMessage = invalidRequestMessage; break; } if (!string.IsNullOrEmpty(resultMessage)) { // Show error message ShowError(resultMessage); pnlReset.Visible = false; return; } } }
// Token: 0x06002D80 RID: 11648 RVA: 0x000CCE8C File Offset: 0x000CB08C internal static bool CanNavigateToUri(Uri uri) { return(!uri.IsAbsoluteUri || uri.IsUnc || uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeMailto || (uri.Scheme == PackUriHelper.UriSchemePack && !string.IsNullOrEmpty(uri.Fragment)) || SecurityHelper.CallerHasWebPermission(uri)); }
public string c(Commande Commnade) { var r = new CommandResult(); string commandName = Commnade.d; Command command = null; //string desencry = null; var inCourseRequest = InCourseRequest.New(); OrdenesApplication ordenesApplication = OrdenesApplication.Instance; //inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader(); try { //SecurityHelper.ensureAuthenticated(inCourseRequest); //AESEncryptor encryptor = new AESEncryptor(); //desencry = encryptor.DesencriptarQuery(Commnade.d, MAEUserSession.Instancia.Global); //desencry = desencry.Replace("@s", "M4Trader.ordenes.server").Replace("@a", "M4Trader.ordenes.mvc"); Commnade.d = Commnade.d.Replace("@s", "M4Trader.ordenes.server").Replace("@a", "M4Trader.ordenes.mvc"); command = JsonConvert.DeserializeObject <Command>(Commnade.d, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }); commandName = command.GetType().Name; var opts = command.Options; inCourseRequest.Agencia = ordenesApplication.GetSecurityAgenciaFromHeader(); if (!(command is RefrescarCacheCommand) && command.GetIdAccion != (int)IdAccion.Login && !(command is M4Trader.ordenes.server.AppLiteralesCommand) && !(command is M4Trader.ordenes.server.AppThemeCommand)) { inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader(); SecurityHelper.ensureAuthorized(command, inCourseRequest); inCourseRequest.Identity_rid = MAEUserSession.Instancia.IdUsuario; } CommandLog.Start(command, inCourseRequest); command.PreProcess(); command.Validate(); r.Data = command.Execute(inCourseRequest).Data; r.Status = "EX0000"; r.RequestId = inCourseRequest.Id.ToString(); CommandLog.FinishOK(commandName, r, inCourseRequest); try { command.ExecuteAfterSuccess(); } catch { } } catch (JsonSerializationException) { Commnade.d = Commnade.d.Replace("M4Trader.ordenes.mvc", "M4Trader.ordenes.server"); command = JsonConvert.DeserializeObject <Command>(Commnade.d, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }); commandName = command.GetType().Name; var opts = command.Options; if (!(command is RefrescarCacheCommand) && command.GetIdAccion != (int)IdAccion.Login && !(command is M4Trader.ordenes.server.AppLiteralesCommand)) { inCourseRequest.SecurityTokenId = ordenesApplication.GetSecurityTokenIdFromHeader(); SecurityHelper.ensureAuthorized(command, inCourseRequest); inCourseRequest.Identity_rid = MAEUserSession.Instancia.IdUsuario; } CommandLog.Start(command, inCourseRequest); command.PreProcess(); command.Validate(); r.Data = command.Execute(inCourseRequest).Data; r.Status = "EX0000"; r.RequestId = inCourseRequest.Id.ToString(); CommandLog.FinishOK(commandName, r, inCourseRequest); try { command.ExecuteAfterSuccess(); } catch { } } catch (SessionException sex) { CommandLog.StartDesencriptado(Commnade.d, inCourseRequest); var cr = new CommandResult(); cr.Data = ExecutionResult.ReturnWithError("Sessión Expirada", inCourseRequest.Id).Data; cr.Status = "SE6666"; CommandLog.FinishWithError(commandName, sex, inCourseRequest); r = cr; } catch (PreConditionNotEnsuredException ex) { CommandLog.StartDesencriptado(Commnade.d, inCourseRequest); r.Data = ExecutionResult.ReturnWithError(ex.Message, inCourseRequest.Id).Data; r.Status = "FE9999"; CommandLog.FinishWithError(commandName, ex, inCourseRequest); } catch (FunctionalException fe) { CommandLog.StartDesencriptado(Commnade.d, inCourseRequest); r.Data = ExecutionResult.ReturnWithError(fe.Message, inCourseRequest.Id).Data; r.Status = string.Format("FE{0}", fe.Code.ToString("0000")); CommandLog.FinishWithError(commandName, fe, inCourseRequest); } catch (M4TraderApplicationException maex) { CommandLog.StartDesencriptado(Commnade.d, inCourseRequest); r.Data = ExecutionResult.ReturnWithError(maex.Message, inCourseRequest.Id).Data; r.Status = string.Format("FE{0}", maex.Codigo); CommandLog.FinishWithError(commandName, maex, inCourseRequest); } catch (MAECommunicationException mce) { CommandLog.StartDesencriptado(Commnade.d, inCourseRequest); r.Data = ExecutionResult.ReturnWithError(mce.Message, inCourseRequest.Id).Data; r.Status = "FE9999"; CommandLog.FinishWithError(commandName, mce, inCourseRequest); } catch (MAEConcurrencyException mce) { CommandLog.StartDesencriptado(Commnade.d, inCourseRequest); r.Data = ExecutionResult.ReturnWithError(mce.Message, inCourseRequest.Id).Data; r.Status = "FE00055"; CommandLog.FinishWithError(commandName, mce, inCourseRequest); } catch (Exception ex) { CommandLog.StartDesencriptado(Commnade.d, inCourseRequest); r.Data = ExecutionResult.ReturnWithError(ex.Message, inCourseRequest.Id).Data; r.Status = "TE9999"; CommandLog.FinishWithError(commandName, ex, inCourseRequest); } finally { if (command != null) { command.Dispose(); } } r.RequestId = inCourseRequest.Id.ToString(); WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"; return(JsonConvert.SerializeObject(r)); }
/// <summary> /// Hashes checksum value with passcode and secret /// </summary> /// <param name="passcode">Public passcode which is provided by Webmoney</param> /// <param name="secret">Secret key which is provided by Webmoney</param> public void HashChecksum(WMService service) { string message = this.HashMessage() + service.MerchantCode + service.Passcode; Checksum = SecurityHelper.HMACHSA1(message, service.SecretKey); }
public GeneralResultDTO ChangePassword(Guid userGUID, string oldPassword, string newPassword, string confirmPassword) { #region Validation if (string.IsNullOrEmpty(oldPassword)) { return(new GeneralResultDTO { success = false, errorMessage = ResHelper.GetString("Kadena.Settings.Password.OldPasswordIsEmpty", LocalizationContext.CurrentCulture.CultureCode) }); } if (oldPassword.Contains(" ")) { return(new GeneralResultDTO { success = false, errorMessage = ResHelper.GetString("Kadena.Settings.Password.OldPasswordContainsWhiteSpaces", LocalizationContext.CurrentCulture.CultureCode) }); } if (string.IsNullOrEmpty(newPassword)) { return(new GeneralResultDTO { success = false, errorMessage = ResHelper.GetString("Kadena.Settings.Password.NewPasswordIsEmpty", LocalizationContext.CurrentCulture.CultureCode) }); } if (newPassword.Contains(" ")) { return(new GeneralResultDTO { success = false, errorMessage = ResHelper.GetString("Kadena.Settings.Password.NewPasswordContainsWhiteSpaces", LocalizationContext.CurrentCulture.CultureCode) }); } if (string.IsNullOrEmpty(confirmPassword)) { return(new GeneralResultDTO { success = false, errorMessage = ResHelper.GetString("Kadena.Settings.Password.ConfirmPasswordIsEmpty", LocalizationContext.CurrentCulture.CultureCode) }); } if (confirmPassword.Contains(" ")) { return(new GeneralResultDTO { success = false, errorMessage = ResHelper.GetString("Kadena.Settings.Password.ConfirmPasswordContainsWhiteSpaces", LocalizationContext.CurrentCulture.CultureCode) }); } if (newPassword != confirmPassword) { return(new GeneralResultDTO { success = false, errorMessage = ResHelper.GetString("Kadena.Settings.Password.PasswordsDontMatch", LocalizationContext.CurrentCulture.CultureCode) }); } if (!SecurityHelper.CheckPasswordPolicy(newPassword, SiteContext.CurrentSiteName)) { var errorMessage = string.Empty; var customMessage = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSPolicyViolationMessage"); if (!string.IsNullOrEmpty(customMessage)) { errorMessage = ResHelper.LocalizeString(customMessage, LocalizationContext.CurrentCulture.CultureCode); } return(new GeneralResultDTO { success = false, errorMessage = errorMessage }); } #endregion return(ChangePasswordInternal(userGUID, oldPassword, newPassword)); }
public ActionResponse Add(UserModel model, SmtpClient smtp, string adminEmail) { using (var unitWork = new UnitOfWork(context)) { ActionResponse response = new ActionResponse(); try { EFOrganization organization = null; ISecurityHelper sHelper = new SecurityHelper(); IMessageHelper mHelper; if (!model.IsNewOrganization) { organization = unitWork.OrganizationRepository.GetByID(model.OrganizationId); if (organization == null) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetNotFound("Organization"); return(response); } } else { EFOrganizationTypes organizationType = null; if (model.IsNewOrganization) { organizationType = unitWork.OrganizationTypesRepository.Get(o => o.TypeName.Equals("Default")); if (organizationType == null) { mHelper = new MessageHelper(); response.Success = false; response.Message = mHelper.GetNotFound("Organization Type"); return(response); } organization = new EFOrganization() { OrganizationName = model.OrganizationName, OrganizationType = organizationType }; unitWork.Save(); model.OrganizationId = organization.Id; } } string passwordHash = sHelper.GetPasswordHash(model.Password); //TODO: Set approved to false to make it approved through notification var newUser = unitWork.UserRepository.Insert(new EFUser() { Name = model.Name, Email = model.Email, UserType = UserTypes.Standard, Organization = organization, Password = passwordHash, IsApproved = true, IsActive = true, RegistrationDate = DateTime.Now }); unitWork.Save(); //Get emails for all the users //TODO: To bind the email and notifications with user account creation /*var users = unitWork.UserRepository.GetMany(u => u.OrganizationId.Equals(organization.Id) && u.IsApproved == true); * List<EmailsModel> usersEmailList = new List<EmailsModel>(); * foreach (var user in users) * { * usersEmailList.Add(new EmailsModel() * { * Email = user.Email, * UserName = user.Name, * UserType = user.UserType * }); * } * * if (usersEmailList.Count == 0) * { * var managerUsers = unitWork.UserRepository.GetMany(u => u.UserType == UserTypes.Manager || u.UserType == UserTypes.SuperAdmin); * foreach (var user in managerUsers) * { * usersEmailList.Add(new EmailsModel() * { * Email = user.Email, * UserName = user.Name, * UserType = user.UserType * }); * } * } * * if (usersEmailList.Count > 0) * { * //Send emails * IEmailHelper emailHelper = new EmailHelper(smtp, adminEmail); * emailHelper.SendNewRegistrationEmail(usersEmailList, organization.OrganizationName); * mHelper = new MessageHelper(); * string notificationMessage = mHelper.NewUserForOrganization(organization.OrganizationName, model.Name); * * //Add notification * unitWork.NotificationsRepository.Insert(new EFUserNotifications() * { * UserType = model.UserType, * Organization = organization, * Message = notificationMessage, * TreatmentId = newUser.Id, * Dated = DateTime.Now, * IsSeen = false, * NotificationType = NotificationTypes.NewUser * }); * unitWork.Save(); * }*/ response.ReturnedId = newUser.Id; } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return(response); } }
private string HashPassword(string value) { return(SecurityHelper.ComputeSha256Hash(value)); }
protected override void UpdateUnmanagedPropertyState(SafeHandle unmanagedEffect) { SecurityHelper.DemandUIWindowPermission(); }
public ActionResult Regist(LoginModel model) { if (string.IsNullOrEmpty(model.RegistUserName)) { ModelState.AddModelError("regist_error", "用户名不能为空!"); model.HasError = true; return(View(model)); } if (string.IsNullOrEmpty(model.RegistPassword)) { ModelState.AddModelError("regist_error", "密码不能为空!"); model.HasError = true; return(View(model)); } if (model.RegistPassword.Length < 3) { ModelState.AddModelError("regist_error", "密码不能少于3位!"); model.HasError = true; return(View(model)); } /* * if (string.IsNullOrEmpty(model.Mobile)) * { * * ModelState.AddModelError("regist_error", "邮箱不能为空!"); * * return View(model); * } * * System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^[a-z]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\\.][a-z]{2,3}([\\.][a-z]{2})?$/i"); * if (!regex.IsMatch(model.Mobile)) * { * ModelState.AddModelError("regist_error", "邮箱格式输入错误!"); * * return View(model); * } * */ if (model.RegistPassword != model.RegistConfirmPassword) { ModelState.AddModelError("regist_error", "两次输入密码不一致!"); model.HasError = true; return(View(model)); } var account = accountService.CheckIfAccountNameExists(model.RegistUserName); if (null != account) { ModelState.AddModelError("regist_error", "用户名已经被占用,请修改新用户名!"); model.HasError = true; return(View(model)); } /* * account = accountService.CheckIfAccountMobileExists(model.Mobile); * * if (null != account) * { * ModelState.AddModelError("regist_error", "邮箱已经被占用,请使用修改新用户名!"); * model.HasError = true; * return View(model); * } */ account = new Account(); account.Id = StringHelper.GuidString(); account.UserName = model.RegistUserName; account.Password = model.RegistPassword; account.Mobile = model.Mobile; account.UserType = (int)EnumUserType.Web; account.status = 1; account.Password = SecurityHelper.EncryptToSHA1(account.Password); account.CreateDate = DateTime.Now; account.AccountType = (int)EnumAccountType.User; accountService.CreateAccount(account); return(RedirectToAction("Login")); }
public JObject VerifyCaptcha([FromBody] CaptchaVerificationData data) { return SecurityHelper.VerifyCaptcha(data, FrontendSettingsViaduc.Instance.GetServerSettings()); }
private string globalMarkupDefinitionsPath = string.Empty; //these are at a higher level than the current site, can be used by multiple sites protected void Page_Load(object sender, EventArgs e) { SecurityHelper.DisableBrowserCache(); }
/// <summary> /// 生成种子数据 /// </summary> /// <param name="builder"></param> /// <returns></returns> public static ModelBuilder SeedData(this ModelBuilder builder) { string remark = "seed by efcore auto migration"; builder.Entity <SystemUserEntity>().HasData ( new SystemUserEntity() { Id = 1, CreateTime = DateTime.Now, Status = 1, UserName = "******", RealName = "admin", Password = SecurityHelper.MD5("111111") } ); builder.Entity <SystemConfigEntity>().HasData ( new SystemConfigEntity() { CreateTime = DateTime.Now, IsReuired = true, Key = "Email_SmtpServer", Name = "邮件服务器", Value = "", Group = "邮件配置", Remark = "smtp服务器地址", Sort = 1 }, new SystemConfigEntity() { CreateTime = DateTime.Now, IsReuired = true, Key = "Email_SmtpPort", Name = "邮件服务器端口", Value = "", Group = "邮件配置", Remark = "smtp端口号", Sort = 2 }, new SystemConfigEntity() { CreateTime = DateTime.Now, IsReuired = true, Key = "Email_FromAccount", Name = "发件人账号", Value = "", Group = "邮件配置", Remark = "邮箱账号", Sort = 3 }, new SystemConfigEntity() { CreateTime = DateTime.Now, IsReuired = true, Key = "Email_FromAccountPwd", Name = "发件人账号密码", Value = "", Group = "邮件配置", Remark = "登录密码或授权码等", Sort = 4 }, new SystemConfigEntity() { CreateTime = DateTime.Now, IsReuired = true, Key = "Assembly_ImagePullPolicy", Name = "文件包拉取策略", Value = "Always", Group = "程序集配置", Remark = "Always-总是拉取,IfNotPresent-本地没有时拉取,默认是Always", Sort = 1 }, new SystemConfigEntity() { CreateTime = DateTime.Now, IsReuired = true, Key = "Http_RequestTimeout", Name = "请求超时时间", Value = "10", Group = "HTTP配置", Remark = "单位是秒,默认值是10", Sort = 1 }, new SystemConfigEntity() { CreateTime = DateTime.Now, IsReuired = true, Key = "System_WorkerUnHealthTimes", Name = "Worker允许无响应次数", Value = "3", Group = "系统配置", Remark = "健康检查失败达到最大次数会被下线剔除,默认值是3", Sort = 1 } ); return(builder); }
/// <summary> /// 与api接口交互 /// </summary> /// <param name="target"></param> /// <param name="param"></param> /// <returns></returns> public static string RequestApi(string target, string param, string method = "POST") { string ret = string.Empty; string userName = ConfigHelper.GetAppSettings("itorm.api.itormName"); var passWord = ConfigHelper.GetAppSettings("itorm.api.webpass"); var md5key = ConfigHelper.GetAppSettings("itorm.api.strMd5Key"); var version = ConfigHelper.GetAppSettings("itorm.api.version"); var buildParam = param; var arrayParam = param.ToArray(); Array.Sort(arrayParam);//对字符串进行排序 buildParam = new string(arrayParam); string key = string.Format("{0}{1}{2}{3}{4}", userName, passWord, target, md5key, buildParam); string sign = SecurityHelper.GetMD5String(key); string body = string.Empty; StringBuilder requestStringUri = new StringBuilder(); requestStringUri.Append(ITOrm.Utility.Const.Constant.CurrentApiHost + "itapi/" + target); if (!string.IsNullOrEmpty(param)) { body = string.Format("itormName={0}&sign={1}&{2}&version={3}", userName, sign, param, version); if (method.ToLower().Contains("get")) { requestStringUri.AppendFormat("?{0}", body); } } else { body = string.Format("itormName={0}&sign={1}&version={2}", userName, sign, version); if (method.ToLower().Contains("get")) { requestStringUri.AppendFormat("?{0}", body); } } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestStringUri.ToString()); request.Method = method; request.KeepAlive = false; if (method.ToLower().Contains("post")) { request.ContentType = "application/x-www-form-urlencoded"; byte[] aryBuf = Encoding.GetEncoding("utf-8").GetBytes(body); request.ContentLength = aryBuf.Length; using (Stream writer = request.GetRequestStream()) { writer.Write(aryBuf, 0, aryBuf.Length); writer.Close(); writer.Dispose(); } } using (WebResponse response = request.GetResponse()) { StreamReader reader = new StreamReader(response.GetResponseStream() , Encoding.GetEncoding("utf-8") ); ret = reader.ReadToEnd(); reader.Close(); reader.Dispose(); } return(ret); }
public static string GetMd5(long userId, int clientType, long timestamp, string md5Key) { var source = userId + "|" + clientType + "|" + timestamp + "|" + md5Key; return(SecurityHelper.GetMd5(source)); }
/// <summary> /// Generates JWT token for the user authenticated by email and password. /// </summary> /// <param name="email">Email.</param> /// <param name="password">Password.</param> /// <returns>The <see cref="Task{String}"/> instance.</returns> public async Task <string> AuthenticateAsync(string email, string password) { UserDto userDto = await GetAsync(email, SecurityHelper.Hash(password)); return(SecurityHelper.CreateToken(userDto, _configuration)); }
/// <summary> /// 对字符串进行 HMAC-SHA512 加密 /// </summary> /// <param name="self"> 字符串本身 </param> /// <param name="key"> 密钥 </param> /// <param name="encoding">编码,为 null 时取默认值</param> /// <returns> 加密后的哈希值 </returns> public static string ToHmacSha512(this string self, string key, Encoding encoding = null) { return(SecurityHelper.HmacSha512Encrypt(self, key, encoding)); }
public JsonResult ChangeAccess(int userId, string action, string canLib, string isAdmin) { CmsUser currentUser = SecurityHelper.CurrentCmsUser(db); if (currentUser.RoleId < RoleType.Super) { throw new Exception("Access Denided."); } CmsUser user = db.Set <CmsUser>().SingleOrDefault(e => e.Id == userId); if (user != null) { switch (action) { case "setAccess": // full elib access 4 user.RoleId = isAdmin == "1" ? RoleType.Admin : RoleType.Normal; ((DbContext)db).Entry(user).State = EntityState.Modified; /* * Permission p = db.Permission.SingleOrDefault( * e => e.User.Id == userId && e.Target == "LIB"); * * if (p != null) * { * p.AccessMode = canLib == "1" ? 1 : 0; * db.Entry(p).State = EntityState.Modified; * } * else * { * Permission permission = new Permission() * { * User = user, * Target = "LIB", * AccessMode = canLib == "1" ? 1 : 0 * }; * db.Permission.Add(permission); * }*/ db.SaveChanges(); break; case "removeAccess": ClearPermissions(user); db.Set <CmsUser>().Remove(user); db.SaveChanges(); break; case "clearAccess": ClearPermissions(user); db.SaveChanges(); break; } } return(Json(new { Result = "Success" })); }
/// <summary> /// 对字符串进行 SHA384 加密 /// </summary> /// <param name="self"> 字符串本身 </param> /// <param name="encoding">编码,为 null 时取默认值</param> /// <returns> 加密后的哈希值 </returns> public static string ToSha384(this string self, Encoding encoding = null) { return(SecurityHelper.Sha384Encrypt(self, encoding)); }
public ViewResult Change(string sectionId, string pageId, string userName, PermissionType permission, bool overwrite = false) { CmsUser currentUser = SecurityHelper.CurrentCmsUser(db); if (currentUser.RoleId < RoleType.Super) { throw new Exception("Access Denided."); } //user if (string.IsNullOrEmpty(userName)) { ViewBag.Message = "User Name is Required"; return(View("error")); } userName = userName.ToLower(); CmsUser user = db.Set <CmsUser>().SingleOrDefault(e => e.AdName == userName); if (user == null && permission != PermissionType.Denied) { //new user user = new CmsUser(); user.AdName = userName; user.UserName = HtmlHelpers.FormatName(null, userName).ToString(); user.RoleId = RoleType.Normal; db.Set <CmsUser>().Add(user); db.SaveChanges(); } else if (user != null) { if (permission == PermissionType.Denied) { //remove users ClearPermissions(user); db.Set <CmsUser>().Remove(user); db.SaveChanges(); } else { if (string.IsNullOrEmpty(pageId)) { //navi int sid = Convert.ToInt32(sectionId); //handle overwrite NaviNode currentNode = db.Set <NaviNode>().Single(e => e.Id == sid); if (overwrite == true) { ClearPermissions(user); } NaviPermission np = db.Set <NaviPermission>().SingleOrDefault(e => e.Section.Id == sid && e.User.Id == user.Id); //new navi permission if (np == null) { np = new NaviPermission(); np.User = user; np.AccessMode = permission; np.Section = db.Set <NaviNode>().Single(e => e.Id == sid); db.Set <NaviPermission>().Add(np); } //modify else if (np != null) { if (permission != np.AccessMode) { np.AccessMode = permission; ((DbContext)db).Entry(np).State = EntityState.Modified; } } db.SaveChanges(); } else { //page int pid = Convert.ToInt32(pageId); PagePermission pp = db.Set <PagePermission>().SingleOrDefault(e => e.Page.Id == pid && e.User.Id == user.Id); //new page permission if (pp == null) { pp = new PagePermission(); pp.User = user; pp.AccessMode = permission; pp.Page = db.Set <CmsPage>().Single(e => e.Id == pid); db.Set <PagePermission>().Add(pp); } //modify else if (pp != null) { if (permission != pp.AccessMode) { pp.AccessMode = permission; ((DbContext)db).Entry(pp).State = EntityState.Modified; } } db.SaveChanges(); } } } ViewBag.RoleId = SecurityHelper.CurrentCmsUserRole(db); return(View("PermissionGranted")); }
private void cmdOK_Click(object sender, System.EventArgs e) { txtFirstName.Text = txtFirstName.Text.Trim(); txtLastName.Text = txtLastName.Text.Trim(); txtEmail.Text = txtEmail.Text.Trim(); txtPassword.Text = txtPassword.Text.Trim(); if (txtFirstName.Text == string.Empty) { MessageBox.Show("The first name is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtLastName.Text == string.Empty) { MessageBox.Show("The last name is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (cboCountry.SelectedIndex == 0) { MessageBox.Show("The country is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtEmail.Text == string.Empty) { MessageBox.Show("The email is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtPassword.Text == string.Empty) { MessageBox.Show("The password is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtPassword.Text != txtVerify.Text) { MessageBox.Show("The password must be verified.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ResultModel result = null; try { var model = new UserAccount(); model.FirstName = txtFirstName.Text; model.LastName = txtLastName.Text; model.City = txtCity.Text; model.Region = txtRegion.Text; model.Postcode = txtPostalCode.Text; model.Country = cboCountry.SelectedItem.ToString(); model.Email = txtEmail.Text; model.PremiumKey = txtPremium.Text; model.Password = txtPassword.Text; model.MachineKey = SecurityHelper.GetMachineID(); model.Version = VersionHelper.GetCurrentVersion(); model.AllowStats = chkStat.Checked; result = VersionHelper.RegisterUser(model); } catch (Exception ex) { MessageBox.Show("There was an error trying to register. Please visit the main nHydrate site: https://github.com/nHydrate/nHydrate.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!result.Success) { MessageBox.Show(result.Text, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var key = result.Text; //Validate premium key AddinAppData.Instance.PremiumValidated = false; //if (!string.IsNullOrEmpty(txtPremium.Text)) //{ // var result = service.VerifyPremiumKey(txtEmail.Text, txtPassword.Text, SecurityHelper.GetMachineID(), txtPremium.Text); // if (string.IsNullOrEmpty(result)) // { // AddinAppData.Instance.PremiumValidated = true; // MessageBox.Show("The premium key has been verified and applied. All application features have been enabled.", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information); // } // else // { // //Display the reason for the error // MessageBox.Show("An error has occurred while verifying your premium key. The failure reason is listed below.\n\n'" + result + "'", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Error); // } //} AddinAppData.Instance.Key = key; AddinAppData.Instance.PremiumKey = txtPremium.Text; AddinAppData.Instance.AllowStats = chkStat.Checked; AddinAppData.Instance.Save(); this.DialogResult = DialogResult.OK; this.Close(); }
/// <summary> /// 用户登录 /// </summary> /// <returns></returns> public Result <dynamic> Login(string mobile, string password) { #region 数据验证 var result = new Result <dynamic>(); if (mobile.IsNullOrEmpty()) { result.Code = ResultCode.Error; result.Message = "登录账号不能为空"; return(result); } if (password.IsNullOrEmpty()) { result.Code = ResultCode.Error; result.Message = "登录密码不能为空"; return(result); } #endregion var encryptedPwd = SecurityHelper.Encrypt(password); var member = MemberRepository.Get(mobile); if (member != null) { if (member.EncryptedPwd != encryptedPwd) { result.Code = ResultCode.Error; result.Message = "账号或者密码错误"; } string token = Guid.NewGuid().ToString().Replace("-", "").ToLower(); var cache = new RedisCacheHelper <Model.Member>(); cache.Set(token, new Model.Member() { id = member.Id, display_name = member.DisplayName }, TimeSpan.FromDays(5)); result.Code = ResultCode.Success; result.Message = "登录成功"; result.Data = new MemberLoginResponse { id = member.Id, mobile = member.MobilePhone, portrait = member.Portrait, display_name = member.DisplayName, gender = member.Gender, location_area = member.LocationArea, birthday = member.Birthday, account_balance = member.AccountBalance, amount_total = member.AmountTotal, amount_withdrawn = member.AmountWithdrawn, total_score = member.TotalScore, total_withdraw_score = member.TotalWithdrawScore, token = token }; } else { result.Code = ResultCode.Error; result.Message = "数据库操作异常"; } return(result); }