Exemplo n.º 1
0
        public IActionResult Register(RegisterViewModel regiModel)
        {
            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();
                user.UserName  = regiModel.UserName;
                user.Email     = regiModel.Email;
                user.FullName  = regiModel.FullName;
                user.BirthDate = regiModel.BirthDate;

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

                if (result.Succeeded)
                {
                    if (!roleManager.RoleExistsAsync("NormalUser").Result)
                    {
                        MyIdentityRole role = new MyIdentityRole();
                        role.Name        = "NormalUser";
                        role.Description = "Perform normal operations.";
                        IdentityResult roleResult = roleManager.CreateAsync(role).Result;

                        if (!roleResult.Succeeded)
                        {
                            ModelState.AddModelError("", "Error while creating role!");
                            return(View(regiModel));
                        }
                    }
                    userManager.AddToRoleAsync(user, "NormalUser").Wait();

                    return(RedirectToAction("Login", "Account"));
                }
            }
            return(View(regiModel));
        }
Exemplo n.º 2
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            MyIdentityDbContext          db          = new MyIdentityDbContext();
            RoleStore <MyIdentityRole>   roleStore   = new RoleStore <MyIdentityRole>(db);
            RoleManager <MyIdentityRole> roleManager = new
                                                       RoleManager <MyIdentityRole>(roleStore);

            if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator",
                                                            "јдминистратор обладает полными правами в системе");
                roleManager.Create(newRole);
            }
            if (!roleManager.RoleExists("AdminD"))
            {
                MyIdentityRole newRole = new MyIdentityRole("AdminD",
                                                            "ќператоры могут только добавл¤ть и измен¤ть данные в системе");

                roleManager.Create(newRole);
            }
            if (!roleManager.RoleExists("Client"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Client",
                                                            "Ёто клиент, он может покупать");

                roleManager.Create(newRole);
            }
        }
Exemplo n.º 3
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            MyIdentityDbContext          db          = new MyIdentityDbContext();
            RoleStore <MyIdentityRole>   roleStore   = new RoleStore <MyIdentityRole>(db);
            RoleManager <MyIdentityRole> roleManager = new RoleManager <MyIdentityRole>(roleStore);

            if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator", "Администратор обладает полными правами в системе");
                roleManager.Create(newRole);
            }
            if (!roleManager.RoleExists("Operator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Operator", "Операторы могут только добавлять и изменять данные в системе");
                roleManager.Create(newRole);
            }
            if (!roleManager.RoleExists("Student"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Student", "Студенты могут просматривать данные о нарушениях");
                roleManager.Create(newRole);
            }
            if (!roleManager.RoleExists("Boss"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Boss", "Директор млжет просматривать всё!");
                roleManager.Create(newRole);
            }
        }
Exemplo n.º 4
0
        //   [Authorize(Roles = "admin")]
        public IActionResult Role()
        {
            MyIdentityRole role = new MyIdentityRole
            {
                Name = "admin"
            };

            roleManager.CreateAsync(role);
            return(RedirectToAction("Index"));
        }
Exemplo n.º 5
0
        public IActionResult Create(string roleName)
        {
            MyIdentityRole role = new MyIdentityRole
            {
                Name = roleName
            };
            var result = roleManager.CreateAsync(role).Result;

            return(RedirectToAction("Index"));
        }
Exemplo n.º 6
0
 public static async Task SeedRolesAsync(RoleManager <MyIdentityRole> roleManager)
 {
     foreach (var role in Enum.GetValues(typeof(MyAppRoleTypes)))
     {
         MyIdentityRole roleObj = new MyIdentityRole()
         {
             Name        = role.ToString(),
             Description = $"The {role} for the Application"
         };
         await roleManager.CreateAsync(roleObj);
     }
 }
Exemplo n.º 7
0
        public IActionResult Create(CreateViewModel userData)
        {
            if (!ModelState.IsValid)
            {
                return(View(userData));
            }

            var user = new MyIdentityUser {
                UserName     = userData.UserName,
                UserBirthday = userData.Birthday,
                UserAvatar   = "http://via.placeholder.com/45x45",
                UserGender   = userData.Gender
            };

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

            if (result.Succeeded)
            {
                if (!_roleManager.RoleExistsAsync("Employee").Result)
                {
                    var role = new MyIdentityRole {
                        Name        = "Employee",
                        Description = "Dành cho nhân viên"
                    };

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

                    if (!roleResult.Succeeded)
                    {
                        ModelState.AddModelError("", "Lỗi khi tạo quyền");

                        return(View(userData));
                    }
                }

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

                return(RedirectToAction("Login", "Account"));
            }

            foreach (var item in result.Errors)
            {
                ModelState.AddModelError("", item.Description);
            }

            return(View(userData));
        }
Exemplo n.º 8
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            AreaRegistration.RegisterAllAreas();

            DependencyResolver.SetResolver(new NinjectDependencyResolver());

            //log4net.Config.XmlConfigurator.Configure();
            //DependencyResolver.Current.GetService<ILogger>();

            MyIdentityDbContext          db          = new MyIdentityDbContext();
            RoleStore <MyIdentityRole>   roleStore   = new RoleStore <MyIdentityRole>(db);
            RoleManager <MyIdentityRole> roleManager = new RoleManager <MyIdentityRole>(roleStore);

            if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator", "Administrators can add, edit and delete data.");
                roleManager.Create(newRole);
            }

            if (!roleManager.RoleExists("SalesPerson"))
            {
                MyIdentityRole newRole = new MyIdentityRole("SalesPerson", "SalesPersons can only add or edit data.");
                roleManager.Create(newRole);
            }

            if (!roleManager.RoleExists("Cashier"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Cashier", "Cashiers can only add or edit data.");
                roleManager.Create(newRole);
            }

            if (!roleManager.RoleExists("StoreKeeper"))
            {
                MyIdentityRole newRole = new MyIdentityRole("StoreKeeper", "StoreKeepers can only add or edit data.");
                roleManager.Create(newRole);
            }
        }
        public static void SeedRoles(RoleManager <MyIdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("Parceiro").Result)
            {
                MyIdentityRole role = new MyIdentityRole();
                role.Name = "Parceiro";
                IdentityResult roleResult = roleManager.
                                            CreateAsync(role).Result;
            }


            if (!roleManager.RoleExistsAsync("Administrator").Result)
            {
                MyIdentityRole role = new MyIdentityRole();
                role.Name = "Administrator";
                IdentityResult roleResult = roleManager.
                                            CreateAsync(role).Result;
            }
        }
        public static async Task SeedRolesAsync(RoleManager <MyIdentityRole> roleManager)
        {
            //MyIdentityRole role = new MyIdentityRole()
            //{
            //     Name = "Administrator",
            //     Description = "The Administrator for the Application"
            //};
            //await roleManager.CreateAsync(role);

            foreach (MyAppRoleTypes role in Enum.GetValues(typeof(MyAppRoleTypes)))
            {
                MyIdentityRole roleObj = new MyIdentityRole()
                {
                    Name        = role.ToString(),
                    Description = $"The {role} for the Application"
                };
                await roleManager.CreateAsync(roleObj);
            }
        }
Exemplo n.º 11
0
        public static void SeedRoles(RoleManager <MyIdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("NormalUser").Result)
            {
                MyIdentityRole role = new MyIdentityRole();
                role.Name        = "NormalUser";
                role.Description = "Perform normal operations.";
                IdentityResult roleResult = roleManager.
                                            CreateAsync(role).Result;
            }


            if (!roleManager.RoleExistsAsync("Administrator").Result)
            {
                MyIdentityRole role = new MyIdentityRole();
                role.Name        = "Administrator";
                role.Description = "Perform all the operations.";
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Delete(string id)
        {
            MyIdentityRole role = await roleManager.FindByIdAsync(id);

            if (role != null)
            {
                IdentityResult result = await roleManager.DeleteAsync(role);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
            }
            else
            {
                return(RedirectToPage("Index"));
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 13
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            MyIdentityDbContext db = new MyIdentityDbContext();
            RoleStore<MyIdentityRole> roleStore = new RoleStore<MyIdentityRole>(db);
            RoleManager<MyIdentityRole> roleManager = new RoleManager<MyIdentityRole>(roleStore);

            if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole role = new MyIdentityRole("Administrator", "Administrators can add, edit and delete all items.");
                roleManager.Create(role);
            }

            if (!roleManager.RoleExists("Operator"))
            {
                MyIdentityRole role = new MyIdentityRole("Operator", "Operator can only add or edit items.");
                roleManager.Create(role);
            }
        }
Exemplo n.º 14
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            MyIdentityDbContext          db          = new MyIdentityDbContext();
            RoleStore <MyIdentityRole>   roleStore   = new RoleStore <MyIdentityRole>(db);
            RoleManager <MyIdentityRole> roleManager = new RoleManager <MyIdentityRole>(roleStore);

            if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator", "Administrators can add, edit and delete data.");
                roleManager.Create(newRole);
            }

            if (!roleManager.RoleExists("User"))
            {
                MyIdentityRole newRole = new MyIdentityRole("User", "Regular users.");
                roleManager.Create(newRole);
            }
        }
Exemplo n.º 15
0
        public async Task <IActionResult> Create(MyIdentityRole nRole)
        {
            if (ModelState.IsValid)
            {
                var result = await roleManager.FindByNameAsync(nRole.Name);

                if (result == null)
                {
                    IdentityResult newresult = await roleManager.CreateAsync(nRole);

                    if (newresult.Succeeded)
                    {
                        ViewBag.status = "Operation done successfully.";
                    }
                    else
                    {
                        ViewBag.status = "Operation failed";
                    }
                }
            }
            return(RedirectToAction("Index"));
        }
        [ValidateAntiForgeryToken]  //xss açıkları için önlem almış olursun
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)  // bana gelen modelin geçerli olup olmadığını kontrol et
            {
                MyIdentityUser user = new MyIdentityUser()
                {
                    UserName = model.UserName,
                    Email    = model.Email,
                    TCNO     = model.TCNO
                };

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

                if (result.Succeeded)
                {
                    if (!roleManager.RoleExistsAsync("NormalUser").Result)
                    {
                        MyIdentityRole role = new MyIdentityRole
                        {
                            Name        = "NormalUser",
                            Description = "SiteUsers"
                        };

                        IdentityResult roleResult = await roleManager.CreateAsync(role);

                        if (!roleResult.Succeeded)
                        {
                            ModelState.AddModelError("", "role oluşturulurken hata meydana geldi");
                            return View(model)
                        }
                    }
                    userManager.AddToRoleAsync(user, "NormalUser").Wait();
                    return(RedirectToAction("login", "account"));
                }
            }
            return(View(model));
        }
Exemplo n.º 17
0
        public IActionResult Register(RegisterViewModel obj)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser();
                Console.WriteLine(user);
                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)
                {
                    if (!_roleManager.RoleExistsAsync("NormalUser").Result)
                    {
                        MyIdentityRole role = new MyIdentityRole();
                        role.Name        = "NormalUser";
                        role.Description = "Perform normal operations.";
                        IdentityResult roleResult = _roleManager.
                                                    CreateAsync(role).Result;
                        if (!roleResult.Succeeded)
                        {
                            ModelState.AddModelError("",
                                                     "Error while creating role!");
                            return(View(obj));
                        }
                    }

                    _userManager.AddToRoleAsync(user,
                                                "NormalUser").Wait();
                    return(RedirectToAction("Login", "Account"));
                }
            }
            return(View("Index"));
        }
Exemplo n.º 18
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //BundleConfig.RegisterBundles(BundleTable.Bundles);

            MyIdentityDbContext          db          = new MyIdentityDbContext();
            RoleStore <MyIdentityRole>   roleStore   = new RoleStore <MyIdentityRole>(db);
            RoleManager <MyIdentityRole> roleManager = new RoleManager <MyIdentityRole>(roleStore);

            if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator", "Administrators can add, edit and delete data.");
                roleManager.Create(newRole);
            }

            if (!roleManager.RoleExists("Operator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Operator", "Operators can only add or edit data.");
                roleManager.Create(newRole);
            }
        }
Exemplo n.º 19
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            MyIdentityDbContext          db          = new MyIdentityDbContext();
            RoleStore <MyIdentityRole>   roleStore   = new RoleStore <MyIdentityRole>(db);
            RoleManager <MyIdentityRole> roleManager = new RoleManager <MyIdentityRole>(roleStore);

            if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator", "јдминистратор обладает полными правами в системе");
                roleManager.Create(newRole);
            }
            if (!roleManager.RoleExists("Client"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Client", " лиент может просматривать информацию");

                roleManager.Create(newRole);
            }
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Join(MyIdentityRole role)
        {
            var userID  = userManager.GetUserId(User);
            var appUser = userManager.FindByIdAsync(userID).Result;
            var nrole   = await roleManager.FindByIdAsync(role.Id);

            string name = nrole.Name;

            if (ModelState.IsValid)
            {
                var result = userManager.IsInRoleAsync(appUser, nrole.Name).Result;
                if (!result)
                {
                    await userManager.AddToRoleAsync(appUser, name);
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Exemplo n.º 21
0
        public async Task <IActionResult> Join(string id)
        {
            MyIdentityRole role = await roleManager.FindByIdAsync(id);

            return(View(role));
        }
        public async Task <MyServiceResult> SignUp(MySignUpModel model)
        {
            try
            {
                if (model is null)
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Lỗi đăng ký"
                    });
                }

                MyIdentityUser objMyIdentityUserFind = await this._UserManager.FindByNameAsync(model.UserName);

                if (objMyIdentityUserFind is null)
                {
                    MyIdentityUser objMyIdentityUserCreate = this._IMapper.Map <MyIdentityUser>(model);
                    IdentityResult objIdentityResult       = await this._UserManager.CreateAsync(objMyIdentityUserCreate, model.Password);

                    if (objIdentityResult.Succeeded)
                    {
                        string roleName = "";
                        if (string.IsNullOrWhiteSpace(model.RoleId))
                        {
                            string formatRoleString = model.RoleName.CapitalizeSentences();
                            bool   existsRole       = await this._RoleManager.RoleExistsAsync(formatRoleString);

                            if (existsRole == false)
                            {
                                await this._RoleManager.CreateAsync(new MyIdentityRole
                                {
                                    Name = model.RoleName
                                });

                                roleName = formatRoleString;
                            }
                        }
                        else
                        {
                            MyIdentityRole objMyIdentityRole = await this._RoleManager.FindByIdAsync(model.RoleId);

                            if (objIdentityResult is null)
                            {
                                return(new MyServiceResult
                                {
                                    Successed = false,
                                    Content = "Đăng ký thất bại"
                                });
                            }
                            roleName = objMyIdentityRole.Name;
                        }
                        IdentityResult objIdentityResultAddRole = await this._UserManager.AddToRoleAsync(objMyIdentityUserCreate, roleName);

                        if (objIdentityResultAddRole.Succeeded)
                        {
                            return(new MyServiceResult
                            {
                                Successed = true,
                                Content = "Đăng ký thành công"
                            });
                        }
                        else
                        {
                            return(new MyServiceResult
                            {
                                Successed = false,
                                Content = "Đăng ký thất bại"
                            });
                        }
                    }
                    else
                    {
                        return(new MyServiceResult
                        {
                            Successed = false,
                            Content = "Đăng ký thất bại"
                        });
                    }
                }
                else
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Người dùng đã tồn tại"
                    });
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task <MyServiceResult> UpdateInformation(string userId, MyUpdateUserModel model)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userId))
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Người dùng không tồn tại"
                    });
                }
                MyIdentityUser objMyIdentityUser = await this._UserManager.FindByIdAsync(userId);

                if (objMyIdentityUser is null)
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Người dùng không tồn tại",
                    });
                }

                MyIdentityUser objMyIdentityUserNew = this._IMapper.Map <MyUpdateUserModel, MyIdentityUser>(model, objMyIdentityUser);
                this._EFDbContext.Entry <MyIdentityUser>(objMyIdentityUserNew).State = EntityState.Modified;
                int saveChangeResult = await this._EFDbContext.SaveChangesAsync();

                if (saveChangeResult > 0)
                {
                    MyIdentityUser objMyIdentityUser1 = await this._UserManager.FindByIdAsync(userId);

                    if (objMyIdentityUser1 is null)
                    {
                        return(new MyServiceResult
                        {
                            Successed = false,
                            Content = "Người dùng không tồn tại",
                        });
                    }

                    if (!string.IsNullOrEmpty(model.Role))
                    {
                        bool isExistRole = await _RoleManager.RoleExistsAsync(model.Role);

                        if (isExistRole)
                        {
                            IList <string> iListRole = await _UserManager.GetRolesAsync(objMyIdentityUser1);

                            string roleUser = iListRole.First();
                            if (iListRole.Count > 0 && !string.Equals(roleUser, model.Role))
                            {
                                IdentityResult resultRemoveRole = await _UserManager.RemoveFromRoleAsync(objMyIdentityUser1, roleUser);

                                if (resultRemoveRole.Succeeded)
                                {
                                    MyIdentityRole objMyIdentityRole = await _RoleManager.FindByIdAsync(model.Role);

                                    IdentityResult resultAddNewRole = await _UserManager.AddToRoleAsync(objMyIdentityUser1, objMyIdentityRole.Name);

                                    if (resultAddNewRole.Succeeded)
                                    {
                                        return(new MyServiceResult
                                        {
                                            Successed = true,
                                            Content = "Cập nhật thông tin người dùng thành công"
                                        });
                                    }
                                    else
                                    {
                                        return(new MyServiceResult
                                        {
                                            Successed = false,
                                            Content = "Cập nhật thông tin người dùng thất bại"
                                        });
                                    }
                                }
                            }
                        }
                    }
                    return(new MyServiceResult
                    {
                        Successed = true,
                        Content = "Cập nhật thông tin người dùng thành công"
                    });
                }
                else
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Cập nhật thông tin người dùng thất bại"
                    });
                }
            }
            catch (Exception)
            {
                throw;
            }
        }