├── OpenBulletAPI ├── libman.json ├── appsettings.Development.json ├── Models │ ├── AppSettings.cs │ ├── User.cs │ └── Config.cs ├── Program.cs ├── OpenBulletAPI.csproj ├── Configs │ ├── test │ │ └── test.loli │ └── test2 │ │ └── test.loli ├── Controllers │ ├── ValuesController.cs │ ├── UsersController.cs │ └── ConfigsController.cs ├── appsettings.json ├── Services │ ├── UserService.cs │ └── ConfigService.cs └── Startup.cs ├── README.md ├── LICENSE ├── OpenBulletAPI.sln └── .gitignore /OpenBulletAPI/libman.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "defaultProvider": "cdnjs", 4 | "libraries": [] 5 | } -------------------------------------------------------------------------------- /OpenBulletAPI/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenBullet API 2 | Self-hosted auth-based config serving API. Build with .NET core 2.2 so it can run on almost any platform. 3 | 4 | Go [here](https://openbullet.github.io/ob1/remote.html) to learn how to use this. 5 | -------------------------------------------------------------------------------- /OpenBulletAPI/Models/AppSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace OpenBulletAPI.Models 7 | { 8 | public class AppSettings 9 | { 10 | public bool AutoBindFirstIP { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /OpenBulletAPI/Models/User.cs: -------------------------------------------------------------------------------- 1 | using LiteDB; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace OpenBulletAPI.Models 8 | { 9 | public class User 10 | { 11 | [BsonId] 12 | public string Key { get; set; } 13 | 14 | [BsonField("Groups")] 15 | public string[] Groups { get; set; } 16 | 17 | [BsonField("IPs")] 18 | public string[] IPs { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /OpenBulletAPI/Models/Config.cs: -------------------------------------------------------------------------------- 1 | using LiteDB; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace OpenBulletAPI.Models 8 | { 9 | public class Config 10 | { 11 | [BsonId] 12 | public string Id { get; set; } 13 | 14 | [BsonField("Name")] 15 | public string Name { get; set; } 16 | 17 | [BsonField("Code")] 18 | public string Code { get; set; } 19 | 20 | [BsonField("Whitelist")] 21 | public string[] Whitelist { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /OpenBulletAPI/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace OpenBulletAPI 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseUrls("http://0.0.0.0:5000") 23 | .UseStartup(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /OpenBulletAPI/OpenBulletAPI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | InProcess 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | PreserveNewest 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /OpenBulletAPI/Configs/test/test.loli: -------------------------------------------------------------------------------- 1 | [SETTINGS] 2 | { 3 | "Name": "test", 4 | "SuggestedBots": 1, 5 | "LastModified": "2019-04-25T00:05:14.8651852+02:00", 6 | "AdditionalInfo": "", 7 | "Author": "", 8 | "Version": "1.0.2", 9 | "IgnoreResponseErrors": false, 10 | "NeedsProxies": false, 11 | "OnlySocks": false, 12 | "OnlySsl": false, 13 | "MaxProxyUses": 0, 14 | "AllowedWordlist1": "", 15 | "AllowedWordlist2": "", 16 | "DataRules": [], 17 | "CustomInputs": [], 18 | "ForceHeadless": false, 19 | "AlwaysOpen": false, 20 | "AlwaysQuit": false, 21 | "DisableNotifications": false, 22 | "CustomUserAgent": "", 23 | "RandomUA": false, 24 | "CustomCMDArgs": "" 25 | } 26 | 27 | [SCRIPT] 28 | REQUEST GET "https://google.com" 29 | 30 | HEADER "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko" 31 | HEADER "Pragma: no-cache" 32 | HEADER "Accept: */*" 33 | 34 | -------------------------------------------------------------------------------- /OpenBulletAPI/Configs/test2/test.loli: -------------------------------------------------------------------------------- 1 | [SETTINGS] 2 | { 3 | "Name": "test", 4 | "SuggestedBots": 1, 5 | "LastModified": "2019-04-25T00:05:14.8651852+02:00", 6 | "AdditionalInfo": "", 7 | "Author": "", 8 | "Version": "1.0.2", 9 | "IgnoreResponseErrors": false, 10 | "NeedsProxies": false, 11 | "OnlySocks": false, 12 | "OnlySsl": false, 13 | "MaxProxyUses": 0, 14 | "AllowedWordlist1": "", 15 | "AllowedWordlist2": "", 16 | "DataRules": [], 17 | "CustomInputs": [], 18 | "ForceHeadless": false, 19 | "AlwaysOpen": false, 20 | "AlwaysQuit": false, 21 | "DisableNotifications": false, 22 | "CustomUserAgent": "", 23 | "RandomUA": false, 24 | "CustomCMDArgs": "" 25 | } 26 | 27 | [SCRIPT] 28 | REQUEST GET "https://google.com" 29 | 30 | HEADER "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko" 31 | HEADER "Pragma: no-cache" 32 | HEADER "Accept: */*" 33 | 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /OpenBulletAPI/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace OpenBulletAPI.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | [ApiController] 11 | public class ValuesController : ControllerBase 12 | { 13 | // GET api/values 14 | [HttpGet] 15 | public ActionResult> Get() 16 | { 17 | return new string[] { "value1", "value2" }; 18 | } 19 | 20 | // GET api/values/5 21 | [HttpGet("{id}")] 22 | public ActionResult Get(int id) 23 | { 24 | return "value"; 25 | } 26 | 27 | // POST api/values 28 | [HttpPost] 29 | public void Post([FromBody] string value) 30 | { 31 | } 32 | 33 | // PUT api/values/5 34 | [HttpPut("{id}")] 35 | public void Put(int id, [FromBody] string value) 36 | { 37 | } 38 | 39 | // DELETE api/values/5 40 | [HttpDelete("{id}")] 41 | public void Delete(int id) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /OpenBulletAPI.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28803.202 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenBulletAPI", "OpenBulletAPI\OpenBulletAPI.csproj", "{13DCD674-1A68-4FAE-9108-D2A9E3004252}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {13DCD674-1A68-4FAE-9108-D2A9E3004252}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {13DCD674-1A68-4FAE-9108-D2A9E3004252}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {13DCD674-1A68-4FAE-9108-D2A9E3004252}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {13DCD674-1A68-4FAE-9108-D2A9E3004252}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {EB7A771A-978F-4781-AF9A-D4E07BEB774D} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /OpenBulletAPI/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "db": "ob.db", 4 | "configFolder": "Configs", 5 | "secretKey": "secretPassword" 6 | }, 7 | "AppSettings": { 8 | "AutoBindFirstIP": false 9 | }, 10 | "Logging": { 11 | "LogLevel": { 12 | "Default": "Warning" 13 | } 14 | }, 15 | "AllowedHosts": "*", 16 | 17 | "IpRateLimiting": { 18 | "EnableEndpointRateLimiting": false, 19 | "StackBlockedRequests": false, 20 | "RealIpHeader": "X-Real-IP", 21 | "ClientIdHeader": "X-ClientId", 22 | "HttpStatusCode": 429, 23 | "IpWhitelist": [ "127.0.0.1", "::1/10", "192.168.0.0/24" ], 24 | "EndpointWhitelist": [ "get:/api/license", "*:/api/status" ], 25 | "ClientWhitelist": [ "dev-id-1", "dev-id-2" ], 26 | "GeneralRules": [ 27 | { 28 | "Endpoint": "*", 29 | "Period": "1s", 30 | "Limit": 2 31 | }, 32 | { 33 | "Endpoint": "*", 34 | "Period": "15m", 35 | "Limit": 100 36 | }, 37 | { 38 | "Endpoint": "*", 39 | "Period": "12h", 40 | "Limit": 1000 41 | }, 42 | { 43 | "Endpoint": "*", 44 | "Period": "7d", 45 | "Limit": 10000 46 | } 47 | ] 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /OpenBulletAPI/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Mvc; 7 | using OpenBulletAPI.Models; 8 | using OpenBulletAPI.Services; 9 | 10 | namespace OpenBulletAPI.Controllers 11 | { 12 | [Route("api/[controller]")] 13 | [ApiController] 14 | public class UsersController : ControllerBase 15 | { 16 | private readonly UserService _userService; 17 | private string Auth 18 | { 19 | get 20 | { 21 | var auth = Request.Headers["Authorization"].FirstOrDefault(); 22 | return auth == null ? "" : auth; 23 | } 24 | } 25 | 26 | public UsersController(UserService userService) 27 | { 28 | _userService = userService; 29 | } 30 | 31 | // GET api/user 32 | // Admin-only 33 | [HttpGet] 34 | public ActionResult> Get() 35 | { 36 | return _userService.Get(Auth); 37 | } 38 | 39 | // GET api/user/KEY_HERE 40 | // Admin-only 41 | [HttpGet("{key}", Name = "GetUser")] 42 | public ActionResult Get(string key) 43 | { 44 | var user = _userService.Get(Auth, key); 45 | 46 | if (user == null) 47 | { 48 | return NotFound(); 49 | } 50 | 51 | return user; 52 | } 53 | 54 | // POST api/user 55 | // Admin-only 56 | [HttpPost] 57 | public ActionResult Create(User user) 58 | { 59 | _userService.Create(Auth, user); 60 | 61 | return CreatedAtRoute("GetUser", new { key = user.Key }, user); 62 | } 63 | 64 | // PUT api/user/KEY_HERE 65 | // Admin-only 66 | [HttpPut("{key}")] 67 | public IActionResult Update(string key, User userIn) 68 | { 69 | var user = _userService.Get(Auth, key); 70 | 71 | if (user == null) 72 | { 73 | return NotFound(); 74 | } 75 | 76 | _userService.Update(Auth, userIn); 77 | 78 | return NoContent(); 79 | } 80 | 81 | // DELETE api/user/KEY_HERE 82 | // Admin-only 83 | [HttpDelete("{key}")] 84 | public IActionResult Delete(string key) 85 | { 86 | var user = _userService.Get(Auth, key); 87 | 88 | if (user == null) 89 | { 90 | return NotFound(); 91 | } 92 | 93 | _userService.Remove(Auth, user.Key); 94 | 95 | return NoContent(); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /OpenBulletAPI/Services/UserService.cs: -------------------------------------------------------------------------------- 1 | using LiteDB; 2 | using Microsoft.Extensions.Configuration; 3 | using OpenBulletAPI.Models; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace OpenBulletAPI.Services 10 | { 11 | public class UserService 12 | { 13 | private readonly LiteCollection _users; 14 | private readonly string _secretKey; 15 | 16 | public User GetUser(string key) 17 | { 18 | return _users.Find(user => user.Key == key).FirstOrDefault(); 19 | } 20 | 21 | public void UpdateUser(User user) 22 | { 23 | _users.Update(user); 24 | } 25 | 26 | public UserService(IConfiguration configuration) 27 | { 28 | using (var db = new LiteDatabase(configuration.GetConnectionString("db"))) 29 | { 30 | _users = db.GetCollection("Users"); 31 | } 32 | 33 | _secretKey = configuration.GetConnectionString("secretKey"); 34 | } 35 | 36 | public List Get(string secretKey) 37 | { 38 | if (IsAdmin(secretKey)) 39 | { 40 | return _users.FindAll().ToList(); 41 | } 42 | else 43 | { 44 | return new List(); 45 | } 46 | } 47 | 48 | public User Get(string secretKey, string key) 49 | { 50 | if (IsAdmin(secretKey)) 51 | { 52 | return GetUser(key); 53 | } 54 | else 55 | { 56 | return null; 57 | } 58 | } 59 | 60 | public User Create(string secretKey, User user) 61 | { 62 | if (IsAdmin(secretKey)) 63 | { 64 | _users.Insert(user); 65 | return user; 66 | } 67 | else 68 | { 69 | return null; 70 | } 71 | } 72 | 73 | public void Update(string secretKey, User user) 74 | { 75 | if (IsAdmin(secretKey)) 76 | { 77 | _users.Update(user); 78 | } 79 | } 80 | 81 | public void Remove(string secretKey, User user) 82 | { 83 | if (IsAdmin(secretKey)) 84 | { 85 | _users.Delete(c => c.Key == user.Key); 86 | } 87 | } 88 | 89 | public void Remove(string secretKey, string key) 90 | { 91 | if (IsAdmin(secretKey)) 92 | { 93 | _users.Delete(user => user.Key == key); 94 | } 95 | } 96 | 97 | private bool IsAdmin(string secretKey) 98 | { 99 | return secretKey == _secretKey; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /OpenBulletAPI/Services/ConfigService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using OpenBulletAPI.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using LiteDB; 8 | using Microsoft.AspNetCore.Mvc; 9 | using System.IO; 10 | using System.IO.Compression; 11 | 12 | namespace OpenBulletAPI.Services 13 | { 14 | public class ConfigService 15 | { 16 | private readonly string _configFolder; 17 | 18 | public ConfigService(IConfiguration configuration) 19 | { 20 | _configFolder = configuration.GetConnectionString("configFolder"); 21 | } 22 | 23 | public MemoryStream Get(string[] groups) 24 | { 25 | using (MemoryStream ms = new MemoryStream()) 26 | { 27 | using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true)) 28 | { 29 | // List all the configs the user can access 30 | foreach (var group in groups.Where(g => g.Trim() != "")) 31 | { 32 | var dir = Path.Combine(_configFolder, group); 33 | 34 | ZipFolderRecursively(archive, dir, _configFolder); 35 | } 36 | } 37 | 38 | return ms; 39 | } 40 | } 41 | 42 | private void ZipFolderRecursively(ZipArchive archive, string currentDir, string baseDir) 43 | { 44 | // Add all the files 45 | foreach (var file in Directory.EnumerateFiles(currentDir).Where(file => file.EndsWith(".loli"))) 46 | { 47 | // Create the file entry and write the file content 48 | var zipArchiveEntry = archive.CreateEntry($"{file.Substring(baseDir.Length + 1)}", CompressionLevel.Fastest); 49 | var fileContent = File.ReadAllBytes(file); 50 | using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(fileContent, 0, fileContent.Length); 51 | } 52 | 53 | // Add subfolders recursively 54 | foreach (var dir in Directory.EnumerateDirectories(currentDir)) 55 | { 56 | ZipFolderRecursively(archive, dir, baseDir); 57 | } 58 | } 59 | 60 | public async Task Upload(Stream file, string group, string name) 61 | { 62 | if (group != "" && name.EndsWith(".loli")) 63 | { 64 | var dir = Path.Combine(_configFolder, group); 65 | Directory.CreateDirectory(dir); 66 | var comb = Path.Combine(dir, Path.GetFileName(name)); 67 | 68 | using (var stream = new FileStream(comb, System.IO.FileMode.Create)) 69 | { 70 | await file.CopyToAsync(stream); 71 | return true; 72 | } 73 | } 74 | 75 | return false; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /OpenBulletAPI/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using AspNetCoreRateLimit; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Http; 9 | using Microsoft.AspNetCore.HttpsPolicy; 10 | using Microsoft.AspNetCore.Mvc; 11 | using Microsoft.Extensions.Configuration; 12 | using Microsoft.Extensions.DependencyInjection; 13 | using Microsoft.Extensions.Logging; 14 | using Microsoft.Extensions.Options; 15 | using OpenBulletAPI.Models; 16 | using OpenBulletAPI.Services; 17 | 18 | namespace OpenBulletAPI 19 | { 20 | public class Startup 21 | { 22 | public Startup(IConfiguration configuration) 23 | { 24 | Configuration = configuration; 25 | } 26 | 27 | public IConfiguration Configuration { get; } 28 | 29 | // This method gets called by the runtime. Use this method to add services to the container. 30 | public void ConfigureServices(IServiceCollection services) 31 | { 32 | // add the app settings 33 | services.Configure(Configuration.GetSection("AppSettings")); 34 | 35 | // needed to load configuration from appsettings.json 36 | services.AddOptions(); 37 | 38 | // needed to store rate limit counters and ip rules 39 | services.AddMemoryCache(); 40 | 41 | //load general configuration from appsettings.json 42 | services.Configure(Configuration.GetSection("IpRateLimiting")); 43 | 44 | //load ip rules from appsettings.json 45 | services.Configure(Configuration.GetSection("IpRateLimitPolicies")); 46 | 47 | // inject counter and rules stores 48 | services.AddSingleton(); 49 | services.AddSingleton(); 50 | 51 | // Add framework services. 52 | services.AddMvc(); 53 | 54 | // https://github.com/aspnet/Hosting/issues/793 55 | // the IHttpContextAccessor service is not registered by default. 56 | // the clientId/clientIp resolvers use it. 57 | services.AddSingleton(); 58 | 59 | // configuration (resolvers, counter key builders) 60 | services.AddSingleton(); 61 | 62 | services.AddScoped(); 63 | services.AddScoped(); 64 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 65 | } 66 | 67 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 68 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 69 | { 70 | if (env.IsDevelopment()) 71 | { 72 | app.UseDeveloperExceptionPage(); 73 | } 74 | else 75 | { 76 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 77 | app.UseHsts(); 78 | } 79 | 80 | app.UseIpRateLimiting(); 81 | 82 | // app.UseClientRateLimiting(); 83 | 84 | app.UseHttpsRedirection(); 85 | app.UseMvc(); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /OpenBulletAPI/Controllers/ConfigsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Options; 4 | using OpenBulletAPI.Models; 5 | using OpenBulletAPI.Services; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Text; 11 | using System.Threading.Tasks; 12 | 13 | namespace OpenBulletAPI.Controllers 14 | { 15 | [Route("api/[controller]")] 16 | [ApiController] 17 | public class ConfigsController : ControllerBase 18 | { 19 | private readonly ConfigService _configService; 20 | private readonly UserService _userService; 21 | private readonly AppSettings _appSettings; 22 | private string Auth 23 | { 24 | get 25 | { 26 | var auth = Request.Headers["Authorization"].FirstOrDefault(); 27 | return auth == null ? "" : auth; 28 | } 29 | } 30 | 31 | private string[] GetGroups() 32 | { 33 | if (Auth.StartsWith("Basic")) 34 | { 35 | // Login to external API and get the groups 36 | throw new Exception("UserPass Authentication not implemented on this API"); 37 | } 38 | else // Otherwise we assume it's an API key 39 | { 40 | // Retrieve the user 41 | var user = _userService.GetUser(Auth); 42 | 43 | // Check if the user exists 44 | if (user == null) 45 | { 46 | throw new Exception("The user does not exist"); 47 | } 48 | 49 | // Check the IP if the IPs whitelist is not blank 50 | var ip = Request.HttpContext.Connection.RemoteIpAddress.ToString(); 51 | if (user.IPs != null && user.IPs.Count(i => !string.IsNullOrWhiteSpace(i)) > 0) 52 | { 53 | if (!user.IPs.Contains(ip)) 54 | { 55 | throw new Exception("Unauthorized IP"); 56 | } 57 | } 58 | 59 | // If we set AutoBindFirstIP to true, add the current IP to the array 60 | if (_appSettings.AutoBindFirstIP && (user.IPs == null || user.IPs.Count(i => !string.IsNullOrWhiteSpace(i)) == 0)) 61 | { 62 | user.IPs = new string[] { ip }; 63 | _userService.UpdateUser(user); 64 | } 65 | 66 | return user.Groups; 67 | } 68 | } 69 | 70 | public ConfigsController(IOptions settings, ConfigService configService, UserService userService) 71 | { 72 | _configService = configService; 73 | _userService = userService; 74 | _appSettings = settings.Value; 75 | } 76 | 77 | [HttpGet] 78 | public async Task Get() 79 | { 80 | try 81 | { 82 | var groups = GetGroups(); 83 | 84 | return File(_configService.Get(groups).ToArray(), "application/zip", "Configs.zip"); 85 | } 86 | catch (Exception ex) 87 | { 88 | return Content(ex.Message); 89 | } 90 | } 91 | 92 | [HttpPost] 93 | public async Task UploadFile(IFormFile file) 94 | { 95 | if (file == null || file.Length == 0) 96 | return Content("No file selected"); 97 | 98 | if (await _configService.Upload(file.OpenReadStream(), Request.Headers["Group"].FirstOrDefault(), Request.Headers["Name"].FirstOrDefault())) 99 | { 100 | return Content("Uploaded!"); 101 | } 102 | else 103 | { 104 | return Content("Failed to upload"); 105 | } 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | ob.db 16 | 17 | # Build results 18 | [Dd]ebug/ 19 | [Dd]ebugPublic/ 20 | [Rr]elease/ 21 | [Rr]eleases/ 22 | x64/ 23 | x86/ 24 | bld/ 25 | [Bb]in/ 26 | [Oo]bj/ 27 | [Ll]og/ 28 | 29 | # Visual Studio 2015/2017 cache/options directory 30 | .vs/ 31 | # Uncomment if you have tasks that create the project's static files in wwwroot 32 | #wwwroot/ 33 | 34 | # Visual Studio 2017 auto generated files 35 | Generated\ Files/ 36 | 37 | # MSTest test Results 38 | [Tt]est[Rr]esult*/ 39 | [Bb]uild[Ll]og.* 40 | 41 | # NUNIT 42 | *.VisualState.xml 43 | TestResult.xml 44 | 45 | # Build Results of an ATL Project 46 | [Dd]ebugPS/ 47 | [Rr]eleasePS/ 48 | dlldata.c 49 | 50 | # Benchmark Results 51 | BenchmarkDotNet.Artifacts/ 52 | 53 | # .NET Core 54 | project.lock.json 55 | project.fragment.lock.json 56 | artifacts/ 57 | **/Properties/launchSettings.json 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_i.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *.log 83 | *.vspscc 84 | *.vssscc 85 | .builds 86 | *.pidb 87 | *.svclog 88 | *.scc 89 | 90 | # Chutzpah Test files 91 | _Chutzpah* 92 | 93 | # Visual C++ cache files 94 | ipch/ 95 | *.aps 96 | *.ncb 97 | *.opendb 98 | *.opensdf 99 | *.sdf 100 | *.cachefile 101 | *.VC.db 102 | *.VC.VC.opendb 103 | 104 | # Visual Studio profiler 105 | *.psess 106 | *.vsp 107 | *.vspx 108 | *.sap 109 | 110 | # Visual Studio Trace Files 111 | *.e2e 112 | 113 | # TFS 2012 Local Workspace 114 | $tf/ 115 | 116 | # Guidance Automation Toolkit 117 | *.gpState 118 | 119 | # ReSharper is a .NET coding add-in 120 | _ReSharper*/ 121 | *.[Rr]e[Ss]harper 122 | *.DotSettings.user 123 | 124 | # JustCode is a .NET coding add-in 125 | .JustCode 126 | 127 | # TeamCity is a build add-in 128 | _TeamCity* 129 | 130 | # DotCover is a Code Coverage Tool 131 | *.dotCover 132 | 133 | # AxoCover is a Code Coverage Tool 134 | .axoCover/* 135 | !.axoCover/settings.json 136 | 137 | # Visual Studio code coverage results 138 | *.coverage 139 | *.coveragexml 140 | 141 | # NCrunch 142 | _NCrunch_* 143 | .*crunch*.local.xml 144 | nCrunchTemp_* 145 | 146 | # MightyMoose 147 | *.mm.* 148 | AutoTest.Net/ 149 | 150 | # Web workbench (sass) 151 | .sass-cache/ 152 | 153 | # Installshield output folder 154 | [Ee]xpress/ 155 | 156 | # DocProject is a documentation generator add-in 157 | DocProject/buildhelp/ 158 | DocProject/Help/*.HxT 159 | DocProject/Help/*.HxC 160 | DocProject/Help/*.hhc 161 | DocProject/Help/*.hhk 162 | DocProject/Help/*.hhp 163 | DocProject/Help/Html2 164 | DocProject/Help/html 165 | 166 | # Click-Once directory 167 | publish/ 168 | 169 | # Publish Web Output 170 | *.[Pp]ublish.xml 171 | *.azurePubxml 172 | # Note: Comment the next line if you want to checkin your web deploy settings, 173 | # but database connection strings (with potential passwords) will be unencrypted 174 | *.pubxml 175 | *.publishproj 176 | 177 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 178 | # checkin your Azure Web App publish settings, but sensitive information contained 179 | # in these scripts will be unencrypted 180 | PublishScripts/ 181 | 182 | # NuGet Packages 183 | *.nupkg 184 | # The packages folder can be ignored because of Package Restore 185 | **/[Pp]ackages/* 186 | # except build/, which is used as an MSBuild target. 187 | !**/[Pp]ackages/build/ 188 | # Uncomment if necessary however generally it will be regenerated when needed 189 | #!**/[Pp]ackages/repositories.config 190 | # NuGet v3's project.json files produces more ignorable files 191 | *.nuget.props 192 | *.nuget.targets 193 | 194 | # Microsoft Azure Build Output 195 | csx/ 196 | *.build.csdef 197 | 198 | # Microsoft Azure Emulator 199 | ecf/ 200 | rcf/ 201 | 202 | # Windows Store app package directories and files 203 | AppPackages/ 204 | BundleArtifacts/ 205 | Package.StoreAssociation.xml 206 | _pkginfo.txt 207 | *.appx 208 | 209 | # Visual Studio cache files 210 | # files ending in .cache can be ignored 211 | *.[Cc]ache 212 | # but keep track of directories ending in .cache 213 | !*.[Cc]ache/ 214 | 215 | # Others 216 | ClientBin/ 217 | ~$* 218 | *~ 219 | *.dbmdl 220 | *.dbproj.schemaview 221 | *.jfm 222 | *.pfx 223 | *.publishsettings 224 | orleans.codegen.cs 225 | 226 | # Including strong name files can present a security risk 227 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 228 | #*.snk 229 | 230 | # Since there are multiple workflows, uncomment next line to ignore bower_components 231 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 232 | #bower_components/ 233 | 234 | # RIA/Silverlight projects 235 | Generated_Code/ 236 | 237 | # Backup & report files from converting an old project file 238 | # to a newer Visual Studio version. Backup files are not needed, 239 | # because we have git ;-) 240 | _UpgradeReport_Files/ 241 | Backup*/ 242 | UpgradeLog*.XML 243 | UpgradeLog*.htm 244 | ServiceFabricBackup/ 245 | *.rptproj.bak 246 | 247 | # SQL Server files 248 | *.mdf 249 | *.ldf 250 | *.ndf 251 | 252 | # Business Intelligence projects 253 | *.rdl.data 254 | *.bim.layout 255 | *.bim_*.settings 256 | *.rptproj.rsuser 257 | 258 | # Microsoft Fakes 259 | FakesAssemblies/ 260 | 261 | # GhostDoc plugin setting file 262 | *.GhostDoc.xml 263 | 264 | # Node.js Tools for Visual Studio 265 | .ntvs_analysis.dat 266 | node_modules/ 267 | 268 | # Visual Studio 6 build log 269 | *.plg 270 | 271 | # Visual Studio 6 workspace options file 272 | *.opt 273 | 274 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 275 | *.vbw 276 | 277 | # Visual Studio LightSwitch build output 278 | **/*.HTMLClient/GeneratedArtifacts 279 | **/*.DesktopClient/GeneratedArtifacts 280 | **/*.DesktopClient/ModelManifest.xml 281 | **/*.Server/GeneratedArtifacts 282 | **/*.Server/ModelManifest.xml 283 | _Pvt_Extensions 284 | 285 | # Paket dependency manager 286 | .paket/paket.exe 287 | paket-files/ 288 | 289 | # FAKE - F# Make 290 | .fake/ 291 | 292 | # JetBrains Rider 293 | .idea/ 294 | *.sln.iml 295 | 296 | # CodeRush 297 | .cr/ 298 | 299 | # Python Tools for Visual Studio (PTVS) 300 | __pycache__/ 301 | *.pyc 302 | 303 | # Cake - Uncomment if you are using it 304 | # tools/** 305 | # !tools/packages.config 306 | 307 | # Tabs Studio 308 | *.tss 309 | 310 | # Telerik's JustMock configuration file 311 | *.jmconfig 312 | 313 | # BizTalk build output 314 | *.btp.cs 315 | *.btm.cs 316 | *.odx.cs 317 | *.xsd.cs 318 | 319 | # OpenCover UI analysis results 320 | OpenCover/ 321 | 322 | # Azure Stream Analytics local run output 323 | ASALocalRun/ 324 | 325 | # MSBuild Binary and Structured Log 326 | *.binlog 327 | 328 | # NVidia Nsight GPU debugger configuration file 329 | *.nvuser 330 | 331 | # MFractors (Xamarin productivity tool) working folder 332 | .mfractor/ 333 | --------------------------------------------------------------------------------