public void DeleteCustomer(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); _customerRepository.Delete(customer); }
public virtual void SignIn(Customer customer, bool createPersistentCookie) { var now = DateTime.UtcNow.ToLocalTime(); var ticket = new FormsAuthenticationTicket( 1 /*version*/, _customerSettings.UsernamesEnabled ? customer.Username : customer.Email, now, now.Add(_expirationTimeSpan), createPersistentCookie, _customerSettings.UsernamesEnabled ? customer.Username : customer.Email, FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.HttpOnly = true; if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } cookie.Secure = FormsAuthentication.RequireSSL; cookie.Path = FormsAuthentication.FormsCookiePath; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } _httpContext.Response.Cookies.Add(cookie); _cachedCustomer = customer; }
/// <summary> /// Ctor /// </summary> /// <param name="customer">Customer</param> /// <param name="email">Email</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="passwordFormat">Password fprmat</param> /// <param name="isApproved">Is approved</param> public CustomerRegistrationRequest(Customer customer, string email, string username, string password, PasswordFormat passwordFormat, bool isApproved = true) { this.Customer = customer; this.Email = email; this.Username = username; this.Password = password; this.PasswordFormat = passwordFormat; this.IsApproved = isApproved; }
private static void FilteredLog(ILogger logger, LogLevel level, string message, Exception exception = null, Customer customer = null) { //don't log thread abort exception if (exception is System.Threading.ThreadAbortException) return; if (logger.IsEnabled(level)) { string fullMessage = exception == null ? string.Empty : exception.ToString(); logger.InsertLog(level, message, fullMessage, customer); } }
public virtual Customer GetAuthenticatedCustomer() { if (_cachedCustomer != null) return _cachedCustomer; if (_httpContext == null || _httpContext.Request == null || !_httpContext.Request.IsAuthenticated || !(_httpContext.User.Identity is FormsIdentity)) { return null; } var formsIdentity = (FormsIdentity)_httpContext.User.Identity; var customer = GetAuthenticatedCustomerFromTicket(formsIdentity.Ticket); if (customer != null && customer.Active && !customer.Deleted && customer.IsRegistered()) _cachedCustomer = customer; return _cachedCustomer; }
private bool AccountDoesNotExistAndUserIsNotLoggedOn(Customer userFound, Customer userLoggedIn) { return userFound == null && userLoggedIn == null; }
public static void Warning(this ILogger logger, string message, Exception exception = null, Customer customer = null) { FilteredLog(logger, LogLevel.Warning, message, exception, customer); }
protected virtual void PrepareCustomerModel(CustomerModel model, Customer customer, bool excludeProperties) { if (customer != null) { model.Id = customer.Id; if (!excludeProperties) { model.Email = customer.Email; model.Username = customer.Username; model.Active = customer.Active; model.TimeZoneId = customer.GetAttribute<string>(SystemCustomerAttributeNames.TimeZoneId); model.VatNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.VatNumber); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc); model.LastActivityDate = _dateTimeHelper.ConvertToUserTime(customer.LastActivityDateUtc, DateTimeKind.Utc); model.LastIpAddress = customer.LastIpAddress; model.LastVisitedPage = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastVisitedPage); model.SelectedCustomerRoleIds = customer.CustomerRoles.Select(cr => cr.Id).ToArray(); //form fields model.FirstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName); model.LastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName); model.Gender = customer.GetAttribute<string>(SystemCustomerAttributeNames.Gender); model.DateOfBirth = customer.GetAttribute<DateTime?>(SystemCustomerAttributeNames.DateOfBirth); model.Company = customer.GetAttribute<string>(SystemCustomerAttributeNames.Company); model.StreetAddress = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress); model.StreetAddress2 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress2); model.ZipPostalCode = customer.GetAttribute<string>(SystemCustomerAttributeNames.ZipPostalCode); model.City = customer.GetAttribute<string>(SystemCustomerAttributeNames.City); model.CountryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId); model.StateProvinceId = customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId); model.Phone = customer.GetAttribute<string>(SystemCustomerAttributeNames.Phone); model.Fax = customer.GetAttribute<string>(SystemCustomerAttributeNames.Fax); } } model.UsernamesEnabled = _customerSettings.UsernamesEnabled; model.AllowUsersToChangeUsernames = _customerSettings.AllowUsersToChangeUsernames; model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone; foreach (var tzi in _dateTimeHelper.GetSystemTimeZones()) model.AvailableTimeZones.Add(new SelectListItem { Text = tzi.DisplayName, Value = tzi.Id, Selected = (tzi.Id == model.TimeZoneId) }); model.DisplayVatNumber = false; model.GenderEnabled = _customerSettings.GenderEnabled; model.DateOfBirthEnabled = _customerSettings.DateOfBirthEnabled; model.CompanyEnabled = _customerSettings.CompanyEnabled; model.StreetAddressEnabled = _customerSettings.StreetAddressEnabled; model.StreetAddress2Enabled = _customerSettings.StreetAddress2Enabled; model.ZipPostalCodeEnabled = _customerSettings.ZipPostalCodeEnabled; model.CityEnabled = _customerSettings.CityEnabled; model.CountryEnabled = _customerSettings.CountryEnabled; model.StateProvinceEnabled = _customerSettings.StateProvinceEnabled; model.PhoneEnabled = _customerSettings.PhoneEnabled; model.FaxEnabled = _customerSettings.FaxEnabled; //customer roles model.AvailableCustomerRoles = _customerService .GetAllCustomerRoles(true) .Select(cr => cr.ToModel()) .ToList(); model.AddRewardPointsValue = 0; model.AddRewardPointsMessage = "Some comment here..."; //external authentication records if (customer != null) { model.AssociatedExternalAuthRecords = GetAssociatedExternalAuthRecords(customer); } //sending of the welcome message: //1. "admin approval" registration method //2. already created customer //3. registered model.AllowSendingOfWelcomeMessage = _customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval && customer != null && customer.IsRegistered(); //sending of the activation message //1. "email validation" registration method //2. already created customer //3. registered //4. not active model.AllowReSendingOfActivationMessage = _customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && customer != null && customer.IsRegistered() && !customer.Active; }
protected virtual IList<CustomerModel.AssociatedExternalAuthModel> GetAssociatedExternalAuthRecords(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); var result = new List<CustomerModel.AssociatedExternalAuthModel>(); foreach (var record in _openAuthenticationService.GetExternalIdentifiersFor(customer)) { var method = _openAuthenticationService.LoadExternalAuthenticationMethodBySystemName(record.ProviderSystemName); if (method == null) continue; result.Add(new CustomerModel.AssociatedExternalAuthModel { Id = record.Id, Email = record.Email, ExternalIdentifier = record.ExternalIdentifier, AuthMethodName = "" }); } return result; }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="customer">The customer to associate log record with</param> /// <returns>A log item</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { return null; }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="customer">The customer to associate log record with</param> /// <returns>A log item</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { //check ignore word/phrase list? if (IgnoreLog(shortMessage) || IgnoreLog(fullMessage)) return null; var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), Customer = customer, PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; _logRepository.Insert(log); return log; }
/// <summary> /// Sets a customer username /// </summary> /// <param name="customer">Customer</param> /// <param name="newUsername">New Username</param> public virtual void SetUsername(Customer customer, string newUsername) { if (customer == null) throw new ArgumentNullException("customer"); if (!_customerSettings.UsernamesEnabled) throw new NopException("Usernames are disabled"); if (!_customerSettings.AllowUsersToChangeUsernames) throw new NopException("Changing usernames is not allowed"); newUsername = newUsername.Trim(); if (newUsername.Length > 100) throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong")); var user2 = _customerService.GetCustomerByUsername(newUsername); if (user2 != null && customer.Id != user2.Id) throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameAlreadyExists")); customer.Username = newUsername; _customerService.UpdateCustomer(customer); }
private bool AccountAlreadyExists(Customer userFound, Customer userLoggedIn) { return userFound != null && userLoggedIn != null; }
/// <summary> /// Authorize permission /// </summary> /// <param name="permission">Permission record</param> /// <param name="customer">Customer</param> /// <returns>true - authorized; otherwise, false</returns> public virtual bool Authorize(PermissionRecord permission, Customer customer) { if (permission == null) return false; if (customer == null) return false; //old implementation of Authorize method //var customerRoles = customer.CustomerRoles.Where(cr => cr.Active); //foreach (var role in customerRoles) // foreach (var permission1 in role.PermissionRecords) // if (permission1.SystemName.Equals(permission.SystemName, StringComparison.InvariantCultureIgnoreCase)) // return true; //return false; return Authorize(permission.SystemName, customer); }
/// <summary> /// Authorize permission /// </summary> /// <param name="permissionRecordSystemName">Permission record system name</param> /// <param name="customer">Customer</param> /// <returns>true - authorized; otherwise, false</returns> public virtual bool Authorize(string permissionRecordSystemName, Customer customer) { if (String.IsNullOrEmpty(permissionRecordSystemName)) return false; var customerRoles = customer.CustomerRoles.Where(cr => cr.Active); foreach (var role in customerRoles) if (Authorize(permissionRecordSystemName, role)) //yes, we have such permission return true; //no permission found return false; }
public ActionResult Create(CustomerModel model, bool continueEditing, FormCollection form) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageCustomers)) return AccessDeniedView(); if (!String.IsNullOrWhiteSpace(model.Email)) { var cust2 = _customerService.GetCustomerByEmail(model.Email); if (cust2 != null) ModelState.AddModelError("", "Email is already registered"); } if (!String.IsNullOrWhiteSpace(model.Username) & _customerSettings.UsernamesEnabled) { var cust2 = _customerService.GetCustomerByUsername(model.Username); if (cust2 != null) ModelState.AddModelError("", "Username is already registered"); } //validate customer roles var allCustomerRoles = _customerService.GetAllCustomerRoles(true); var newCustomerRoles = new List<CustomerRole>(); foreach (var customerRole in allCustomerRoles) if (model.SelectedCustomerRoleIds != null && model.SelectedCustomerRoleIds.Contains(customerRole.Id)) newCustomerRoles.Add(customerRole); var customerRolesError = ValidateCustomerRoles(newCustomerRoles); if (!String.IsNullOrEmpty(customerRolesError)) { ModelState.AddModelError("", customerRolesError); ErrorNotification(customerRolesError, false); } if (ModelState.IsValid) { var customer = new Customer { CustomerGuid = Guid.NewGuid(), Email = model.Email, Username = model.Username, Active = model.Active, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; _customerService.InsertCustomer(customer); //form fields if (_dateTimeSettings.AllowCustomersToSetTimeZone) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId); if (_customerSettings.GenderEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender); _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName); _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName); if (_customerSettings.DateOfBirthEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, model.DateOfBirth); if (_customerSettings.CompanyEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company); if (_customerSettings.StreetAddressEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress); if (_customerSettings.StreetAddress2Enabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2); if (_customerSettings.ZipPostalCodeEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode); if (_customerSettings.CityEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City); if (_customerSettings.CountryEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId); if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.StateProvinceId); if (_customerSettings.PhoneEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone); if (_customerSettings.FaxEnabled) _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax); //TODO:Muh_bakılacak //custom customer attributes //var customerAttributes = ParseCustomCustomerAttributes(customer, form); //_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomCustomerAttributes, customerAttributes); //password if (!String.IsNullOrWhiteSpace(model.Password)) { var changePassRequest = new ChangePasswordRequest(model.Email, false, _customerSettings.DefaultPasswordFormat, model.Password); var changePassResult = _customerRegistrationService.ChangePassword(changePassRequest); if (!changePassResult.Success) { foreach (var changePassError in changePassResult.Errors) ErrorNotification(changePassError); } } //customer roles foreach (var customerRole in newCustomerRoles) { //ensure that the current customer cannot add to "Administrators" system role if he's not an admin himself if (customerRole.SystemName == SystemCustomerRoleNames.Administrators && !_workContext.CurrentCustomer.IsAdmin()) continue; customer.CustomerRoles.Add(customerRole); } _customerService.UpdateCustomer(customer); //activity log _customerActivityService.InsertActivity("AddNewCustomer", _localizationService.GetResource("ActivityLog.AddNewCustomer"), customer.Id); SuccessNotification(_localizationService.GetResource("Admin.Customers.Customers.Added")); return continueEditing ? RedirectToAction("Edit", new { id = customer.Id }) : RedirectToAction("List"); } //If we got this far, something failed, redisplay form PrepareCustomerModel(model, null, true); return View(model); }
protected virtual CustomerModel PrepareCustomerModelForList(Customer customer) { return new CustomerModel { Id = customer.Id, Email = customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest"), Username = customer.Username, CustomerRoleNames = GetCustomerRolesNames(customer.CustomerRoles.ToList()), Active = customer.Active, CreatedOn = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc), LastActivityDate = _dateTimeHelper.ConvertToUserTime(customer.LastActivityDateUtc, DateTimeKind.Utc), }; }
/// <summary> /// Sets a user email /// </summary> /// <param name="customer">Customer</param> /// <param name="newEmail">New email</param> public virtual void SetEmail(Customer customer, string newEmail) { if (customer == null) throw new ArgumentNullException("customer"); if (newEmail == null) throw new NopException("Email cannot be null"); newEmail = newEmail.Trim(); string oldEmail = customer.Email; if (!CommonHelper.IsValidEmail(newEmail)) throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid")); if (newEmail.Length > 100) throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong")); var customer2 = _customerService.GetCustomerByEmail(newEmail); if (customer2 != null && customer.Id != customer2.Id) throw new NopException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists")); customer.Email = newEmail; _customerService.UpdateCustomer(customer); }
private bool AccountIsAssignedToLoggedOnAccount(Customer userFound, Customer userLoggedIn) { return userFound.Id.Equals(userLoggedIn.Id); }
/// <summary> /// Gets a customer time zone /// </summary> /// <param name="customer">Customer</param> /// <returns>Customer time zone; if customer is null, then default store time zone</returns> public virtual TimeZoneInfo GetCustomerTimeZone(Customer customer) { //registered user TimeZoneInfo timeZoneInfo = null; if (_dateTimeSettings.AllowCustomersToSetTimeZone) { string timeZoneId = string.Empty; if (customer != null) timeZoneId = customer.GetAttribute<string>(SystemCustomerAttributeNames.TimeZoneId, _genericAttributeService); try { if (!String.IsNullOrEmpty(timeZoneId)) timeZoneInfo = FindTimeZoneById(timeZoneId); } catch (Exception exc) { Debug.Write(exc.ToString()); } } //default timezone if (timeZoneInfo == null) timeZoneInfo = this.DefaultStoreTimeZone; return timeZoneInfo; }
protected virtual void InstallCustomersAndUsers(string defaultUserEmail, string defaultUserPassword) { var crAdministrators = new CustomerRole { Name = "Administrators", Active = true, IsSystemRole = true, SystemName = SystemCustomerRoleNames.Administrators, }; var crForumModerators = new CustomerRole { Name = "Forum Moderators", Active = true, IsSystemRole = true, SystemName = SystemCustomerRoleNames.ForumModerators, }; var crRegistered = new CustomerRole { Name = "Registered", Active = true, IsSystemRole = true, SystemName = SystemCustomerRoleNames.Registered, }; var crGuests = new CustomerRole { Name = "Guests", Active = true, IsSystemRole = true, SystemName = SystemCustomerRoleNames.Guests, }; var crVendors = new CustomerRole { Name = "Vendors", Active = true, IsSystemRole = true, SystemName = SystemCustomerRoleNames.Vendors, }; var customerRoles = new List<CustomerRole> { crAdministrators, crForumModerators, crRegistered, crGuests, crVendors }; _customerRoleRepository.Insert(customerRoles); //admin user var adminUser = new Customer { CustomerGuid = Guid.NewGuid(), Email = defaultUserEmail, Username = defaultUserEmail, Password = defaultUserPassword, PasswordFormat = PasswordFormat.Clear, PasswordSalt = "", Active = true, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; var defaultAdminUserAddress = new Address { Name = "Muharremm haliloðlu", Address1 = "beykoz", Address2 = "" }; adminUser.Addresses.Add(defaultAdminUserAddress); adminUser.CustomerRoles.Add(crAdministrators); adminUser.CustomerRoles.Add(crForumModerators); adminUser.CustomerRoles.Add(crRegistered); _customerRepository.Insert(adminUser); //set default customer name //_genericAttributeService.SaveAttribute(adminUser, SystemCustomerAttributeNames.FirstName, "John"); //_genericAttributeService.SaveAttribute(adminUser, SystemCustomerAttributeNames.LastName, "Smith"); //search engine (crawler) built-in user var searchEngineUser = new Customer { Email = "builtin@search_engine_record.com", CustomerGuid = Guid.NewGuid(), PasswordFormat = PasswordFormat.Clear, Active = true, IsSystemAccount = true, SystemName = SystemCustomerNames.SearchEngine, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; searchEngineUser.CustomerRoles.Add(crGuests); _customerRepository.Insert(searchEngineUser); //built-in user for background tasks var backgroundTaskUser = new Customer { Email = "*****@*****.**", CustomerGuid = Guid.NewGuid(), PasswordFormat = PasswordFormat.Clear, Active = true, IsSystemAccount = true, SystemName = SystemCustomerNames.BackgroundTask, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; backgroundTaskUser.CustomerRoles.Add(crGuests); _customerRepository.Insert(backgroundTaskUser); }
public virtual void SignOut() { _cachedCustomer = null; FormsAuthentication.SignOut(); }
/// <summary> /// Insert a guest customer /// </summary> /// <returns>Customer</returns> public virtual Customer InsertGuestCustomer() { var customer = new Customer { CustomerGuid = Guid.NewGuid(), Active = true, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; //add to 'Guests' role var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests); if (guestRole == null) throw new NopException("'Guests' role could not be loaded"); customer.CustomerRoles.Add(guestRole); _customerRepository.Insert(customer); return customer; }
public void UpdateCustomer(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); _customerRepository.Update(customer); //event notification _eventPublisher.EntityUpdated(customer); }
/// <summary> /// Inserts an activity log item /// </summary> /// <param name="systemKeyword">The system keyword</param> /// <param name="comment">The activity comment</param> /// <param name="customer">The customer</param> /// <param name="commentParams">The activity comment parameters for string.Format() function.</param> /// <returns>Activity log item</returns> public virtual ActivityLog InsertActivity(string systemKeyword, string comment, Customer customer, params object[] commentParams) { if (customer == null) return null; var activityTypes = GetAllActivityTypesCached(); var activityType = activityTypes.ToList().Find(at => at.SystemKeyword == systemKeyword); if (activityType == null || !activityType.Enabled) return null; comment = CommonHelper.EnsureNotNull(comment); comment = string.Format(comment, commentParams); comment = CommonHelper.EnsureMaximumLength(comment, 4000); var activity = new ActivityLog(); activity.ActivityLogTypeId = activityType.Id; activity.Customer = customer; activity.Comment = comment; activity.CreatedOnUtc = DateTime.UtcNow; _activityLogRepository.Insert(activity); return activity; }