public void MembershipRole_GetRolesForUserTests()
        {
            string[] results;
            string   userName;

            //-------------------------------------------------------
            // existing user with roles
            //-------------------------------------------------------
            userName = TestUtils.Users[6].Username;
            results  = _provider.GetRolesForUser(userName);
            Assert.IsNotNull(results);
            Assert.AreEqual(3, results.Length);
            Assert.AreEqual <string>(TestUtils.ProviderRoles[1], results[0]);
            Assert.AreEqual <string>(TestUtils.ProviderRoles[2], results[1]);
            Assert.AreEqual <string>(TestUtils.ProviderRoles[3], results[2]);

            //-------------------------------------------------------
            // existing user without roles
            //-------------------------------------------------------
            userName = TestUtils.Users[12].Username;
            results  = _provider.GetRolesForUser(userName);
            Assert.IsNotNull(results);
            Assert.AreEqual(0, results.Length);

            //-------------------------------------------------------
            // null usernmae
            //-------------------------------------------------------
            userName = null;
            try
            {
                results = _provider.GetRolesForUser(userName);
                Assert.Fail("Provider did not throw expected ArgumentNullException");
            }
            catch (ArgumentNullException)
            {
                //ignore expected exception
            }

            //-------------------------------------------------------
            // empty username
            //-------------------------------------------------------
            userName = string.Empty;
            try
            {
                results = _provider.GetRolesForUser(userName);
                Assert.Fail("Provider did not throw expected ArgumentException");
            }
            catch (ArgumentException)
            {
                //ignore expected exception
            }
        }
Exemplo n.º 2
0
        public ActionResult Edit(Guid id)
        {
            if (id != User.Id() && !User.IsInRole(Definitions.Roles.Administrator))
            {
                return(RedirectToAction("Unauthorized", "Home"));
            }

            if (MembershipService.IsReadOnly())
            {
                return(RedirectToAction("Detail", "Account", new { id = id }));
            }

            var user = MembershipService.GetUserModel(id);

            if (user != null)
            {
                var model = new UserEditModel
                {
                    Id            = user.Id,
                    Username      = user.Username,
                    Name          = user.GivenName,
                    Surname       = user.Surname,
                    Email         = user.Email,
                    Roles         = RoleProvider.GetAllRoles(),
                    SelectedRoles = RoleProvider.GetRolesForUser(user.Id)
                };
                return(View(model));
            }
            return(View());
        }
        /// <summary>
        /// The GetRoles method returns a list of roles for the user.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <param name="portalAlias">The portal alias.</param>
        /// <returns>A <code>IList&lt;RainbowRole&gt;</code> containing the user's roles</returns>
        public IList <RainbowRole> GetRoles(string email, string portalAlias)
        {
            string      userName = MembershipProvider.GetUserNameByEmail(portalAlias, email);
            RainbowUser user     = (RainbowUser)MembershipProvider.GetUser(portalAlias, userName, true);

            return(RoleProvider.GetRolesForUser(portalAlias, user.ProviderUserKey));
        }
        internal static bool HasAccess(this IPublicAccessService publicAccessService, int documentId, object providerUserKey, IContentService contentService, MembershipProvider membershipProvider, RoleProvider roleProvider)
        {
            var content = contentService.GetById(documentId);

            if (content == null)
            {
                return(true);
            }

            var entry = publicAccessService.GetEntryForContent(content);

            if (entry == null)
            {
                return(true);
            }

            var member = membershipProvider.GetUser(providerUserKey, false);

            if (member == null)
            {
                return(false);
            }

            var roles = roleProvider.GetRolesForUser(member.UserName);

            return(entry.Rules.Any(x => x.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType &&
                                   roles.Contains(x.RuleValue)));
        }
Exemplo n.º 5
0
        public ActionResult Edit(string id)
        {
            if (!id.Equals(User.Id(), StringComparison.OrdinalIgnoreCase) && !User.IsInRole(Definitions.Roles.Administrator))
            {
                return(RedirectToAction("Unauthorized", "Home"));
            }

            if (MembershipService.IsReadOnly())
            {
                return(RedirectToAction("Detail", "Account", new { id = id }));
            }

            if (!String.IsNullOrEmpty(id))
            {
                var user = MembershipService.GetUser(id);
                if (user != null)
                {
                    var model = new UserEditModel
                    {
                        Username = user.Name,
                        Name     = user.GivenName,
                        Surname  = user.Surname,
                        Email    = user.Email,
                        Roles    = RoleProvider.GetRolesForUser(user.Name),
                    };
                    PopulateRoles();
                    return(View(model));
                }
            }
            return(View());
        }
        public override string[] GetRolesForUser(string username)
        {
            if (!Initialized)
            {
                return(_prevProvider.GetRolesForUser(username));
            }
            if (string.IsNullOrEmpty(username))
            {
                MySqlSimpleMembershipProvider.NullArgumentException("username");
            }

            string connString = ConnectionString;
            int    userid     = MySqlSimpleMembershipProvider.GetUserId(username, connString, UserTableName, UserIdColumn, UserNameColumn);

            if (userid > 0)
            {
                using (MySqlDatabaseWrapper dbConn = new MySqlDatabaseWrapper(connString))
                {
                    var roles = dbConn.ExecuteQuery(string.Format("select rt.rolename from {0} as urt join {1} as rt on urt.roleid = rt.roleid where urt.userid=?;", _userInRolesTable, _rolesTable), userid);
                    if (roles.Count() > 0)
                    {
                        return(roles.Select(role => role[0].ToString()).ToArray());
                    }
                }
            }
            return(null);
        }
        public static void AddUserToRolesIfNotInYet(this RoleProvider p, string username, List <string> roles)
        {
            string[]      rsUserIn = p.GetRolesForUser(username);
            List <string> rsToAdd  = new List <string>();

            if (rsUserIn != null)
            {
                foreach (string role in roles)
                {
                    if (!rsUserIn.Contains(role))
                    {
                        rsToAdd.Add(role);
                    }
                }
            }
            else
            {
                rsToAdd = roles;
            }

            if (rsToAdd.Count > 0)
            {
                Utils.BaseRoleProvider().AddUsersToRoles(new string[] { username }, rsToAdd.ToArray());
            }
        }
Exemplo n.º 8
0
        public void RoleAttachTest1()
        {
            if (mp.GetUser(specialUN, false) == null)
            {
                CreateSpecialUser();
            }
            string roleName = Guid.NewGuid().ToString().Replace("-", "");

            rp.CreateRole(roleName);
            Assert.IsTrue(rp.RoleExists(roleName));
            rp.AddUsersToRoles(new[] { specialUN }, new[] { roleName });
            Assert.Contains(roleName, rp.GetRolesForUser(specialUN));
            rp.RemoveUsersFromRoles(new[] { specialUN }, new[] { roleName });
            Assert.IsFalse(rp.IsUserInRole(specialUN, roleName));

            rp.DeleteRole(roleName, false);
        }
Exemplo n.º 9
0
 public List <string> GetRolesForUser(string userName)
 {
     if (String.IsNullOrEmpty(userName))
     {
         throw new ArgumentException("Value cannot be null or empty.", "userName");
     }
     return(_provider.GetRolesForUser(userName).ToList());
 }
        public bool IsRepositoryAdministrator(Guid userId, Guid repositoryId)
        {
            bool result = false;

            result |= Repository.GetRepository(repositoryId).Administrators.Any(x => x.Id == userId);
            result |= RoleProvider.GetRolesForUser(userId).Contains(Definitions.Roles.Administrator);

            return(result);
        }
Exemplo n.º 11
0
        public bool IsRepositoryAdministrator(string username, string repositoryName)
        {
            bool result = false;

            result |= Repository.GetRepository(repositoryName).Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
            result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);

            return(result);
        }
Exemplo n.º 12
0
        public string GetRole(string username)
        {
            var roles = _provider.GetRolesForUser(username);

            if (roles != null && roles.Count() > 0)
            {
                return(roles[0]);
            }
            return(null);
        }
Exemplo n.º 13
0
        public bool HasPermission(string username, string repositoryName)
        {
            bool result = false;

            RepositoryModel repositoryModel = Repository.GetRepository(repositoryName);

            result |= repositoryModel.Users.Contains(username, StringComparer.OrdinalIgnoreCase);
            result |= repositoryModel.Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
            result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
            result |= TeamRepository.GetTeams(username).Any(x => repositoryModel.Teams.Contains(x.Name, StringComparer.OrdinalIgnoreCase));

            return(result);
        }
Exemplo n.º 14
0
        public static bool HasAccess(this IPublicAccessService publicAccessService, string path, MembershipUser member, RoleProvider roleProvider)
        {
            var entry = publicAccessService.GetEntryForContent(path.EnsureEndsWith(path));

            if (entry == null)
            {
                return(true);
            }

            var roles = roleProvider.GetRolesForUser(member.UserName);

            return(entry.Rules.Any(x => x.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType &&
                                   roles.Contains(x.RuleValue)));
        }
        public bool HasPermission(Guid userId, Guid repositoryId)
        {
            bool result = false;

            RepositoryModel repositoryModel = Repository.GetRepository(repositoryId);
            UserModel       user            = MemberShipService.GetUserModel(userId);

            result |= repositoryModel.Users.Any(x => x.Id == userId);
            result |= repositoryModel.Administrators.Any(x => x.Id == userId);
            result |= RoleProvider.GetRolesForUser(user.Id).Contains(Definitions.Roles.Administrator);
            result |= TeamRepository.GetTeams(userId).Any(x => repositoryModel.Teams.Select(y => y.Name).Contains(x.Name, StringComparer.OrdinalIgnoreCase));

            return(result);
        }
Exemplo n.º 16
0
        public IList <RegisterModel> GetUserRole(string username)
        {
            var roles = roleProvider.GetRolesForUser(username);

            IList <RegisterModel> registerModels = new List <RegisterModel>();

            foreach (var r in roles)
            {
                var registerModel = new RegisterModel {
                    UserName = username, RoleModelName = r
                };
                registerModels.Add(registerModel);
            }

            return(registerModels);
        }
Exemplo n.º 17
0
        public void Can_Get_Roles_For_User()
        {
            var user = new User {
                Username = "******", Password = "******"
            };

            MembershipProvider.CreateAccount(user);

            RoleProvider.CreateRole("admin");
            RoleProvider.CreateRole("sales");
            RoleProvider.CreateRole("engineering");

            RoleProvider.AddUsersToRoles(new[] { "sallen" }, new[] { "admin", "engineering" });

            Assert.True(RoleProvider.GetRolesForUser("sallen").Length == 2);
        }
        public string[] GetRolesForCurrentUser()
        {
            try {
                ApplicationServiceHelper.EnsureRoleServiceEnabled();
                EnsureProviderEnabled();

                IPrincipal   user     = ApplicationServiceHelper.GetCurrentUser(HttpContext.Current);
                string       username = ApplicationServiceHelper.GetUserName(user);
                RoleProvider provider = GetRoleProvider(user);

                return(provider.GetRolesForUser(username));
            }
            catch (Exception e) {
                LogException(e);
                throw;
            }
        }
Exemplo n.º 19
0
        public override string[] GetRolesForUser(string username)
        {
            LogDebug("Entering CachedProvider.GetRolesForUser");
            string[] roles;

            if (_cache.ContainsKey(username))
            {
                roles = ((List <string>)_cache[username]).ToArray();
                return(roles);
            }
            roles = _provider.GetRolesForUser(username);
            if (roles != null && roles.Length > 0)
            {
                _cache[username] = new List <string>(roles);
            }
            return(roles);
        }
        public override string[] GetRolesForUser(string username)
        {
            List <string> userRoles = new List <string>();

            foreach (string providerName in m_ProviderList)
            {
                RoleProvider rp    = Roles.Providers[providerName];
                string[]     roles = rp.GetRolesForUser(username);
                foreach (string role in roles)
                {
                    if (!userRoles.Contains(role))
                    {
                        userRoles.Add(role);
                    }
                }
            }
            return(userRoles.ToArray());
        }
Exemplo n.º 21
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controller = (filterContext.Controller as LeonniApplicationController);

            if (controller != null)
            {
                if (filterContext.HttpContext != null && filterContext.HttpContext.User != null && filterContext.HttpContext.User.Identity != null)
                {
                    if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                    {
                        MembershipUser objUser         = Membership.GetUser(filterContext.HttpContext.User.Identity.Name);
                        RoleProvider   objRoleProvider = Roles.Providers["DefaultRoleProvider"];
                        var            repo            = DependencyResolver.Current.GetService <IUserProfileRepository>();

                        controller.CurrentUser = new LoginModel();

                        if (objUser != null)
                        {
                            controller.CurrentUser.UserId   = (Guid)objUser.ProviderUserKey;
                            controller.CurrentUser.UserName = objUser.UserName;
                            var objUserProfile = repo.GetSingle(x => x.UserId == (Guid)objUser.ProviderUserKey);
                            if (objUserProfile != null)
                            {
                                controller.IsLeonniTeam = repo.GetSingle(x => x.UserId == (Guid)objUser.ProviderUserKey).IsLeonniTeam;
                            }
                            else
                            {
                                controller.IsLeonniTeam = false;
                            }
                            //objRoleProvider.
                            controller.CurrentRole = objRoleProvider.GetRolesForUser(filterContext.HttpContext.User.Identity.Name)[0];
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Always derive controller from LeonniApplicationController");
            }

            base.OnActionExecuting(filterContext);
        }
Exemplo n.º 22
0
        private UserDetailModelList GetDetailUsers()
        {
            var users = MembershipService.GetAllUsers();
            var model = new UserDetailModelList();

            model.IsReadOnly = MembershipService.IsReadOnly();
            foreach (var user in users)
            {
                model.Add(new UserDetailModel
                {
                    Username   = user.Name,
                    Name       = user.GivenName,
                    Surname    = user.Surname,
                    Email      = user.Email,
                    Roles      = RoleProvider.GetRolesForUser(user.Name),
                    IsReadOnly = model.IsReadOnly
                });
            }
            return(model);
        }
Exemplo n.º 23
0
        public ActionResult Detail(Guid id)
        {
            UserModel user = MembershipService.GetUserModel(id);

            if (user != null)
            {
                var model = new UserDetailModel
                {
                    Id         = user.Id,
                    Username   = user.Username,
                    Name       = user.GivenName,
                    Surname    = user.Surname,
                    Email      = user.Email,
                    Roles      = RoleProvider.GetRolesForUser(user.Id),
                    IsReadOnly = MembershipService.IsReadOnly()
                };
                return(View(model));
            }
            return(View());
        }
Exemplo n.º 24
0
 public ActionResult Detail(string id)
 {
     if (!String.IsNullOrEmpty(id))
     {
         UserModel user = MembershipService.GetUser(id);
         if (user != null)
         {
             var model = new UserDetailModel
             {
                 Username   = user.Name,
                 Name       = user.GivenName,
                 Surname    = user.Surname,
                 Email      = user.Email,
                 Roles      = RoleProvider.GetRolesForUser(user.Name),
                 IsReadOnly = MembershipService.IsReadOnly()
             };
             return(View(model));
         }
     }
     return(View());
 }
Exemplo n.º 25
0
        private IDictionary <string, bool> HasAccess(IEnumerable <string> paths, RoleProvider roleProvider)
        {
            // ensure we only lookup user roles once
            string[] userRoles = null;
            string[] getUserRoles(string username)
            {
                if (userRoles != null)
                {
                    return(userRoles);
                }
                userRoles = roleProvider.GetRolesForUser(username).ToArray();
                return(userRoles);
            }

            var result = new Dictionary <string, bool>();

            foreach (var path in paths)
            {
                result[path] = IsLoggedIn() && _publicAccessService.HasAccess(path, CurrentUserName, getUserRoles);
            }
            return(result);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Returns true or false if the currently logged in member is authorized based on the parameters provided
        /// </summary>
        /// <param name="allowTypes"></param>
        /// <param name="allowGroups"></param>
        /// <param name="allowMembers"></param>
        /// <returns></returns>
        public virtual bool IsMemberAuthorized(
            IEnumerable <string> allowTypes  = null,
            IEnumerable <string> allowGroups = null,
            IEnumerable <int> allowMembers   = null)
        {
            if (allowTypes == null)
            {
                allowTypes = Enumerable.Empty <string>();
            }
            if (allowGroups == null)
            {
                allowGroups = Enumerable.Empty <string>();
            }
            if (allowMembers == null)
            {
                allowMembers = Enumerable.Empty <int>();
            }

            // Allow by default
            var allowAction = true;

            if (IsLoggedIn() == false)
            {
                // If not logged on, not allowed
                allowAction = false;
            }
            else
            {
                var provider = _membershipProvider;

                string username;

                if (provider.IsUmbracoMembershipProvider())
                {
                    var member = GetCurrentPersistedMember();
                    // If a member could not be resolved from the provider, we are clearly not authorized and can break right here
                    if (member == null)
                    {
                        return(false);
                    }
                    username = member.Username;

                    // If types defined, check member is of one of those types
                    var allowTypesList = allowTypes as IList <string> ?? allowTypes.ToList();
                    if (allowTypesList.Any(allowType => allowType != string.Empty))
                    {
                        // Allow only if member's type is in list
                        allowAction = allowTypesList.Select(x => x.ToLowerInvariant()).Contains(member.ContentType.Alias.ToLowerInvariant());
                    }

                    // If specific members defined, check member is of one of those
                    if (allowAction && allowMembers.Any())
                    {
                        // Allow only if member's Id is in the list
                        allowAction = allowMembers.Contains(member.Id);
                    }
                }
                else
                {
                    var member = provider.GetCurrentUser();
                    // If a member could not be resolved from the provider, we are clearly not authorized and can break right here
                    if (member == null)
                    {
                        return(false);
                    }
                    username = member.UserName;
                }

                // If groups defined, check member is of one of those groups
                var allowGroupsList = allowGroups as IList <string> ?? allowGroups.ToList();
                if (allowAction && allowGroupsList.Any(allowGroup => allowGroup != string.Empty))
                {
                    // Allow only if member is assigned to a group in the list
                    var groups = _roleProvider.GetRolesForUser(username);
                    allowAction = allowGroupsList.Select(s => s.ToLowerInvariant()).Intersect(groups.Select(myGroup => myGroup.ToLowerInvariant())).Any();
                }
            }

            return(allowAction);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Finds the roles by user.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <returns></returns>
 public IEnumerable <string> FindByUser(MembershipUser user)
 {
     return(_roleProvider.GetRolesForUser(user.UserName));
 }
 public bool MemberIsAdministrator(string username)
 {
     return(!string.IsNullOrEmpty(username) && _roleProvider.GetRolesForUser(username).Any(x => x.ToUpperInvariant() == Groups.Administrators.ToUpperInvariant()));
 }
Exemplo n.º 29
0
 public List <string> GetRolesForUser(string username)
 {
     return(_provider.GetRolesForUser(username).ToList <string>());
 }
Exemplo n.º 30
0
 public string[] GetRolesForUser()
 {
     return(roleProvider.GetRolesForUser(null));
 }