public async Task <IActionResult> Delete([FromForm] string id)
        {
            try
            {
                if (this.ValidRoleForAction(_context, _auth, new string[] { "Admin" }))
                {
                    AppIdentityRole item = await _auth.GetRoleByIdAsync(id);

                    if (item != null)
                    {
                        var result = await _auth.DeleteRole(item);

                        if (result != null)
                        {
                            return(Ok(item));
                        }
                        else
                        {
                            return(BadRequest("Model cannot be  deleted"));
                        }
                    }
                    else
                    {
                        return(NotFound("Model not found"));
                    }
                }
                return(Forbid());
            }
            catch (Exception ex)
            {
                var arguments = this.GetBaseData(_context, _auth);
                _logger.LogException(ex, arguments.Email, arguments.Path);
                return(BadRequest($"{ex.GetType().Name} was thrown."));
            }
        }
        public async Task <IActionResult> Update([FromForm] RoleModel model)
        {
            try
            {
                if (this.ValidRoleForAction(_context, _auth, new string[] { "Admin" }))
                {
                    if (ModelState.IsValid)
                    {
                        AppIdentityRole item = await _auth.GetRoleByIdAsync(model.Id);

                        item.Name = model.Name;
                        var saved = await _auth.UpdateRole(item);

                        if (saved != null)
                        {
                            return(Ok(item));
                        }
                        else
                        {
                            return(BadRequest("Item cannot be updated"));
                        }
                    }
                    return(BadRequest("Model is not valid"));
                }
                return(Forbid());
            }
            catch (Exception ex)
            {
                var arguments = this.GetBaseData(_context, _auth);
                _logger.LogException(ex, arguments.Email, arguments.Path);
                return(BadRequest($"{ex.GetType().Name} was thrown."));
            }
        }
        public async Task <IActionResult> NewEmployee(NewEmployeeViewModel employee)
        {
            if (ModelState.IsValid)
            {
                var user = new AppIdentityUser
                {
                    UserName    = employee.UserName,
                    Name        = employee.Name,
                    Surname     = employee.Surname,
                    Email       = employee.Email,
                    BirthDate   = employee.BirthDate,
                    PhoneNumber = employee.MobileNumber
                };

                IdentityResult result = await _userManager.CreateAsync(user, employee.Password);

                if (result.Succeeded)
                {
                    AppIdentityRole appIdentityRole = await _roleManager.FindByIdAsync(employee.DepartmentId.ToString());

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

                        if (roleResult.Succeeded)
                        {
                            return(RedirectToAction("Index"));
                        }
                    }
                }
            }
            PopulateRolesDropDown(employee.DepartmentId);
            return(View(employee));
        }
 public IActionResult Register(Register obj)
 {
     if (ModelState.IsValid)
     {
         //if Manager role not exist create it
         //not good for real app
         if (!roleManager.RoleExistsAsync("Manager").Result)
         {
             AppIdentityRole role = new AppIdentityRole();
             role.Name        = "Manager";
             role.Description = "Can perform CRUD operations.";
             IdentityResult roleResult =
                 roleManager.CreateAsync(role).Result;
         }
         AppIdentityUser user = new AppIdentityUser();
         user.UserName  = obj.UserName;
         user.Email     = obj.Email;
         user.FullName  = obj.FullName;
         user.BirthDate = obj.BirthDate;
         IdentityResult result = userManager.CreateAsync
                                     (user, obj.Password).Result;
         if (result.Succeeded)
         {
             userManager.AddToRoleAsync(user, "Manager").Wait();
             return(RedirectToAction("SignIn", "Security"));
         }
         else
         {
             ModelState.AddModelError("", "Invalid user details!");
         }
     }
     return(View(obj));
 }
Esempio n. 5
0
        public IActionResult Register(Register register)
        {
            if (ModelState.IsValid)
            {
                if (!_roleManager.RoleExistsAsync("Manager").Result)
                {
                    var role = new AppIdentityRole();
                    role.Name        = "Manager";
                    role.Description = "Manager can perform CRUD operations";

                    var roleResult = _roleManager.CreateAsync(role).Result;
                }

                var user = new AppIdentityUser();
                user.UserName  = register.UserName;
                user.Email     = register.Email;
                user.FullName  = register.FullName;
                user.BirthDate = register.BirthDate;

                var result = _userManager.CreateAsync(user, register.Password).Result;

                if (result.Succeeded)
                {
                    _userManager.AddToRoleAsync(user, "Manager").Wait();
                    return(RedirectToAction("SignIn", "Security"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid User details");
                }
            }

            return(View(register));
        }
Esempio n. 6
0
        public async Task <CreateRoleRes> CreateNewRole(CreateRoleReq newRole)
        {
            CreateRoleRes response = new CreateRoleRes();

            try
            {
                AppIdentityRole appIdentityRole = new AppIdentityRole
                {
                    Name         = newRole.RoleName,
                    IsActive     = newRole.IsActive,
                    RolePriority = newRole.RolePriority
                };
                var result = await _roleManager.CreateAsync(appIdentityRole);

                if (result.Succeeded)
                {
                    response.RoleId   = appIdentityRole.Id;
                    response.RoleName = appIdentityRole.Name;
                    response.Message  = "Vai trò mới đã được tạo";
                }
                else
                {
                    response.Message = "Đã có lỗi xảy ra xin liên hệ với Quản trị hệ thống";
                    return(response);
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.Message = "Có lỗi đã xảy ra, xin mời liên lạc Quản trị hệ thống";
                return(response);
            }
        }
Esempio n. 7
0
        public async Task Initialize(IServiceProvider serviceProvider)
        {
            var dbContext = serviceProvider.GetService <AppDbContext>();

            // init roles
            _roles = dbContext.Roles.ToDictionary(_ => _.Id,
                                                  _ => Enum.TryParse(_.Name, out UserRole role) ? role : throw new AppException("Invalid roles in db"));
            var missedRoles = Enum.GetValues(typeof(UserRole)).OfType <UserRole>().Except(_roles.Values).ToArray();

            if (missedRoles.Any())
            {
                var roleManager = serviceProvider.GetRequiredService <RoleManager <AppIdentityRole> >();
                foreach (var role in missedRoles)
                {
                    var appRole = new AppIdentityRole(role.ToString());
                    await roleManager.CreateAsync(appRole);

                    _roles.Add(appRole.Id, role);
                }
            }

            _roleIds = _roles.ToDictionary(_ => _.Value, _ => _.Key);

            // init first admin user
            if (!await dbContext.Users.AnyAsync())
            {
                var usersService = serviceProvider.GetRequiredService <IUsersService>();
                var authConfig   = serviceProvider.GetRequiredService <IOptionsSnapshot <AuthConfig> >().Value;
                await usersService.SignUp(authConfig.InitialAdmin, UserRole.Admin);
            }
        }
Esempio n. 8
0
        public IActionResult Register(Register obj)
        {
            if (ModelState.IsValid)
            {
                if (!roleManager.RoleExistsAsync("Manager").Result)
                {
                    AppIdentityRole role = new AppIdentityRole();
                    role.Name = "Manager";
                    IdentityResult roleResult = roleManager.
                                                CreateAsync(role).Result;
                }

                AppIdentityUser user = new AppIdentityUser();
                user.UserName = obj.UserName;
                user.Email    = obj.Email;

                IdentityResult result = userManager.CreateAsync
                                            (user, obj.Password).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "Manager").Wait();
                    return(RedirectToAction("SignIn", "Security"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid user details");
                }
            }
            return(View(obj));
        }
Esempio n. 9
0
        /// <summary>
        /// Seeds the roles.
        /// </summary>
        /// <param name="roleManager">The role manager.</param>
        public static void SeedRoles(RoleManager <AppIdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("Admin").Result)
            {
                AppIdentityRole role = new AppIdentityRole();
                role.Name        = "Admin";
                role.Description = "Perform all the operations.";
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (!roleManager.RoleExistsAsync("Super User").Result)
            {
                AppIdentityRole role = new AppIdentityRole();
                role.Name        = "Super User";
                role.Description = "Perform super user operations.";
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (!roleManager.RoleExistsAsync("User").Result)
            {
                AppIdentityRole role = new AppIdentityRole();
                role.Name        = "User";
                role.Description = "Perform user operations.";
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (!roleManager.RoleExistsAsync("Email").Result)
            {
                AppIdentityRole role = new AppIdentityRole();
                role.Name        = "Email";
                role.Description = "Perform email role operations.";
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }
        }
Esempio n. 10
0
        private void CreateRolesandUsers()
        {
            _roleManager = DIManager.Instance.Provider.GetService <RoleManager <AppIdentityRole> >();
            _userManager = DIManager.Instance.Provider.GetService <UserManager <ApplicationUser> >();

            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!_roleManager.RoleExistsAsync("SUPERADMIN").Result)
            {
                // first we create Admin rool
                var role = new AppIdentityRole();
                role.Name = "SUPERADMIN";
                _roleManager.CreateAsync(role);

                //Here we create a Admin super user who will maintain the website
            }
            if (_userManager.Users.FirstOrDefault(x => x.Email == "*****@*****.**") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                user.Gender   = 1;

                string userPWD = "Elibrary1!";

                var chkUser = _userManager.CreateAsync(user, userPWD);

                //Add default User to Role Admin
                if (chkUser.Result.Succeeded)
                {
                    var result1 = _userManager.AddToRoleAsync(user, "SuperAdmin");
                }
            }
        }
        public async Task <IActionResult> Create(CreateRoleViewModel model)
        {
            string message = String.Empty;

            if (ModelState.IsValid)
            {
                AppIdentityRole newRole = new AppIdentityRole()
                {
                    Id           = Guid.NewGuid().ToString(),
                    Name         = model.RoleName,
                    RolePriority = model.RolePriority,
                    IsActive     = true
                };
                var result = await _roleManager.CreateAsync(newRole);

                if (result.Succeeded)
                {
                    message = "Phân quyền mới đã được tạo";
                    TempData["UserMessage"] = SystemUtilites.SendSystemNotification(NotificationType.Success, message);
                    return(RedirectToAction(actionName: "Index"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            message = "Lỗi không xác định, xin mời thao tác lại";
            TempData["UserMessage"] = SystemUtilites.SendSystemNotification(NotificationType.Error, message);
            return(RedirectToAction(actionName: "Index"));
        }
Esempio n. 12
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                if (!await roleManager.RoleExistsAsync("Manager"))
                {
                    AppIdentityRole role = new AppIdentityRole();
                    role.Name        = "Manager";
                    role.Description = "Can perform CRUD operations.";
                    IdentityResult roleResult = await roleManager.
                                                CreateAsync(role);
                }

                AppIdentityUser user = new AppIdentityUser();
                user.UserName  = RegisterData.UserName;
                user.Email     = RegisterData.Email;
                user.FullName  = RegisterData.FullName;
                user.BirthDate = RegisterData.BirthDate;

                IdentityResult result = await userManager.CreateAsync
                                            (user, RegisterData.Password);

                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, "Manager");

                    return(RedirectToPage("/Security/SignIn"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid user details!");
                }
            }
            return(Page());
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                if (!_roleManager.RoleExistsAsync("Manager").Result)
                {
                    AppIdentityRole role = new AppIdentityRole();
                    role.Name = "Manager";
                    IdentityResult roleResult = _roleManager.
                                                CreateAsync(role).Result;
                }

                var user = new AppIdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    _userManager.AddToRoleAsync(user, "Manager").Wait();

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

                    /*var callbackUrl = Url.Page(
                     *  "/Account/ConfirmEmail",
                     *  pageHandler: null,
                     *  values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                     *  protocol: Request.Scheme);*/

                    /* await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                     *   $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
                     */
                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 14
0
        public async Task <bool> CreateNewRole(string roleName)
        {
            AppIdentityRole role = new AppIdentityRole();

            role.Name        = roleName;
            role.Description = "Perform " + roleName + " operations.";
            IdentityResult roleResult = this.roleManager.CreateAsync(role).Result;

            return(await Task.FromResult(roleResult.Succeeded));
        }
Esempio n. 15
0
        public async Task <IActionResult> Delete(string roleId)
        {
            AppIdentityRole roleDel = await _roleManager.FindByIdAsync(roleId);

            var result = await _roleManager.DeleteAsync(roleDel);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Something was wrong, please try again");
            }
            return(RedirectToAction(actionName: "Manage"));
        }
        public async Task <IActionResult> RolGüncelle(string rolId)
        {
            AppIdentityRole role = await _roleManager.FindByIdAsync(rolId);

            UserRoleViewModel model = new UserRoleViewModel
            {
                Name  = role.Name,
                RolId = rolId
            };

            return(ViewComponent("RolGuncelle", model));
        }
        public async Task <AppIdentityRole> GetRoleByIdAsync(string id)
        {
            AppIdentityRole role = await _roleManager.FindByIdAsync(id);

            if (role != null)
            {
                return(role);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 18
0
        public IResult RoleCreate(Role role)
        {
            AppIdentityRole appIdentityRole = new AppIdentityRole();

            appIdentityRole.Name = role.RoleName;
            var result = _roleManager.CreateAsync(appIdentityRole).Result;

            if (!result.Succeeded)
            {
                return(new ErrorResult(result.Errors.FirstOrDefault().Description));
            }

            return(new SuccessResult());
        }
Esempio n. 19
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                return(RedirectToLocal(returnUrl));
            }

            var email = info.Principal.FindFirstValue(ClaimTypes.Email);
            var user  = new AppIdentityUser {
                UserName = email, Email = email, Name = email
            };
            var createResult = await _userManager.CreateAsync(user);

            if (createResult.Succeeded)
            {
                AppIdentityRole role = await _roleManager.FindByNameAsync("Translator");

                IdentityResult roleResult = await _userManager.AddToRoleAsync(user, role.Name);

                if (roleResult.Succeeded)
                {
                    createResult = await _userManager.AddLoginAsync(user, info);

                    if (createResult.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
            }

            return(RedirectToAction("Login"));
        }
Esempio n. 20
0
        public async Task <IActionResult> Edit(string roleId)
        {
            AppIdentityRole role = await _roleManager.FindByIdAsync(roleId);

            if (role == null)
            {
                return(NotFound());
            }
            EditRoleViewModel roleEdit = new EditRoleViewModel()
            {
                RoleId   = role.Id,
                RoleName = role.Name
            };

            return(View(roleEdit));
        }
        public async Task <IActionResult> KullaniciRolSilme(string rolId)
        {
            AppIdentityRole role = await _roleManager.FindByIdAsync(rolId);

            IdentityResult result = await _roleManager.DeleteAsync(role);

            if (result.Succeeded)
            {
                System.Threading.Thread.Sleep(500);
                return(RedirectToAction("KullaniciRol"));
            }
            else
            {
                return(RedirectToAction("KullaniciRol"));
            }
        }
        public async Task <IActionResult> EditEmployee(Guid id, NewEmployeeViewModel model)
        {
            if (!String.IsNullOrEmpty(id.ToString()))
            {
                AppIdentityUser user = await _userManager.FindByIdAsync(id.ToString());

                if (user != null)
                {
                    var existingRole = _userManager.GetRolesAsync(user).Result.Single();
                    var roleId       = _roleManager.Roles.Single(r => r.Name == existingRole).Id;

                    user.Name        = model.Name;
                    user.Surname     = model.Surname;
                    user.UserName    = model.UserName;
                    user.Email       = model.Email;
                    user.BirthDate   = model.BirthDate;
                    user.PhoneNumber = model.MobileNumber;

                    IdentityResult result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        if (roleId != model.DepartmentId)
                        {
                            IdentityResult resultt = await _userManager.RemoveFromRoleAsync(user, existingRole);

                            if (resultt.Succeeded)
                            {
                                AppIdentityRole role = await _roleManager.FindByIdAsync(model.DepartmentId.ToString());

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

                                    if (newRoleResult.Succeeded)
                                    {
                                        return(RedirectToAction("Employees"));
                                    }
                                }
                            }
                        }
                    }
                }
                return(RedirectToAction("Employees"));
            }
            return(RedirectToAction("Employees"));
        }
        public async Task <AppIdentityRole> UpdateRole(AppIdentityRole role)
        {
            if (role != null)
            {
                IdentityResult result = await _roleManager.UpdateAsync(role);

                if (result.Succeeded)
                {
                    return(role);
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
Esempio n. 24
0
        /// <summary>
        /// Seeds the roles.
        /// </summary>
        /// <param name="roleManager">The role manager.</param>
        public static void SeedRoles(RoleManager <AppIdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("Admin").Result)
            {
                AppIdentityRole role = new AppIdentityRole();
                role.Name    = "Admin";
                role.IsAdmin = true;
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (!roleManager.RoleExistsAsync("User").Result)
            {
                AppIdentityRole role = new AppIdentityRole();
                role.Name = "User";
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }
        }
Esempio n. 25
0
        public IResult RoleDelete(string roleId)
        {
            AppIdentityRole appIdentityRole = _roleManager.FindByIdAsync(roleId).Result;

            if (appIdentityRole != null)
            {
                var result = _roleManager.DeleteAsync(appIdentityRole).Result;
                if (result.Succeeded)
                {
                    return(new SuccessResult());
                }

                return(new ErrorResult(result.Errors.FirstOrDefault().Description));
            }

            return(new ErrorResult("Role not found"));
        }
        public async Task <AppIdentityRole> CreateRole(string roleName)
        {
            AppIdentityRole role = new AppIdentityRole()
            {
                Name = roleName
            };
            IdentityResult result = await _roleManager.CreateAsync(role);

            if (result.Succeeded)
            {
                return(role);
            }
            else
            {
                return(null);
            }
        }
        public async Task <IActionResult> KullaniciRolGüncelle(UserRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppIdentityRole role = await _roleManager.FindByIdAsync(model.RolId);

                role.Name = model.Name;
                IdentityResult result = await _roleManager.UpdateAsync(role);

                if (result.Succeeded)
                {
                    TempData["message"] = "Rol başarıyla Güncellendi";
                    return(RedirectToAction("KullaniciRol"));
                }
            }
            return(ViewComponent("RolGuncelle", model));
        }
        public async Task <IActionResult> EditRole(Guid id, NewRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppIdentityRole role = await _roleManager.FindByIdAsync(id.ToString());

                role.Name        = model.RoleName;
                role.Description = model.Description;

                IdentityResult result = await _roleManager.UpdateAsync(role);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Roles"));
                }
            }
            return(View(model));
        }
Esempio n. 29
0
        public async Task <IActionResult> Register(RegisterViewModel registerViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(registerViewModel));
            }

            var user = new AppIdentityUser
            {
                UserName = registerViewModel.UserName,
                Email    = registerViewModel.Email,
            };

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

            if (result.Succeeded)
            {
                //Ilk Kayıt için
                if (!await _roleManager.RoleExistsAsync("Admin"))
                {
                    var users = new AppIdentityRole("Admin");
                    var res   = await _roleManager.CreateAsync(users);

                    if (res.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(user, "Admin");
                    }
                }

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


                // Eposta Onayı
                var confirmationCode = _userManager.GenerateEmailConfirmationTokenAsync(user);
                var callBackUrl      = Url.Action("ConfirmEmail", "Security",
                                                  new { userId = user.Id, code = confirmationCode });

                // Send mail

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

            return(View(registerViewModel));
        }
        public async Task <IActionResult> DeleteRole(Guid id)
        {
            if (!String.IsNullOrEmpty(id.ToString()))
            {
                AppIdentityRole appIdentityRole = await _roleManager.FindByIdAsync(id.ToString());

                if (appIdentityRole != null)
                {
                    IdentityResult result = _roleManager.DeleteAsync(appIdentityRole).Result;

                    if (result.Succeeded)
                    {
                        return(RedirectToAction(nameof(Roles)));
                    }
                    return(RedirectToAction(nameof(Roles)));
                }
            }
            return(RedirectToAction(nameof(Roles)));
        }