public ActionResult CheckEmployeeManage(long id) { if (Session["CheckFeed"] == null || !(bool) Session["CheckSystemManage"]) { Response.Write("<script>history.go(0);</script>"); return View("Error"); } var employeeService = new EmployeeService(); var roleService = new RoleService(); var listService = new ListService(); List<role> roles = roleService.FindByEmployeeId(id); employee employee = employeeService.Find(id); var employeeModel = new EmployeeModel { EmployeeId = employee.Id, EmployeeNumber = employee.Number, EmployeeName = employee.Name, Rfid = employee.RFID, Sex = employee.Sex, ConfirmPassWd = employee.Password, PassWd = employee.Password, Logon = employee.LogOn, Birthday = Convert.ToDateTime(employee.Birthday), Memo = employee.Memo }; List<long> roleType = roles.Select(role => role.role_type.Id).ToList(); employeeModel.RoleTypeId = roleType; ViewData["Role"] = listService.GetRoleTypeList(); ViewData["Sex"] = listService.GetSexTypeList(); ViewBag.Title = "查看人员信息"; return View("AddNewEmployeeManage", employeeModel); }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { var service = new RoleService(); foreach (var item in usernames) { service.AddRolesToUser(roleNames, item); } }
/// <summary> /// 实现控制反转 /// </summary> /// <param name="moduleFunctionRepos"></param> public Admin_EmployeeController(IEmployeeRepository employeeRepos, IRoleRepository rolerepos, ICustomerRepository customerrepos, ecoBio.Wms.Backstage.Repositories.IDynamicToken tokenRepos, ecoBio.Wms.Backstage.Repositories.IDepartmentListRepository departmentListRepos) { _roleservice = new RoleService(rolerepos); _employeeservice = new EmployeeService(employeeRepos); _custoimerservice = new CustomerService(customerrepos); _tokenRepos = new Service.Management.DynamicTokenService(tokenRepos); _departmentListRepos = new Service.Management.DepartmentListService(departmentListRepos); }
public UserInfo GetUserWithAuth(string userName) { var user = Bus.GetMasterDataSync(ConfigHelper.GetAppSettingString("UserServiceCode"), "FindByName", new { name = userName }, ConfigHelper.GetAppSettingString("SystemCode"), t => t.ToObject<UserInfo>()); if (user == null) return null; var roleService = new RoleService(); var lstRoleRight = new List<string>(); roleService.Where(r => r.sys_Member.Any(m => m.UserName == user.Name)) .Select(r => r.RoleRightStr.Split(',')) .ToList() .ForEach(lstRoleRight.AddRange); user.RightList = lstRoleRight.Distinct().ToList(); return user; }
TestResult AddUser() { using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory(true))) { var RoleService = new RoleService(unitOfWork); var UserService = new UserService(unitOfWork); var testUser = new User { Login = "******", Password = "******", //Password = "******", Email = "*****@*****.**", CreatedDate = DateTime.Now, //FirstName = "Ivan", //MiddleName = "Semenovich", //LastName = "Peresvetov", FirstName = "Иван", MiddleName = "Семенович", LastName = "Пересветов", Roles = new List<Role>(new Role[] { RoleService.Get().First() }), }; UserService.Add(testUser); try { var result = unitOfWork.Commit(); if (result.Count > 0) return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, result.First().ErrorMessage); } catch (Exception ex) { while (ex.InnerException != null) ex = ex.InnerException; return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, ex.Message); } } using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory(false))) { var UserService = new UserService(unitOfWork); User testUser = UserService.Get(user => user.Login == "ivan_test").FirstOrDefault(); if(testUser == null) return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, "Can't find added user."); else return new TestResult(TestResultType.Success, MethodBase.GetCurrentMethod().Name, "User added successfully."); } }
/// <summary> /// 根据角色id来获取员工编号和姓名字符串 /// </summary> /// <param name="roleId">角色id</param> /// <returns>返回指定角色id的员工编号和姓名字符串</returns> public string GetEmployeeNumAndName(long roleId) { var roles = new RoleService().FindByRoleIdAndState(roleId, false); var strEmployee = new StringBuilder(); foreach (var role in roles) { var employee = Find(role.EmployeeId); strEmployee.Append(employee.Number + ":" + employee.Name + ","); } if (roles.Count > 0) { strEmployee.Remove(strEmployee.Length - 1, 1); } return strEmployee.ToString(); }
public AuthController(RoleService roleService, RoleFunctionService roleFunctionService) { _roleService = roleService; _roleFunctionService = roleFunctionService; }
public RoleController(IConfiguration cfg, ILogger <RoleController> logger, IEnumerable <IManagerService> managerServices, ConnectionMultiplexer multiplexer) : base(cfg, logger, managerServices, multiplexer) { roleService = GetService <RoleService>(); resourceService = GetService <ResourceService>(); }
public _1005_RegisterController(ILogger <_1005_RegisterController> logging, IIdentityService <GameUser> identityService, RoleService roleService) : base(roleService) { this._logging = logging; this.identityService = identityService; }
public RoleController(RoleService service) { RoleService = service; }
public ValueController(RoleService roleService) { _roleservice = roleService; }
public override bool RoleExists(string roleName) { return(RoleService.RoleExists(roleName)); }
public ActionResult DeletePost(Guid id) { bool isTopicStarter; Topic topic; using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Got to get a lot of things here as we have to check permissions // Get the post var post = _postService.Get(id); // get this so we know where to redirect after isTopicStarter = post.IsTopicStarter; // Get the topic topic = post.Topic; // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, UsersRole); if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionDeletePosts].IsTicked) { var deleteTopic = _postService.Delete(post); unitOfWork.SaveChanges(); var postIdList = new List <Guid>(); if (deleteTopic) { postIdList = topic.Posts.Select(x => x.Id).ToList(); _topicService.Delete(topic); } try { unitOfWork.Commit(); // Successful, delete post or posts if its a topic deleted if (_luceneService.CheckIndexExists()) { if (deleteTopic) { foreach (var guid in postIdList) { _luceneService.Delete(guid); } } else { _luceneService.Delete(post.Id); } } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } } } // Deleted successfully if (isTopicStarter) { // Redirect to root as this was a topic and deleted TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Topic.Deleted"), MessageType = GenericMessages.success }; return(RedirectToAction("Index", "Home")); } // Show message that post is deleted TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Post.Deleted"), MessageType = GenericMessages.success }; return(Redirect(topic.NiceUrl)); }
public RolesController(RoleService roleService, RoleClaimService roleClaimService) { _roleService = roleService; _roleClaimService = roleClaimService; }
public void Seed(IServiceCollection services) { var roleManager = services.BuildServiceProvider().GetService <RoleManager <RoleEntity> >(); RoleService.CreateRolesAsync(roleManager).ConfigureAwait(false); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IPathResolver pathResolver, RoleService roleService, SiteLookupService siteLookupService) { loggerFactory.AddSerilog(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseStatusCodePagesWithReExecute("/Error/Index/{0}"); } var dbContext = app.ApplicationServices.GetService <Data.Context>(); try { var pending = dbContext.GetPendingMigrations(); if (pending != null && pending.Count() > 0) { Log.Logger.Warning($"Applying {pending.Count()} database migrations, last is: {pending.Last()}"); } } catch (Exception ex) { Log.Logger.Error($"Error looking up migrations to perform: {ex.Message}"); } dbContext.Migrate(); Task.Run(() => siteLookupService.GetDefaultSiteIdAsync()).Wait(); Task.Run(() => roleService.SyncPermissionsAsync()).Wait(); app.UseRequestLocalization(); app.UseResponseCompression(); // configure static files with 7 day cache app.UseStaticFiles(new StaticFileOptions() { OnPrepareResponse = _ => { var headers = _.Context.Response.GetTypedHeaders(); headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue() { MaxAge = TimeSpan.FromDays(7) }; } }); string contentPath = pathResolver.ResolveContentFilePath(); if (!Directory.Exists(contentPath)) { try { Directory.CreateDirectory(contentPath); } catch (Exception ex) { Console.WriteLine($"Unable to create directory '{contentPath}' in {Directory.GetCurrentDirectory()}"); throw (ex); } } string pathString = pathResolver.ResolveContentPath(); if (!pathString.StartsWith("/")) { pathString = "/" + pathString; } // configure /content with 7 day cache app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(contentPath), RequestPath = new PathString(pathString), OnPrepareResponse = _ => { var headers = _.Context.Response.GetTypedHeaders(); headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue() { MaxAge = TimeSpan.FromDays(7) }; } }); app.UseSession(); // set cookie authentication options var cookieAuthOptions = new CookieAuthenticationOptions { AuthenticationScheme = Controllers.Authentication.SchemeGRACookie, LoginPath = new PathString("/SignIn/"), AccessDeniedPath = new PathString("/"), AutomaticAuthenticate = true, AutomaticChallenge = true }; // if there's a data protection path, set it up - for clustered/multi-server configs if (!string.IsNullOrEmpty(Configuration[ConfigurationKey.DataProtectionPath])) { string protectionPath = Configuration[ConfigurationKey.DataProtectionPath]; cookieAuthOptions.DataProtectionProvider = DataProtectionProvider.Create( new DirectoryInfo(Path.Combine(protectionPath, "cookies"))); } app.UseCookieAuthentication(cookieAuthOptions); // sitePath is also referenced in GRA.Controllers.Filter.SiteFilter app.UseMvc(routes => { routes.MapRoute( name: null, template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: null, template: "{sitePath}/Info/{stub}", defaults: new { controller = "Info", action = "Index" }, constraints: new { sitePath = new SiteRouteConstraint(app.ApplicationServices.GetRequiredService <Controllers.Base.ISitePathValidator>()) }); routes.MapRoute( name: null, template: "Info/{stub}", defaults: new { controller = "Info", action = "Index" }); routes.MapRoute( name: null, template: "{sitePath}/{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }, constraints: new { sitePath = new SiteRouteConstraint(app.ApplicationServices.GetRequiredService <Controllers.Base.ISitePathValidator>()) }); routes.MapRoute( name: null, template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) }); app.Use(async(context, next) => { if (context.WebSockets.IsWebSocketRequest) { var handler = app.ApplicationServices.GetService <WebSocketHandler>(); await handler.Handle(context); } else { await next(); } }); }
public RoleValidator(RoleService roleService) { _roleService = roleService ?? throw new ArgumentNullException(nameof(roleService)); ConfigureRules(); }
public void GetRoleKey(string roleName, char expectedResult) { var roleService = new RoleService(); Assert.AreEqual(expectedResult, roleService.GetRoleKey(roleName)); }
public void IsCorrectRoleName(string roleName, bool expectedResult) { var roleService = new RoleService(); Assert.AreEqual(expectedResult, roleService.IsCorrectRoleName(roleName)); }
public void IsCorrectRoleKey(char roleKey, bool expectedResult) { var roleService = new RoleService(); Assert.AreEqual(expectedResult, roleService.IsCorrectRoleKey(roleKey)); }
public ActionResult DelEmployeeManage(long id) { if (Session["CheckFeed"] == null || !(bool) Session["DelSystemManage"] || !(bool) Session["CheckSystemManage"]) { Response.Write("<script>history.go(0);</script>"); return View("Error"); } var employeeService = new EmployeeService(); var roleService = new RoleService(); employee employee = employeeService.Find(id); List<role> roles = roleService.FindByEmployeeId(id); //如果该员工有生产信息与之关联,则无法删除 if (employee.cure_pig.Count != 0 || employee.feed.Count != 0 || employee.fodder_take.Count != 0 || employee.inspection.Count != 0 || employee.prevention.Count != 0 || employee.sale.Count != 0 || employee.task.Count != 0 || employee.task_employee.Count != 0) { Response.Write("<script language='JavaScript'>alert('该员工有生产信息与之关联,无法删除.');history.go(-1);</script>"); return Content("nothing"); } foreach (role role in roles) { roleService.Delete(role); } employeeService.Delete(employee); return RedirectToAction("EmployeeManage"); }
public JsonResult RoleListVal(TRoleCondition condition) { var data = RoleService.QueryRolesByPaging(condition); return(Json(data)); }
public UserController(UserService userService, RoleService roleService, DepartmentService departmentService) { _userService = userService; _roleService = roleService; _departmentService = departmentService; }
public JsonResult RemoveRole(Guid roleId) { var result = RoleService.RemoveRole(roleId, null); return(Json(result)); }
public UserAccountService(UserService userService, RoleService roleService, IAuthContainer<string> authContainer) { _userService = userService; _roleService = roleService; _authContainer = authContainer; }
public virtual async Task <ActionResult> DeletePost(Guid id) { var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // Got to get a lot of things here as we have to check permissions // Get the post var post = _postService.Get(id); var postId = post.Id; // get this so we know where to redirect after var isTopicStarter = post.IsTopicStarter; // Get the topic var topic = post.Topic; var topicUrl = topic.NiceUrl; // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, loggedOnUsersRole); if (post.User.Id == loggedOnReadOnlyUser.Id || permissions[ForumConfiguration.Instance.PermissionDeletePosts].IsTicked) { try { // Count down total posts User var user = _membershipService.UpdateTotalPosts(post.User.Id, false); // Delete post / topic if (post.IsTopicStarter) { // Delete entire topic var result = await _topicService.Delete(topic); if (!result.Successful) { TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = result.ProcessLog.FirstOrDefault(), MessageType = GenericMessages.success }; return(Redirect(topic.NiceUrl)); } } else { // Deletes single post and associated data var result = await _postService.Delete(post, false); if (!result.Successful) { TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = result.ProcessLog.FirstOrDefault(), MessageType = GenericMessages.success }; return(Redirect(topic.NiceUrl)); } // Remove in replyto's var relatedPosts = _postService.GetReplyToPosts(postId); foreach (var relatedPost in relatedPosts) { relatedPost.InReplyTo = null; } } Context.SaveChanges(); } catch (Exception ex) { Context.RollBack(); LoggingService.Error(ex); ShowMessage(new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Errors.GenericMessage"), MessageType = GenericMessages.danger }); return(Redirect(topicUrl)); } } // Deleted successfully if (isTopicStarter) { // Redirect to root as this was a topic and deleted TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Topic.Deleted"), MessageType = GenericMessages.success }; return(RedirectToAction("Index", "Home")); } // Show message that post is deleted TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Post.Deleted"), MessageType = GenericMessages.success }; return(Redirect(topic.NiceUrl)); }
public RoleController() { _service = new RoleService(); }
public RoleController(RoleService RoleSvc, PermissionService PerSvc) { this.RoleSvc = RoleSvc; this.PerSvc = PerSvc; }
public ApplicationSeeder( IRepositoryBase repositoryBase, IBrandRepository brandRepository, ILicenseeCommands licenseeCommands, ICurrencyCommands currencyCommands, IBrandCommands brandCommands, ICultureCommands cultureCommands, IPlayerRepository playerRepository, IBrandOperations walletCommands, PlayerCommands playerCommands, IAuthCommands authCommands, IAuthRepository authRepository, RoleService roleService, ISecurityRepository securityRepository, IBankCommands bankCommands, IBankAccountCommands bankAccountCommands, IPaymentLevelCommands paymentLevelCommands, RiskLevelCommands riskLevelCommands, IPaymentRepository paymentRepository, IGameRepository gameRepository, IGameManagement gameManagement, ICurrencyExchangeCommands currencyExchangeCommands, ContentTranslationCommands contentTranslationCommands, BackendIpRegulationService backendIpRegulationService, BrandIpRegulationService brandIpRegulationService, IPaymentGatewaySettingsCommands paymentGatewaySettingsCommands, ISettingsCommands settingsCommands, ISettingsRepository settingsRepository, ICommonSettingsProvider settingsProvider, IMassMessageCommands massMessageCommands, IMessagingRepository messagingRepository, IEventRepository eventRepository, IEventBus eventBus) { _repositoryBase = repositoryBase; _brandRepository = brandRepository; _licenseeCommands = licenseeCommands; _currencyCommands = currencyCommands; _brandCommands = brandCommands; _cultureCommands = cultureCommands; _playerCommands = playerCommands; _authCommands = authCommands; _authRepository = authRepository; _roleService = roleService; _securityRepository = securityRepository; _playerRepository = playerRepository; _walletCommands = walletCommands; _bankCommands = bankCommands; _bankAccountCommands = bankAccountCommands; _paymentLevelCommands = paymentLevelCommands; _riskLevelCommands = riskLevelCommands; _paymentRepository = paymentRepository; _gameRepository = gameRepository; _gameManagement = gameManagement; _currencyExchangeCommands = currencyExchangeCommands; _contentTranslationCommands = contentTranslationCommands; _backendIpRegulationService = backendIpRegulationService; _brandIpRegulationService = brandIpRegulationService; _paymentGatewaySettingsCommands = paymentGatewaySettingsCommands; _settingsCommands = settingsCommands; _settingsRepository = settingsRepository; _settingsProvider = settingsProvider; _massMessageCommands = massMessageCommands; _messagingRepository = messagingRepository; _eventRepository = eventRepository; _eventBus = eventBus; }
public RoleController() : base() { this.Service = new RoleService(this.Entities); }
public ActionResult GoogleSitemap() { using (UnitOfWorkManager.NewUnitOfWork()) { // Get all categoryes var allCategories = _categoryService.GetAll().ToList(); // Get all topics var allTopics = _topicService.GetAll(); // get all members profiles var members = MembershipService.GetAll(); // Sitemap holder var sitemap = new List <SitemapEntry>(); // create permissions var permissions = new Dictionary <Category, PermissionSet>(); // loop through the categories and get the permissions foreach (var category in allCategories) { var permissionSet = RoleService.GetPermissions(category, UsersRole); permissions.Add(category, permissionSet); } // ##### TOPICS // Now loop through the topics and remove any that user does not have permission for foreach (var topic in allTopics) { // Get the permissions for this topic via its parent category var permission = permissions[topic.Category]; // Add only topics user has permission to if (!permission[AppConstants.PermissionDenyAccess].IsTicked) { if (topic.Posts.Any()) { var firstOrDefault = topic.Posts.FirstOrDefault(x => x.IsTopicStarter); if (firstOrDefault != null) { var sitemapEntry = new SitemapEntry { Name = topic.Name, Url = topic.NiceUrl, LastUpdated = topic.LastPost.DateEdited }; sitemap.Add(sitemapEntry); } } } } // #### CATEGORIES foreach (var category in allCategories) { // Get the permissions for this topic via its parent category var permission = permissions[category]; // Add only topics user has permission to if (!permission[AppConstants.PermissionDenyAccess].IsTicked) { var sitemapEntry = new SitemapEntry { Name = category.Name, Url = category.NiceUrl, LastUpdated = category.DateCreated }; sitemap.Add(sitemapEntry); } } // #### MEMBERS foreach (var member in members) { var sitemapEntry = new SitemapEntry { Name = member.UserName, Url = member.NiceUrl, LastUpdated = member.CreateDate }; sitemap.Add(sitemapEntry); } return(new GoogleSitemapResult(sitemap)); } }
public AccountController(ApplicationUserManager userManager, ISecureDataFormat <AuthenticationTicket> accessTokenFormat, RoleService roleService) { _roleService = roleService; UserManager = userManager; AccessTokenFormat = accessTokenFormat; }
public RoleController(ILogger <RoleController> logger, RoleService roleService) { RoleService = roleService; Logger = logger; }
public virtual async Task <ActionResult> Create(CreateEditTopicViewModel topicViewModel) { // Get the user and roles var loggedOnUser = User.GetMembershipUser(MembershipService, false); var loggedOnUsersRole = loggedOnUser.GetRole(RoleService); // Get the category var category = _categoryService.Get(topicViewModel.Category); // First check this user is allowed to create topics in this category var permissions = RoleService.GetPermissions(category, loggedOnUsersRole); // Now we have the category and permissionSet - Populate the optional permissions // This is just in case the viewModel is return back to the view also sort the allowedCategories topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); topicViewModel.Categories = _categoryService.GetBaseSelectListCategories(AllowedCreateCategories(loggedOnUsersRole)); topicViewModel.IsTopicStarter = true; if (topicViewModel.PollAnswers == null) { topicViewModel.PollAnswers = new List <PollAnswer>(); } if (ModelState.IsValid) { // See if the user has actually added some content to the topic if (string.IsNullOrWhiteSpace(topicViewModel.Content)) { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } else { // Map the new topic (Pass null for new topic) var topic = topicViewModel.ToTopic(category, loggedOnUser, null); // Run the create pipeline var createPipeLine = await _topicService.Create(topic, topicViewModel.Files, topicViewModel.Tags, topicViewModel.SubscribeToTopic, topicViewModel.Content, null); if (createPipeLine.Successful == false) { // TODO - Not sure on this? // Remove the topic if unsuccessful, as we may have saved some items. await _topicService.Delete(createPipeLine.EntityToProcess); // Tell the user the topic is awaiting moderation ModelState.AddModelError(string.Empty, createPipeLine.ProcessLog.FirstOrDefault()); return(View(topicViewModel)); } if (createPipeLine.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate)) { var moderate = createPipeLine.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?; if (moderate == true) { // Tell the user the topic is awaiting moderation TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"), MessageType = GenericMessages.info }; return(RedirectToAction("Index", "Home")); } } // Redirect to the newly created topic return(Redirect($"{topic.NiceUrl}?postbadges=true")); } } return(View(topicViewModel)); }
public async Task <IActionResult> AddUsersToRoleAsync([FromBody] UserRoleRequest request) { await RoleService.AddUsersToRoleAsync(request); return(Success()); }
public virtual ActionResult EditPostTopic(Guid id) { // Get the post var post = _postService.Get(id); // Get the topic var topic = post.Topic; // Get the current logged on user var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnloggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, loggedOnloggedOnUsersRole); // Is the user allowed to edit this post if (post.User.Id == loggedOnReadOnlyUser.Id || permissions[ForumConfiguration.Instance.PermissionEditPosts].IsTicked) { // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(loggedOnloggedOnUsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(loggedOnloggedOnUsersRole, ForumConfiguration.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); // If this user hasn't got any allowed cats OR they are not allowed to post then abandon if (allowedAccessCategories.Any() && loggedOnReadOnlyUser.DisablePosting != true) { // Create the model for just the post var viewModel = new CreateEditTopicViewModel { Content = post.PostContent, Id = post.Id, Category = topic.Category.Id, Name = topic.Name, TopicId = topic.Id, OptionalPermissions = GetCheckCreateTopicPermissions(permissions), IsPostEdit = true }; // Now check if this is a topic starter, if so add the rest of the field if (post.IsTopicStarter) { // Remove all Categories that don't have create topic permission allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); // See if this user is subscribed to this topic var topicNotifications = _notificationService.GetTopicNotificationsByUserAndTopic(loggedOnReadOnlyUser, topic); // Populate the properties we can viewModel.IsLocked = topic.IsLocked; viewModel.IsSticky = topic.IsSticky; viewModel.IsTopicStarter = post.IsTopicStarter; viewModel.SubscribeToTopic = topicNotifications.Any(); viewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); // Tags - Populate from the topic if (topic.Tags.Any()) { viewModel.Tags = string.Join <string>(",", topic.Tags.Select(x => x.Tag)); } // Populate the poll answers if (topic.Poll != null && topic.Poll.PollAnswers.Any()) { // Has a poll so add it to the view model viewModel.PollAnswers = topic.Poll.PollAnswers; viewModel.PollCloseAfterDays = topic.Poll.ClosePollAfterDays ?? 0; } // It's a topic viewModel.IsPostEdit = false; } // Return the edit view return(View(viewModel)); } } // If we get here the user has no permission to try and edit the post return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); }
public bool DelEmp(long id) { var employeeService = new EmployeeService(); var roleService = new RoleService(); employee employee = employeeService.Find(id); List<role> roles = roleService.FindByEmployeeId(id); //如果该员工有生产信息与之关联,则无法删除 if (employee.cure_pig.Count != 0 || employee.feed.Count != 0 || employee.fodder_take.Count != 0 || employee.inspection.Count != 0 || employee.prevention.Count != 0 || employee.sale.Count != 0 || employee.task.Count != 0 || employee.task_employee.Count != 0) { return false; } foreach (role role in roles) { roleService.Delete(role); } employeeService.Delete(employee); return true; }
public bool SaveModifyEmployee(EmployeeModel model) { var employeeService = new EmployeeService(); var roleService = new RoleService(); string result = ""; try { //SHA512加密 if (model.ConfirmPassWd != null) { SHA512 sha512 = new SHA512Managed(); byte[] s = sha512.ComputeHash(Encoding.UTF8.GetBytes(model.ConfirmPassWd)); for (int i = 0; i < s.Length; i++) { result += s[i].ToString("X2"); } sha512.Clear(); } //修改人员信息 employee newemployee = employeeService.Find(model.EmployeeId); newemployee.Name = model.EmployeeName; newemployee.Number = model.EmployeeNumber; newemployee.RFID = model.Rfid; newemployee.LogOn = model.Logon; newemployee.Sex = model.Sex; newemployee.State = model.state; newemployee.Birthday = Convert.ToDateTime(model.Birthday); newemployee.Memo = model.Memo; if (model.ConfirmPassWd != null) { newemployee.Password = result.ToLower(); } employeeService.Update(newemployee); //修改角色信息 //如果增加的角色类型数据库中没有,则插入该角色 foreach (long t in model.RoleTypeId) { List<role> roles = roleService.FindByEmployeeId(model.EmployeeId); int flag = 1; foreach (role role in roles) { if (t == role.RoleId) { flag = 0; } } if (flag == 1) { var role = new role { EmployeeId = model.EmployeeId, RoleId = t }; roleService.Insert(role); } } // 如果删除了一个角色类型,则在数据库删除对应的角色类型 List<role> anotherroles = roleService.FindByEmployeeId(model.EmployeeId); foreach (role anotherrole in anotherroles) { int flag = 1; long delete = anotherrole.RoleId; for (int j = 0; j < model.RoleTypeId.Count; j++) { if (anotherrole.RoleId == model.RoleTypeId[j]) { flag = 0; } } if (flag == 1) { roleService = new RoleService(); roleService.Delete( roleService.Find(roleService.FindByEmployeeIdAndRoleId(model.EmployeeId, delete).Id)); } } } catch (Exception) { return false; } return true; }
public void InitializeTest() { m_unitOfWork = new MemoryUnitOfWork(); m_roleRepository = new MemoryRoleRepository(m_unitOfWork); var permissionService = MockRepository.GenerateMock<IPermissionService>(); m_unitOfWork.Commit(); m_target = new RoleService(m_roleRepository, m_unitOfWork, permissionService); }
public EmployeeModel FindEmployeeById(long id) { var employeeService = new EmployeeService(); var roleService = new RoleService(); try { List<role> roles = roleService.FindByEmployeeId(id); employee employee = employeeService.Find(id); var employeeModel = new EmployeeModel { EmployeeId = employee.Id, EmployeeNumber = employee.Number, EmployeeName = employee.Name, Rfid = employee.RFID, Sex = employee.Sex, ConfirmPassWd = employee.Password, PassWd = employee.Password, Logon = employee.LogOn, state=employee.State, Birthday = Convert.ToDateTime(employee.Birthday), Memo = employee.Memo }; List<long> roleType = roles.Select(role => role.role_type.Id).ToList(); employeeModel.RoleTypeId = roleType; return employeeModel; } catch (Exception) { return null; } }
public RoleController(RoleService roleService) { _roleService = roleService; }
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { RoleService.RemoveUsersFromRoles(usernames, roleNames); }
public bool SaveNewEmployee(EmployeeModel model) { var employeeService = new EmployeeService(); var roleService = new RoleService(); try { //SHA412加密 string result = ""; SHA512 sha512 = new SHA512Managed(); byte[] s = sha512.ComputeHash(Encoding.UTF8.GetBytes("123456")); for (int i = 0; i < s.Length; i++) { result += s[i].ToString("X2"); } sha512.Clear(); //添加人员信息 var newemployee = new employee { Name = model.EmployeeName, Number = model.EmployeeNumber, RFID = model.Rfid, Sex = model.Sex, Password = result.ToLower(), LogOn = true, Birthday = Convert.ToDateTime(model.Birthday), Memo = model.Memo, State = true }; employeeService.Insert(newemployee); var roleFlag = new List<long>(); //用来存储角色id,并判断角色id是否重复 //添加角色信息 foreach (long t in model.RoleTypeId) { //用来判断model中的roleid是否跟roleFlag中的重复 int flag = 0; foreach (long l in roleFlag) { if (l == t) { flag = 1; } } //model中的roleid跟roleFlag中的不重复 if (flag == 0) { roleFlag.Add(t); var role = new role { EmployeeId = employeeService.FindByRfid(model.Rfid).Id, RoleId = t }; roleService.Insert(role); } } } catch (Exception) { return false; } return true; }
public KssRoleProvider() { _roleService = IoC.Resolve<RoleService>(); }
public virtual async Task <ActionResult> EditPostTopic(CreateEditTopicViewModel editPostViewModel) { // Get the current user and role var loggedOnUser = User.GetMembershipUser(MembershipService, false); var loggedOnUsersRole = loggedOnUser.GetRole(RoleService, false); // Get the category var category = _categoryService.Get(editPostViewModel.Category); // Get all the permissions for this user var permissions = RoleService.GetPermissions(category, loggedOnUsersRole); // Now we have the category and permissionSet - Populate the optional permissions // This is just in case the viewModel is return back to the view also sort the allowedCategories // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole, ForumConfiguration.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); // TODO ??? Is this correct ?? allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); // Set the categories editPostViewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); // Get the users permissions for the topic editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); // See if this is a topic starter or not editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty; // IS the model valid if (ModelState.IsValid) { // Got to get a lot of things here as we have to check permissions // Get the post var originalPost = _postService.Get(editPostViewModel.Id); // Get the topic var originalTopic = originalPost.Topic; // See if the user has actually added some content to the topic if (string.IsNullOrWhiteSpace(editPostViewModel.Content)) { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } else { bool successful; bool? moderate = false; string message; if (editPostViewModel.IsPostEdit) { var editPostPipe = await _postService.Edit(originalPost, editPostViewModel.Files, originalPost.IsTopicStarter, string.Empty, editPostViewModel.Content); successful = editPostPipe.Successful; message = editPostPipe.ProcessLog.FirstOrDefault(); if (editPostPipe.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate)) { moderate = editPostPipe.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?; } } else { // Map the new topic (Pass null for new topic) var topic = editPostViewModel.ToTopic(category, loggedOnUser, originalTopic); // Run the create pipeline var editPipeLine = await _topicService.Edit(topic, editPostViewModel.Files, editPostViewModel.Tags, editPostViewModel.SubscribeToTopic, editPostViewModel.Content, editPostViewModel.Name, editPostViewModel.PollAnswers, editPostViewModel.PollCloseAfterDays); successful = editPipeLine.Successful; message = editPipeLine.ProcessLog.FirstOrDefault(); if (editPipeLine.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate)) { moderate = editPipeLine.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?; } } // Check if successful if (successful == false) { // Tell the user the topic is awaiting moderation ModelState.AddModelError(string.Empty, message); return(View(editPostViewModel)); } if (moderate == true) { // Tell the user the topic is awaiting moderation TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"), MessageType = GenericMessages.info }; return(RedirectToAction("Index", "Home")); } // Redirect to the newly created topic return(Redirect($"{originalTopic.NiceUrl}?postbadges=true")); } } return(View(editPostViewModel)); }
public ActionResult UserEdit(long id, UserEditViewModel userEdit) { if (!ModelState.IsValid) { return View(userEdit); } using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory())) { var userService = new UserService(unitOfWork); var roleService = new RoleService(unitOfWork);//add User user = userService.Get(u => u.Id == id, null, u => u.Roles, u => u.Roles).FirstOrDefault(); user.Email = userEdit.Email; user.FirstName = userEdit.FirstName; user.LastName = userEdit.LastName; user.Login = userEdit.Login; user.MiddleName = userEdit.MiddleName; user.Roles = roleService.Get(role => userEdit.Roles.Contains(role.Id)).ToList(); user.Roles = userEdit.Roles.Select(r => new Role { Id = r }).ToList(); unitOfWork.Commit(); } /*if (successUser == null) { ModelState.AddModelError("id", App_LocalResources.Resource.UpdateError); return View(userEdit); }*/ return RedirectToAction("Index"); }
public CustomMembershipProvider() { userService = (UserService)new NinjectDependencyResolver().GetService(typeof(UserService)); roleService = (RoleService)new NinjectDependencyResolver().GetService(typeof(RoleService)); }
public virtual async Task <ActionResult> Show(string slug, int?p) { // Set the page index var pageIndex = p ?? 1; var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // Get the topic var topic = _topicService.GetTopicBySlug(slug); if (topic != null) { var settings = SettingsService.GetSettings(); // Note: Don't use topic.Posts as its not a very efficient SQL statement // Use the post service to get them as it includes other used entities in one // statement rather than loads of sql selects var sortQuerystring = Request.QueryString[Constants.PostOrderBy]; var orderBy = !string.IsNullOrWhiteSpace(sortQuerystring) ? EnumUtils.ReturnEnumValueFromString <PostOrderBy>(sortQuerystring) : PostOrderBy.Standard; // Store the amount per page var amountPerPage = settings.PostsPerPage; if (sortQuerystring == Constants.AllPosts) { // Overide to show all posts amountPerPage = int.MaxValue; } // Get the posts var posts = await _postService.GetPagedPostsByTopic(pageIndex, amountPerPage, int.MaxValue, topic.Id, orderBy); // Get the topic starter post var starterPost = _postService.GetTopicStarterPost(topic.Id); // Get the permissions for the category that this topic is in var permissions = RoleService.GetPermissions(topic.Category, loggedOnUsersRole); // If this user doesn't have access to this topic then // redirect with message if (permissions[ForumConfiguration.Instance.PermissionDenyAccess].IsTicked) { return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } // Set editor permissions ViewBag.ImageUploadType = permissions[ForumConfiguration.Instance.PermissionInsertEditorImages].IsTicked ? "forumimageinsert" : "image"; var postIds = posts.Select(x => x.Id).ToList(); var votes = _voteService.GetVotesByPosts(postIds); var favourites = _favouriteService.GetAllPostFavourites(postIds); var viewModel = ViewModelMapping.CreateTopicViewModel(topic, permissions, posts, postIds, starterPost, posts.PageIndex, posts.TotalCount, posts.TotalPages, loggedOnReadOnlyUser, settings, _notificationService, _pollService, votes, favourites, true); // If there is a quote querystring var quote = Request["quote"]; if (!string.IsNullOrWhiteSpace(quote)) { try { // Got a quote var postToQuote = _postService.Get(new Guid(quote)); viewModel.QuotedPost = postToQuote.PostContent; viewModel.ReplyTo = postToQuote.Id; viewModel.ReplyToUsername = postToQuote.User.UserName; } catch (Exception ex) { LoggingService.Error(ex); } } var reply = Request["reply"]; if (!string.IsNullOrWhiteSpace(reply)) { try { // Set the reply var toReply = _postService.Get(new Guid(reply)); viewModel.ReplyTo = toReply.Id; viewModel.ReplyToUsername = toReply.User.UserName; } catch (Exception ex) { LoggingService.Error(ex); } } var updateDatabase = false; // User has permission lets update the topic view count // but only if this topic doesn't belong to the user looking at it var addView = !(User.Identity.IsAuthenticated && loggedOnReadOnlyUser.Id == topic.User.Id); if (addView) { updateDatabase = true; } // Check the poll - To see if it has one, and whether it needs to be closed. if (viewModel.Poll?.Poll?.ClosePollAfterDays != null && viewModel.Poll.Poll.ClosePollAfterDays > 0 && !viewModel.Poll.Poll.IsClosed) { // Check the date the topic was created var endDate = viewModel.Poll.Poll.DateCreated.AddDays((int)viewModel.Poll.Poll.ClosePollAfterDays); if (DateTime.UtcNow > endDate) { topic.Poll.IsClosed = true; viewModel.Topic.Poll.IsClosed = true; updateDatabase = true; } } if (!BotUtils.UserIsBot() && updateDatabase) { if (addView) { // Increase the topic views topic.Views = topic.Views + 1; } try { Context.SaveChanges(); } catch (Exception ex) { LoggingService.Error(ex); } } return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage"))); }
public ActionResult Catalog() { //若未登录,则不初始化左边的菜单栏 if (!User.Identity.IsAuthenticated) { return null; } //若session已有记录,则不再重复获得各个权限的session if (Session["CheckFeed"] != null) { return PartialView(); } employee employee = new EmployeeService().FindByNumber(User.Identity.Name.Split('|')[0]); if (employee == null) { return null; } List<role> roleList = new RoleService().FindByEmployeeId(employee.Id); var roleAuthorityService = new RoleAuthorityService(); List<List<role_authority>> list = roleList.Select(role => roleAuthorityService.FindByRoleTypeId(role.RoleId)).ToList(); //增加权限 Session["AddFeed"] = roleAuthorityService.GetAddAuthority(list, "Feed"); Session["AddPreventionDisease"] = roleAuthorityService.GetAddAuthority(list, "PreventionDisease"); Session["AddTransferPigsty"] = roleAuthorityService.GetAddAuthority(list, "TransferPigsty"); Session["AddInspect"] = roleAuthorityService.GetAddAuthority(list, "Inspect"); Session["AddCure"] = roleAuthorityService.GetAddAuthority(list, "Cure"); Session["AddSale"] = roleAuthorityService.GetAddAuthority(list, "Sale"); Session["AddAddPig"] = roleAuthorityService.GetAddAuthority(list, "AddPig"); Session["AddDataImport"] = roleAuthorityService.GetAddAuthority(list, "DataImport"); Session["AddAddNewPig"] = roleAuthorityService.GetAddAuthority(list, "AddNewPig"); Session["AddPigData"] = roleAuthorityService.GetAddAuthority(list, "PigData"); Session["AddFeedInfo"] = roleAuthorityService.GetAddAuthority(list, "FeedInfo"); Session["AddPreventionDiseaseInfo"] = roleAuthorityService.GetAddAuthority(list, "PreventionDiseaseInfo"); Session["AddTransferPigstyInfo"] = roleAuthorityService.GetAddAuthority(list, "TransferPigstyInfo"); Session["AddInspectInfo"] = roleAuthorityService.GetAddAuthority(list, "InspectInfo"); Session["AddCureInfo"] = roleAuthorityService.GetAddAuthority(list, "CureInfo"); Session["AddSalesInfo"] = roleAuthorityService.GetAddAuthority(list, "SalesInfo"); Session["AddFodderTake"] = roleAuthorityService.GetAddAuthority(list, "FodderTake"); Session["AddMedicineTake"] = roleAuthorityService.GetAddAuthority(list, "MedicineTake"); Session["AddSystemManage"] = roleAuthorityService.GetAddAuthority(list, "SystemManage"); Session["AddEliminateTask"] = roleAuthorityService.GetAddAuthority(list, "EliminateTask"); Session["AddDeadTask"] = roleAuthorityService.GetAddAuthority(list, "DeadTask"); Session["AddEliminateInfo"] = roleAuthorityService.GetAddAuthority(list, "EliminateInfo"); Session["AddDeadInfo"] = roleAuthorityService.GetAddAuthority(list, "DeadInfo"); //删除权限 Session["DelFeed"] = roleAuthorityService.GetDelAuthority(list, "Feed"); Session["DelPreventionDisease"] = roleAuthorityService.GetDelAuthority(list, "PreventionDisease"); Session["DelTransferPigsty"] = roleAuthorityService.GetDelAuthority(list, "TransferPigsty"); Session["DelInspect"] = roleAuthorityService.GetDelAuthority(list, "Inspect"); Session["DelCure"] = roleAuthorityService.GetDelAuthority(list, "Cure"); Session["DelSale"] = roleAuthorityService.GetDelAuthority(list, "Sale"); Session["DelAddPig"] = roleAuthorityService.GetDelAuthority(list, "AddPig"); Session["DelDataImport"] = roleAuthorityService.GetDelAuthority(list, "DataImport"); Session["DelAddNewPig"] = roleAuthorityService.GetDelAuthority(list, "AddNewPig"); Session["DelPigData"] = roleAuthorityService.GetDelAuthority(list, "PigData"); Session["DelFeedInfo"] = roleAuthorityService.GetDelAuthority(list, "FeedInfo"); Session["DelPreventionDiseaseInfo"] = roleAuthorityService.GetDelAuthority(list, "PreventionDiseaseInfo"); Session["DelTransferPigstyInfo"] = roleAuthorityService.GetDelAuthority(list, "TransferPigstyInfo"); Session["DelInspectInfo"] = roleAuthorityService.GetDelAuthority(list, "InspectInfo"); Session["DelCureInfo"] = roleAuthorityService.GetDelAuthority(list, "CureInfo"); Session["DelSalesInfo"] = roleAuthorityService.GetDelAuthority(list, "SalesInfo"); Session["DelFodderTake"] = roleAuthorityService.GetDelAuthority(list, "FodderTake"); Session["DelMedicineTake"] = roleAuthorityService.GetDelAuthority(list, "MedicineTake"); Session["DelSystemManage"] = roleAuthorityService.GetDelAuthority(list, "SystemManage"); Session["DelEliminateTask"] = roleAuthorityService.GetDelAuthority(list, "EliminateTask"); Session["DelDeadTask"] = roleAuthorityService.GetDelAuthority(list, "DeadTask"); Session["DelEliminateInfo"] = roleAuthorityService.GetDelAuthority(list, "EliminateInfo"); Session["DelDeadInfo"] = roleAuthorityService.GetDelAuthority(list, "DeadInfo"); //查看权限,若无查看权限,则默认增删查改权限都没有 Session["CheckFeed"] = roleAuthorityService.GetCheckAuthority(list, "Feed"); Session["CheckPreventionDisease"] = roleAuthorityService.GetCheckAuthority(list, "PreventionDisease"); Session["CheckTransferPigsty"] = roleAuthorityService.GetCheckAuthority(list, "TransferPigsty"); Session["CheckInspect"] = roleAuthorityService.GetCheckAuthority(list, "Inspect"); Session["CheckCure"] = roleAuthorityService.GetCheckAuthority(list, "Cure"); Session["CheckSale"] = roleAuthorityService.GetCheckAuthority(list, "Sale"); Session["CheckAddPig"] = roleAuthorityService.GetCheckAuthority(list, "AddPig"); Session["CheckDataImport"] = roleAuthorityService.GetCheckAuthority(list, "DataImport"); Session["CheckAddNewPig"] = roleAuthorityService.GetCheckAuthority(list, "AddNewPig"); Session["CheckPigData"] = roleAuthorityService.GetCheckAuthority(list, "PigData"); Session["CheckFeedInfo"] = roleAuthorityService.GetCheckAuthority(list, "FeedInfo"); Session["CheckPreventionDiseaseInfo"] = roleAuthorityService.GetCheckAuthority(list, "PreventionDiseaseInfo"); Session["CheckTransferPigstyInfo"] = roleAuthorityService.GetCheckAuthority(list, "TransferPigstyInfo"); Session["CheckInspectInfo"] = roleAuthorityService.GetCheckAuthority(list, "InspectInfo"); Session["CheckCureInfo"] = roleAuthorityService.GetCheckAuthority(list, "CureInfo"); Session["CheckSalesInfo"] = roleAuthorityService.GetCheckAuthority(list, "SalesInfo"); Session["CheckFodderTake"] = roleAuthorityService.GetCheckAuthority(list, "FodderTake"); Session["CheckMedicineTake"] = roleAuthorityService.GetCheckAuthority(list, "MedicineTake"); Session["CheckSystemManage"] = roleAuthorityService.GetCheckAuthority(list, "SystemManage"); Session["CheckEliminateTask"] = roleAuthorityService.GetCheckAuthority(list, "EliminateTask"); Session["CheckDeadTask"] = roleAuthorityService.GetCheckAuthority(list, "DeadTask"); Session["CheckEliminateInfo"] = roleAuthorityService.GetCheckAuthority(list, "EliminateInfo"); Session["CheckDeadInfo"] = roleAuthorityService.GetCheckAuthority(list, "DeadInfo"); //编辑权限 Session["EditFeed"] = roleAuthorityService.GetEditAuthority(list, "Feed"); Session["EditPreventionDisease"] = roleAuthorityService.GetEditAuthority(list, "PreventionDisease"); Session["EditTransferPigsty"] = roleAuthorityService.GetEditAuthority(list, "TransferPigsty"); Session["EditInspect"] = roleAuthorityService.GetEditAuthority(list, "Inspect"); Session["EditCure"] = roleAuthorityService.GetEditAuthority(list, "Cure"); Session["EditSale"] = roleAuthorityService.GetEditAuthority(list, "Sale"); Session["EditAddPig"] = roleAuthorityService.GetEditAuthority(list, "AddPig"); Session["EditDataImport"] = roleAuthorityService.GetEditAuthority(list, "DataImport"); Session["EditAddNewPig"] = roleAuthorityService.GetEditAuthority(list, "AddNewPig"); Session["EditPigData"] = roleAuthorityService.GetEditAuthority(list, "PigData"); Session["EditFeedInfo"] = roleAuthorityService.GetEditAuthority(list, "FeedInfo"); Session["EditPreventionDiseaseInfo"] = roleAuthorityService.GetEditAuthority(list, "PreventionDiseaseInfo"); Session["EditTransferPigstyInfo"] = roleAuthorityService.GetEditAuthority(list, "TransferPigstyInfo"); Session["EditInspectInfo"] = roleAuthorityService.GetEditAuthority(list, "InspectInfo"); Session["EditCureInfo"] = roleAuthorityService.GetEditAuthority(list, "CureInfo"); Session["EditSalesInfo"] = roleAuthorityService.GetEditAuthority(list, "SalesInfo"); Session["EditFodderTake"] = roleAuthorityService.GetEditAuthority(list, "FodderTake"); Session["EditMedicineTake"] = roleAuthorityService.GetEditAuthority(list, "MedicineTake"); Session["EditSystemManage"] = roleAuthorityService.GetEditAuthority(list, "SystemManage"); Session["EditEliminateTask"] = roleAuthorityService.GetEditAuthority(list, "EliminateTask"); Session["EditDeadTask"] = roleAuthorityService.GetEditAuthority(list, "DeadTask"); Session["EditEliminateInfo"] = roleAuthorityService.GetEditAuthority(list, "EliminateInfo"); Session["EditDeadInfo"] = roleAuthorityService.GetEditAuthority(list, "DeadInfo"); return PartialView(); }
public ActionResult EditPost(EditPostViewModel editPostViewModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // Got to get a lot of things here as we have to check permissions // Get the post var post = _postService.Get(editPostViewModel.Id); // Get the topic var topic = post.Topic; // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, UsersRole); if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionEditPosts].IsTicked) { // User has permission so update the post post.PostContent = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Content)); post.DateEdited = DateTime.UtcNow; // if topic starter update the topic if (post.IsTopicStarter) { // if category has changed then update it if (topic.Category.Id != editPostViewModel.Category) { var cat = _categoryService.Get(editPostViewModel.Category); topic.Category = cat; } topic.IsLocked = editPostViewModel.IsLocked; topic.IsSticky = editPostViewModel.IsSticky; topic.Name = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name)); // See if there is a poll if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0) { // Now sort the poll answers, what to add and what to remove // Poll answers already in this poll. var postedIds = editPostViewModel.PollAnswers.Select(x => x.Id); //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList(); var existingAnswers = editPostViewModel.PollAnswers.Where(x => topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList(); var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList(); var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList(); // Loop through existing and update names if need be //TODO: Need to think about this in future versions if they change the name //TODO: As they could game the system by getting votes and changing name? foreach (var existPollAnswer in existingAnswers) { // Get the existing answer from the current topic var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id); if (pa != null && pa.Answer != existPollAnswer.Answer) { // If the answer has changed then update it pa.Answer = existPollAnswer.Answer; } } // Loop through and remove the old poll answers and delete foreach (var oldPollAnswer in pollAnswersToRemove) { // Delete _pollAnswerService.Delete(oldPollAnswer); // Remove from Poll topic.Poll.PollAnswers.Remove(oldPollAnswer); } // Poll answers to add foreach (var newPollAnswer in newPollAnswers) { var npa = new PollAnswer { Poll = topic.Poll, Answer = newPollAnswer.Answer }; _pollAnswerService.Add(npa); topic.Poll.PollAnswers.Add(npa); } } else { // Need to check if this topic has a poll, because if it does // All the answers have now been removed so remove the poll. if (topic.Poll != null) { //Firstly remove the answers if there are any if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any()) { var answersToDelete = new List <PollAnswer>(); answersToDelete.AddRange(topic.Poll.PollAnswers); foreach (var answer in answersToDelete) { // Delete _pollAnswerService.Delete(answer); // Remove from Poll topic.Poll.PollAnswers.Remove(answer); } } // Now delete the poll var pollToDelete = topic.Poll; _pollService.Delete(pollToDelete); // Remove from topic. topic.Poll = null; } } // Tags topic.Tags.Clear(); if (!string.IsNullOrEmpty(editPostViewModel.Tags)) { _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic); } } // redirect back to topic TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Post.Updated"), MessageType = GenericMessages.success }; try { unitOfWork.Commit(); // Successful, add this post to the Lucene index if (_luceneService.CheckIndexExists()) { _luceneService.AddUpdate(_luceneService.MapToModel(post)); } return(Redirect(topic.NiceUrl)); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); throw new Exception(LocalizationService.GetResourceString("Errors.GenericError")); } } return(NoPermission(topic)); } }