public static void Start() { using (var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new UsersDbContext()))) { foreach (var roleName in RolesList.Where(roleName => !roleManager.RoleExists(roleName))) { roleManager.Create(new IdentityRole(roleName)); } } using ( var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new UsersDbContext())) ) { if (userManager.FindByName(Constants.AdminUserName) != null) { return; } var admin = new ApplicationUser {UserName = Constants.AdminUserName}; var result = userManager.Create(admin, "AdminPass"); if (!result.Succeeded) { var txt = new StringBuilder(); foreach (var error in result.Errors) { txt.AppendLine(error); } throw new Exception(txt.ToString()); } userManager.AddToRole(admin.Id, Constants.Roles.Admin); } }
public async Task<ActionResult> RegisterStudent(RegisterViewModel model) { try { if (ModelState.IsValid) { var user = new ApplicationUser {UserName = model.Login}; var result = await UserManager.CreateAsync(user, model.Password); await UserManager.AddToRoleAsync(user.Id, Constants.Roles.Student); if (result.Succeeded) { await SignInManager.SignInAsync(user, false, false); var studentInfo = new Student { Id = user.Id, Name = model.StudentRegisterVewModel.Name, Surname = model.StudentRegisterVewModel.Surname }; StudentRepository.InsertStudent(studentInfo); if (model.StudentRegisterVewModel.SubjectIds != null) { foreach (var subjectId in model.StudentRegisterVewModel.SubjectIds) { var subject = SubjectRepository.GetSubjectId(Guid.Parse(subjectId)); StudentRepository.AddSubjectForStudent(studentInfo, subject); } } return RedirectToAction("Index", "Home"); } AddErrors(result); } } catch (Exception e) { } // If we got this far, something failed, redisplay form return RedirectToAction("Index", "Home"); }
public async Task<ActionResult> RegisterProfessor(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser {UserName = model.Login, Email = model.Login}; var result = await UserManager.CreateAsync(user, model.Password); await UserManager.AddToRoleAsync(user.Id, Constants.Roles.Professor); if (result.Succeeded) { await SignInManager.SignInAsync(user, false, false); var professorInfo = new Professor { Id = user.Id, Name = model.ProfessorRegisterVewModel.Name, Surname = model.ProfessorRegisterVewModel.Surname }; ProfessorRepository.InsertProfessor(professorInfo); if (model.ProfessorRegisterVewModel.Subjects != null) { foreach (var subjectName in model.ProfessorRegisterVewModel.Subjects) { var subject = new Subject { Id = Guid.NewGuid(), Name = subjectName, Professor = professorInfo }; SubjectRepository.InsertSubject(subject); ProfessorRepository.AddSubjectForProfessor(professorInfo, subject); } } return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return RedirectToAction("Index", "Home"); }