public virtual void SignIn(User user, bool createPersistentCookie) {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1,
                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;

            var userContext = new UserContext { User = user };
            foreach(var authenticationEventHandler in _authenticationEventHandlers) {
                authenticationEventHandler.SignIn(userContext);
            }

        }
 public virtual void SignOut() {
     _cachedUser = null;
     foreach (var authenticationEventHandler in _authenticationEventHandlers) {
         authenticationEventHandler.SignOut();
     }
     FormsAuthentication.SignOut();
 }
示例#3
0
        protected virtual void PrepareUserModel(UserModel model, User user, bool excludeProperties) {
            if (user != null) {
                model.Id = user.Id;
                if (!excludeProperties) {
                    model.Email = user.Email;
                    model.Username = user.Username;
                    model.AdminComment = user.AdminComment;
                    model.Active = user.Active;

                    model.CreatedOnUtc = _dateTimeHelper.ConvertToUserTime(user.CreatedOnUtc, DateTimeKind.Utc);
                    model.LastActivityDateUtc = _dateTimeHelper.ConvertToUserTime(user.LastActivityDateUtc, DateTimeKind.Utc);
                    model.LastIpAddress = user.LastIpAddress;

                    model.SelectedUserRoleIds = user.UserRoles.Select(cr => cr.Id).ToArray();
                }
            }

            //user roles
            model.AvailableUserRoles = _userService
                .GetAllUserRoles(true)
                .Select(cr => cr.ToModel())
                .ToList();
            //department
            foreach (var at in _departmentService.GetAll()) {
                model.AvailableDepartments.Add(new SelectListItem {
                    Value = at.Id.ToString(),
                    Text = at.GetFormattedBreadCrumb(_departmentService),
                    Selected = (user != null && user.DepartmentId == at.Id)
                });
            }
        }
示例#4
0
 protected virtual UserModel PrepareUserModelForList(User user) {
     return new UserModel {
         Id = user.Id,
         UserGuid = user.UserGuid,
         Email = user.Email,
         Username = user.Username,
         UserRoleNames = GetUserRolesNames(user.UserRoles.ToList()),
         Active = user.Active,
         DepartmentModel = user.Department.ToModel(),
         CreatedOnUtc = _dateTimeHelper.ConvertToUserTime(user.CreatedOnUtc),
         LastActivityDateUtc = _dateTimeHelper.ConvertToUserTime(user.LastActivityDateUtc),
     };
 }
示例#5
0
        /// <summary>
        /// Inserts the activity.
        /// </summary>
        /// <param name="systemKeyword">The system keyword.</param>
        /// <param name="comment">The comment.</param>
        /// <param name="user">The user.</param>
        /// <param name="commentParams">The comment parameters.</param>
        /// <returns></returns>
        public virtual ActivityLog InsertActivity(string systemKeyword,
            string comment, User user, params object[] commentParams) {
            if (user == 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.User = user;
            activity.Comment = comment;
            activity.CreatedOnUtc = DateTime.UtcNow;

            _activityLogRepository.Insert(activity);

            return activity;
        }
        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.Active && !user.Deleted && user.IsRegistered())
                _cachedUser = user;
            return _cachedUser;
        }
        protected virtual void InstallUsersAndRoles(string defaultUsername, string defaultUserPassword) {
            var crAdministrators = new UserRole {
                Name = "Administrators",
                Active = true,
                IsSystemRole = true,
                SystemName = SystemUserRoleNames.Administrators,
            };
            _userRoleRepository.Insert(crAdministrators);

            var crRegistered = new UserRole {
                Name = "Registered",
                Active = true,
                IsSystemRole = true,
                SystemName = SystemUserRoleNames.Registered,
            };
            _userRoleRepository.Insert(crRegistered);

            var crGuests = new UserRole {
                Name = "Guests",
                Active = true,
                IsSystemRole = true,
                SystemName = SystemUserRoleNames.Guests,
            };
            _userRoleRepository.Insert(crGuests);

            //admin user
            var adminUser = new User {
                UserGuid = Guid.NewGuid(),
                Email = "",
                Username = defaultUsername,
                Password = defaultUserPassword,
                PasswordFormat = PasswordFormat.Clear,
                PasswordSalt = "",
                Active = true,
                DepartmentId = 1,
                CreatedOnUtc = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow,
            };

            adminUser.UserRoles.Add(crAdministrators);
            adminUser.UserRoles.Add(crRegistered);
            _userRepository.Insert(adminUser);

        }
示例#8
0
        /// <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, User user) {
            if (String.IsNullOrEmpty(permissionRecordSystemName))
                return false;

            var permissionContext = new PermissionContext { User = user, PermissionRecordSystemName = permissionRecordSystemName };
            foreach (var permissionEventHandler in _permissionEventHandlers)
                permissionEventHandler.Authorize(permissionContext);

            var userRoles = user.UserRoles.Where(cr => cr.Active);
            foreach (var role in userRoles)
                if (Authorize(permissionRecordSystemName, role))
                    //yes, we have such permission
                    return true;

            //no permission found
            return false;
        }
示例#9
0
        /// <summary>
        /// Insert a guest User
        /// </summary>
        /// <returns>User</returns>
        public virtual User InsertGuestUser() {
            var User = new User {
                UserGuid = Guid.NewGuid(),
                Active = true,
                CreatedOnUtc = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow,
                DepartmentId = 1
            };

            //add to 'Guests' role
            var guestRole = GetUserRoleBySystemName(SystemUserRoleNames.Guests);
            if (guestRole == null)
                throw new NutException("'Guests' role could not be loaded");
            User.UserRoles.Add(guestRole);

            _userRepository.Insert(User);

            return User;
        }
示例#10
0
        /// <summary>
        /// Authorizes the specified permissions.
        /// </summary>
        /// <param name="permissions">The permissions.</param>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        public bool Authorize(IEnumerable<PermissionRecord> permissions, User user) {
            foreach (var permission in permissions)
                if (Authorize(permission, user))
                    //yes, we have such permission
                    return true;

            //no permission found
            return false;
        }
示例#11
0
        public ActionResult Create(UserModel model, bool continueEditing, FormCollection form) {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageUsers))
                return AccessDeniedView();

            if (!String.IsNullOrWhiteSpace(model.Username)) {
                var cust2 = _userService.GetUserByUsername(model.Username);
                if (cust2 != null)
                    ModelState.AddModelError("", "Username is already registered");
            }

            //validate customer roles
            var allUserRoles = _userService.GetAllUserRoles(true);
            var newUserRoles = new List<UserRole>();
            foreach (var customerRole in allUserRoles)
                if (model.SelectedUserRoleIds != null && model.SelectedUserRoleIds.Contains(customerRole.Id))
                    newUserRoles.Add(customerRole);
            var userRolesError = ValidateUserRoles(newUserRoles);
            if (!String.IsNullOrEmpty(userRolesError)) {
                ModelState.AddModelError("", userRolesError);
                ErrorNotification(userRolesError, false);
            }

            if (ModelState.IsValid) {
                var user = new User {
                    UserGuid = Guid.NewGuid(),
                    Email = model.Email,
                    Username = model.Username,
                    AdminComment = model.AdminComment,
                    Active = model.Active,
                    Deleted = model.Deleted,
                    DepartmentId = model.DepartmentId,
                    CreatedOnUtc = DateTime.UtcNow,
                    LastActivityDateUtc = DateTime.UtcNow,
                };
                _userService.InsertUser(user);


                //password
                if (!String.IsNullOrWhiteSpace(model.Password)) {
                    var changePassRequest = new ChangePasswordRequest(model.Username, false, PasswordFormat.Hashed, model.Password);
                    var changePassResult = _userRegistrationService.ChangePassword(changePassRequest);
                    if (!changePassResult.Success) {
                        foreach (var changePassError in changePassResult.Errors)
                            ErrorNotification(changePassError);
                    }
                }

                //customer roles
                foreach (var userRole in newUserRoles) {
                    //ensure that the current customer cannot add to "Administrators" system role if he's not an admin himself
                    if (userRole.SystemName == SystemUserRoleNames.Administrators &&
                        !_workContext.CurrentUser.IsAdmin())
                        continue;

                    user.UserRoles.Add(userRole);
                }
                _userService.UpdateUser(user);

                //activity log
                // _customerActivityService.InsertActivity("AddNewCustomer", _localizationService.GetResource("ActivityLog.AddNewCustomer"), user.Id);

                SuccessNotification(_localizationService.GetResource("Admin.Customers.Customers.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = user.Id }) : RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            PrepareUserModel(model, null, true);
            return View(model);

        }
示例#12
0
        /// <summary>
        /// Updates the User
        /// </summary>
        /// <param name="user">User</param>
        public virtual void UpdateUser(User user) {
            if (user == null)
                throw new ArgumentNullException("User");

            _userRepository.Update(user);
        }
示例#13
0
        /// <summary>
        /// Insert a User
        /// </summary>
        /// <param name="user">User</param>
        public virtual void InsertUser(User user) {
            if (user == null)
                throw new ArgumentNullException("User");

            var userContext = new UserContext { User = user, Cancel = false };
            foreach(var userEventHandler in _userEventHandlers) {
                userEventHandler.Creating(userContext);
            }

            _userRepository.Insert(user);


            foreach (var userEventHandler in _userEventHandlers) {
                userEventHandler.Created(userContext);
            }
        }
示例#14
0
        /// <summary>
        /// Sets a user email
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="newEmail">New email</param>
        public virtual void SetEmail(User user, string newEmail) {
            if (user == null)
                throw new ArgumentNullException("customer");

            if (newEmail == null)
                throw new NutException("Email cannot be null");

            newEmail = newEmail.Trim();
            string oldEmail = user.Email;

            if (!CommonHelper.IsValidEmail(newEmail))
                throw new NutException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));

            if (newEmail.Length > 100)
                throw new NutException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));

            var customer2 = _userService.GetUserByEmail(user.Email);
            if (customer2 != null && user.Id != customer2.Id)
                throw new NutException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));

            user.Email = newEmail;
            _userService.UpdateUser(user);

        }
示例#15
0
        /// <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;

            return Authorize(permission.SystemName, user);
        }
示例#16
0
        /// <summary>
        /// Sets a customer username
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="newUsername">New Username</param>
        public virtual void SetUsername(User user, string newUsername) {
            if (user == null)
                throw new ArgumentNullException("customer");

            newUsername = newUsername.Trim();

            if (newUsername.Length > 100)
                throw new NutException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong"));

            var user2 = _userService.GetUserByUsername(user.Username);
            if (user2 != null && user.Id != user2.Id)
                throw new NutException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameAlreadyExists"));

            user.Username = newUsername;
            _userService.UpdateUser(user);
        }
示例#17
0
        /// <summary>
        /// Delete a User
        /// </summary>
        /// <param name="User">User</param>
        public virtual void DeleteUser(User User) {
            if (User == null)
                throw new ArgumentNullException("User");

            if (User.IsSystemAccount)
                throw new NutException(string.Format("System User account ({0}) could not be deleted", User.Username));

            User.Deleted = true;

            UpdateUser(User);
        }