private static void FilteredLog(ILogger logger, LogLevel level, string message, Exception exception = null, User user = null) { //don't log thread abort exception if ((exception != null) && (exception is System.Threading.ThreadAbortException)) return; if (logger.IsEnabled(level)) { string fullMessage = exception == null ? string.Empty : exception.ToString(); logger.Insert(level, message, fullMessage, user); } }
public virtual void AddUserTokens(IList<Token> tokens, User user) { tokens.Add(new Token("User.Username", user.Username)); tokens.Add(new Token("User.FullName", user.FormatUserName())); string accountActivationUrl = "{0}{1}".FormatWith(webHelper.AbsoluteWebRoot.ToString(), SystemRouteUrls.AccountActivation.Replace("{userId}", user.UserGuid.ToString()).Replace("{token}", user.GetAttribute<string>(SystemUserAttributeNames.AccountActivationToken))); tokens.Add(new Token("User.AccountActivationURL", accountActivationUrl, true)); string passwordRecoveryUrl = "{0}{1}".FormatWith(webHelper.AbsoluteWebRoot.ToString(), SystemRouteUrls.PasswordRecoveryConfirm.Replace("{userId}", user.UserGuid.ToString()).Replace("{token}", user.GetAttribute<string>(SystemUserAttributeNames.PasswordRecoveryToken))); tokens.Add(new Token("User.PasswordRecoveryURL", passwordRecoveryUrl, true)); }
/// <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, User user) { if (permission == null) return false; if (user == null) return false; var userRoles = user.UserRoles.Where(cr => cr.Active); foreach (var role in userRoles) foreach (var permission1 in role.PermissionRecords) if (permission1.SystemName.Equals(permission.SystemName, StringComparison.InvariantCultureIgnoreCase)) return true; return false; }
/// <summary> /// Sends an email with the password recovery message to the user /// </summary> /// <param name="user">user instance</param> /// <param name="languageId">Message language identifier</param> /// <returns>Queued email identifier</returns> public virtual Guid SendUserPasswordRecoveryMessage(User user, Guid languageId) { Guard.IsNotNull(user, "user"); languageId = EnsureLanguageIsActive(languageId); var messageTemplate = GetLocalizedActiveMessageTemplate("User.PasswordRecovery", languageId); if (messageTemplate == null) return Guid.Empty; var userTokens = GenerateTokens(user); var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId); var toEmail = user.Username; var toName = user.GetFullName(); return SendNotification(messageTemplate, emailAccount, languageId, userTokens, toEmail, toName); }
/// <summary> /// Get an authenticated user details /// </summary> /// <returns></returns> public virtual User GetAuthenticatedUser() { if (_cachedUser != null) return _cachedUser; if (httpContext == null || httpContext.Request == null || !httpContext.Request.IsAuthenticated || !(httpContext.User.Identity is FormsIdentity)) { return null; } var formsIdentity = (FormsIdentity)httpContext.User.Identity; var user = GetAuthenticatedUserFromTicket(formsIdentity.Ticket); if (user != null && user.CurrentPublishingStatus == PublishingStatus.Active && user.IsRegistered()) _cachedUser = user; return _cachedUser; }
private UserModel PrepareUserModel(User user) { Guard.IsNotNull(user, "user"); var model = new UserModel() { RowId = user.RowId, Username = user.Username, FirstName = encryptionService.AESDecrypt( user.GetAttribute<string>(SystemUserAttributeNames.FirstName), user), LastName = encryptionService.AESDecrypt( user.GetAttribute<string>(SystemUserAttributeNames.LastName), user), UserRoleNames = user.UserRoles.Select(ur => ur.Name).ToDelimitedString(", "), CreatedOn = user.CreatedOn.ToString(StateKeyManager.DateFormat), LastActivityDate = user.LastActivityDate.HasValue ? user.LastActivityDate.Value.ToString(StateKeyManager.DateTimeFormat) : string.Empty }; PrepareOfficeAssociationModel(model, user, officeService, cacheManager); PrepareAuditHistoryModel(model, user); return model; }
/// <summary> /// Authorize role /// </summary> /// <param name="role">User Role record</param> /// <param name="user">User</param> /// <returns>true - authorized; otherwise, false</returns> public virtual bool AuthorizeRole(UserRole role, User user) { if (role == null) return false; if (user == null) return false; var userRoles = user.UserRoles.Where(ur => ur.Active); foreach (var userRole in userRoles) if (userRole.SystemName.Equals(role.SystemName, StringComparison.InvariantCultureIgnoreCase)) return true; return false; }
protected User GetCurrentUser() { if (_cachedUser != null) return _cachedUser; User user = null; if (httpContext != null) { //registered user if (user == null) { user = authenticationService.GetAuthenticatedUser(); } //impersonate user if required (currently used for 'phone order' support) if (user != null && user.CurrentPublishingStatus == PublishingStatus.Active) { Guid? impersonatedUserId = user.GetAttribute<Guid?>(SystemUserAttributeNames.ImpersonatedUserId); if (impersonatedUserId.HasValue && !impersonatedUserId.Value.IsEmpty()) { var impersonatedUser = userservice.GetById(impersonatedUserId.Value); if (impersonatedUser != null && impersonatedUser.CurrentPublishingStatus == PublishingStatus.Active) { //set impersonated user _originalUserIfImpersonated = user; user = impersonatedUser; } } } } //validation if (user != null && user.CurrentPublishingStatus == PublishingStatus.Active) { //update last activity date bool updateLastActivity = false; if (user.LastActivityDate.HasValue) { if (user.LastActivityDate.Value.AddMinutes(1.0) < DateTime.UtcNow) { updateLastActivity = true; } } else updateLastActivity = true; if (updateLastActivity) { user.LastActivityDate = DateTime.UtcNow; userservice.Update(user); } _cachedUser = user; } return _cachedUser; }
/// <summary> /// Sign out a user /// </summary> public void SignOut() { // call the authentication service to logout the user authenticationService.SignOut(); _cachedUser = null; }
/// <summary> /// Register User /// </summary> /// <param name="request">Request</param> /// <returns>Result</returns> public virtual DataResult<User> RegisterUser(UserRegistrationRequest request) { Guard.IsNotNull(request, "Request"); var result = new DataResult<User>(); if (!CommonHelper.IsValidEmail(request.Username)) { result.AddError(this.localizationService.GetResource("Common.WrongEmail")); return result; } if (String.IsNullOrWhiteSpace(request.Password)) { result.AddError(this.localizationService.GetResource("Users.Fields.Password")); return result; } //validate unique user if (!this.userService.IsUnique(request.Username)) { result.AddError(this.localizationService.GetResource("Users.Fields.Username.NotUnique")); return result; } var user = new User() { CreatedOn = DateTime.UtcNow, Username = request.Username, Password = request.Password, // we have already encrypted the password on client side CurrentPublishingStatus = request.CurrentPublishingStatus, // whether its an active user }; //add to 'Registered' role var registeredRole = this.userService.GetUserRoleBySystemName(SystemUserRoleNames.Users); if ( registeredRole == null ) throw new SiteException("'" + SystemUserRoleNames.Users + "' role could not be loaded"); user.UserRoles.Add(registeredRole); // if administrator if (request.IsAdministrator) { // set the enterprise administrator role var administratorRole = this.userService.GetUserRoleBySystemName(SystemUserRoleNames.Administrators); if (administratorRole == null) throw new SiteException("'" + SystemUserRoleNames.Administrators + "' role could not be loaded"); user.UserRoles.Add(administratorRole); } // add audit history user.AuditHistory.Add ( userActivityService.InsertActivity(SystemActivityLogTypeNames.Add, user.ToString(), StateKeyManager.USER_ACTIVITY_COMMENT, request.Username) ); // insert the user this.userService.Insert(user); // upadate attributes attributeService.SaveAttribute(user, SystemUserAttributeNames.FirstName, encryptionService.AESEncrypt(request.FirstName, user)); attributeService.SaveAttribute(user, SystemUserAttributeNames.LastName, encryptionService.AESEncrypt(request.LastName, user)); if ( !string.IsNullOrEmpty(request.Mobile)) attributeService.SaveAttribute(user, SystemUserAttributeNames.Mobile, encryptionService.AESEncrypt( request.Mobile,user)); // create activation token attributeService.SaveAttribute(user, SystemUserAttributeNames.AccountActivationToken, Guid.NewGuid().ToString()); // set the data result result.Data = user; 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 Log Insert(LogLevel logLevel, string shortMessage, string fullMessage = "", User user = null) { return null; }
private IList<Token> GenerateTokens(User user) { var tokens = new List<Token>(); messageTokenProvider.AddDefaultTokens(tokens); messageTokenProvider.AddUserTokens(tokens, user); return tokens; }
/// <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 Insert(LogLevel logLevel, string shortMessage, string fullMessage = "", User user = null) { var log = new Log() { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = webHelper.GetCurrentIpAddress(), User = user, PageUrl = webHelper.GetThisPageUrl(true), ReferrerUrl = webHelper.GetUrlReferrer(), CreatedOn = DateTime.UtcNow }; logRepository.Insert(log); return log; }
public static void Warning(this ILogger logger, string message, Exception exception = null, User user = null) { FilteredLog(logger, LogLevel.Warning, message, exception, user); }
/// <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 GetUserTimeZone(User user) { //registered user TimeZoneInfo timeZoneInfo = null; if (dateTimeSettings.AllowUsersToSetTimeZone) { string timeZoneId = string.Empty; if (user != null) timeZoneId = user.TimeZoneId; try { if (!String.IsNullOrEmpty(timeZoneId)) timeZoneInfo = FindTimeZoneById(timeZoneId); } catch (Exception exc) { Debug.Write(exc.ToString()); } } //default timezone if (timeZoneInfo == null) timeZoneInfo = this.DefaultTimeZone; return timeZoneInfo; }
/// <summary> /// Validate a user login /// </summary> /// <param name="user"></param> public virtual void SignIn(User user, bool createPersistentCookie) { var now = DateTime.UtcNow.ToLocalTime(); var ticket = new FormsAuthenticationTicket( 1 /*version*/, user.Username, now, now.Add(expirationTimeSpan), createPersistentCookie, user.Username, 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); _cachedUser = user; // user valid login credentials user.FailedPasswordAttemptCount = 0; userService.Update(user); // reset invalid credentials count EngineContext.Current.Resolve<IUserActivityService>().LoginHistory(); }
/// <summary> /// Sign out a user /// </summary> public virtual void SignOut() { _cachedUser = null; // sign out of form authentication also FormsAuthentication.SignOut(); }