public async Task <IActionResult> RoleUsers(string roleName)
        {
            var role = await _roleManager.FindByNameAsync(roleName);

            if (role == null)
            {
                return(NotFound());
            }

            var users = await _userManager.GetUsersInRoleAsync(roleName);

            return(View(users));
        }
コード例 #2
0
        public ActionResult Edit(AdminUserEditModel model, string[] selectRoles)
        {
            if (ModelState.IsValid)
            {
                var user = userManager.FindByIdAsync(model.AdminId).Result;
                if (model.WillChangePassword)
                {
                    user.PasswordHash = userManager.PasswordHasher.HashPassword(model.Password);
                }
                user.Roles.Clear();
                foreach (string roleName in selectRoles)
                {
                    var         Role     = roleManager.FindByNameAsync(roleName).Result;
                    AppUserRole userRole = new AppUserRole {
                        RoleId = Role.Id,
                        UserId = user.Id
                    };
                    user.Roles.Add(userRole);
                }

                var updateResult = userManager.UpdateAsync(user).Result;
                if (updateResult.Succeeded)
                {
                    TempData["message"] = "정보 수정이 완료되었습니다.";
                    return(RedirectToAction("Index"));
                }
                else
                {
                    AddErrorsFromResult(updateResult);
                }
            }
            return(View(model));
        }
コード例 #3
0
ファイル: Configuration.cs プロジェクト: munzerawad/WebShop
        private async Task SeedAsync(AppContext context)
        {
            var user = new ShopUser()
            {
                UserName  = AdminUser.UserName,
                Email     = AdminUser.Email,
                FirstName = AdminUser.FirstName,
                LastName  = AdminUser.LastName,
            };
            var role = new AppRole(RoleNames.Admin);

            ///
            UserStore <ShopUser> uStore = new UserStore <ShopUser>(context);
            var userManager             = new AppUserManager(uStore);
            RoleStore <AppRole> rStore  = new RoleStore <AppRole>(context);
            var roleManager             = new AppRoleManager(rStore);
            var adminRole = await roleManager.FindByNameAsync(RoleNames.Admin);

            if (adminRole == null)
            {
                adminRole = new AppRole(RoleNames.Admin);
                await roleManager.CreateAsync(adminRole);
            }

            // await roleManager.CreateAsync(new AppRole(RoleNames.Admin));
            var result = await userManager.CreateAsync(user, AdminUser.Password);

            user = await userManager.FindByNameAsync(AdminUser.UserName);

            await userManager.AddToRoleAsync(user.Id, RoleNames.Admin);
        }
コード例 #4
0
        public async Task <IHttpActionResult> Create(CreateRoleModel model)
        {
            var currentRole = await AppRoleManager.FindByNameAsync(model.Name);

            if (currentRole != null)
            {
                ModelState.AddModelError("Name", "A role with this name already exists");
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var role = new IdentityRole {
                Name = model.Name
            };

            var result = await this.AppRoleManager.CreateAsync(role);

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

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

            return(Created(locationHeader, TheModelFactory.CreateViewModel(role)));
        }
コード例 #5
0
ファイル: GroupController.cs プロジェクト: hanuoc/tenatms
 public async Task <HttpResponseMessage> Delete(HttpRequestMessage request, int id)
 {
     if (_groupService.IsGroupEmpty(id, _groupService.GetGroupLeadIdByGroup(id)))
     {
         var result = _groupService.Delete(id);
         if (result != null)
         {
             var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
             var user          = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID) && x.GroupId == id)).FirstOrDefault();
             if (user != null)
             {
                 user.GroupId = null;
                 var resultUpdate = await AppUserManager.UpdateAsync(user);
             }
             _groupService.SaveChange();
             return(request.CreateResponse(HttpStatusCode.OK, id));
         }
         else
         {
             return(request.CreateResponse(HttpStatusCode.BadRequest, id));
         }
     }
     else
     {
         Func <HttpResponseMessage> func = () =>
         {
             return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.ERROR_ExistMemberInGroup));
         };
         return(await CreateHttpResponse(request, func));
     }
 }
コード例 #6
0
ファイル: GroupController.cs プロジェクト: hanuoc/tenatms
        public async Task <HttpResponseMessage> GetAllPaging(HttpRequestMessage request, int page, int pageSize, string roleName, string userID)
        {
            Func <HttpResponseMessage> func = () =>
            {
                if (roleName.Equals(CommonConstants.GroupLead))
                {
                    var lstGr     = _groupService.GetAllGroup();
                    var listGroup = Mapper.Map <List <Group>, List <GroupViewModel> >(lstGr);
                    List <GroupViewModel> listGroupTmp = new List <GroupViewModel>();
                    var users = AppUserManager.Users.Where(x => x.Id.Equals(userID)).ToList();
                    foreach (var item in listGroup)
                    {
                        var user = users.Where(x => x.GroupId == item.ID).FirstOrDefault();
                        if (user != null)
                        {
                            item.GroupLeadID      = user != null ? user.Id : CommonConstants.StringEmpty;
                            item.GroupLead        = user != null ? user.FullName : CommonConstants.DefaultGroupLeader;
                            item.GroupLeadAccount = user != null ? user.UserName : CommonConstants.DefaultGroupLeader;
                            listGroupTmp.Add(item);
                        }
                    }
                    int totalRow = listGroupTmp.Count;
                    PaginationSet <GroupViewModel> pagedSet = new PaginationSet <GroupViewModel>()
                    {
                        PageIndex = page,
                        PageSize  = pageSize,
                        TotalRows = totalRow,
                        Items     = listGroupTmp,
                    };
                    return(request.CreateResponse(HttpStatusCode.OK, pagedSet));
                }
                else
                {
                    var lstGr     = _groupService.GetAllGroup();
                    var listGroup = Mapper.Map <List <Group>, List <GroupViewModel> >(lstGr);
                    int totalRow  = listGroup.Count;

                    listGroup = listGroup.Where(x => !x.Name.Equals("SuperAdmin")).Skip((page - 1) * pageSize).Take(pageSize).ToList();
                    var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                    var users         = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID))).ToList();
                    foreach (var item in listGroup)
                    {
                        var user = users.Where(x => x.GroupId == item.ID).FirstOrDefault();
                        item.GroupLeadID      = user != null ? user.Id : CommonConstants.StringEmpty;
                        item.GroupLead        = user != null ? user.FullName : CommonConstants.DefaultGroupLeader;
                        item.GroupLeadAccount = user != null ? user.UserName : CommonConstants.DefaultGroupLeader;
                    }
                    PaginationSet <GroupViewModel> pagedSet = new PaginationSet <GroupViewModel>()
                    {
                        PageIndex = page,
                        PageSize  = pageSize,
                        TotalRows = totalRow,
                        Items     = listGroup,
                    };
                    return(request.CreateResponse(HttpStatusCode.OK, pagedSet));
                }
            };

            return(await CreateHttpResponse(request, func));
        }
コード例 #7
0
        public async Task <HttpResponseMessage> GetAllUserConfigDelegation(HttpRequestMessage request, int page, int pageSize, string groupID, string[] lstFullName)
        {
            Func <HttpResponseMessage> func = () =>
            {
                if (string.IsNullOrEmpty(groupID))
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, nameof(groupID) + MessageSystem.NoValues));
                }
                var groupleaderID  = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                var convertGroupID = Int32.Parse(groupID);
                var user           = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID)) && x.GroupId == convertGroupID).ToList();
                var model          = _configDelegationService.GetListUserConfigDelegationFilter(groupID, lstFullName).Where(x => !x.UserId.Equals(user[0].Id));
                var data           = model.Skip((page - 1) * pageSize).Take(pageSize);
                var paginationSet  = new PaginationSet <ConfigDelegationModel>()
                {
                    Items     = data,
                    PageIndex = page,
                    TotalRows = model.Count(),
                    PageSize  = pageSize
                };
                return(request.CreateResponse(HttpStatusCode.OK, paginationSet));
            };

            return(await CreateHttpResponse(request, func));
        }
コード例 #8
0
        private async Task <Tuple <ApplicationUser, string> > RegisterPelanggan(string email, string password)
        {
            try
            {
                ApplicationUser user = new Models.ApplicationUser {
                    UserName = email, Email = email, LockoutEnabled = false, EmailConfirmed = false
                };
                var created = await UserManager.CreateAsync(user, password);

                if (created.Succeeded)
                {
                    string roleName = "Pelanggan";
                    if (!await AppRoleManager.RoleExistsAsync(roleName))
                    {
                        var r           = new MySql.AspNet.Identity.IdentityRole("125", roleName);
                        var roleCreated = await AppRoleManager.CreateAsync(r);

                        if (!roleCreated.Succeeded)
                        {
                            throw new SystemException("Role Tidak Berhasil Disimpan");
                        }
                    }

                    var role = await AppRoleManager.FindByNameAsync(roleName);

                    if (role != null)
                    {
                        var added = await UserManager.AddToRoleAsync(user.Id, roleName);

                        if (!added.Succeeded)
                        {
                            throw new SystemException(string.Format("User Tidak Berhasil Di tambahkan Ke Role {0}", roleName));
                        }
                    }
                    else
                    {
                        throw new SystemException(string.Format("Role {0} Tidak Ditemukan", roleName));
                    }
                }
                else
                {
                    throw new SystemException("User TIdak Berhasil Dibuat");
                }
                string c = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                string strcode     = HttpUtility.UrlEncode(c);
                var    callbackUrl = Url.Link("DefaultApi", new { controller = "User/ConfirmPassword", userId = user.Id, code = strcode });
                await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return(Tuple.Create(user, strcode));
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }
コード例 #9
0
ファイル: AppUserController.cs プロジェクト: hanuoc/tenatms
 public async Task <HttpResponseMessage> GetGroupLeadToAssign(HttpRequestMessage request)
 {
     return(await CreateHttpResponse(request, () =>
     {
         HttpResponseMessage response = null;
         var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
         var user = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID) && x.GroupId == null)).ToList();
         response = request.CreateResponse(HttpStatusCode.OK, Mapper.Map <List <AppUser>, List <AppUserViewModel> >(user));
         return response;
     }));
 }
コード例 #10
0
ファイル: AppUserController.cs プロジェクト: hanuoc/tenatms
        public async Task <HttpResponseMessage> GetAllAppUser(HttpRequestMessage request, string userlogin, int groupId)
        {
            return(await CreateHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;

                var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                var user = AppUserManager.Users.Where(x => x.Id != userlogin && !(x.Roles.Any(r => r.RoleId.Equals(groupleaderID)) && x.GroupId == groupId)).Distinct().ToList();
                //var user = AppUserManager.Users.Select(x => new { x.Id, x.FullName, x.Email, x.Roles, x.GroupId }).Where(x => x.Id != userlogin && x.Roles.Any(r=> r.RoleId.Equals(groupleaderID)) && x.GroupId == groupId).Distinct().ToList();
                response = request.CreateResponse(HttpStatusCode.OK, user);
                return response;
            }));
        }
コード例 #11
0
        private async Task <ApplicationUser> RegisterPetugas(string email)
        {
            try
            {
                var user = new Models.ApplicationUser {
                    UserName = email, Email = email, LockoutEnabled = true, EmailConfirmed = true
                };
                var created = await UserManager.CreateAsync(user, "Petugas#123");

                if (created.Succeeded)
                {
                    string roleName = "Petugas";
                    if (!await AppRoleManager.RoleExistsAsync(roleName))
                    {
                        var r           = new MySql.AspNet.Identity.IdentityRole("123", roleName);
                        var roleCreated = await AppRoleManager.CreateAsync(r);

                        if (!roleCreated.Succeeded)
                        {
                            throw new SystemException("Role Tidak Berhasil Disimpan");
                        }
                    }

                    var role = await AppRoleManager.FindByNameAsync(roleName);

                    if (role != null)
                    {
                        var added = await UserManager.AddToRoleAsync(user.Id, roleName);

                        if (!added.Succeeded)
                        {
                            throw new SystemException(string.Format("User Tidak Berhasil Di tambahkan Ke Role {0}", roleName));
                        }
                    }
                    else
                    {
                        throw new SystemException(string.Format("Role {0} Tidak Ditemukan", roleName));
                    }
                }
                else
                {
                    throw new SystemException("User TIdak Berhasil Dibuat");
                }

                return(user);
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }
コード例 #12
0
        public async Task <IHttpActionResult> GetUsersInRoleList(string roleName)
        {
            var role = await AppRoleManager.FindByNameAsync(roleName);

            if (role != null)
            {
                List <UserInRoleModel> usersInRole = new List <UserInRoleModel>();
                var users = AppUserManager.Users.ToList();
                foreach (var user in users)
                {
                    usersInRole.Add(new UserInRoleModel()
                    {
                        UserId   = user.Id,
                        UserName = user.UserName,
                        RoleId   = role.Id,
                        IsInRole = AppUserManager.GetRoles(user.Id).Contains(roleName)
                    });
                }
                return(Ok(usersInRole));
            }

            return(NotFound());
        }
コード例 #13
0
ファイル: GroupController.cs プロジェクト: hanuoc/tenatms
 public async Task <HttpResponseMessage> DeleteMulti(HttpRequestMessage request, List <GroupCreateUpdateModel> listGroupDelete)
 {
     if (listGroupDelete.Count != 0)
     {
         int numberOfGroupInvalid = 0;
         foreach (var group in listGroupDelete)
         {
             if (!_groupService.IsGroupEmpty(group.ID, group.GroupLeadID))
             {
                 numberOfGroupInvalid++;
             }
         }
         if (numberOfGroupInvalid == 0)
         {
             foreach (var group in listGroupDelete)
             {
                 if (_groupService.Delete(group.ID) != null)
                 {
                     var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                     var user          = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID) && x.GroupId == group.ID)).FirstOrDefault();
                     if (user != null)
                     {
                         user.GroupId = null;
                         var resultUpdate = await AppUserManager.UpdateAsync(user);
                     }
                     _groupService.SaveChange();
                 }
             }
             return(request.CreateResponse(HttpStatusCode.OK, listGroupDelete));
         }
         else
         {
             return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.ERROR_ExistMemberInGroup));
         }
     }
     return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.SelectGroupToDelete));
 }
コード例 #14
0
        private void CheckAdminUserYN()
        {
            var  adminRole   = roleManager.FindByNameAsync("Administrators");
            long adminRoleId = -1;

            if (adminRole.Result == null)
            {
                var appRole = new AppRole {
                    Name = "Administrators"
                };
                var result = roleManager.CreateAsync(appRole).Result;
                if (result.Succeeded)
                {
                    adminRoleId = appRole.Id;
                }
            }

            var adminUser = userManager.FindByNameAsync("*****@*****.**");

            if (adminUser.Result == null)
            {
                var appUser = new AppUser {
                    UserName = "******",
                    Email    = "*****@*****.**",
                };
                var result = userManager.CreateAsync(appUser, "dbaldud123@").Result;

                if (result.Succeeded)
                {
                    appUser.Roles.Add(new AppUserRole {
                        UserId = appUser.Id,
                        RoleId = adminRoleId
                    });
                }
                userManager.Update(appUser);
            }
        }
コード例 #15
0
        public async Task <IActionResult> AddRole(AddUserRole model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user == null)
            {
                return(BadRequest());
            }

            var role = await _roleManager.FindByNameAsync(model.SelectedRole);

            if (role == null)
            {
                return(BadRequest());
            }

            var result = await _userManager.AddToRoleAsync(user, role.Name);

            if (result.Succeeded)
            {
                await _userManager.UpdateSecurityStampAsync(user);

                await _signInManager.RefreshSignInAsync(user);

                return(RedirectToRoute("GetUserRoles", new { userName = user.UserName }));
            }

            AddErrors(result);

            return(View(model));
        }
コード例 #16
0
ファイル: AppUserController.cs プロジェクト: hanuoc/tenatms
        public async Task <HttpResponseMessage> Create(HttpRequestMessage request, AppUserViewModel applicationUserViewModel)
        {
            if (ModelState.IsValid)
            {
                if (User != null && MemoryCacheHelper.RemoveUserEditByAdmin(User.Identity.Name))
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, CommonConstants.Error_Edit_By_Admin));
                }
                if (applicationUserViewModel.Roles.Contains(CommonConstants.GroupLead) && applicationUserViewModel.GroupId != null)
                {
                    var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                    var groupLeader   = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID) && x.GroupId == applicationUserViewModel.GroupId)).FirstOrDefault();
                    if (groupLeader != null && !groupLeader.Equals(applicationUserViewModel))
                    {
                        return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.Error_Create_Exist_Group_Lead));
                    }
                }

                var username = AppUserManager.FindByNameAsync(applicationUserViewModel.UserName).Result;
                var email    = AppUserManager.FindByEmailAsync(applicationUserViewModel.Email).Result;
                //if (username != null && email != null)
                //{
                //    if (username.Status == false)
                //    {
                //        return request.CreateResponse(HttpStatusCode.OK, "Inaction");
                //    }
                //}
                if (username != null)
                {
                    if (username.Status == true)
                    {
                        return(request.CreateErrorResponse(HttpStatusCode.BadRequest, MessageSystem.MessageDuplicateUserName));
                    }
                }

                if (email != null)
                {
                    if (email.Status == true)
                    {
                        return(request.CreateErrorResponse(HttpStatusCode.BadRequest, MessageSystem.MessageDuplicateEmail));
                    }
                    else
                    {
                        return(request.CreateResponse(HttpStatusCode.OK, "Inaction"));
                    }
                }
                var newAppUser = new AppUser();
                newAppUser.UpdateUser(applicationUserViewModel);
                newAppUser.Status = true;
                try
                {
                    newAppUser.Id = Guid.NewGuid().ToString();
                    if (applicationUserViewModel.ListUserNo != null && applicationUserViewModel.ListUserNo.Count() > 0)
                    {
                        if (!ValidateUserNo(applicationUserViewModel.ListUserNo.Split('-')))
                        {
                            return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.MessageUserNoNotValid));
                        }
                        if (_fingermachineuserService.IsUserNoExist(applicationUserViewModel.ListUserNo.Split('-').ToList()))
                        {
                            return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.MessageUserNoExist));
                        }
                    }
                    var checkStartDateAndBirthDay = _userService.CheckStartDateAndBirthDay(applicationUserViewModel.BirthDay, applicationUserViewModel.StartWorkingDay);
                    if (!string.IsNullOrEmpty(checkStartDateAndBirthDay))
                    {
                        return(request.CreateErrorResponse(HttpStatusCode.BadRequest, checkStartDateAndBirthDay));
                    }
                    var result = await AppUserManager.CreateAsync(newAppUser, applicationUserViewModel.Password);

                    if (result.Succeeded)
                    {
                        var roles = applicationUserViewModel.Roles.ToArray();
                        await AppUserManager.AddToRolesAsync(newAppUser.Id, roles);

                        //Create entitle day of user new
                        _entitleDayAppUserService.CreateEntitleDayAppUser(newAppUser);
                        //Add user into table config delegation
                        var configDelegation = new ConfigDelegation();
                        configDelegation.UserId = newAppUser.Id;
                        _configDelegateionService.Add(configDelegation);
                        _configDelegateionService.SaveChange();

                        if (applicationUserViewModel.ListUserNo != null)
                        {
                            List <string> lstUserno = applicationUserViewModel.ListUserNo.Split('-').ToList();
                            if (lstUserno.Count() > 0)
                            {
                                if (_fingermachineuserService.IsUserNoExist(lstUserno))
                                {
                                    return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.MessageUserNoExist));
                                }
                                else
                                {
                                    foreach (var item in lstUserno)
                                    {
                                        _fingermachineuserService.Create(new FingerMachineUser()
                                        {
                                            ID = item, UserId = newAppUser.Id
                                        });
                                    }
                                    _unitOfWork.Commit();
                                }
                            }
                        }
                        return(request.CreateResponse(HttpStatusCode.OK, applicationUserViewModel));
                    }

                    else
                    {
                        return(request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join(",", result.Errors)));
                    }
                }
                catch (NameDuplicatedException dex)
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, dex.Message));
                }
                catch (Exception ex)
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
                }
            }
            else
            {
                return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
        }
コード例 #17
0
ファイル: AppUserController.cs プロジェクト: hanuoc/tenatms
        //[Permission(Action = "Update", Function = "USER")]
        public async Task <HttpResponseMessage> Update(HttpRequestMessage request, AppUserViewModel applicationUserViewModel)
        {
            if (ModelState.IsValid)
            {
                if (User != null && MemoryCacheHelper.RemoveUserEditByAdmin(User.Identity.Name) && User.Identity.Name != applicationUserViewModel.UserName)
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, CommonConstants.Error_Edit_By_Admin));
                }

                var appUser = await AppUserManager.FindByIdAsync(applicationUserViewModel.Id);

                if (applicationUserViewModel.Roles.Contains(CommonConstants.GroupLead) && applicationUserViewModel.GroupId != null)
                {
                    var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                    var groupLeader   = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID) && x.GroupId == applicationUserViewModel.GroupId)).FirstOrDefault();
                    if (groupLeader != null && !groupLeader.Equals(appUser))
                    {
                        return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.Error_Exist_Group_Lead));
                    }
                }
                var roleIDNew = AppRoleManager.FindByNameAsync(applicationUserViewModel.Roles.FirstOrDefault()).Result.Id;
                if (applicationUserViewModel.UserName == User.Identity.Name && appUser.Roles.FirstOrDefault().RoleId != roleIDNew)
                {
                    return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.Unable_Update_Role_YourSelf));
                }
                var checkStartDateAndBirthDay = _userService.CheckStartDateAndBirthDay(applicationUserViewModel.BirthDay, applicationUserViewModel.StartWorkingDay);
                if (!string.IsNullOrEmpty(checkStartDateAndBirthDay))
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, checkStartDateAndBirthDay));
                }
                try
                {
                    var FingerManchineUser = _fingermachineuserService.GetFingerMachineUserByUserID(applicationUserViewModel.Id);
                    var lstUserNoAdd       = applicationUserViewModel.ListUserNo.Split('-').ToList().Except(FingerManchineUser.Select(x => x.ID));
                    if (!ValidateUserNo(lstUserNoAdd))
                    {
                        return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.MessageUserNoNotValid));
                    }
                    if (FingerManchineUser.Count > 0)
                    {
                        var lstUserNoRemove = FingerManchineUser.Select(x => x.ID).Except(applicationUserViewModel.ListUserNo.Split('-').ToList());
                        if (FingerManchineUser.Select(x => x.ID).ToList().Count() > 0 && (lstUserNoAdd.Count() > 0 || lstUserNoRemove.Count() > 0))
                        {
                            if (_fingermachineuserService.IsUserNoExist(lstUserNoAdd.ToList()))//_fingermachineuserService.IsFingerManchineUserExist(applicationUserViewModel.AccNameInMachineFinger))
                            {
                                return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.MessageUserNoExist));
                            }
                            if (_fingerTimeSheetService.IsUserNoExistTimeSheet(lstUserNoAdd.ToList()) || _fingerTimeSheetService.IsUserNoExistTimeSheet(lstUserNoRemove.ToList()))
                            {
                                return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.MessageExistTimeSheetEmpNo));
                            }
                            _fingermachineuserService.Update(lstUserNoAdd.ToList(), lstUserNoRemove.ToList(), applicationUserViewModel.Id);
                        }
                    }
                    else
                    {
                        if (_fingermachineuserService.IsUserNoExist(lstUserNoAdd.ToList()))
                        {
                            return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.MessageUserNoExist));
                        }
                    }
                    if (applicationUserViewModel.ListUserNo.Split('-').Count() > 0 && !string.IsNullOrEmpty(applicationUserViewModel.ListUserNo.Split('-')[0]) && FingerManchineUser.Count == 0)
                    {
                        foreach (var item in applicationUserViewModel.ListUserNo.Split('-').Distinct())
                        {
                            _fingermachineuserService.Create(new FingerMachineUser()
                            {
                                ID = item, UserId = applicationUserViewModel.Id
                            });
                        }
                        _unitOfWork.Commit();
                    }
                    //Update Not Done


                    appUser.UpdateUser(applicationUserViewModel);
                    var result = await AppUserManager.UpdateAsync(appUser);

                    if (result.Succeeded)
                    {
                        if (User.IsInRole(CommonConstants.Admin) && User.Identity.Name != applicationUserViewModel.UserName)
                        {
                            _userService.AddListUserEditByAdmin(applicationUserViewModel.UserName);
                        }
                        var userRoles = await AppUserManager.GetRolesAsync(appUser.Id);

                        var selectedRole = applicationUserViewModel.Roles.ToArray();
                        selectedRole = selectedRole ?? new string[] { };
                        await AppUserManager.RemoveFromRolesAsync(appUser.Id, userRoles.ToArray());

                        await AppUserManager.AddToRolesAsync(appUser.Id, selectedRole.ToArray());

                        return(request.CreateResponse(HttpStatusCode.OK, applicationUserViewModel));
                    }
                    return(request.CreateResponse(HttpStatusCode.BadRequest, Common.Constants.MessageSystem.MessageDuplicateEmail));
                }
                catch (NameDuplicatedException dex)
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, dex.Message));
                }
            }
            return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
        }
コード例 #18
0
 public async Task <ApplicationRole> FindByNameAsync(string roleName)
 {
     return(await _roleManager.FindByNameAsync(roleName));
 }
コード例 #19
0
        protected override void Seed(PrivateTutorOnline.Models.TutorOnlineDBContext context)
        {
            const string AdminUsername = "******";
            const string AdminPassword = "******";
            const string roleName      = "Admin";
            //const string AdminEmail = "*****@*****.**";
            const string AdminEmail = "*****@*****.**";


            if (AppRoleManager.FindByNameAsync("Admin") != null)
            {
                AppRoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Admin"));
            }
            if (AppRoleManager.FindByNameAsync("Customer") != null)
            {
                AppRoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Customer"));
            }
            if (AppRoleManager.FindByNameAsync("Tutor") != null)
            {
                AppRoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Tutor"));
            }


            //Initializer Admin account
            var admin = UserManager.FindByName(AdminUsername);

            if (admin == null)
            {
                admin = new ApplicationUser {
                    UserName = AdminUsername, Email = AdminEmail
                };
                IdentityResult AdminCreationResult = UserManager.Create(admin, AdminPassword);
                AdminCreationResult = UserManager.SetLockoutEnabled(admin.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = UserManager.GetRoles(admin.Id);

            if (!rolesForUser.Contains(roleName))
            {
                Task <IdentityResult> AdminRoleAddition = UserManager.AddToRoleAsync(admin.Id, roleName);
            }


            //Initializer Customer account
            //ApplicationUser customerUser = new ApplicationUser() { UserName = "******", Email = "*****@*****.**" };
            //var CustomerCreationResult = UserManager.CreateAsync(customerUser, AdminPassword);
            //if (CustomerCreationResult.IsCompleted)
            //    CustomerCreationResult = UserManager.SetLockoutEnabledAsync(customerUser.Id, false);
            //if (CustomerCreationResult.IsCompleted)
            //    UserManager.AddToRoleAsync(customerUser.Id, "Customer");

            //Initializer Tutor account
            //var tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //var result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            ////Initializer Tutor List account
            // tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            //tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            //tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            //tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");



            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
            if ((context.Subjects.Count() == 0))
            {
                context.Subjects.AddOrUpdate(
                    new Models.Subject()
                {
                    Name = "Toán"
                },
                    new Models.Subject()
                {
                    Name = "Tiếng Anh"
                },
                    new Models.Subject()
                {
                    Name = "Lý"
                },
                    new Models.Subject()
                {
                    Name = "Hóa"
                },
                    new Models.Subject()
                {
                    Name = "Sinh"
                },
                    new Models.Subject()
                {
                    Name = "Sử"
                },
                    new Models.Subject()
                {
                    Name = "Địa Lý"
                },
                    new Models.Subject()
                {
                    Name = "Vẽ"
                },
                    new Models.Subject()
                {
                    Name = "Vi Tính"
                },
                    new Models.Subject()
                {
                    Name = "Đàn-Nhạc"
                }
                    );
            }
            if (context.Grades.Count() == 0)
            {
                context.Grades.AddOrUpdate(
                    new Models.Grade()
                {
                    Name = "1"
                },
                    new Models.Grade()
                {
                    Name = "2"
                },
                    new Models.Grade()
                {
                    Name = "3"
                },
                    new Models.Grade()
                {
                    Name = "4"
                },
                    new Models.Grade()
                {
                    Name = "5"
                },
                    new Models.Grade()
                {
                    Name = "6"
                },
                    new Models.Grade()
                {
                    Name = "7"
                },
                    new Models.Grade()
                {
                    Name = "8"
                },
                    new Models.Grade()
                {
                    Name = "9"
                },
                    new Models.Grade()
                {
                    Name = "10"
                },
                    new Models.Grade()
                {
                    Name = "11"
                },
                    new Models.Grade()
                {
                    Name = "12"
                },
                    new Models.Grade()
                {
                    Name = "Luyện thi đại học"
                }
                    );
            }

            if (context.Customers.SingleOrDefault(c => c.Email == "*****@*****.**") == null)
            {
                //context.Customers.Add(
                //   new Models.Customer()
                //   {
                //       FullName = "Đinh Văn Thành",
                //       PhoneNumber = "01213546546",
                //       Email = "*****@*****.**",
                //       City = "TPHCM",
                //       District = "Quận 5",
                //       Ward = "Phường 13",
                //       Street = "An Dương Vương",
                //       UserId = customerUser.Id,
                //       IsEnable = true,
                //       IsActivate = false
                //   }
                //);
            }

            if (context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null &&
                context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null &&
                context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null &&
                context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null
                )
            {
                //context.Tutors.AddOrUpdate(
                //new Models.Tutor()
                //{
                //    FullName = "Hoàng Tuấn Anh",
                //    Gender = Enums.Gender.Male,
                //    DateOfBirth = new DateTime(1994, 11, 2),
                //    Email = "*****@*****.**",
                //    PhoneNumber = "01526487656",
                //    IdentityNumber = "0225644478",
                //    City = "TPHCM",
                //    District = "Bình Tân",
                //    Ward = "Phú Thạnh",
                //    Street = "Nguyễn Sơn",
                //    HomeTown = "Tỉnh Hà Nam",
                //    University = "ĐH Sư Phạm TPHCM",
                //    MajorSubject = "Sư Phạm Toán Học",
                //    GraduationYear = "2016",
                //    Advantage = "Đã từng đi dạy",
                //    Degree = Enums.AcademicDegree.Teacher,
                //    Image = new byte[] { },
                //    IsEnable = true,
                //    IsActivate = true
                //},
                //new Models.Tutor()
                //{
                //    FullName = "Nguyễn Ngọc Ánh",
                //    Gender = Enums.Gender.Female,
                //    DateOfBirth = new DateTime(1993, 2, 2),
                //    Email = "*****@*****.**",
                //    PhoneNumber = "01526487656",
                //    IdentityNumber = "0225644478",
                //    City = "TPHCM",
                //    District = "Quận 5",
                //    Ward = "13",
                //    Street = "An Dương Vương",
                //    HomeTown = "TP Hải Phòng",
                //    University = "ĐH Ngoại Thương TPHCM",
                //    MajorSubject = "Quản trị kinh doanh",
                //    GraduationYear = "2015",
                //    Advantage = "Đã từng đi dạy",
                //    Degree = Enums.AcademicDegree.Master,
                //    Image = new byte[] { },
                //    IsEnable = true,
                //    IsActivate = true
                //},
                //new Models.Tutor()
                //{
                //    FullName = "Vương Tuấn Kiệt",
                //    Gender = Enums.Gender.Male,
                //    DateOfBirth = new DateTime(1995, 11, 11),
                //    Email = "*****@*****.**",
                //    PhoneNumber = "01526487656",
                //    IdentityNumber = "0225644478",
                //    City = "TPHCM",
                //    District = "Quận 1",
                //    Ward = "Hai Bà Trưng",
                //    Street = "Nguyễn Kiệm",
                //    HomeTown = "Tỉnh Đồng Tháp",
                //    University = "Cao Đẳng Kinh Tế Đối Ngoại",
                //    MajorSubject = "Kế toán",
                //    GraduationYear = "2017",
                //    Advantage = "Đã từng đi dạy",
                //    Degree = Enums.AcademicDegree.Student,
                //    Image = new byte[] { },
                //    IsEnable = true,
                //    IsActivate = true
                //},
                // new Models.Tutor()
                // {
                //     FullName = "Đỗ Thị Phương Nhung",
                //     Gender = Enums.Gender.Female,
                //     DateOfBirth = new DateTime(1996, 5, 13),
                //     Email = "*****@*****.**",
                //     PhoneNumber = "01526487656",
                //     IdentityNumber = "0225644478",
                //     City = "Đà Nẵng",
                //     District = "Cát Bà",
                //     Ward = "Phú Xuân",
                //     Street = "Nguyễn Sơn",
                //     HomeTown = "Thủ đô Hà Nội",
                //     University = "Đại Học Sài Gòn",
                //     MajorSubject = "Sư Phạm Tiếng Anh",
                //     GraduationYear = "2017",
                //     Advantage = "Đã từng đi dạy",
                //     Degree = Enums.AcademicDegree.Bachelor,
                //     Image = new byte[] { },
                //     IsEnable = true,
                //     IsActivate = true
                // },
                // new Models.Tutor()
                // {
                //     FullName = "Huỳnh Tấn Dũng",
                //     Gender = Enums.Gender.Male,
                //     DateOfBirth = new DateTime(1994, 5, 11),
                //     Email = "*****@*****.**",
                //     PhoneNumber = "01526487656",
                //     IdentityNumber = "0225644478",
                //     City = "Đà Nẵng",
                //     District = "Cát Bà",
                //     Ward = "Phú Xuân",
                //     Street = "Nguyễn Sơn",
                //     HomeTown = "Thủ đô Hà Nội",
                //     University = "Đại Học Sài Gòn",
                //     MajorSubject = "Sư Phạm Tiếng Anh",
                //     GraduationYear = "2017",
                //     Advantage = "Đã từng đi dạy",
                //     Degree = Enums.AcademicDegree.Bachelor,
                //     Image = new byte[] { },
                //     IsEnable = true,
                //     IsActivate = true,
                //     UserId = tutor.Id
                // }  );
            }
        }