public static Permission RegisterPermissions(Permission parent) { Permission commands = DefaultPermissions.RegisterPermission(ROOT, "Gives the user the ability to use all CraftBukkit commands", parent); RegisterWhitelist(commands); RegisterBan(commands); RegisterUnban(commands); RegisterOp(commands); RegisterSave(commands); RegisterTime(commands); DefaultPermissions.RegisterPermission(PREFIX + "kill", "Allows the user to commit suicide", PermissionDefault.True, commands); DefaultPermissions.RegisterPermission(PREFIX + "me", "Allows the user to perform a chat action", PermissionDefault.True, commands); DefaultPermissions.RegisterPermission(PREFIX + "tell", "Allows the user to privately message another player", PermissionDefault.True, commands); DefaultPermissions.RegisterPermission(PREFIX + "say", "Allows the user to talk as the console", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "give", "Allows the user to give items to players", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "teleport", "Allows the user to teleport players", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "kick", "Allows the user to kick players", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "stop", "Allows the user to stop the server", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "list", "Allows the user to list all online players", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "help", "Allows the user to view the vanilla help menu", PermissionDefault.True, commands); DefaultPermissions.RegisterPermission(PREFIX + "plugins", "Allows the user to view the list of plugins running on this server", PermissionDefault.True, commands); DefaultPermissions.RegisterPermission(PREFIX + "reload", "Allows the user to reload the server settings", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "version", "Allows the user to view the version of the server", PermissionDefault.True, commands); DefaultPermissions.RegisterPermission(PREFIX + "gamemode", "Allows the user to change the gamemode of another player", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "xp", "Allows the user to give themselves or others arbitrary values of experience", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "toggledownfall", "Allows the user to toggle rain on/off for a given world", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "defaultgamemode", "Allows the user to change the default gamemode of the server", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "seed", "Allows the user to view the seed of the world", PermissionDefault.OP, commands); DefaultPermissions.RegisterPermission(PREFIX + "effect", "Allows the user to add/remove effects on players", PermissionDefault.OP, commands); commands.RecalculatePermissibles(); return(commands); }
public static void ConfigureAuthentication(this IServiceCollection services) { services.AddIdentity <User, Role>() .AddEntityFrameworkStores <PgDbContext>() .AddDefaultTokenProviders(); services.Configure <IdentityOptions>(options => { // Password settings. options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredUniqueChars = 2; options.Lockout.AllowedForNewUsers = false; options.Lockout.MaxFailedAccessAttempts = 5; }); services.AddAuthorization(options => { foreach (var permission in DefaultPermissions.All()) { options.AddPolicy(permission.Name, policy => policy.Requirements.Add(new PermissionRequirement(permission))); } }); }
private RolePermissions VanillaGetRolePermissions(UInt64 RoleId) { if (!File.Exists($"./data/role-permissions/{RoleId}.json")) { CreateRolePermissions(RoleId); } return(RolePermissions.Deserialize(RoleId).Update(DefaultPermissions.Deserialize())); }
private UserPermissions VanillaGetUserPermissions(UInt64 UserId) { if (!File.Exists($"./data/{UserId}/permissions.json")) { CreateUserPermissions(UserId); } return(UserPermissions.Deserialize(UserId).Update(DefaultPermissions.Deserialize())); }
private static Permission RegisterUnban(Permission parent) { Permission unban = DefaultPermissions.RegisterPermission(PREFIX + "unban", "Allows the user to unban people", PermissionDefault.OP, parent); DefaultPermissions.RegisterPermission(PREFIX + "unban.player", "Allows the user to unban players", unban); DefaultPermissions.RegisterPermission(PREFIX + "unban.ip", "Allows the user to unban IP addresses", unban); unban.RecalculatePermissibles(); return(unban); }
private static Permission RegisterOp(Permission parent) { Permission op = DefaultPermissions.RegisterPermission(PREFIX + "op", "Allows the user to change operators", PermissionDefault.OP, parent); DefaultPermissions.RegisterPermission(PREFIX + "op.give", "Allows the user to give a player operator status", op); DefaultPermissions.RegisterPermission(PREFIX + "op.take", "Allows the user to take a players operator status", op); op.RecalculatePermissibles(); return(op); }
private static Permission RegisterTime(Permission parent) { Permission time = DefaultPermissions.RegisterPermission(PREFIX + "time", "Allows the user to alter the time", PermissionDefault.OP, parent); DefaultPermissions.RegisterPermission(PREFIX + "time.add", "Allows the user to fast-forward time", time); DefaultPermissions.RegisterPermission(PREFIX + "time.set", "Allows the user to change the time", time); time.RecalculatePermissibles(); return(time); }
public static Boolean HasPermission(this DiscordMember member, String permission) { UserPermissions permissions = activeEngine.GetUserPermissions(member.Id); if (permissions.IsAdministrator) { return(true); } if (permissions[permission] == PermissionValue.Allowed) { return(true); } else if (permissions[permission] == PermissionValue.Denied) { return(false); } List <UInt64> roles = permissions.AssignedRoles.ToList(); roles.AddRange(from v in member.Roles where !roles.Contains(v.Id) select v.Id); while (roles.Count != 0) { RolePermissions rolePermissions = activeEngine.GetRolePermissions(roles[0]); if (rolePermissions.IsAdministrator || rolePermissions[permission] == PermissionValue.Allowed) { return(true); } else if (rolePermissions[permission] == PermissionValue.Denied) { return(false); } if (rolePermissions.Parent != 0) { roles.Add(rolePermissions.Parent); } roles.Remove(roles[0]); } DefaultPermissions defaults = DefaultPermissions.Deserialize(); if (defaults[permission] == PermissionValue.Allowed || defaults.IsAdministrator) { return(true); } return(false); }
private void VanillaSetRoleAdministrator(UInt64 RoleId, Boolean Administrator) { if (!File.Exists($"./data/role-permissions/{RoleId}.json")) { CreateRolePermissions(RoleId); } RolePermissions permissions = RolePermissions.Deserialize(RoleId).Update(DefaultPermissions.Deserialize()); permissions.IsAdministrator = Administrator; RolePermissions.Serialize(permissions); }
private void VanillaSetUserAdministrator(UInt64 UserId, Boolean Administrator) { if (!File.Exists($"./data/{UserId}/permissions.json")) { CreateUserPermissions(UserId); } UserPermissions permissions = UserPermissions.Deserialize(UserId).Update(DefaultPermissions.Deserialize()); permissions.IsAdministrator = Administrator; UserPermissions.Serialize(permissions); }
private static Permission RegisterSave(Permission parent) { Permission save = DefaultPermissions.RegisterPermission(PREFIX + "save", "Allows the user to save the worlds", PermissionDefault.OP, parent); DefaultPermissions.RegisterPermission(PREFIX + "save.enable", "Allows the user to enable automatic saving", save); DefaultPermissions.RegisterPermission(PREFIX + "save.disable", "Allows the user to disable automatic saving", save); DefaultPermissions.RegisterPermission(PREFIX + "save.perform", "Allows the user to perform a manual save", save); save.RecalculatePermissibles(); return(save); }
private void VanillaCreateRolePermissions(UInt64 RoleId) { RolePermissions permissions = RolePermissions.Create(RoleId, DefaultPermissions.Deserialize()); Directory.CreateDirectory($"./data/role-permissions"); if (!File.Exists($"./data/role-permissions/{RoleId}.json")) { File.Create($"./data/role-permissions/{RoleId}.json").Close(); } RolePermissions.Serialize(permissions); }
private void VanillaCreateUserPermissions(UInt64 UserId) { UserPermissions permissions = UserPermissions.Create(UserId, DefaultPermissions.Deserialize()); Directory.CreateDirectory($"./data/{UserId}"); if (!File.Exists($"./data/{UserId}/permissions.json")) { File.Create($"./data/{UserId}/permissions.json").Close(); } UserPermissions.Serialize(permissions); }
private static void UpdateDatabase(IApplicationBuilder app) { using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { using (var context = serviceScope.ServiceProvider.GetService <ProblemDbContext>()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); var permissionAppService = serviceScope.ServiceProvider.GetRequiredService <IPermissionAppService>(); permissionAppService.InitializePermissions(DefaultPermissions.All()); } } }
public static void ConfigureAuthentication(this IServiceCollection services, IConfiguration configuration) { services.AddIdentity <User, Role>() .AddEntityFrameworkStores <ProblemDbContext>() .AddDefaultTokenProviders(); services.AddAuthorization(options => { foreach (var permission in DefaultPermissions.All()) { options.AddPolicy(permission.Name, policy => policy.Requirements.Add(new PermissionRequirement(permission))); } }); }
private static Permission RegisterWhitelist(Permission parent) { Permission whitelist = DefaultPermissions.RegisterPermission(PREFIX + "whitelist", "Allows the user to modify the server whitelist", PermissionDefault.OP, parent); DefaultPermissions.RegisterPermission(PREFIX + "whitelist.add", "Allows the user to add a player to the server whitelist", whitelist); DefaultPermissions.RegisterPermission(PREFIX + "whitelist.remove", "Allows the user to remove a player from the server whitelist", whitelist); DefaultPermissions.RegisterPermission(PREFIX + "whitelist.reload", "Allows the user to reload the server whitelist", whitelist); DefaultPermissions.RegisterPermission(PREFIX + "whitelist.enable", "Allows the user to enable the server whitelist", whitelist); DefaultPermissions.RegisterPermission(PREFIX + "whitelist.disable", "Allows the user to disable the server whitelist", whitelist); DefaultPermissions.RegisterPermission(PREFIX + "whitelist.list", "Allows the user to list all the users on the server whitelist", whitelist); whitelist.RecalculatePermissibles(); return(whitelist); }
private static void UpdateDefaultPermissions() { DefaultPermissions permissions = DefaultPermissions.Empty; StreamReader reader = new("./config/permissions/vanilla.pdecl.json"); permissions += JsonConvert.DeserializeObject <PermissionDeclaration[]>(reader.ReadToEnd()); reader.Close(); IEnumerable <String> modFiles = from x in Directory.GetFiles("./mod-data/permissions/declarations") where x.EndsWith(".pdecl.json") select x; foreach (String v in modFiles) { reader = new(v); permissions += JsonConvert.DeserializeObject <PermissionDeclaration[]>(reader.ReadToEnd()); reader.Close(); } permissions.UpdateGuid = Guid.NewGuid(); if (!File.Exists("./config/permissions/default.json")) { File.Create("./config/permissions/default.json").Close(); } StreamWriter writer = new("./config/permissions/default.json"); writer.Write(JsonConvert.SerializeObject(permissions)); writer.Close(); List <String> checksums = new(); checksums.Add("./config/permissions/vanilla.pdecl.json".GetSHA512Checksum()); foreach (String v in modFiles) { checksums.Add(v.GetSHA512Checksum()); } writer = new("./cache/permissions/intermediate/default"); writer.Write(JsonConvert.SerializeObject(checksums)); writer.Flush(); writer.Close(); }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (DefaultPermissions.Any(x => x.IsNullOrWhiteSpace())) { yield return(new ValidationResult("A permission value cannot be null or empty", new[] { "Permissions" })); } foreach (var assignedPermission in AssignedPermissions) { foreach (var permission in assignedPermission.Value) { if (permission.IsNullOrWhiteSpace()) { yield return(new ValidationResult("A permission value cannot be null or empty", new[] { "AssignedPermissions" })); } } } }
private static String[] ParseWildcards(String permission) { if (!permission.Contains('*')) { return(new[] { permission }); } if (permission[permission.IndexOf('*') - 1] != '.') { throw new ArgumentException("Invalid wildcard.", nameof(permission)); } DefaultPermissions permissions = DefaultPermissions.Deserialize(); return((from x in permissions.Permissions where x.Key.StartsWith(permission.Split('*')[0]) select x.Key).ToArray()); }
public static RolePermission[] BuildRolePermissions() { //grant all permissions to admin role var rolePermissions = DefaultPermissions.All().Select(p => new RolePermission { PermissionId = p.Id, RoleId = DefaultRoles.Admin.Id }).ToList(); //grant member access permission to member role rolePermissions.Add(new RolePermission { PermissionId = DefaultPermissions.MemberAccess.Id, RoleId = DefaultRoles.Member.Id }); return(rolePermissions.ToArray()); }
private void VanillaGrantUserPermissions(UInt64 UserId, String[] Permissions) { if (!File.Exists($"./data/{UserId}/permissions.json")) { CreateUserPermissions(UserId); } UserPermissions permissions = UserPermissions.Deserialize(UserId).Update(DefaultPermissions.Deserialize()); foreach (String v in Permissions) { foreach (String v1 in ParseWildcards(v)) { permissions[v1] = PermissionValue.Allowed; } } UserPermissions.Serialize(permissions); }
private void VanillaGrantRolePermissions(UInt64 RoleId, String[] Permissions) { if (!File.Exists($"./data/role-permissions/{RoleId}.json")) { CreateRolePermissions(RoleId); } RolePermissions permissions = RolePermissions.Deserialize(RoleId).Update(DefaultPermissions.Deserialize()); foreach (String v in Permissions) { foreach (String v1 in ParseWildcards(v)) { permissions[v1] = PermissionValue.Allowed; } } RolePermissions.Serialize(permissions); }
private static Boolean ShouldUpdateDefaultPermissions() { if (!File.Exists("./config/permissions/default.json")) { File.Create("./config/permissions/default.json").Close(); return(true); } if (!File.Exists("./cache/permissions/intermediate/default")) { File.Create("./cache/permissions/intermediate/default").Close(); return(true); } DefaultPermissions permissions = DefaultPermissions.Empty; StreamReader reader = new("./config/permissions/vanilla.pdecl.json"); permissions += JsonConvert.DeserializeObject <PermissionDeclaration[]>(reader.ReadToEnd()); reader.Close(); IEnumerable <String> modFiles = from x in Directory.GetFiles("./mod-data/permissions/declarations") where x.EndsWith(".pdecl.json") select x; foreach (String v in modFiles) { reader = new(v); permissions += JsonConvert.DeserializeObject <PermissionDeclaration[]>(reader.ReadToEnd()); reader.Close(); } reader = new("./config/permissions/default.json"); if (permissions != JsonConvert.DeserializeObject <DefaultPermissions>(reader.ReadToEnd())) { reader.Close(); return(true); } return(false); }
public static int Main(string[] args) { //AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File( "Logs/Logs.txt", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .CreateLogger(); try { Log.Information("Starting web host"); Log.Information("Starting web host"); var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var permissionAppService = scope.ServiceProvider.GetRequiredService <IPermissionService>(); permissionAppService.InitializePermissions(DefaultPermissions.All()); } host.Run(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return(1); } finally { Log.CloseAndFlush(); } }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (DefaultPermissions?.Any(x => x.IsNullOrWhiteSpace()) ?? false) { yield return(new ValidationResult("A permission value cannot be null or empty", new[] { "Permissions" })); } if (AssignedPermissions is not null) { foreach (KeyValuePair <int, IEnumerable <string> > assignedPermission in AssignedPermissions) { foreach (var permission in assignedPermission.Value) { if (permission.IsNullOrWhiteSpace()) { yield return(new ValidationResult( "A permission value cannot be null or empty", new[] { "AssignedPermissions" })); } } } } }
public static Permission[] BuildPermissions() { return(DefaultPermissions.All().ToArray()); }
private void VanillaUpdateUserPermissions(UInt64 UserId) { UserPermissions permissions = UserPermissions.Deserialize(UserId); UserPermissions.Serialize(permissions.Update(DefaultPermissions.Deserialize())); }
private void VanillaUpdateRolePermissions(UInt64 RoleId) { RolePermissions permissions = RolePermissions.Deserialize(RoleId); RolePermissions.Serialize(permissions.Update(DefaultPermissions.Deserialize())); }
/// <summary> /// 判断用户是否对特定的栏目具有特定的权限 /// </summary> /// <param name="permissions">用户请求的权限</param> /// <param name="menuID">栏目主键</param> /// <param name="userSignonGUID">用户登录后的验证串</param> /// <returns></returns> public bool CanUserProcessOperation(DefaultPermissions permissions, string menuID, string userSignonGUID) { int perCodeNum = EnumHandler<DefaultPermissions>.GetIntFromEnum(permissions); return CanUserProcessOperation(perCodeNum, menuID, userSignonGUID); }
private static void Initialize() { if (!Directory.Exists("./config/permissions")) { Console.WriteLine("Missing permission configuration, aborting startup. Please contact the InsanityBot team immediately" + "\nPress any key to continue..."); Console.ReadKey(); Process.GetCurrentProcess().Kill(); } // check for default mappings and declarations if (!File.Exists("./config/permissions/vanilla.mappings.json")) { Console.WriteLine("Missing vanilla permission mappings, aborting startup. Please contact the InsanityBot team immediately" + "\nPress any key to continue..."); Console.ReadKey(); Process.GetCurrentProcess().Kill(); } if (!File.Exists("./config/permissions/vanilla.pdecl.json")) { Console.WriteLine("Missing vanilla permission declaration, aborting startup. Please contact the InsanityBot team immediately" + "\nPress any key to continue..."); Console.ReadKey(); Process.GetCurrentProcess().Kill(); } // create role directory if (!Directory.Exists(DefaultPermissionFileSpecifications.Role.Path)) { Directory.CreateDirectory(DefaultPermissionFileSpecifications.Role.Path); } // create script directory if (!Directory.Exists(DefaultPermissionFileSpecifications.Script.Path)) { Directory.CreateDirectory(DefaultPermissionFileSpecifications.Script.Path); } // create mapping directory if (!Directory.Exists("./mod-data/permissions/mappings")) { Directory.CreateDirectory("./mod-data/permissions/mappings"); } // create declaration directory if (!Directory.Exists("./mod-data/permissions/declarations")) { Directory.CreateDirectory("./mod-data/permissions/declarations"); } // create intermediary directory if (!Directory.Exists("./cache/permissions/intermediate")) { Directory.CreateDirectory("./cache/permissions/intermediate"); } // check whether default permissions are up-to-date if (ShouldUpdateDefaultPermissions()) { UpdateDefaultPermissions(); } // check whether mappings are up-to-date if (ShouldUpdateMappings()) { UpdateMappings(); } // apply overrides to default and mappings DefaultPermissions.Serialize(LoadDefaultPermissions()); PermissionMapping toSerialize = LoadMappings(); StreamWriter writer = new("./config/permissions/mappings.json"); writer.Write(JsonConvert.SerializeObject(toSerialize)); writer.Close(); }
/// <summary> /// 验证用户是否有权限做该操作 /// </summary> /// <param name="menuPower">操作所需的权限<seealso cref="MenuPower"/></param> /// <returns>布尔值</returns> protected bool CanUserProcessOperation(DefaultPermissions permission) { try { // 权限验证 string signOnValidGuid = this.UserCacheInfo.GUID; // 当前栏目ID,在派生类中重写 string menuID = this.MenuID; return new BLL.Menu().CanUserProcessOperation(permission, menuID,signOnValidGuid); } catch (Exception ex) { throw ex; } }
private static DefaultPermissions LoadDefaultPermissions() { DefaultPermissions permissions = DefaultPermissions.Deserialize(); return(permissions.ApplyOverrides(DefaultPermissionOverrides.Deserialize())); }