Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        private async Task CreateRoleForAstrid(ApplicationRole astridRole)
        {
            bool exists = await _roleManager.RoleExistsAsync(astridRole.Name);

            if (!exists)
            {
                await _roleManager.CreateAsync(astridRole);
            }
        }
Ejemplo n.º 3
0
        public async Task <IdentityResult> CreateRole(string role)
        {
            var exists = await _applicationRoleManager.RoleExistsAsync(role);

            if (exists)
            {
                return(new IdentityResult($"The {role} exists already."));
            }
            return(await _applicationRoleManager.CreateAsync(new IdentityRole(role)));
        }
Ejemplo n.º 4
0
        public async Task <ActionResult> AddRole(string roleName, string userId)
        {
            if (await RoleManager.RoleExistsAsync(roleName))
            {
                await UserManager.AddToRoleAsync(userId, roleName);
            }

            return(RedirectToAction("Index", new ManageRolesViewModel()
            {
                CurrentUserId = userId
            }));
        }
Ejemplo n.º 5
0
        public async Task CheckRole(string roleName)
        {
            var roleStore = new RoleStore <Role, int, UserRole>(context);
            ApplicationRoleManager roleManager = new ApplicationRoleManager(roleStore);

            if (!await roleManager.RoleExistsAsync(roleName))
            {
                var role = new Role();
                role.Name = roleName;
                roleManager.Create <Role, int>(role);
            }
        }
Ejemplo n.º 6
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (!await RoleManager.RoleExistsAsync("Users"))
                {
                    var roleResult = await RoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Users"));

                    if (!roleResult.Succeeded)
                    {
                        AddErrors(roleResult);
                        return(View(model));
                    }
                }
                var role = await RoleManager.FindByNameAsync("Users");

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);



                if (result.Succeeded)
                {
                    result = await UserManager.AddToRoleAsync(user.Id, "Users");

                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        return(RedirectToAction("Index", "Home"));
                    }
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> CreateRole_POST(CreateRoleViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (await RoleManager.RoleExistsAsync(model.Role))
            {
                ModelState.AddModelError("Role",
                                         $"The role '{model.Role}' is already registered!");
            }
            else
            {
                await RoleManager.CreateAsync(new ApplicationRole(model.Role));

                TempData["Message"] = $"Role '{model.Role}' created successfully!";
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Ejemplo n.º 8
0
        public async Task <bool> CreateRole(ClaimsPrincipal claim, ApplicationRoleViewModel data)
        {
            data.CreatedBy  = ExtBusinessLogic.UserValue(claim);
            data.ModifiedBy = ExtBusinessLogic.UserValue(claim);
            ApplicationRole roleData  = _mapper.Map <ApplicationRole>(data);
            bool            roleExist = await _roleManager.RoleExistsAsync(roleData.Name);

            if (roleExist)
            {
                throw new WebApiApplicationException(StatusCodes.Status409Conflict, ErrorMessages.RoleAlreadyExist);
            }

            roleData.GenerateNewId();
            var result = await _roleManager.CreateAsync(roleData);

            if (!result.Succeeded)
            {
                throw new WebApiApplicationException(StatusCodes.Status400BadRequest, ErrorMessages.CommonErrorMessage, result.Errors.ToList());
            }

            return(true);
        }
Ejemplo n.º 9
0
 public async Task <bool> RoleExistsAsync(string roleName)
 {
     return(await _appRoleManager.RoleExistsAsync(roleName));
 }
Ejemplo n.º 10
0
 private async Task <bool> RoleExistsAsync(string name)
 => await _roleManager.RoleExistsAsync(name);
Ejemplo n.º 11
0
        public async Task <ActionResult> RegisterStudent(RegisterStudentViewModel model)
        {
            var userdb = ApplicationDbContext.Create();

            if (string.IsNullOrWhiteSpace(model.SelectedCourse))
            {
                ModelState.AddModelError("Courses", "You Choosed Not valid Course");
            }
            int courseId = 0;

            if (model.SelectedCourse != null)
            {
                var validCourseId = int.TryParse(model.SelectedCourse, out int parametercourseId);
                if (validCourseId)
                {
                    courseId = parametercourseId;
                }
                else
                {
                    ModelState.AddModelError("Courses", "You Choosed Not valid Course");
                }

                //when admin create a student user we check for validation of choosed course .
                if (courseId < 1)
                {
                    ModelState.AddModelError("Courses", "You Choosed Not valid Course");
                }
                if (!userdb.Courses.Select(cid => cid.Id).Contains(courseId))
                {
                    ModelState.AddModelError("Courses", "You Choosed Not valid Course");
                }
            }
            //check if the user already registered in our system
            if (ModelState.IsValid)
            {
                var usercheck = await UserManager.FindByEmailAsync(model.Email);

                if (usercheck != null)
                {
                    ModelState.AddModelError("Email", "User Already registered");
                }
            }
            if (!await RoleManager.RoleExistsAsync("student"))
            {
                ModelState.AddModelError("", "Unkown Error , Student role deleted from the database maybe?");
            }
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, CourseId = courseId
                };
                //Auto generate password and set it to the account
                string genpas = PasswordGenerator();
                var    result = await UserManager.CreateAsync(user, genpas);

                //put the user in the choosed role
                await UserManager.AddToRoleAsync(user.Id, "student");

                if (result.Succeeded)
                {
                    // await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    #region //create message body
                    StringBuilder message = new StringBuilder();
                    // generating the message
                    message.Append("Welcome " + user.FullName + "! You registered in our System as student");
                    message.AppendLine("And Your password is (" + genpas + ") .<br/>");
                    message.AppendLine("We suggest you to change your auto generated pssword for more security .<br/>");
                    message.AppendLine(" Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a><br/>");
                    #endregion
                    await UserManager.SendEmailAsync(user.Id, "Confirm your account", message.ToString());

                    return(RedirectToAction("Index", "Courses"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form

            //if error happened we need to re create the courses list
            #region


            //same as before but courses list
            var courseList = userdb.Courses.Select(c => new { c.Name, c.Id, c.EndDate }).Where(sa => sa.EndDate > DateTime.Today);
            List <SelectListItem> courseListWithDefault = courseList.Select(course => new SelectListItem {
                Text = course.Name, Value = course.Id.ToString()
            }).ToList();
            var courseTip = new SelectListItem {
                Value = null,
                Text  = "--- Select Course---"
            };
            courseListWithDefault.Insert(0, courseTip);
            model.Courses = courseListWithDefault;
            #endregion
            //create a template of the user registert view model and set its properties{lists} our we created
            return(View(model));
        }
Ejemplo n.º 12
0
        protected override void Seed(ApplicationIdentityDbContext context)
        {
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context), context);
            var roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            userManager.PasswordValidator = new PasswordValidator()
            {
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireNonLetterOrDigit = false,
                RequireUppercase        = false,
                RequiredLength          = 1
            };

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

            var adminRole     = new ApplicationRole(GlobalInfo.Admin);
            var candidateRole = new ApplicationRole(GlobalInfo.Client);
            var managerRole   = new ApplicationRole(GlobalInfo.BankWorker);

            if (!roleManager.RoleExistsAsync(GlobalInfo.Admin).Result)
            {
                roleManager.CreateAsync(adminRole).Wait();
                roleManager.CreateAsync(candidateRole).Wait();
                roleManager.CreateAsync(managerRole).Wait();
            }

            var admin = new ApplicationUser
            {
                Email          = "*****@*****.**",
                EmailConfirmed = true,
                UserName       = "******",
                DomainId       = new Guid("B4B6780C-F3BE-4554-BFFD-BCFD18E93A94"),
                IsActive       = true
            };

            if (userManager.CreateAsync(admin, "123").Result == IdentityResult.Success)
            {
                userManager.AddToRoleAsync(admin.Id, adminRole.Name).Wait();
                userManager.AddProfileAsync(admin.DomainId, new UserProfileInfo
                {
                    FirstName = "Admin",
                    LastName  = "Admin"
                }).Wait();
            }

            var candidate = new ApplicationUser
            {
                Email          = "*****@*****.**",
                EmailConfirmed = true,
                UserName       = "******",
                DomainId       = new Guid("14620737-9BDF-4B4D-B6B9-01CD1EBE69EB"),
                IsActive       = true
            };

            if (userManager.CreateAsync(candidate, "123").Result == IdentityResult.Success)
            {
                userManager.AddToRoleAsync(candidate.Id, candidateRole.Name).Wait();
                userManager.AddProfileAsync(candidate.DomainId, new UserProfileInfo
                {
                    FirstName = "Petr",
                    LastName  = "Sidorenko"
                }).Wait();
            }

            var manager = new ApplicationUser
            {
                Email          = "*****@*****.**",
                EmailConfirmed = true,
                UserName       = "******",
                DomainId       = new Guid("4eabfa0e-118e-4131-8ec9-1dbd29f68d3a"),
                IsActive       = true
            };

            if (userManager.CreateAsync(manager, "123").Result == IdentityResult.Success)
            {
                userManager.AddToRoleAsync(manager.Id, managerRole.Name).Wait();
                userManager.AddProfileAsync(manager.DomainId, new UserProfileInfo
                {
                    FirstName = "BelarusBank",
                    LastName  = "BankWorker"
                }).Wait();
            }

            var BTABankWorker = new ApplicationUser
            {
                Email          = "*****@*****.**",
                EmailConfirmed = true,
                UserName       = "******",
                DomainId       = new Guid("AF789597-4EA1-4478-85E7-5A7D03D47948"),
                IsActive       = true
            };

            if (userManager.CreateAsync(BTABankWorker, "123").Result == IdentityResult.Success)
            {
                userManager.AddToRoleAsync(BTABankWorker.Id, managerRole.Name).Wait();
                userManager.AddProfileAsync(BTABankWorker.DomainId, new UserProfileInfo
                {
                    FirstName = "BTABank",
                    LastName  = "BankWorker"
                }).Wait();
            }
        }