Example #1
0
        public ActionResult Index()
        {
            var userRoles = new List<RolesViewModel>();
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            //Get all the usernames
            foreach (var user in userStore.Users)
            {
                var r = new RolesViewModel
                {
                    UserName = user.UserName
                };
                userRoles.Add(r);
            }
            //Get all the Roles for our users

            var numberOfDefault = 0;

            foreach (var user in userRoles)
            {
                user.RoleNames = userManager.GetRoles(userStore.Users.First(s => s.UserName == user.UserName).Id);

                if(user.RoleNames.Contains("Default"))
                {
                    numberOfDefault++;
                    TempData["ValidationMessageDefaultUser"] = numberOfDefault + " " + "New User(s) Have Registered";
                    TempData["ValidationMessageIcon"] = "1";
                }
            }

            return View(userRoles);
        }
 public Boolean isAdminUser()
 {
     //if user is Authenticated (logged in)
     if (User.Identity.IsAuthenticated)
     {
         //create a variable user with data from the users identity
         var user = User.Identity;
         //create a new instance of the Dbcontext
         ApplicationDbContext context = new ApplicationDbContext();
         //give variable UserManager data from the user
         var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
         //get the role of the current user
         var s = UserManager.GetRoles(user.GetUserId());
         //check to see if the current role is Admin
         if (s[0].ToString() == "Admin")
         {
             //return true;
             ViewBag.admin = true;
         }
         else
         {
             //return false;
             ViewBag.admin = false;
         }
     }
     return false;
 }
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            if (ModelState.IsValid)
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                ViewBag.Token = "2";

                if (userManager.IsInRole(user.Id, RoleName))
                {
                    userManager.RemoveFromRole(user.Id, RoleName);
                    ViewBag.ResultMessage = "Role removed from this user successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                }

                // prepopulat roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;

                var userList = context.Users.OrderBy(r => r.Email).ToList().Select(rr => new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();
                ViewBag.userNames = userList;

                ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);
            }

            return View("ManageUserRoles");
        }
        public ActionResult Search(string tb_SearchBox)
        {
            List<List<string>> userRoleList = new List<List<string>>();
            if (string.IsNullOrEmpty(tb_SearchBox))
            {
                tb_SearchBox = "";
            }
            var results = (from contact in db.ContactProfiles
                           where
                               contact.FirstName.Contains(tb_SearchBox)
                               || contact.LastName.Contains(tb_SearchBox)
                               || contact.AlternateEmail.Contains(tb_SearchBox)
                               || contact.PrimaryEmail.Contains(tb_SearchBox)
                           select contact).OrderByDescending(m=>m.LastName).ToList();

            foreach (var item in results)
            {

                UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(item.PrimaryEmail, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                List<string>roleList = _userManager.GetRoles(user.Id).ToList();

                userRoleList.Add(roleList);
            }
            userRoleList.Reverse();
            ViewBag.Roles = userRoleList;

            return View("Index", results);
        }
Example #5
0
        //Get Index page
        public ActionResult Index()
        {
            var userRoles = new List<RolesViewModel>();
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            //Get all the usernames
            foreach (var user in userStore.Users)
            {
                var r = new RolesViewModel
                {
                    UserName = user.UserName
                };
                userRoles.Add(r);
            }
            //Get all the Roles for our users
            foreach (var user in userRoles)
            {
                user.RoleNames = userManager.GetRoles(userStore.Users.First(s => s.UserName == user.UserName).Id);

                if (user.RoleNames.Contains("Default"))
                {
                    TempData["ValidationMessageIcon"] = "1";
                }
            }

            return View(db.Indices.ToList());
        }
 public ActionResult ChangeRoleOfUserInGroup(string mail)
 {
     //SKapa VM instans
     UserChangeRoleViewModel changeVM = new UserChangeRoleViewModel();
     var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     //Välj en user till Viewmodell
     //ViewBag.Name = changeVM.Name;
     changeVM.Users = repo.ApplicationUsers().Select(u => new SelectListItem
     {
         Text = u.UserName,
         Value = u.Id,
     });
     //ApplicationUser usr = repo.ApplicationUsers().First();
     //Välj vilken av users roll som skall ändras
     //List<IdentityRole> cVM = new List<IdentityRole>();
     changeVM.SelectedUser = repo.ApplicationUsers().Single(m => m.Email == mail).Id;
     changeVM.OldRoles = userManager.GetRoles(changeVM.SelectedUser).Select(o => new SelectListItem
     {
         Text = o,
         Value = o
     });
     //Välj en ny roll till Viewmodell
     changeVM.Roles = repo.RolesList().Select(r => new SelectListItem
     {
         Text = r.Name,
         Value = r.Name
     });
     //Returna View med VM
     return View(changeVM);
 }
Example #7
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> userNameHeaderValues = null;
            if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_USERID, out userNameHeaderValues))
            {
                if (!IsValidEmissRequest(request))
                {
                    var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not a Valid Request");
                    return Task.FromResult<HttpResponseMessage>(response);
                }

                IEnumerable<String> expireHeaderValues = null;
                if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_EXPIRES, out expireHeaderValues))
                {
                    if (IsExpiredRequest(expireHeaderValues.FirstOrDefault()))
                    {
                        var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Your Request Has Expired");
                        return Task.FromResult<HttpResponseMessage>(response);
                    }
                }

                var userName = userNameHeaderValues.First();
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindByName(userName);
                if (user != null)
                {
                    string signature = CryptographyHelper.Sign(request, user.SecretKey);
                    if (signature.Equals(request.Headers.GetValues(KawalDesaHeaders.X_KD_SIGNATURE).FirstOrDefault()))
                    {
                        var identity = new KawalDesaIdentity(user, "Emiss");
                        var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                }
            }
            else if (HttpContext.Current.Session != null && !String.IsNullOrEmpty((string)HttpContext.Current.Session[KawalDesaController.USERID_KEY]))
            {
                var session = HttpContext.Current.Session;
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindById((string)session[KawalDesaController.USERID_KEY]);
                if (user != null)
                {
                    var identity = new KawalDesaIdentity(user, "Session");
                    var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
            }

            return base.SendAsync(request, cancellationToken);
        }
Example #8
0
        public static void AddUsertoRole(UserManager<ApplicationUser> userManager, ApplicationUser user, string roleName)
        {
            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(roleName))
            {
                var result = userManager.AddToRole(user.Id, roleName);
            }
        }
Example #9
0
        private static void SetupRolesAndUsers(DbContext context)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            // add roles
            if (!roleManager.RoleExists(Role.Guest.ToString()))
                roleManager.Create(new IdentityRole(Role.Guest.ToString()));
            if (!roleManager.RoleExists(Role.Supplier.ToString()))
                roleManager.Create(new IdentityRole(Role.Supplier.ToString()));
            if (!roleManager.RoleExists(Role.Deactivated.ToString()))
                roleManager.Create(new IdentityRole(Role.Deactivated.ToString()));
            if (!roleManager.RoleExists(Role.User.ToString()))
                roleManager.Create(new IdentityRole(Role.User.ToString()));
            var adminRole = roleManager.FindByName(Role.Admin.ToString());
            if (adminRole == null)
            {
                adminRole = new IdentityRole(Role.Admin.ToString());
                roleManager.Create(adminRole);
            }
            #if DEBUG
            //add admin user
            var admin = userManager.Find(Admin_User, Admin_Pass);
            if (admin == null)
            {
                admin = new ApplicationUser
                {
                    UserName = Admin_User,
                    Email = Admin_Mail,
                    EmailConfirmed = true
                };
                var result = userManager.Create(admin, Admin_Pass);
                // TODO: verify returned IdentityResult
                userManager.AddToRole(admin.Id, Role.Admin.ToString());
                result = userManager.SetLockoutEnabled(admin.Id, false);
            }

            var rolesForUser = userManager.GetRoles(admin.Id);
            if (!rolesForUser.Contains(adminRole.Name))
            {
                var result = userManager.AddToRole(admin.Id, adminRole.Name);
            }

            //add normal user
            if (userManager.Find("[email protected]", "1q2w3e4r") == null)
            {
                var user = new ApplicationUser
                {
                    UserName = "[email protected]",
                    Email = "[email protected]",
                    EmailConfirmed = true
                };
                userManager.Create(user, "1q2w3e4r");
                // TODO: verify returned IdentityResult
                userManager.AddToRole(user.Id, Role.User.ToString());
            }
            #endif
        }
 public async Task<ActionResult> AssignRole(string username, string rolename)
 {
     UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(_identityDb);
     UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);
     var user = userManager.Users.FirstOrDefault(u => u.UserName == username);
     await Task.Run(() => userManager.RemoveFromRoles(user.Id, userManager.GetRoles(user.Id).ToArray()));
     //var role = roles.FirstOrDefault(r => r == rolename);
     //if(role == null)
     userManager.AddToRole(user.Id, rolename);
     return RedirectToAction("Users", "Admin");
 }
		public static List<UserRolesInfo> GetUserRolesInfo(this IQueryable<ApplicationUser> applicationUsers, int count, UserManager<ApplicationUser> userManager)
		{
			return applicationUsers
				.OrderBy(u => u.UserName)
				.Take(count).ToList()
				.Select(user => new UserRolesInfo
				{
					UserId = user.Id,
					UserName = user.UserName,
					UserVisibleName = user.VisibleName,
					Roles = userManager.GetRoles(user.Id).ToList()
				}).ToList();
		}
Example #12
0
 public ActionResult AssignRole(AssignRoleViewModel vm)
 {
     using (var context = new ApplicationDbContext())
     {
         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
         var role = _roleRepo.GetById(vm.RoleID);
         manager.AddToRole(vm.UserID, role.Name);
         vm.Roles = manager.GetRoles(vm.UserID);
         vm.User = _repo.GetById(vm.UserID);
     }
     ViewBag.RoleID = new SelectList(_roleRepo.Get(), "Id", "Name", vm.RoleID);
     return View(vm);
 }
Example #13
0
        public ActionResult AssignRole(string id)
        {
            AssignRoleViewModel vm = new AssignRoleViewModel();
            using (var context = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                vm.Roles = manager.GetRoles(id);
                vm.UserID = id;
                vm.User = _repo.GetById(id);
            }
            ViewBag.RoleID = new SelectList(_roleRepo.Get(), "Id", "Name");

            return View(vm);
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            using (var db = new DB())
            {
                IEnumerable<string> authorizationHeaderValues = null;
                if (request.Headers.TryGetValues("Authorization", out authorizationHeaderValues))
                {
                    try
                    {
                        var auth = authorizationHeaderValues.First().Split(null)[1];
                        var token = JsonWebToken.Decode(auth, ConfigurationManager.AppSettings["Auth.SecretKey"]);
                        var userManager = new UserManager<User>(new CUserStore<User>(db));
                        var user = userManager.FindById(token.UserId);
                        if (user != null)
                        {
                            var identity = new KawalDesaIdentity(user, "exAuth");
                            var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                            Thread.CurrentPrincipal = principal;
                            if (HttpContext.Current != null)
                            {
                                HttpContext.Current.User = principal;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogManager.GetLogger(typeof(AuthorizationHandler)).Error("Auth error", e);
                    }
                }
                else if (HttpContext.Current.Session != null && !String.IsNullOrEmpty((string)HttpContext.Current.Session[KawalDesaController.USERID_KEY]))
                {
                    var session = HttpContext.Current.Session;
                    var userManager = new UserManager<User>(new CUserStore<User>(db));
                    var user = userManager.FindById((string)session[KawalDesaController.USERID_KEY]);
                    if (user != null)
                    {
                        var identity = new KawalDesaIdentity(user, "Session");
                        var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                }

                return base.SendAsync(request, cancellationToken);
            }
        }
Example #15
0
        public static void DefaultUser(ApplicationDbContext db)
        {

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

            var name = AppConfig.DefaultUser;
            var pwd = AppConfig.DefaultUserPassword;
            const string adminRole = "Admin";
            const string dashboardRole = "Dashboard";
            const string investigateRole = "Investigate";

            //Create Role Admin if it does not exist
            var ar = roleManager.FindByName(adminRole);
            if (ar == null)
            {
                ar = new IdentityRole(adminRole);
                var roleresult = roleManager.Create(ar);
            }

            var dr = roleManager.FindByName(dashboardRole);
            if (dr == null)
            {
                dr = new IdentityRole(dashboardRole);
                var roleresult = roleManager.Create(dr);
            }

            var ir = roleManager.FindByName(investigateRole);
            if (ir == null)
            {
                ir = new IdentityRole(investigateRole);
                var roleresult = roleManager.Create(ir);
            }

            var user = userManager.FindByName(name);
            if (user == null)
            {
                user = new ApplicationUser { UserName = name, Email = name, EmailConfirmed = true };
                var createUser = userManager.Create(user, pwd);
                createUser = userManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains("Admin"))
            {
                var result = userManager.AddToRole(user.Id, "Admin");
            }
        }
        //select available modeule
    
        public ActionResult SelectModuleIndex(string UserID)
        {
            ApplicationDbContext context = new ApplicationDbContext();
            DisplayManagerRoleDelete ObjRole = new DisplayManagerRoleDelete();
            ModuleSelectVM ObjS = new ModuleSelectVM();
            var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
           ObjS.AllRoles = userManager.GetRoles(UserID);

           var LoggedUserID = User.Identity.GetUserId();
           ObjS.BuildingUser = db.BuildingUser.Where(c => c.UserID == LoggedUserID).FirstOrDefault();


           return View(ObjS);
        }
 public ActionResult GetRoles(string UserName)
 {
     if (!string.IsNullOrWhiteSpace(UserName))
     {
         ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
         var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
         ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);
         // prepopulat roles for the view dropdown
         var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
         var schemeList = db.Schemes.Select(m => new { Value = m.Name, Text = m.Name }).Distinct().ToList();
         ViewBag.Roles = list;
         var listUsers = context.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
         ViewBag.Users = listUsers;
         ViewBag.SchemeList = new MultiSelectList(schemeList, "Value", "Text");
     }
     return View("Index");
 }
Example #18
0
        internal static void DefaultUser(ApplicationDbContext ctx)
        {
            var userManager = new UserManager<User>(new UserStore<User>(ctx));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ctx));

            var adminUser = AppConfig.DefaultAdminAccount;
            var adminPassword = AppConfig.DefaultAdminAccountPassword;
            const string roleName = "Admin";

            var role = roleManager.FindByName(roleName);
            if (role == null)
            {
                role = new IdentityRole(roleName);
                var createRoleResult = roleManager.Create(role);
            }

            var user = userManager.FindByName(adminUser);
            if (user == null)
            {
                user = new User
                {
                    UserName = adminUser,
                    Email = adminUser,
                    LockoutEnabled = false,
                    EmailConfirmed = true,
                    UserProfile = new UserProfile()
                    {
                        Title = "N/A",
                        Forename = "System",
                        Surname = "Administrator",
                        Alias = "Sysadmin",
                        JobTitle = "Administrator"
                    }
                };
                var createUserResult = userManager.Create(user, adminPassword);
                createUserResult = userManager.SetLockoutEnabled(user.Id, false);
            }

            var rolesForUser = userManager.GetRoles(user.Id);
            if (!rolesForUser.Contains(role.Name))
            {
                var addUserToRoleResult = userManager.AddToRole(user.Id, role.Name);
            }
        }
Example #19
0
        /// <summary>
        /// Displays available tasks/links
        /// </summary>
        /// <returns>Json response</returns>
        public ActionResult Diagram()
        {
            DiagramAdapter DAdapter = new DiagramAdapter();
            JsonResult json = new JsonResult();
            IList<string> roles = new List<string>();
            EmployeeViewModel employee = null;
            IEnumerable<TaskWFM> gottenTasks = null;

            using (WorkFlowService wfs = new WorkFlowService("WorkFlowDbConnection"))
            {
                using (UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
                {
                    ApplicationUser user = userManager.FindByName(User.Identity.Name);
                    if (user != null)
                    {
                        roles = userManager.GetRoles(user.Id);
                        EmployeeWFM employeeWMF = wfs.GetEmployeeByIdentityID(user.Id);
                        employee = DataMapperView.DoMapping<EmployeeWFM, EmployeeViewModel>(employeeWMF);
                    }
                }
                if (roles.Contains("admin") || roles.Contains("manager") || employee != null)
                {
                    if (roles.Contains("admin") || roles.Contains("manager"))
                    {
                        gottenTasks = wfs.GetAllTasks();
                    }
                    else
                    {
                        gottenTasks = wfs.GetEmployeeTasks(employee.HolderCode);
                    }
                    List<TaskViewModel> viewTasks = new ViewModelConverter().CreateTaskRange(gottenTasks);

                    IEnumerable<LinkWFM> gottenLinks = wfs.GetAllLinks();
                    List<LinkViewModel> viewLinks = new ViewModelConverter().CreateLinkRange(gottenLinks);

                    json = DAdapter.CreateJson(viewTasks, viewLinks);
                }
                else
                {
                    return View(json);
                }
            }
            return View(json);
        }
Example #20
0
        public IHttpActionResult RemoveAdminFromUser(string username)
        {
            var user = this.Data.Users.All().ToList().FirstOrDefault(u => u.UserName == username);

            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            string adminCheck = um.GetRoles(user.Id).FirstOrDefault(a => a.Contains("AppAdmin"));

            if (adminCheck == string.Empty)
            {
                return this.BadRequest(string.Format("user {0} is not admin", user.UserName));
            }

            um.RemoveFromRoleAsync(user.Id, "AppAdmin");

            this.Data.SaveChanges();

            return this.Ok(string.Format("user: {0} is not admin now", user.UserName));
        }
        public ActionResult GetRoles(string UserName)
        {
            if (!string.IsNullOrWhiteSpace(UserName))
            {
                UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                var account = new AccountController();

                ViewBag.RolesForThisUser = _userManager.GetRoles(user.Id);

                // prepopulat roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                var userlist = context.Users.OrderBy(r => r.UserName).ToList().Select(rr =>
                new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
                ViewBag.Roles = list;
                ViewBag.Users = userlist;
            }

            return View("Index");
        }
Example #22
0
        // GET: Users
        public ActionResult Index(string currentFilter, int? page, string searchString = "")
        {
            IQueryable<AspNetUser> userList = null;
            int pageNumber = page ?? 1;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
                searchString = string.Empty;
            }
            ViewBag.CurrentFilter = searchString;
            userList = _repo.Get(d => d.UserName.ToLower().Contains(searchString.ToLower()), d => d.UserName);

            var q = userList.ToPagedList(pageNumber, QuizApp.Web.Helpers.Constants.PageSize);
            var account = new AccountController(_repo);
            using (var context = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                foreach (var itm in q)
                {
                    string userName = itm.UserName;
                    itm.RoleNames = manager.GetRoles(itm.Id);
                }
            }
            return View(q);
        }
Example #23
0
        // GET: Admin/Seguridad
        public ActionResult Index()
        {
            List<UserViewModel> usuarios = new List<UserViewModel>();

            var users = UserManager.Users.ToList();

            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            foreach (ApplicationUser user in users)
            {
                var roles = userManager.GetRoles(user.Id);
                string persona;
                if (user.USER_PERSONA_ID != null)
                {
                    persona = context.Personas.Find(user.USER_PERSONA_ID).PERSONA_NOMBRE_COMPLETO;
                }
                else
                {
                    persona = "";
                }

                usuarios.Add(new UserViewModel()
                {
                    Id = user.Id,
                    RoleName = string.Join(", ", roles),
                    UserName = user.UserName,
                    Email = user.Email,
                    Persona = persona
                });

            }

            ViewBag.error = Session["error"];
            return View(usuarios.ToList());
        }
        public ActionResult GetRoles(GetRolesViewModel model)
        {
            if(ModelState.IsValid)
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(model.UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                ViewBag.RolesForThisUser = userManager.GetRoles(user.Id);

                // prepopulat roles for the view dropdown
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                ViewBag.Roles = list;

                var userList = context.Users.OrderBy(r => r.Email).ToList().Select(rr=> new SelectListItem { Value = rr.Email.ToString(), Text = rr.Email }).ToList();
                ViewBag.userNames = userList;
            }

            return View("ManageUserRoles");
        }
 protected string getCurrentRole(object id)
 {
     var userStore = new UserStore<IdentityUser>();
     var userManager = new UserManager<IdentityUser>(userStore);
     return userManager.GetRoles(id.ToString()).First();
 }
        public IEnumerable<UserViewModel> UserViewModelsByGroupId(int? id)
        {
            List<UserViewModel> viewModels = new List<UserViewModel>();
            Group group = db.Groups.Single(d => d.Id == id);
            Department dep = db.Departments.Single(d => d.Id == group.DepartmentId);
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            ICollection<ApplicationUser> users = db.Groups.Single(u => u.Id == id).Users;
            //IList<string> UserRoles = userManager.GetRoles(user.Id);

            foreach (ApplicationUser user in users.ToList())
            {
                if (users.Count > 0)
                {
                    IList<string> UserRoles = userManager.GetRoles(user.Id);
                    if (UserRoles.Count == 0)
                    {
                        if (user.Adress != null)
                        {
                            viewModels.Add(new UserViewModel
                            {
                                City = user.Adress.City,
                                Email = user.Email,
                                Number = user.PhoneNumber,
                                Street = user.Adress.Street,
                                StreetNumber = user.Adress.StreetNumber,
                                ZipCode = user.Adress.ZipCode,
                                DepartmentId = group.DepartmentId,
                                DName = dep.Name,
                                UserRole = ""
                            });
                        }
                        else
                        {
                            viewModels.Add(new UserViewModel
                            {
                                Email = user.Email,
                                Number = user.PhoneNumber,
                                DepartmentId = group.DepartmentId,
                                DName = dep.Name,
                                UserRole = ""
                            });
                        }
                    }
                    foreach (string role in UserRoles)
                    {
                        if (user.Adress != null)
                        {
                            viewModels.Add(new UserViewModel
                            {
                                City = user.Adress.City,
                                Email = user.Email,
                                Number = user.PhoneNumber,
                                Street = user.Adress.Street,
                                StreetNumber = user.Adress.StreetNumber,
                                ZipCode = user.Adress.ZipCode,
                                DepartmentId = group.DepartmentId,
                                DName = dep.Name,
                                UserRole = role
                            });
                        }
                        else
                        {
                            viewModels.Add(new UserViewModel
                            {
                                Email = user.Email,
                                Number = user.PhoneNumber,
                                DepartmentId = group.DepartmentId,
                                DName = dep.Name,
                                UserRole = role
                            });
                        }
                    }

                }
                else
                {
                    viewModels.Add(new UserViewModel
                    {
                        Email = user.Email,
                        Number = user.PhoneNumber,
                        DepartmentId = group.DepartmentId,
                        UserRole = ""
                    });
                }
            }

            return viewModels;
        }
 public IEnumerable<UserViewModel> UserViewModelsApplicants()
 {
     List<UserViewModel> viewModels = new List<UserViewModel>();
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     foreach (ApplicationUser user in db.Users.ToList())
     {
         if (db.Users.ToList().Count > 0)
         {
             IList<string> UserRoles = userManager.GetRoles(user.Id);
             if (UserRoles.Count == 0)
             {
                 if (user.Adress != null)
                 {
                     viewModels.Add(new UserViewModel
                     {
                         City = user.Adress.City,
                         Email = user.Email,
                         Number = user.PhoneNumber,
                         Street = user.Adress.Street,
                         StreetNumber = user.Adress.StreetNumber,
                         ZipCode = user.Adress.ZipCode,
                         UserRole = ""
                     });
                 }
                 else
                 {
                     viewModels.Add(new UserViewModel
                     {
                         Email = user.Email,
                         Number = user.PhoneNumber
                     });
                 }
             }
             foreach (string role in UserRoles)
             {
                 if (role == "applicant")
                 {
                     if (user.Adress != null)
                     {
                         viewModels.Add(new UserViewModel
                         {
                             City = user.Adress.City,
                             Email = user.Email,
                             Number = user.PhoneNumber,
                             Street = user.Adress.Street,
                             StreetNumber = user.Adress.StreetNumber,
                             ZipCode = user.Adress.ZipCode,
                             UserRole = role
                         });
                     }
                     else
                     {
                         viewModels.Add(new UserViewModel
                         {
                             Email = user.Email,
                             Number = user.PhoneNumber,
                             UserRole = role
                         });
                     }
                 }
             }
         }
         else
         {
             viewModels.Add(new UserViewModel
             {
                 Email = user.Email,
                 Number = user.PhoneNumber,
                 UserRole = ""
             });
         }
     }
     return viewModels;
 }
 public ActionResult Edit(string id)
 {
     ApplicationDbContext db = new ApplicationDbContext();
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     var u_manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
     string role_name = u_manager.GetRoles(id).FirstOrDefault() == null ? "" : u_manager.GetRoles(id).FirstOrDefault();
     ApplicationUser applicationUser = db.Users.Find(id);
     EditViewModel appUser = new EditViewModel();
     appUser.ContactNo = applicationUser.PhoneNumber;
     appUser.Email = applicationUser.Email;
     appUser.FirstName = DataHelper.ToPascalConvention(applicationUser.FirstName);
     appUser.LastName = DataHelper.ToPascalConvention(applicationUser.LastName);
     appUser.Password = applicationUser.Password;
     appUser.RoleName = role_name;
     appUser.UserId = applicationUser.Id;
     appUser.ConfirmPassword = applicationUser.Password;           
     appUser.selectedProduct = DBHandler.getUserProductsByUserId(applicationUser.Id);
     appUser.Products = DBHandler.GetProducts();
     appUser.RoleId = db.Roles.Where(r => r.Name.ToLower() == role_name.ToLower()).First().Id;
     ViewBag.RoleId = new SelectList(db.Roles, "Id", "Name", appUser.RoleId);
     if (appUser == null)
     {
         return HttpNotFound();
     }
     return View(appUser);
 }
Example #29
0
        public async Task<IHttpActionResult> GetUserProfileByEmail()
        {
            string emailAddress = HttpContext.Current.Request.Form[0];

            var query = (from u in this.db.Users
                         join c in this.db.Clients on u.ClientId equals c.ClientId
                         where u.EmailAddress == emailAddress
                         select new
                                    {
                                        c.ClientId, c.Name, u.UserId, u.ASPNetUserId, u.FirstName, u.LastName
                                    }).ToArray();

            // get user role
            var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new AuthContext()));
            string role = userManager.GetRoles(query.First().ASPNetUserId)[0];

            var result = query.Select(x => new
                                               {
                                                   x.ClientId, 
                                                   ClientName = x.Name, 
                                                   x.UserId, 
                                                   x.FirstName, 
                                                   x.LastName, 
                                                   Role = role
                                               }).ToArray();

            return this.Ok(result);
        }
        protected void grvUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var row = grvUsers.Rows[e.RowIndex];
            var id = grvUsers.DataKeys[e.RowIndex].Value.ToString();

            var firstName = ((TextBox)row.FindControl("txtFirstName")).Text;
            var lastName = ((TextBox)row.FindControl("txtLastName")).Text;
            var email = ((TextBox)row.FindControl("txtEmail")).Text;
            var currentPassword = ((TextBox)row.FindControl("txtCurrentPassword")).Text;
            var newPassword = ((TextBox)row.FindControl("txtNewPassword")).Text;
            var role = ((DropDownList)row.FindControl("ddlRoleEdit")).Text;
            var jobClinic = ((DropDownList)row.FindControl("ddlJobClinicEdit")).Text; //TODO: Automatically edit RelationType (exept Writer) on files.
            var isActive = ((CheckBox)row.FindControl("chkIsActive")).Checked;

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var user = userManager.FindById(id);

            if (user != null && (
                userManager.FindById(SharedClass.CurrentUser).UserName == "Admin" ||
                user.UserName != "Admin"
                ))
            {
                if (newPassword != "")
                {
                    var result = userManager.ChangePassword(id, currentPassword, newPassword);
                }
                userManager.SetEmail(id, email);
                userManager.RemoveFromRoles(id, userManager.GetRoles(id).ToArray());
                userManager.AddToRole(id, role);

                using (Medical_Clinic_Entities mc = new Medical_Clinic_Entities())
                {
                    BSI__Clinic_Employee employee = mc.BSI__Clinic_Employees.Where(o => o.Id == id).First();
                    employee.First_Name = firstName;
                    employee.Last_Name = lastName;
                    employee.Job_Clinic = jobClinic;
                    employee.Is_Active = isActive;

                    mc.SaveChanges();
                }
            }
            grvUsers.EditIndex = -1;
        }