示例#1
0
        public static ApplicationRole ApplicationRole(int? counter)
        {
            var rtValue = new ApplicationRole();
            rtValue.Level = counter;

            return rtValue;
        }
        public async Task<ActionResult> Create(CreateViewModel createViewModel)
        {
            if (!ModelState.IsValid)
            {
                return View(createViewModel);
            }

            Session["RoleName"] = createViewModel.Name;

            var role = new ApplicationRole()
            {
                Name = createViewModel.Name,
                Description = createViewModel.Description,
                CreatedDate = DateTime.Now
            };
            var result = await RoleManager.CreateAsync(role);
            if (result.Succeeded)
            {
                TempData["RoleId"] = role.Id;
                TempData["RoleName"] = role.Name;
                TempData["Message"] = RolesMessage.CreateSuccess;
                return RedirectToAction("index", "roles");
            }
            AddErrors(result);

            return View(createViewModel);
        }
        public async Task<ActionResult> Create(CreateRoleViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                viewModel.Controllers = GetControllers();
                return View(viewModel);
            }

            var role = new ApplicationRole
            {
                Name = viewModel.Name,
                RoleAccesses = new List<RoleAccess>()
            };

            //
            foreach (var controller in viewModel.SelectedControllers)
            {
                foreach (var action in controller.Actions)
                {
                    role.RoleAccesses.Add(new RoleAccess { Controller = controller.Name, Action = action.Name });
                }
            }

            await RoleManager.CreateAsync(role);
            return RedirectToAction("Index");
        }
 public async Task CopyRole(string source, string target)
 {
     var sourceIsSytemRole = SystemRoleViewModels.Any(x => x.Name == source);
     ApplicationRole copy;
     if (sourceIsSytemRole)
     {
         var sourceViewModel = RoleModels().First(x => x.Name == source);
         copy = new ApplicationRole() { Name = target };
         foreach (var roleClaimRowViewModel in sourceViewModel.Claims)
         {
             copy.RoleClaims.Add(new ApplicationClaim(roleClaimRowViewModel.Type, roleClaimRowViewModel.Value));
         }
     }
     else
     {
         var original = await _roleManager.FindByNameAsync(source);
         if (original == null) throw new ApplicationException("source role not found");
         copy = new ApplicationRole(target);
         foreach (var applicationClaim in original.RoleClaims)
         {
             copy.RoleClaims.Add(applicationClaim);
         }
     }
     var result = await _roleManager.CreateAsync(copy);
     if (!result.Succeeded) throw new ApplicationException(string.Join("\n", result.Errors));
     _cache.RemoveItem(_roleViewModelsCacheKey);
 }
        public async Task<string> CreateRoleAsync(string roleName, string desc)
        {
            string message = string.Empty;
            try
            {
                bool roleExists = await roleManager.RoleExistsAsync(roleName);

                if (!roleExists)
                {
                    ApplicationRole role = new ApplicationRole(roleName);
                    role.Description = desc;
                    await roleManager.CreateAsync(role);
                    message = string.Format("Success : {0} role created successfuly", roleName);
                }
                else
                {
                    message = string.Format("Error : Role already exists with the same name - {0}", roleName);
                }
            }
            catch (Exception ex)
            {
                message = string.Format("Error : Exception occured at role creation {0}", ex.Message);
            }
            return message;
        }
示例#6
0
 private async Task SeedRoles()
 {
     if (!await roleManager.RoleExistsAsync("Administrator"))
     {
         ApplicationRole administratorRole = new ApplicationRole { Name = "Administrator" };
         await roleManager.CreateAsync(administratorRole);
     }
 }
示例#7
0
        void see_how_i_do(TaskRole something)
        {
            if (something is ApplicationTask)
                _current_task = (ApplicationTask)something;

            if (something is ApplicationRole)
                _currentApplicationRole = (ApplicationRole) something;
        }
示例#8
0
 internal static RoleModel From(ApplicationRole role)
 {
     return new RoleModel()
     {
         RoleId = role.Id,
         RoleName = role.Name
     };
 }
示例#9
0
 public RoleReturnModel Create(ApplicationRole appRole)
 {
     return new RoleReturnModel
     {
         Url = _UrlHelper.Link("GetRoleById", new { id = appRole.Id }),
         Id = appRole.Id,
         Name = appRole.Name
     };
 }
示例#10
0
 // начальная инициализация бд
 public async Task SetInitialData(UserDTO adminDto, List<string> roles)
 {
     foreach (var roleName in roles)
     {
         var role = await Database.RoleManager.FindByNameAsync(roleName);
         if (role == null)
         {
             role = new ApplicationRole { Name = roleName };
             await Database.RoleManager.CreateAsync(role);
         }
     }
     await Create(adminDto);
 }
示例#11
0
        public async Task<IHttpActionResult> PostRole(ApplicationRole role)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await repository.AddAsync(role);
            if (result.Succeeded)
            {
                return Ok(role);
            } else {
                return BadRequest(ModelState);
            }
        }
示例#12
0
        public static void SeedIdentityForEF(ApplicationDbContext context)
        {
            if ((!context.Roles.Any()) && (!context.Users.Any()))
            {
                var roleStore = new ApplicationRoleStore(context);
                //var roleManager = new RoleManager<ApplicationRole, int>(roleStore);

                var roleManager = new ApplicationRoleManager(roleStore);

                var role = new ApplicationRole
                {
                    Name = "Admin",
                    Description = "Super Admin User group"
                };
                roleManager.Create(role);

                var userStore = new UserStore<ApplicationUser,
                                                ApplicationRole,
                                                int,
                                                ApplicationUserLogin,
                                                ApplicationUserRole,
                                                ApplicationUserClaim>(context);
                var userManager = new ApplicationUserManager(userStore);

                var user = new ApplicationUser
                {
                    Email = "*****@*****.**",
                    UserName = "******",
                    EmailConfirmed = true
                };

                user.FirstName = "Jack";
                user.LastName = "Smith";

                userManager.Create(user, "P@ssword");
                var result = userManager.SetLockoutEnabled(user.Id, false);

                userManager.AddToRole(user.Id, "Admin");

                //added group manager
                var groupManager = new ApplicationGroupManager(roleManager,userManager);
                var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All");

                groupManager.CreateGroup(newGroup);
                groupManager.SetUserGroups(user.Id, new int[] { newGroup.Id });
                groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name });
            }
        }
        public async Task<ActionResult> Create([Bind(Include = "Name")] ApplicationRoleViewModel applicationRoleViewModel)
        {
            if (ModelState.IsValid)
            {
                var applicationRole = new ApplicationRole(applicationRoleViewModel.Name);
                var roleResult = await RoleManager.CreateAsync(applicationRole);
                if (!roleResult.Succeeded)
                {
                    ModelState.AddModelError("", roleResult.Errors.First());
                    return View();
                }
                return RedirectToAction("Index");
            }

            return View(applicationRoleViewModel);
        }
        public async Task<IActionResult> AssignRoles()
        {
            var user = await _userManager.GetUserAsync(User);

            if (!(await _roleManager.RoleExistsAsync("Administrators")))
            {
                var role = new ApplicationRole() { Name = "Administrators" };
                role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = ClaimTypes.PrimarySid, ClaimValue = "001" });

                await _roleManager.CreateAsync(role);
            }

            await _userManager.AddToRoleAsync(user, "Administrators");

            return RedirectToAction(nameof(ShowUsers));
        }
示例#15
0
        //TODO: Look in to how this could be accomplished at the same time as the Update user call
        public async Task<ServiceProcessingResult> UpdateUserRoleIfNecessary(string newRoleName, ApplicationRole oldRole, string userId)
        {
            var processingResult = new ServiceProcessingResult { IsSuccessful = true };
            if (newRoleName == oldRole.Name)
            {
                return processingResult;
            }

            if (GetRoleWithName(newRoleName) != null && await _userManager.IsInRoleAsync(userId, newRoleName) == false)
            {
                try
                {
                    var result = await _userManager.RemoveFromRoleAsync(userId, oldRole.Name);
                    if (!result.Succeeded)
                    {
                        var identityErrors = String.Join("\n", result.Errors);
                        var logMessage = String.Format("Failed to remove user from role. Errors: {0}", identityErrors);
                        Logger.Error(logMessage);

                        processingResult.IsSuccessful = false;
                        processingResult.Error = ErrorValues.USER_ROLE_UPDATE_FAILED_ERROR;
                        return processingResult;
                    }

                    result = await _userManager.AddToRoleAsync(userId, newRoleName);
                    if (!result.Succeeded)
                    {
                        var identityErrors = String.Join("\n", result.Errors);
                        var logMessage = String.Format("Failed to add user to role. Errors: {0}", identityErrors);
                        Logger.Error(logMessage);

                        processingResult.IsSuccessful = false;
                        processingResult.Error = ErrorValues.USER_ROLE_UPDATE_FAILED_ERROR;
                    }
                }
                catch (Exception ex)
                {
                    processingResult.IsSuccessful = false;
                    processingResult.Error = ErrorValues.USER_ROLE_UPDATE_FAILED_ERROR;
                    Logger.Error("Failed to update user role.", ex);
                }
            }

            return processingResult;
        }
        public async Task<IHttpActionResult> Create(CreateRoleBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var role = new ApplicationRole(model.Name);

            var result = await AppRoleManager.CreateAsync(role);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            var locationHeader = new Uri(Url.Link("GetRoleById", new {id = role.Id}));

            return Created(locationHeader, TheModelFactory.Create(role));
        }
        public async Task UpdateAsync_should_update_the_role()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenAsyncSession())
                {
                    // Arrange
                    var service = GetRavenRoleStore(session);
                    var role = new ApplicationRole("Admin");
                    await service.CreateAsync(role);

                    // Act
                    await service.UpdateAsync(role);

                    // Assert
                    var actual = await session.LoadAsync<ApplicationRole>(role.Id);
                    actual.Name.Should().Be("Admin");
                }
            }
        }
示例#18
0
        public async Task<IHttpActionResult> PutRole(string id, ApplicationRole role)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != role.Id)
            {
                return BadRequest();
            }

            var result = await repository.UpdateAsync(role, role.Id);
            if (result.Succeeded)
            {
                return StatusCode(HttpStatusCode.NoContent);
            } else
            {
                return BadRequest();
            }
        }
示例#19
0
        public string GetResourcesFor(ApplicationRole role)
        {
            switch (role)
            {
                case ApplicationRole.MasterAdmin:
                    return "session.create session.edit session.view session.delete"
                           + " schoolInfo.create schoolInfo.edit schoolInfo.view"
                           + " enrollment.create enrollment.edit enrollment.view"
                           + " courseGeneration.create courseGeneration.edit courseGeneration.view courseGeneration.delete"
                           + " user.create user.edit user.view"
                           + " scheduleStudents.create scheduleStudents.edit scheduleStudents.view"
                           + " assessment.create assessment.edit assessment.view"
                           + " attendance.create attendance.edit attendance.view attendance.clearAllFlags"
                           + " grades.edit grades.view";

                case ApplicationRole.Admin:
                    return "session.edit session.view"
                           + " schoolInfo.edit schoolInfo.view"
                           + " enrollment.create enrollment.edit enrollment.view"
                           + " courseGeneration.create courseGeneration.edit courseGeneration.view courseGeneration.delete"
                           + " user.create user.edit user.view"
                           + " scheduleStudents.create scheduleStudents.edit scheduleStudents.view"
                           + " assessment.create assessment.edit assessment.view"
                           + " attendance.view"
                           + " grades.view";

                case ApplicationRole.Teacher:
                    return "session.view"
                           + " schoolInfo.view"
                           + " enrollment.view"
                           + " courseGeneration.view"
                           + " user.view"
                           + " scheduleStudents.view"
                           + " assessment.create assessment.edit assessment.view"
                           + " attendance.edit attendance.view"
                           + " grades.create grades.edit grades.view";
            }

            return string.Empty;
        }
        private static void CreateDefaultData(IAsyncDocumentSession session)
        {
            var role = new ApplicationRole("Admin");
            session.StoreAsync(role);

            var hasher = new PasswordHasher();
            var passwordHash = hasher.HashPassword("admin");
            var superUser = new ApplicationUser("SuperAdmin")
            {
                Email = "*****@*****.**",
                FirstName = "Super",
                LastName = "Admin",
                UserName = "******",
                PasswordHash = passwordHash,
                EmailConfirmed = true,
                Roles = {"Admin"}
            };

            session.StoreAsync(superUser);

            session.SaveChangesAsync();
        }
        public async Task CreateAsync_should_create_a_new_role()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenAsyncSession())
                {
                    // Assert
                    var role = new ApplicationRole("Admin");

                    var service = GetRavenRoleStore(session);

                    // Act
                    await service.CreateAsync(role);

                    // Assert
                    var id = ApplicationRole.GenerateKey("Admin");
                    var actual = await session.LoadAsync<ApplicationRole>(id);

                    actual.Id.Should().Be(id);
                    actual.Name.Should().Be("Admin");
                }
            }
        }
示例#22
0
        public async Task<ActionResult> AddRole(RoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();

                var newRole = new ApplicationRole(model.RoleName);
                newRole.Description = model.RoleDescription;

                var roleResult = await roleManager.CreateAsync(newRole);

                if (!roleResult.Succeeded)
                {
                    ModelState.AddModelError("", roleResult.Errors.First());
                    return View();
                }

                return RedirectToAction("AddRole");
            }


            return View();
        }
        public static ServiceProcessingResult<ValidationResult> ValidateRoleAssignmentFor(ApplicationRole roleBeingAssigned,
            ApplicationRole loggedInUserRole)
        {
            var processingResult = new ServiceProcessingResult<ValidationResult> { IsSuccessful = true };
            var validationResult = new ValidationResult
            {
                IsValid = true
            };

            if (roleBeingAssigned == null)
            {
                validationResult.IsValid = false;
                validationResult.Errors.Add("Invalid role. Please select a valid role and try again.");
            }
            else if (!loggedInUserRole.CanAssign(roleBeingAssigned))
            {
                validationResult.IsValid = false;
                validationResult.Errors.Add(CannotAssignRoleToUserUserHelp);
            }
            processingResult.Data = validationResult;

            return processingResult;
        }
示例#24
0
 public void AddRole(ApplicationRole role) =>
 _roleManager.CreateAsync(role);
示例#25
0
 public async Task <IdentityResult> CreateAsync(ApplicationRole role)
 {
     return(await _roleManager.CreateAsync(role));
 }
 public ApplicationRoleShould()
 {
     _roles = new ApplicationRole();
 }
        /// <summary>
        /// Roles and users and permissions assigned to them can be changed through application.
        /// </summary>
        private void InitialDataSetup()
        {
            InMemoryRepository repository = new InMemoryRepository();

            var superUserRole = new ApplicationRole
            {
                Id          = 1,
                Role        = "Super User",
                Permissions = { AppPermissions.MANAGE_PERMISSIONS, AppPermissions.MANAGE_ROLES, AppPermissions.MANAGE_ADMINISTRATOR_PROFILE }
            };
            var adminManagerRole = new ApplicationRole
            {
                Id          = 2,
                Role        = "Administrators Manager",
                Permissions = { AppPermissions.VIEW_ADMINISTRATOR_PROFILES, AppPermissions.MANAGE_STUDENT_PROFILE }
            };
            var studentsAdministratorRole = new ApplicationRole
            {
                Id          = 3,
                Role        = "Students Manager",
                Permissions = { AppPermissions.VIEW_OWN_ADMIN_PROFILE, AppPermissions.MANAGE_STUDENT_PROFILE }
            };
            var teachingAssistantRole = new ApplicationRole
            {
                Id          = 4,
                Role        = "Teaching Assistant",
                Permissions = { AppPermissions.VIEW_STUDENT_PROFILES }
            };
            var studentRole = new ApplicationRole {
                Id = 5, Role = "Student", Permissions = { AppPermissions.VIEW_OWN_STUDENT_PROFILE }
            };

            repository.Add(superUserRole);
            repository.Add(adminManagerRole);
            repository.Add(studentsAdministratorRole);
            repository.Add(teachingAssistantRole);
            repository.Add(studentRole);

            var superuser = new ApplicationUser
            {
                Id       = 1,
                Username = "******",
                Roles    = { superUserRole }
            };

            var superadmin = new ApplicationUser
            {
                Id       = 2,
                Username = "******",
                Roles    = { adminManagerRole, studentsAdministratorRole }
            };

            var superadmin2 = new ApplicationUser
            {
                Id       = 3,
                Username = "******",
                Roles    = { adminManagerRole }
            };

            var admin = new ApplicationUser
            {
                Id       = 4,
                Username = "******",
                Roles    = { studentsAdministratorRole }
            };

            var student1 = new ApplicationUser
            {
                Id       = 5,
                Username = "******",   //This student is TA who can view other student's profiles
                Roles    = { studentRole, teachingAssistantRole }
            };

            var student2 = new ApplicationUser
            {
                Id       = 6,
                Username = "******",
                Roles    = { studentRole }
            };

            repository.Add(superuser);
            repository.Add(superadmin);
            repository.Add(superadmin2);
            repository.Add(admin);
            repository.Add(student1);
            repository.Add(student2);

            repository.Add(new Administrator {
                Id = 1, Name = "Bob Smith", User = superuser
            });
            repository.Add(new Administrator {
                Id = 2, Name = "Paul Smith", User = superadmin
            });
            repository.Add(new Administrator {
                Id = 3, Name = "Paul J. Smith", User = superadmin2
            });
            repository.Add(new Administrator {
                Id = 4, Name = "Michael Sindhu", User = admin
            });
            repository.Add(new Student {
                Id = 5, Name = "Jeff Studants", User = student1
            });
            repository.Add(new Student {
                Id = 6, Name = "Mitchel Studants", User = student2
            });
        }
示例#28
0
 public void RemoveRole(ApplicationRole applicationRole)
 {
     _context.ApplicationRoles.Remove(applicationRole);
 }
 public RoleViewModel(ApplicationRole role)
 {
     Id   = role.Id;
     Name = role.Name;
 }
示例#30
0
        public async Task <Tuple <bool, string[]> > DeleteRoleAsync(ApplicationRole role)
        {
            var result = await _roleManager.DeleteAsync(role);

            return(Tuple.Create(result.Succeeded, result.Errors.Select(e => e.Description).ToArray()));
        }
示例#31
0
        protected async Task PopulateUsers()
        {
            var role1 = new ApplicationRole()
            {
                Id   = "role1",
                Name = "role1",
            };
            var role2 = new ApplicationRole()
            {
                Id   = "role2",
                Name = "role2",
            };
            var role3 = new ApplicationRole()
            {
                Id   = "role3",
                Name = "role3",
            };

            await this.DbContext.Roles.AddAsync(role1);

            await this.DbContext.Roles.AddAsync(role2);

            await this.DbContext.Roles.AddAsync(role3);

            await this.DbContext.SaveChangesAsync();

            await this.DbContext.Users.AddAsync(new ApplicationUser()
            {
                Id          = "user1",
                FirstName   = "first1",
                LastName    = "last1",
                Email       = "*****@*****.**",
                PhoneNumber = "111111",
                Roles       = new List <IdentityUserRole <string> >()
                {
                    new IdentityUserRole <string>()
                    {
                        UserId = "user1", RoleId = "role1",
                    }
                },
            });

            await this.DbContext.Users.AddAsync(new ApplicationUser()
            {
                Id          = "user2",
                FirstName   = "first2",
                LastName    = "last2",
                Email       = "*****@*****.**",
                PhoneNumber = "222222",
                Roles       = new List <IdentityUserRole <string> >()
                {
                    new IdentityUserRole <string>()
                    {
                        UserId = "user2", RoleId = "role2",
                    }, new IdentityUserRole <string>()
                    {
                        UserId = "user2", RoleId = "role3",
                    }
                },
            });

            await this.DbContext.Users.AddAsync(new ApplicationUser()
            {
                Id          = "user3",
                FirstName   = "first3",
                LastName    = "last3",
                Email       = "*****@*****.**",
                PhoneNumber = "333333",
                Roles       = new List <IdentityUserRole <string> >()
                {
                    new IdentityUserRole <string>()
                    {
                        UserId = "user3", RoleId = "role3",
                    }
                },
            });

            await this.DbContext.SaveChangesAsync();
        }
示例#32
0
 public void Update(ApplicationRole entity)
 {
     this.Data.Roles.Update(entity);
     this.Data.SaveChanges();
 }
示例#33
0
 public void Create(ApplicationRole entity)
 {
     this.Data.Roles.Add(entity);
     this.Data.SaveChanges();
 }
示例#34
0
        public async Task <(bool Succeeded, string[] Errors)> DeleteRoleAsync(ApplicationRole role)
        {
            var result = await _roleManager.DeleteAsync(role);

            return(result.Succeeded, result.Errors.Select(e => e.Description).ToArray());
        }
示例#35
0
        public static void EnsureSeedData(IServiceProvider serviceProvider)
        {
            //1.dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
            //2.dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
            //3.dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o Data
            //4.dotnet run /seed
            Console.WriteLine("Seeding database...");

            using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                {
                    var context = scope.ServiceProvider.GetService <ApplicationDbContext>();
                    context.Database.Migrate();

                    var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                    var roleMgr = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >();

                    var BlogCore_Users     = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")));
                    var BlogCore_Roles     = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")));
                    var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")));

                    foreach (var user in BlogCore_Users)
                    {
                        if (user == null || user.uLoginName == null)
                        {
                            continue;
                        }
                        var userItem = userMgr.FindByNameAsync(user.uLoginName).Result;
                        var rid      = BlogCore_UserRoles.FirstOrDefault(d => d.UserId == user.uID)?.RoleId;
                        var rName    = BlogCore_Roles.Where(d => d.Id == rid).Select(d => d.Id).ToList();
                        var roleName = BlogCore_Roles.FirstOrDefault(d => d.Id == rid)?.Name;

                        if (userItem == null)
                        {
                            if (rid > 0 && rName.Count > 0)
                            {
                                userItem = new ApplicationUser
                                {
                                    UserName   = user.uLoginName,
                                    LoginName  = user.uRealName,
                                    sex        = user.sex,
                                    age        = user.age,
                                    birth      = user.birth,
                                    addr       = user.addr,
                                    tdIsDelete = user.tdIsDelete
                                };

                                //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result;

                                // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了
                                var pwdInit = "BlogIdp123$InitPwd";
                                //if (userItem.UserName== "blogadmin")
                                //{
                                //    pwdInit = "#InitPwd";
                                //}
                                var result = userMgr.CreateAsync(userItem, pwdInit).Result;
                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }

                                var claims = new List <Claim> {
                                    new Claim(JwtClaimTypes.Name, user.uRealName),
                                    new Claim(JwtClaimTypes.Email, $"{user.uLoginName}@email.com"),
                                    new Claim("rolename", roleName),
                                };

                                claims.AddRange(rName.Select(s => new Claim(JwtClaimTypes.Role, s.ToString())));


                                result = userMgr.AddClaimsAsync(userItem, claims).Result;


                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }
                                Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表
                            }
                            else
                            {
                                Console.WriteLine($"{user?.uLoginName} doesn't have a corresponding role.");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"{userItem?.UserName} already exists");
                        }
                    }

                    foreach (var role in BlogCore_Roles)
                    {
                        if (role == null || role.Name == null)
                        {
                            continue;
                        }
                        var roleItem = roleMgr.FindByNameAsync(role.Name).Result;

                        if (roleItem != null)
                        {
                            role.Name = role.Name + Guid.NewGuid().ToString("N");
                        }

                        roleItem = new ApplicationRole
                        {
                            CreateBy    = role.CreateBy,
                            Description = role.Description,
                            IsDeleted   = role.IsDeleted != null ? (bool)role.IsDeleted : true,
                            CreateId    = role.CreateId,
                            CreateTime  = role.CreateTime,
                            Enabled     = role.Enabled,
                            Name        = role.Name,
                            OrderSort   = role.OrderSort,
                        };

                        var result = roleMgr.CreateAsync(roleItem).Result;
                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }
                        Console.WriteLine($"{roleItem?.Name} created");//AspNetUserClaims 表
                    }
                }
            }

            Console.WriteLine("Done seeding database.");
            Console.WriteLine();
        }
示例#36
0
 public async Task<IActionResult> DeleteRole(string id, ApplicationRole model)
 {
     if (ModelState.IsValid)
     {
         var data = await _roleManager.FindByIdAsync(id);
         var result = await _roleManager.DeleteAsync(data);
         if (result.Succeeded)
         {
             return RedirectToAction(nameof(AdminController.RoleIndex));
         }
         AddErrors(result);
     }
     return View(model);
 }
示例#37
0
 protected override Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim <string> CreateRoleClaim(ApplicationRole role, Claim claim) =>
 new Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim <string>
 {
     RoleId     = role.Id,
     ClaimType  = claim.Type,
     ClaimValue = claim.Value
 };
示例#38
0
        protected override void Seed(IdentityDataContext context)
        {
            if (!context.Roles.Any(x => x.Name == "admin"))
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);

                var role = new ApplicationRole()
                {
                    Name        = "admin",
                    Description = "yönetici rolü"
                };

                manager.Create(role);
            }

            if (!context.Roles.Any(x => x.Name == "user"))
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);

                var role = new ApplicationRole()
                {
                    Name        = "user",
                    Description = "user rolü"
                };

                manager.Create(role);
            }

            if (!context.Roles.Any(x => x.Name == "emregulten"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);

                var user = new ApplicationUser()
                {
                    Name     = "emre",
                    Surname  = "Gulten",
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

                manager.Create(user, "1234567");
                manager.AddToRole(user.Id, "admin");
                manager.AddToRole(user.Id, "user");
            }

            if (!context.Roles.Any(x => x.Name == "aligulten"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);

                var user = new ApplicationUser()
                {
                    Name     = "ali",
                    Surname  = "Gulten",
                    UserName = "******",
                    Email    = "*****@*****.**"
                };

                manager.Create(user, "1234567");

                manager.AddToRole(user.Id, "user");
            }

            base.Seed(context);
        }
示例#39
0
 public void UpdateRole(ApplicationRole applicationRole)
 {
     _context.ApplicationRoles.Update(applicationRole);
 }
示例#40
0
        public static async Task Initialize(ApplicationDbContext context,
                                            UserManager <ApplicationUser> userManager,
                                            RoleManager <ApplicationRole> roleManager)
        {
            //context.Database.EnsureCreated();


            string password = "******";

            //foreach (var role in roles) {
            //    if (await roleManager.FindByNameAsync(role.Name) == null)
            //    {
            //        await roleManager.CreateAsync(role);
            //    }
            //}

            if (await roleManager.FindByNameAsync("Admin") == null)
            {
                ApplicationRole role = new ApplicationRole();
                role.Name = "Admin";
                await roleManager.CreateAsync(role);
            }
            if (await roleManager.FindByNameAsync("Coach") == null)
            {
                ApplicationRole role = new ApplicationRole();
                role.Name = "Coach";
                await roleManager.CreateAsync(role);
            }
            if (await roleManager.FindByNameAsync("Athlete") == null)
            {
                ApplicationRole role = new ApplicationRole();
                role.Name = "Athlete";
                await roleManager.CreateAsync(role);
            }


            foreach (var user in useres)
            {
                if (await userManager.FindByNameAsync(user.UserName) == null)
                {
                    var result = await userManager.CreateAsync(user);

                    if (result.Succeeded)
                    {
                        await userManager.AddPasswordAsync(user, password);

                        if (user.UserName == "mitchel")
                        {
                            await userManager.AddToRoleAsync(user, "Coach");
                        }
                        else
                        {
                            await userManager.AddToRoleAsync(user, "Athlete");
                        }
                    }
                }
            }

            #region TestType

            foreach (var type in testTypes)
            {
                if (context.TestType.FirstOrDefault(t => t.Name == type.Name) == null)
                {
                    context.TestType.Add(type);
                    context.SaveChanges();
                    if (type.ID > 0)
                    {
                        if (type.Name == "Coopertest")
                        {
                            foreach (var rating in cooperTestfitnessRatings)
                            {
                                rating.TestTypeID = type.ID;
                                context.FitnessRating.Add(rating);
                                context.SaveChanges();
                            }
                        }
                        else
                        {
                            foreach (var rating in sprintTestfitnessRatings)
                            {
                                rating.TestTypeID = type.ID;
                                context.FitnessRating.Add(rating);
                                context.SaveChanges();
                            }
                        }
                    }
                }
            }
            #endregion

            #region CoachAthlate
            var userList = await userManager.GetUsersInRoleAsync("Coach");

            var coachUser   = userList.FirstOrDefault();
            var athleteList = await userManager.GetUsersInRoleAsync("Athlete");

            var coachAtheles = context.CoachAthlete.Where(c => c.CoachID == coachUser.Id && !c.IsRemoved).ToList();
            if (coachAtheles == null || coachAtheles.Count <= 0)
            {
                foreach (var athlete in athleteList)
                {
                    var coachAthlete = new CoachAthlete();
                    coachAthlete.CoachID   = coachUser.Id;
                    coachAthlete.AthleteID = athlete.Id;
                    context.CoachAthlete.Add(coachAthlete);
                    context.SaveChanges();
                }
            }
            #endregion
        }
示例#41
0
 public async Task AddRole(ApplicationRole applicationRole)
 {
     await _context.ApplicationRoles.AddAsync(applicationRole);
 }
示例#42
0
 public ApplicationUserRoles(ApplicationUser user, ApplicationRole role)
 {
     this.UserId = user.Id;
     this.RoleId = role.Id;
 }
示例#43
0
 public static ApplicationIdentityRole CopyApplicationRoleProperties(this ApplicationIdentityRole identityRole, ApplicationRole applicationRole)
 {
     if (identityRole == null)
     {
         return(null);
     }
     if (applicationRole == null)
     {
         return(null);
     }
     identityRole.Name = applicationRole.Name;
     identityRole.Id   = applicationRole.Id;
     foreach (var userRole in applicationRole.Users)
     {
         identityRole.Users.Add(userRole.ToIdentityUserRole());
     }
     return(identityRole);
 }
示例#44
0
        // GET: /Roles/Edit/5
        public async Task<ActionResult> Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var role = await RoleManager.FindByIdAsync(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            
            //Role roleModel = new Role { Id = role.Id, Name = role.Name };
            ApplicationRole roleModel = new ApplicationRole { Id = role.Id, Name = role.Name };
            // Update the new Description property for the ViewModel:
            roleModel.Description = role.Description;

            return View(roleModel);
        }
        // 3. Insert Data Into Student Table From ApplicationForm Table If applicantId && IsAdmitted true
        public async Task <Student> SaveStudent(string applicantId)
        {
            if (_context != null)
            {
                // Find applicantId  in ApplicationForm table
                ApplicationForm dbEntry = _context.ApplicationForm.Where(a => a.ApplicantId == applicantId && a.IsSelected == true && a.IsAdmitted == true).FirstOrDefault();

                if (dbEntry != null)
                {
                    // Find StudentIdNo already exit in Student Table
                    Student studentExists = _context.Student.Where(s => s.StudentIdNo == dbEntry.ApplicantId).FirstOrDefault();

                    if (studentExists == null)
                    {
                        try
                        {
                            Student student = new Student()
                            {
                                StudentIdNo          = dbEntry.ApplicantId,
                                FirstName            = dbEntry.FirstName,
                                LastName             = dbEntry.LastName,
                                DateOfBirth          = dbEntry.DateOfBirth,
                                Gender               = dbEntry.Gender,
                                Religion             = dbEntry.Religion,
                                BirthRegistrationNo  = dbEntry.BirthRegistrationNo,
                                ImageUrl             = dbEntry.ImageUrl,
                                FatherName           = dbEntry.FatherName,
                                FatherPhone          = dbEntry.FatherPhone,
                                FatherOccupation     = dbEntry.FatherOccupation,
                                MotherName           = dbEntry.MotherName,
                                MotherPhone          = dbEntry.MotherPhone,
                                MotherOccupation     = dbEntry.MotherOccupation,
                                MonthlyFamillyIncome = dbEntry.MonthlyFamillyIncome,
                                FormarSchoolName     = dbEntry.FormarSchoolName,
                                AdmissionDate        = DateTime.UtcNow,
                                QuotaId              = dbEntry.QuotaId,
                                PresentAddress       = dbEntry.PresentAddress,
                                ParmanentAddress     = dbEntry.ParmanentAddress,
                                PostOfficeId         = dbEntry.PostOfficeId,

                                Password        = "******",
                                ConfirmPassword = "******"
                            };
                            _context.Student.Add(student);
                            try
                            {
                                ApplicationUser user = new ApplicationUser()
                                {
                                    UserName     = student.StudentIdNo,
                                    FirstName    = student.FirstName,
                                    LastName     = student.LastName,
                                    PasswordHash = student.Password
                                };
                                IdentityResult result = await _userManager.CreateAsync(user, student.ConfirmPassword);

                                if (result.Succeeded)
                                {
                                    Task <IdentityResult> roleResult;
                                    //Check that there is an Administrator role and create if not
                                    Task <bool> hasStudentRole = _rollManager.RoleExistsAsync(UserRoles.Student);
                                    hasStudentRole.Wait();
                                    if (!hasStudentRole.Result)
                                    {
                                        ApplicationRole roleCreate = new ApplicationRole();
                                        roleCreate.Name = UserRoles.Student;
                                        roleResult      = _rollManager.CreateAsync(roleCreate);
                                        roleResult.Wait();
                                    }
                                    Task <IdentityResult> newUserRole = _userManager.AddToRoleAsync(user, UserRoles.Student);
                                    newUserRole.Wait();
                                    try
                                    {
                                        //Commit the transaction
                                        await _context.SaveChangesAsync();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            return(student);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    return(null);
                }
                return(null);
            }
            return(null);
        }
示例#46
0
 protected override async Task OnInitializedAsync()
 {
     model = await RoleManager.FindByIdAsync(Id);
 }
        public static void InitializeIdentity(ApplicationDbContext context)
        {
            #region Contracts

            if (context == null) throw new ArgumentNullException();

            #endregion

            // Default - User
            const string adminUserName = "******";
            const string adminUserPassword = "******";

            const string guestUserName = "******";
            const string guestUserPassword = "******";

            // Default - Role
            const string adminRoleName = "Admin";
            const string guestRoleName = "Guest";

            // Default - Permission
            const string aboutPermissionName = "AboutAccess";
            const string contactPermissionName = "ContactAccess";


            // Manager
            var userManager = HttpContext.Current.GetOwinContext().Get<ApplicationUserManager>();
            var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
            var permissionManager = HttpContext.Current.GetOwinContext().Get<ApplicationPermissionManager>();


            // User
            var adminUser = userManager.FindByName(adminUserName);
            if (adminUser == null)
            {
                adminUser = new ApplicationUser { UserName = adminUserName, Email = adminUserName };
                userManager.Create(adminUser, adminUserPassword);
                userManager.SetLockoutEnabled(adminUser.Id, false);
            }

            var guestUser = userManager.FindByName(guestUserName);
            if (guestUser == null)
            {
                guestUser = new ApplicationUser { UserName = guestUserName, Email = guestUserName };
                userManager.Create(guestUser, guestUserPassword);
                userManager.SetLockoutEnabled(guestUser.Id, false);
            }

            // Role
            var adminRole = roleManager.FindByName(adminRoleName);
            if (adminRole == null)
            {
                adminRole = new ApplicationRole(adminRoleName);
                roleManager.Create(adminRole);
            }

            var guestRole = roleManager.FindByName(guestRoleName);
            if (guestRole == null)
            {
                guestRole = new ApplicationRole(guestRoleName);
                roleManager.Create(guestRole);
            }

            // Permission
            var aboutPermission = permissionManager.FindByName(aboutPermissionName);
            if (aboutPermission == null)
            {
                aboutPermission = new ApplicationPermission(aboutPermissionName);
                permissionManager.Create(aboutPermission);
            }

            var contactPermission = permissionManager.FindByName(contactPermissionName);
            if (contactPermission == null)
            {
                contactPermission = new ApplicationPermission(contactPermissionName);
                permissionManager.Create(contactPermission);
            }


            // UserAddToRole 
            IList<string> rolesForUser = null;

            rolesForUser = userManager.GetRoles(adminUser.Id);
            if (rolesForUser.Contains(adminRole.Name) == false)
            {
                userManager.AddToRole(adminUser.Id, adminRole.Name);
            }

            rolesForUser = userManager.GetRoles(guestUser.Id);
            if (rolesForUser.Contains(guestRole.Name) == false)
            {
                userManager.AddToRole(guestUser.Id, guestRole.Name);
            }


            // PermissionAddToRole 
            IList<string> rolesForPermission = null;

            rolesForPermission = permissionManager.GetRolesById(aboutPermission.Id);
            if (rolesForPermission.Contains(adminRole.Name) == false)
            {
                permissionManager.AddToRole(aboutPermission.Id, adminRole.Name);
            }

            rolesForPermission = permissionManager.GetRolesById(contactPermission.Id);
            if (rolesForPermission.Contains(adminRole.Name) == false)
            {
                permissionManager.AddToRole(contactPermission.Id, adminRole.Name);
            }
        }
示例#48
0
        protected override void Seed(MovieReviewsDbContext context)   // Let's seed the DB with default records
        {
            // Seed Movies
            IList <Movie> defaultMovies = new List <Movie>();

            defaultMovies.Add(new Movie()
            {
                MovieName   = "The Matrix",
                MovieYear   = 1999,
                Category    = "Sci-Fi",
                PathToImage = "/Content/Images/matrix.jpg",
                Description = " It depicts a dystopian future in which reality as perceived by most humans is actually a simulated reality called 'the Matrix', created by sentient machines to subdue the human population, while their bodies' heat and electrical activity are used as an energy source",
                Stars       = 10,
                Review      = "Without a doubt one of the best and most influential movies of all time, the Matrix is the defining science fiction film of the 1990's and the biggest leap the genre has taken since Stanley Kubrick's 2001: a Space Odyssey and Ridley Scott's Blade Runner"
            });
            defaultMovies.Add(new Movie()
            {
                MovieName   = "Fight Club",
                MovieYear   = 1999,
                Category    = "Drama",
                PathToImage = "/Content/Images/fight_club.jpg",
                Description = "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.",
                Stars       = 9.5,
                Review      = "The script was tight, the theme fascinating, the acting incredible (especially Edward Norton, as one might expect), the direction inspired, and the cinematography stunning. It is one of the few films of the past five years that deserves to be seen multiple times. In fact, if you have seen it only once, you have missed something"
            });
            defaultMovies.Add(new Movie()
            {
                MovieName   = "Back to the Future",
                MovieYear   = 1985,
                Category    = "Sci-Fi",
                PathToImage = "/Content/Images/back_future.jpg",
                Description = "Marty McFly, a 17-year-old high school student, is accidentally sent thirty years into the past in a time-traveling DeLorean invented by his close friend, the maverick scientist Doc Brown.",
                Stars       = 8.5,
                Review      = "Back To The Future is such an inventive and exciting piece of filmmaking that it is impossible to forget about it. The casting of every character involved was absolutely perfect, and the performances were spectacular"
            });
            defaultMovies.Add(new Movie()
            {
                MovieName   = "Star Wars: Episode IV - A New Hope ",
                MovieYear   = 1977,
                Category    = "Fantasy",
                PathToImage = "/Content/Images/star_wars.jpg",
                Description = "Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a Wookiee and two droids to save the galaxy from the Empire's world-destroying battle station, while also attempting to rescue Princess Leia from the evil Darth Vader.",
                Stars       = 9,
                Review      = "Filmmakers have tried for decades, but they can't make a better space saga. It's the perfect stand-alone science fiction film that's only rivaled by its darker sequel."
            });

            context.Movies.AddRange(defaultMovies);

            // Seed Roles and Users
            if (!context.Roles.Any(i => i.Name == "Administrator"))   // If there is no such role create it
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);
                var role    = new ApplicationRole()
                {
                    Name = "Administrator"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(i => i.Name == "Normal")) // If there is no such role create it
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);
                var role    = new ApplicationRole()
                {
                    Name = "Normal"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(i => i.Name == "Guest")) // If there is no such role create it
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);
                var role    = new ApplicationRole()
                {
                    Name = "Guest"
                };
                manager.Create(role);
            }

            if (!context.Users.Any(i => i.UserName == "root")) //Since this is test environment, create root user with pw root
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser()
                {
                    UserName = "******", Email = "*****@*****.**", FirstName = "root", LastName = "root"
                };
                manager.Create(user, "root123");

                manager.AddToRole(user.Id, "Administrator");
            }
            if (!context.Users.Any(i => i.UserName == "guest")) // guest user
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser()
                {
                    UserName = "******", Email = "*****@*****.**", FirstName = "guest", LastName = "guest"
                };
                manager.Create(user, "guest1337");
                manager.AddToRole(user.Id, "Guest");
            }


            base.Seed(context);
        }
        public async Task<ActionResult> Create(RoleViewModel roleViewModel)
        {
            if (ModelState.IsValid)
            {
                var role = new ApplicationRole(roleViewModel.Name);

                // Save the new Description property:
                role.Description = roleViewModel.Description;
                var roleresult = await RoleManager.CreateAsync(role);
                if (!roleresult.Succeeded)
                {
                    ModelState.AddModelError("", roleresult.Errors.First());
                    return View();
                }
                return RedirectToAction("Index");
            }
            return View();
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Register(UserViewModel model, string returnUrl = null)
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName       = model.Email,
                    Email          = model.Email,
                    Name           = model.Name,
                    Reknown        = model.Reknown,
                    Bio            = model.Bio,
                    EmailConfirmed = false
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    URLShortenerService urlShortener = new URLShortenerService();

                    await new EmailServices().SendEmailAsync(model.Email, "Confirm your account",
                                                             urlShortener.ShortenIt(callbackUrl), EmailServices.EmailType.Register);

                    ApplicationRole mRole = null;
                    if (model.ApplicationRoleId != null)
                    {
                        mRole = await _roleManager.FindByIdAsync(model.ApplicationRoleId);
                    }
                    ApplicationRole applicationRole = mRole != null && mRole.Name.Equals("Admin") ? mRole : await _roleManager.FindByIdAsync(_roleManager.Roles.Single(r => r.Name.Equals("User")).Id);

                    if (applicationRole != null)
                    {
                        IdentityResult roleResult = await _userManager.AddToRoleAsync(user, applicationRole.Name);

                        if (roleResult.Succeeded)
                        {
                            BlobServices bs = new BlobServices();
                            if (user.ProfilePictureImage != null)
                            {
                                user.ProfilePictureImage = await bs.UploadImageToBlobStorageAsync(Convert.FromBase64String(model.ProfilePictureImage), user.Id);
                            }
                            await _userManager.UpdateAsync(user);

                            string message = "User created a new account with password.";
                            _logger.LogInformation(3, message);
                            return(Ok(Json(new { message = message, user = user })));
                        }
                    }
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest(Json(new { messages = errors })));
        }
示例#51
0
 public UserRole(ApplicationRole role)
 {
     Id   = role.Id;
     Name = role.Name;
 }
示例#52
0
        private static async Task SeedUserAsync(
            RoleManager <ApplicationRole> roleManager,
            UserManager <ApplicationUser> userManager, ApplicationDbContext context)
        {
            var role = await roleManager.FindByNameAsync(UserRoles.Admin);

            if (role == null)
            {
                role = new ApplicationRole
                {
                    Id = Guid.NewGuid()
                };
                await roleManager.CreateAsync(new ApplicationRole { Id = role.Id, Name = UserRoles.Admin });
            }
            var studentRole = await roleManager.FindByNameAsync(UserRoles.Student);

            if (studentRole == null)
            {
                await roleManager.CreateAsync(new ApplicationRole { Id = Guid.NewGuid(), Name = UserRoles.Student });
            }

            var teacherRole = await roleManager.FindByNameAsync(UserRoles.Teacher);

            if (teacherRole == null)
            {
                await roleManager.CreateAsync(new ApplicationRole { Id = Guid.NewGuid(), Name = UserRoles.Teacher });
            }

            var user = await userManager.FindByNameAsync(AdminLogin);

            if (user == null)
            {
                user = new ApplicationUser()
                {
                    UserName             = AdminLogin,
                    Email                = AdminEmail,
                    EmailConfirmed       = true,
                    PhoneNumber          = AdminPhone,
                    PhoneNumberConfirmed = true,
                    TwoFactorEnabled     = false,
                    FirstName            = "Админ",
                    LastName             = "Главный",
                    Patronymic           = "Системы",
                };
                var result = await userManager.CreateAsync(user, Password);

                if (!result.Succeeded)
                {
                    return;
                }
                else
                {
                    context.UserRoles.Add(new IdentityUserRole <Guid>
                    {
                        UserId = user.Id,
                        RoleId = role.Id,
                    });
                }
            }

            await context.SaveChangesAsync();
        }
示例#53
0
        public async Task <IActionResult> EditUser(string id, EditUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = await userManager.FindByIdAsync(id);

                if (user != null)
                {
                    user.UserName        = model.Name;
                    user.FirstName       = model.FirstName;
                    user.LastName        = model.LastName;
                    user.Group           = model.Group;
                    user.Email           = model.Email;
                    user.StudentId       = model.StudentId;
                    user.StudyEndDate    = model.StudyEndDate;
                    user.StudyStartDate  = model.StudyStartDate;
                    user.PasswordForShow = model.ApplicationRoleId == "3" ? model.PasswordForShow : string.Empty;

                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (model.OldPassword != model.PasswordForShow && model.ApplicationRoleId == "3")
                    {
                        IdentityResult passwordChangeResult = await userManager.ChangePasswordAsync(user, model.OldPassword, model.PasswordForShow);
                    }
                    if (result.Succeeded)
                    {
                        try
                        {
                            string existingRole   = userManager.GetRolesAsync(user).Result.Single();
                            string existingRoleId = roleManager.Roles.Single(r => r.Name == existingRole).Id;
                            if (existingRoleId != model.ApplicationRoleId)
                            {
                                IdentityResult roleResult = await userManager.RemoveFromRoleAsync(user, existingRole);

                                if (roleResult.Succeeded)
                                {
                                    ApplicationRole applicationRole = await roleManager.FindByIdAsync(model.ApplicationRoleId);

                                    if (applicationRole != null)
                                    {
                                        IdentityResult newRoleResult = await userManager.AddToRoleAsync(user, applicationRole.Name);

                                        if (newRoleResult.Succeeded)
                                        {
                                            return(RedirectToAction("Index"));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                return(RedirectToAction("Index"));
                            }
                        }
                        catch
                        {
                            ApplicationRole applicationRole = await roleManager.FindByIdAsync(model.ApplicationRoleId);

                            if (applicationRole != null)
                            {
                                IdentityResult newRoleResult = await userManager.AddToRoleAsync(user, applicationRole.Name);

                                if (newRoleResult.Succeeded)
                                {
                                    return(RedirectToAction("Index"));
                                }
                            }
                        }
                    }
                }
            }
            return(PartialView("_EditUser", model));
        }
示例#54
0
        protected override void Seed(Workflow.DataAccess.WorkflowDbContext context)
        {
            var userManager =
                new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new WorkflowDbContext()));

            userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };

            var roleManager =
                new RoleManager <ApplicationRole>(new RoleStore <ApplicationRole>(new WorkflowDbContext()));

            string name      = "*****@*****.**";
            string password  = "******";
            string firstName = "Admin";
            string roleName  = "Admin";

            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role = new ApplicationRole(roleName);
                var roleResult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationUser {
                    UserName = name, Email = name, FirstName = firstName
                };
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }

            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }



            string accountNumber = "ABC123";

            context.Customers.AddOrUpdate(
                c => c.AccountNumber,
                new Customer
            {
                AccountNumber = accountNumber,
                CompanyName   = "IT Best Company",
                Address       = "Marsza³kowska 13",
                City          = "Warsaw",
                State         = "Mazowieckie",
                ZipCode       = "02140"
            });

            context.SaveChanges();

            Customer customer = context.Customers.First(c => c.AccountNumber == accountNumber);

            string description = "First work order";

            context.WorkOrders.AddOrUpdate(
                wo => wo.Description,
                new WorkOrder {
                Description = description, CustomerId = customer.Id, WorkOrderStatus = WorkOrderStatus.Created
            });

            context.SaveChanges();

            WorkOrder workOrder = context.WorkOrders.First(wo => wo.Description == description);

            context.Parts.AddOrUpdate(
                p => p.InventoryItemCode,
                new Part {
                InventoryItemCode = "THING1", InventoryItemName = "Thing Number One", Quantity = 1, UnitPrice = 1.23m, WorkOrderId = workOrder.Id
            });

            context.Labors.AddOrUpdate(
                l => l.ServiceItemCode,
                new Labor {
                ServiceItemCode = "INSTALL", ServiceItemName = "Installation", LaborHours = 9.87m, Rate = 35.75m, WorkOrderId = workOrder.Id
            });

            string categoryName = "Devices";

            context.Categories.AddOrUpdate(
                c => c.Name,
                new Category {
                Name = categoryName
            });

            context.SaveChanges();

            Category category = context.Categories.First(c => c.Name == categoryName);

            context.InventoryItems.AddOrUpdate(
                ii => ii.Code,
                new InventoryItem {
                Code = "THING2", Name = "A Second Kind of Thing", UnitPrice = 3.33m, CategoryId = category.Id
            });

            context.ServiceItems.AddOrUpdate(
                si => si.Code,
                new ServiceItem {
                Code = "CLEAN", Name = "General Cleaning", Rate = 23.50m
            });
        }
 public static bool CanAssign(this ApplicationRole creatorRole, ApplicationRole roleBeingAssigned)
 {
     return creatorRole.Rank < roleBeingAssigned.Rank;
 }
示例#56
0
        protected override void Seed(ApplicationContext db)
        {
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(db));

            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(db));


            // создаем две роли
            var role1 = new ApplicationRole {
                Name = "admin"
            };
            var role2 = new ApplicationRole {
                Name = "user"
            };
            var role3 = new ApplicationRole {
                Name = "blockedUser"
            };
            var role4 = new ApplicationRole {
                Name = "moderator"
            };

            // добавляем роли в бд
            roleManager.Create(role1);
            roleManager.Create(role2);
            roleManager.Create(role3);
            roleManager.Create(role4);

            var card1 = new VisaCard()
            {
                Name             = "Test Card1",
                Number           = "1234567891234567",
                Month            = "10",
                Year             = "20",
                SecurityCodeHash = "123"
            };
            var card2 = new MasterCard()
            {
                Name             = "Test Card2",
                Number           = "9887655432216554",
                Month            = "07",
                Year             = "24",
                SecurityCodeHash = "000"
            };
            var card3 = new MasterCard()
            {
                Name             = "Test Card3",
                Number           = "1887655432216552",
                Month            = "02",
                Year             = "26",
                SecurityCodeHash = "000"
            };
            var card4 = new MasterCard()
            {
                Name             = "Test Card4",
                Number           = "1887655432216444",
                Month            = "06",
                Year             = "27",
                SecurityCodeHash = "000"
            };

            var cards = new List <CreditCard>
            {
                card1,
                card2
            };
            var cards1 = new List <CreditCard>
            {
                card3
            };
            var cards2 = new List <CreditCard>
            {
                card4
            };

            db.CreditCards.Add(card1);
            db.CreditCards.Add(card2);
            db.CreditCards.Add(card3);
            db.CreditCards.Add(card4);

            //////////////create payments///////////
            var payment1 = new Payment()
            {
                Amount  = 100,
                Date    = DateTime.Now,
                Details = "First Test payment 100",
                IsSent  = true,
                Name    = "Test Payment",
            };

            var payment2 = new Payment()
            {
                Amount  = 9000,
                Date    = DateTime.Now,
                Details = "First Test payment 9000",
                IsSent  = true,
                Name    = "Test Payment",
            };

            var payments1 = new List <Payment>
            {
                payment1
            };

            var payments2 = new List <Payment>
            {
                payment2
            };

            db.Payments.Add(payment1);
            ////////create accounts/////////////////

            var account1 = new Account()
            {
                Balance         = 1000,
                CreditCard      = card3,
                Number          = 100000091,
                Name            = "Account1",
                PaymentsRecieve = payments1,
                PaymentsSent    = payments2
            };

            var account2 = new Account()
            {
                Balance         = 50000,
                CreditCard      = card4,
                Number          = 100000099,
                Name            = "Account2",
                PaymentsRecieve = payments2,
                PaymentsSent    = payments1
            };


            var accounts1 = new List <Account>
            {
                account1
            };

            var accounts2 = new List <Account>
            {
                account2
            };

            db.Accounts.Add(account1);
            db.Accounts.Add(account2);

            /////////////create user profiles/////////////

            var profile = new ClientProfile()
            {
                Name      = "Admin",
                BirthDate = DateTime.Now,
                Cards     = cards,
            };

            var userProfile1 = new ClientProfile()
            {
                Name      = "User1",
                BirthDate = DateTime.Now,
                Cards     = cards1,
                Accounts  = accounts1,
            };

            var userProfile2 = new ClientProfile()
            {
                Name      = "User2",
                BirthDate = DateTime.Now,
                Cards     = cards2,
                Accounts  = accounts2,
            };

            // создаем пользователей
            var admin = new ApplicationUser {
                Email = "*****@*****.**", UserName = "******", ClientProfile = profile, Role = "admin"
            };
            string password = "******";
            var    result   = userManager.Create(admin, password);

            var user1 = new ApplicationUser {
                Email = "*****@*****.**", UserName = "******", ClientProfile = userProfile1, Role = "user"
            };
            string password1 = "User123";
            var    result1   = userManager.Create(user1, password1);

            var user2 = new ApplicationUser {
                Email = "*****@*****.**", UserName = "******", ClientProfile = userProfile2, Role = "user"
            };
            string password2 = "User123";
            var    result2   = userManager.Create(user2, password2);

            // если создание пользователя прошло успешно
            if (result.Succeeded)
            {
                // добавляем для пользователя роль
                userManager.AddToRole(admin.Id, role1.Name);
            }

            if (result1.Succeeded)
            {
                // добавляем для пользователя роль
                userManager.AddToRole(user1.Id, role2.Name);
            }

            if (result2.Succeeded)
            {
                // добавляем для пользователя роль
                userManager.AddToRole(user2.Id, role2.Name);
            }

            base.Seed(db);
        }
示例#57
0
 public async Task<IActionResult> CreateRole(ApplicationRole model)
 {
     if (ModelState.IsValid)
     {
         var result = await _roleManager.CreateAsync(model);
         if (result.Succeeded)
         {
             return RedirectToAction(nameof(AdminController.RoleIndex));
         }
         AddErrors(result);
     }
     return View(model);
 }
示例#58
0
 public AddRoleCommand Add(ApplicationRole applicationRole)
 {
     return(_mapper.Map <AddRoleCommand>(applicationRole));
 }
示例#59
0
 public async Task<ActionResult> Create(RoleViewModel roleViewModel)
 {
     if (ModelState.IsValid)
     {
         // Use ApplicationRole, not IdentityRole:
         var role = new ApplicationRole(roleViewModel.Name);
         var roleresult = await RoleManager.CreateAsync(role);
         if (!roleresult.Succeeded)
         {
             ModelState.AddModelError("", roleresult.Errors.First());
             return View();
         }
         return RedirectToAction("Index");
     }
     return View();
 }
        //创建用户名为[email protected],密码为“Admin@123456”并把该用户添加到角色组"Admin"中
        public static void InitializeIdentityForEF(ApplicationDbContext db)
        {
            var          userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var          roleManager = HttpContext.Current.GetOwinContext().Get <ApplicationRoleManager>();
            const string name1       = "Admin";         //用户名
            const string email1      = "*****@*****.**"; //邮箱
            const string password1   = "Admin@123456";  //密码
            const string roleName1   = "管理员";           //用户要添加到的角色组
            const string name2       = "user";          //用户名
            const string email2      = "*****@*****.**";  //邮箱
            const string password2   = "User@123456";   //密码
            const string roleName2   = "普通用户";
            var          department1 = new Department {
                Name = "党政办"
            };                                                //机构
            var department2 = new Department {
                Name = "办事机构"
            };

            //如果没有Admin用户组则创建该组
            var role1 = roleManager.FindByName(roleName1);

            if (role1 == null)
            {
                role1 = new ApplicationRole()
                {
                    Name = roleName1, Description = roleName1
                };
                var roleresult = roleManager.Create(role1);
            }

            var role2 = roleManager.FindByName(roleName2);

            if (role2 == null)
            {
                role2 = new ApplicationRole()
                {
                    Name = roleName2, Description = roleName2
                };
                var roleresult = roleManager.Create(role2);
            }
            //如果没有[email protected]用户则创建该用户
            var user1 = userManager.FindByName(name1);

            if (user1 == null)
            {
                user1 = new ApplicationUser
                {
                    UserName = name1,
                    Email    = email1,
                    Password = password1,
                };
                var result = userManager.Create(user1, password1);
                result = userManager.SetLockoutEnabled(user1.Id, false);
            }

            var user2 = userManager.FindByName(name2);

            if (user2 == null)
            {
                user2 = new ApplicationUser
                {
                    UserName = name2,
                    Email    = email2,
                    Password = password2,
                };
                var result = userManager.Create(user2, password2);
                result = userManager.SetLockoutEnabled(user2.Id, false);
            }

            // 把用户[email protected]添加到用户组Admin中
            var rolesForUser1 = userManager.GetRoles(user1.Id);

            if (!rolesForUser1.Contains(role1.Name))
            {
                var result = userManager.AddToRole(user1.Id, role1.Name);
            }

            var rolesForUser2 = userManager.GetRoles(user2.Id);

            if (!rolesForUser2.Contains(role2.Name))
            {
                var result = userManager.AddToRole(user2.Id, role2.Name);
            }
            //添加机构
            var depart1 = db.Departments.FirstOrDefault(t => t.Name == department1.Name);

            if (depart1 == null)
            {
                db.Departments.Add(department1);
            }
            var depart2 = db.Departments.FirstOrDefault(t => t.Name == department2.Name);

            if (depart2 == null)
            {
                db.Departments.Add(department2);
            }
            //保存
            db.SaveChanges();

            //用户添加到机构
            db.Set <UserDepartment>().Add(new UserDepartment {
                DepartmentId = department1.Id, ApplicationUserId = user1.Id
            });
            db.Set <UserDepartment>().Add(new UserDepartment {
                DepartmentId = department2.Id, ApplicationUserId = user2.Id
            });
            db.SaveChanges();
        }