diff --git a/src/Admin/Controllers/HomeController.cs b/src/Admin/Controllers/HomeController.cs index 3573dbcd43..dc8f615da8 100644 --- a/src/Admin/Controllers/HomeController.cs +++ b/src/Admin/Controllers/HomeController.cs @@ -44,22 +44,22 @@ namespace Bit.Admin.Controllers { var response = await _httpClient.GetAsync( $"https://hub.docker.com/v2/repositories/bitwarden/{repository}/tags/"); - if(response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); var data = JObject.Parse(json); var results = data["results"] as JArray; - foreach(var result in results) + foreach (var result in results) { var name = result["name"].ToString(); - if(!string.IsNullOrWhiteSpace(name) && name.Length > 0 && char.IsNumber(name[0])) + if (!string.IsNullOrWhiteSpace(name) && name.Length > 0 && char.IsNumber(name[0])) { return new JsonResult(name); } } } } - catch(HttpRequestException) { } + catch (HttpRequestException) { } return new JsonResult("-"); } @@ -70,14 +70,14 @@ namespace Bit.Admin.Controllers { var response = await _httpClient.GetAsync( $"{_globalSettings.BaseServiceUri.InternalVault}/version.json"); - if(response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); var data = JObject.Parse(json); return new JsonResult(data["version"].ToString()); } } - catch(HttpRequestException) { } + catch (HttpRequestException) { } return new JsonResult("-"); } diff --git a/src/Admin/Controllers/LoginController.cs b/src/Admin/Controllers/LoginController.cs index c2bb47dddb..e6554ddfd1 100644 --- a/src/Admin/Controllers/LoginController.cs +++ b/src/Admin/Controllers/LoginController.cs @@ -19,7 +19,7 @@ namespace Bit.Admin.Controllers public IActionResult Index(string returnUrl = null, string error = null, string success = null, bool accessDenied = false) { - if(string.IsNullOrWhiteSpace(error) && accessDenied) + if (string.IsNullOrWhiteSpace(error) && accessDenied) { error = "Access denied. Please log in."; } @@ -36,7 +36,7 @@ namespace Bit.Admin.Controllers [ValidateAntiForgeryToken] public async Task Index(LoginModel model) { - if(ModelState.IsValid) + if (ModelState.IsValid) { await _signInManager.PasswordlessSignInAsync(model.Email, model.ReturnUrl); return RedirectToAction("Index", new @@ -52,7 +52,7 @@ namespace Bit.Admin.Controllers public async Task Confirm(string email, string token, string returnUrl) { var result = await _signInManager.PasswordlessSignInAsync(email, token, true); - if(!result.Succeeded) + if (!result.Succeeded) { return RedirectToAction("Index", new { @@ -60,7 +60,7 @@ namespace Bit.Admin.Controllers }); } - if(!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl)) + if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } diff --git a/src/Admin/Controllers/LogsController.cs b/src/Admin/Controllers/LogsController.cs index 0e40ae3eef..b33dc48ab4 100644 --- a/src/Admin/Controllers/LogsController.cs +++ b/src/Admin/Controllers/LogsController.cs @@ -30,7 +30,7 @@ namespace Bit.Admin.Controllers LogEventLevel? level = null, string project = null, DateTime? start = null, DateTime? end = null) { var collectionLink = UriFactory.CreateDocumentCollectionUri(Database, Collection); - using(var client = new DocumentClient(new Uri(_globalSettings.DocumentDb.Uri), + using (var client = new DocumentClient(new Uri(_globalSettings.DocumentDb.Uri), _globalSettings.DocumentDb.Key)) { var options = new FeedOptions @@ -40,19 +40,19 @@ namespace Bit.Admin.Controllers }; var query = client.CreateDocumentQuery(collectionLink, options).AsQueryable(); - if(level.HasValue) + if (level.HasValue) { query = query.Where(l => l.Level == level.Value.ToString()); } - if(!string.IsNullOrWhiteSpace(project)) + if (!string.IsNullOrWhiteSpace(project)) { query = query.Where(l => l.Properties != null && l.Properties["Project"] == (object)project); } - if(start.HasValue) + if (start.HasValue) { query = query.Where(l => l.Timestamp >= start.Value); } - if(end.HasValue) + if (end.HasValue) { query = query.Where(l => l.Timestamp <= end.Value); } @@ -76,12 +76,12 @@ namespace Bit.Admin.Controllers public async Task View(Guid id) { - using(var client = new DocumentClient(new Uri(_globalSettings.DocumentDb.Uri), + using (var client = new DocumentClient(new Uri(_globalSettings.DocumentDb.Uri), _globalSettings.DocumentDb.Key)) { var uri = UriFactory.CreateDocumentUri(Database, Collection, id.ToString()); var response = await client.ReadDocumentAsync(uri); - if(response?.Document == null) + if (response?.Document == null) { return RedirectToAction("Index"); } diff --git a/src/Admin/Controllers/OrganizationsController.cs b/src/Admin/Controllers/OrganizationsController.cs index 17029f8d26..2014fc000d 100644 --- a/src/Admin/Controllers/OrganizationsController.cs +++ b/src/Admin/Controllers/OrganizationsController.cs @@ -50,12 +50,12 @@ namespace Bit.Admin.Controllers public async Task Index(string name = null, string userEmail = null, bool? paid = null, int page = 1, int count = 25) { - if(page < 1) + if (page < 1) { page = 1; } - if(count < 1) + if (count < 1) { count = 1; } @@ -78,7 +78,7 @@ namespace Bit.Admin.Controllers public async Task View(Guid id) { var organization = await _organizationRepository.GetByIdAsync(id); - if(organization == null) + if (organization == null) { return RedirectToAction("Index"); } @@ -86,12 +86,12 @@ namespace Bit.Admin.Controllers var ciphers = await _cipherRepository.GetManyByOrganizationIdAsync(id); var collections = await _collectionRepository.GetManyByOrganizationIdAsync(id); IEnumerable groups = null; - if(organization.UseGroups) + if (organization.UseGroups) { groups = await _groupRepository.GetManyByOrganizationIdAsync(id); } IEnumerable policies = null; - if(organization.UsePolicies) + if (organization.UsePolicies) { policies = await _policyRepository.GetManyByOrganizationIdAsync(id); } @@ -103,7 +103,7 @@ namespace Bit.Admin.Controllers public async Task Edit(Guid id) { var organization = await _organizationRepository.GetByIdAsync(id); - if(organization == null) + if (organization == null) { return RedirectToAction("Index"); } @@ -111,12 +111,12 @@ namespace Bit.Admin.Controllers var ciphers = await _cipherRepository.GetManyByOrganizationIdAsync(id); var collections = await _collectionRepository.GetManyByOrganizationIdAsync(id); IEnumerable groups = null; - if(organization.UseGroups) + if (organization.UseGroups) { groups = await _groupRepository.GetManyByOrganizationIdAsync(id); } IEnumerable policies = null; - if(organization.UsePolicies) + if (organization.UsePolicies) { policies = await _policyRepository.GetManyByOrganizationIdAsync(id); } @@ -132,7 +132,7 @@ namespace Bit.Admin.Controllers public async Task Edit(Guid id, OrganizationEditModel model) { var organization = await _organizationRepository.GetByIdAsync(id); - if(organization == null) + if (organization == null) { return RedirectToAction("Index"); } @@ -148,7 +148,7 @@ namespace Bit.Admin.Controllers public async Task Delete(Guid id) { var organization = await _organizationRepository.GetByIdAsync(id); - if(organization != null) + if (organization != null) { await _organizationRepository.DeleteAsync(organization); await _applicationCacheService.DeleteOrganizationAbilityAsync(organization.Id); diff --git a/src/Admin/Controllers/ToolsController.cs b/src/Admin/Controllers/ToolsController.cs index d610e9199e..b1695e71bd 100644 --- a/src/Admin/Controllers/ToolsController.cs +++ b/src/Admin/Controllers/ToolsController.cs @@ -37,7 +37,7 @@ namespace Bit.Admin.Controllers [HttpPost] public async Task ChargeBraintree(ChargeBraintreeModel model) { - if(!ModelState.IsValid) + if (!ModelState.IsValid) { return View(model); } @@ -73,7 +73,7 @@ namespace Bit.Admin.Controllers } }); - if(!transactionResult.IsSuccess()) + if (!transactionResult.IsSuccess()) { ModelState.AddModelError(string.Empty, "Charge failed. " + "Refer to Braintree admin portal for more information."); @@ -98,13 +98,13 @@ namespace Bit.Admin.Controllers [HttpPost] public async Task CreateTransaction(CreateUpdateTransactionModel model) { - if(!ModelState.IsValid) + if (!ModelState.IsValid) { return View("CreateUpdateTransaction", model); } await _transactionRepository.CreateAsync(model.ToTransaction()); - if(model.UserId.HasValue) + if (model.UserId.HasValue) { return RedirectToAction("Edit", "Users", new { id = model.UserId }); } @@ -117,7 +117,7 @@ namespace Bit.Admin.Controllers public async Task EditTransaction(Guid id) { var transaction = await _transactionRepository.GetByIdAsync(id); - if(transaction == null) + if (transaction == null) { return RedirectToAction("Index", "Home"); } @@ -127,12 +127,12 @@ namespace Bit.Admin.Controllers [HttpPost] public async Task EditTransaction(Guid id, CreateUpdateTransactionModel model) { - if(!ModelState.IsValid) + if (!ModelState.IsValid) { return View("CreateUpdateTransaction", model); } await _transactionRepository.ReplaceAsync(model.ToTransaction(id)); - if(model.UserId.HasValue) + if (model.UserId.HasValue) { return RedirectToAction("Edit", "Users", new { id = model.UserId }); } @@ -150,7 +150,7 @@ namespace Bit.Admin.Controllers [HttpPost] public async Task PromoteAdmin(PromoteAdminModel model) { - if(!ModelState.IsValid) + if (!ModelState.IsValid) { return View("PromoteAdmin", model); } @@ -158,16 +158,16 @@ namespace Bit.Admin.Controllers var orgUsers = await _organizationUserRepository.GetManyByOrganizationAsync( model.OrganizationId.Value, null); var user = orgUsers.FirstOrDefault(u => u.UserId == model.UserId.Value); - if(user == null) + if (user == null) { ModelState.AddModelError(nameof(model.UserId), "User Id not found in this organization."); } - else if(user.Type != Core.Enums.OrganizationUserType.Admin) + else if (user.Type != Core.Enums.OrganizationUserType.Admin) { ModelState.AddModelError(nameof(model.UserId), "User is not an admin of this organization."); } - if(!ModelState.IsValid) + if (!ModelState.IsValid) { return View("PromoteAdmin", model); } diff --git a/src/Admin/Controllers/UsersController.cs b/src/Admin/Controllers/UsersController.cs index 19d2410296..19043030cd 100644 --- a/src/Admin/Controllers/UsersController.cs +++ b/src/Admin/Controllers/UsersController.cs @@ -34,12 +34,12 @@ namespace Bit.Admin.Controllers public async Task Index(string email, int page = 1, int count = 25) { - if(page < 1) + if (page < 1) { page = 1; } - if(count < 1) + if (count < 1) { count = 1; } @@ -59,7 +59,7 @@ namespace Bit.Admin.Controllers public async Task View(Guid id) { var user = await _userRepository.GetByIdAsync(id); - if(user == null) + if (user == null) { return RedirectToAction("Index"); } @@ -72,7 +72,7 @@ namespace Bit.Admin.Controllers public async Task Edit(Guid id) { var user = await _userRepository.GetByIdAsync(id); - if(user == null) + if (user == null) { return RedirectToAction("Index"); } @@ -88,7 +88,7 @@ namespace Bit.Admin.Controllers public async Task Edit(Guid id, UserEditModel model) { var user = await _userRepository.GetByIdAsync(id); - if(user == null) + if (user == null) { return RedirectToAction("Index"); } @@ -103,7 +103,7 @@ namespace Bit.Admin.Controllers public async Task Delete(Guid id) { var user = await _userRepository.GetByIdAsync(id); - if(user != null) + if (user != null) { await _userRepository.DeleteAsync(user); } diff --git a/src/Admin/HostedServices/AmazonSqsBlockIpHostedService.cs b/src/Admin/HostedServices/AmazonSqsBlockIpHostedService.cs index 850b1b19eb..bf037d1434 100644 --- a/src/Admin/HostedServices/AmazonSqsBlockIpHostedService.cs +++ b/src/Admin/HostedServices/AmazonSqsBlockIpHostedService.cs @@ -36,7 +36,7 @@ namespace Bit.Admin.HostedServices var unblockIpQueue = await _client.GetQueueUrlAsync("unblock-ip", cancellationToken); var unblockIpQueueUrl = unblockIpQueue.QueueUrl; - while(!cancellationToken.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { var blockMessageResponse = await _client.ReceiveMessageAsync(new ReceiveMessageRequest { @@ -44,15 +44,15 @@ namespace Bit.Admin.HostedServices MaxNumberOfMessages = 10, WaitTimeSeconds = 15 }, cancellationToken); - if(blockMessageResponse.Messages.Any()) + if (blockMessageResponse.Messages.Any()) { - foreach(var message in blockMessageResponse.Messages) + foreach (var message in blockMessageResponse.Messages) { try { await BlockIpAsync(message.Body, cancellationToken); } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Failed to block IP."); } @@ -66,15 +66,15 @@ namespace Bit.Admin.HostedServices MaxNumberOfMessages = 10, WaitTimeSeconds = 15 }, cancellationToken); - if(unblockMessageResponse.Messages.Any()) + if (unblockMessageResponse.Messages.Any()) { - foreach(var message in unblockMessageResponse.Messages) + foreach (var message in unblockMessageResponse.Messages) { try { await UnblockIpAsync(message.Body, cancellationToken); } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Failed to unblock IP."); } diff --git a/src/Admin/HostedServices/AzureQueueBlockIpHostedService.cs b/src/Admin/HostedServices/AzureQueueBlockIpHostedService.cs index fcd71b81eb..57ca20d464 100644 --- a/src/Admin/HostedServices/AzureQueueBlockIpHostedService.cs +++ b/src/Admin/HostedServices/AzureQueueBlockIpHostedService.cs @@ -26,18 +26,18 @@ namespace Bit.Admin.HostedServices _blockIpQueueClient = new QueueClient(_globalSettings.Storage.ConnectionString, "blockip"); _unblockIpQueueClient = new QueueClient(_globalSettings.Storage.ConnectionString, "unblockip"); - while(!cancellationToken.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { var blockMessages = await _blockIpQueueClient.ReceiveMessagesAsync(maxMessages: 32); - if(blockMessages.Value?.Any() ?? false) + if (blockMessages.Value?.Any() ?? false) { - foreach(var message in blockMessages.Value) + foreach (var message in blockMessages.Value) { try { await BlockIpAsync(message.MessageText, cancellationToken); } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Failed to block IP."); } @@ -46,15 +46,15 @@ namespace Bit.Admin.HostedServices } var unblockMessages = await _unblockIpQueueClient.ReceiveMessagesAsync(maxMessages: 32); - if(unblockMessages.Value?.Any() ?? false) + if (unblockMessages.Value?.Any() ?? false) { - foreach(var message in unblockMessages.Value) + foreach (var message in unblockMessages.Value) { try { await UnblockIpAsync(message.MessageText, cancellationToken); } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Failed to unblock IP."); } diff --git a/src/Admin/HostedServices/BlockIpHostedService.cs b/src/Admin/HostedServices/BlockIpHostedService.cs index 6f5272bd23..22f6ea0575 100644 --- a/src/Admin/HostedServices/BlockIpHostedService.cs +++ b/src/Admin/HostedServices/BlockIpHostedService.cs @@ -41,7 +41,7 @@ namespace Bit.Admin.HostedServices public async Task StopAsync(CancellationToken cancellationToken) { - if(_executingTask == null) + if (_executingTask == null) { return; } @@ -78,14 +78,14 @@ namespace Bit.Admin.HostedServices request.Content = new StringContent(bodyContent, Encoding.UTF8, "application/json"); var response = await _httpClient.SendAsync(request, cancellationToken); - if(!response.IsSuccessStatusCode) + if (!response.IsSuccessStatusCode) { return; } var responseString = await response.Content.ReadAsStringAsync(); var accessRuleResponse = JsonConvert.DeserializeObject(responseString); - if(!accessRuleResponse.Success) + if (!accessRuleResponse.Success) { return; } @@ -95,12 +95,12 @@ namespace Bit.Admin.HostedServices protected async Task UnblockIpAsync(string message, CancellationToken cancellationToken) { - if(string.IsNullOrWhiteSpace(message)) + if (string.IsNullOrWhiteSpace(message)) { return; } - if(message.Contains(".") || message.Contains(":")) + if (message.Contains(".") || message.Contains(":")) { // IP address messages var request = new HttpRequestMessage(); @@ -113,19 +113,19 @@ namespace Bit.Admin.HostedServices $"configuration_target=ip&configuration_value={message}"); var response = await _httpClient.SendAsync(request, cancellationToken); - if(!response.IsSuccessStatusCode) + if (!response.IsSuccessStatusCode) { return; } var responseString = await response.Content.ReadAsStringAsync(); var listResponse = JsonConvert.DeserializeObject(responseString); - if(!listResponse.Success) + if (!listResponse.Success) { return; } - foreach(var rule in listResponse.Result) + foreach (var rule in listResponse.Result) { await DeleteAccessRuleAsync(rule.Id, cancellationToken); } diff --git a/src/Admin/HostedServices/DatabaseMigrationHostedService.cs b/src/Admin/HostedServices/DatabaseMigrationHostedService.cs index f42c71bd46..d40adcbfbf 100644 --- a/src/Admin/HostedServices/DatabaseMigrationHostedService.cs +++ b/src/Admin/HostedServices/DatabaseMigrationHostedService.cs @@ -33,7 +33,7 @@ namespace Bit.Admin.HostedServices await Task.Delay(20000); var maxMigrationAttempts = 10; - for(var i = 1; i <= maxMigrationAttempts; i++) + for (var i = 1; i <= maxMigrationAttempts; i++) { try { @@ -41,9 +41,9 @@ namespace Bit.Admin.HostedServices // TODO: Maybe flip a flag somewhere to indicate migration is complete?? break; } - catch(SqlException e) + catch (SqlException e) { - if(i >= maxMigrationAttempts) + if (i >= maxMigrationAttempts) { _logger.LogError(e, "Database failed to migrate."); throw e; diff --git a/src/Admin/Jobs/JobsHostedService.cs b/src/Admin/Jobs/JobsHostedService.cs index 8ea30c83f7..5bbb451074 100644 --- a/src/Admin/Jobs/JobsHostedService.cs +++ b/src/Admin/Jobs/JobsHostedService.cs @@ -30,7 +30,7 @@ namespace Bit.Admin.Jobs var timeZone = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") : TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); - if(_globalSettings.SelfHosted) + if (_globalSettings.SelfHosted) { timeZone = TimeZoneInfo.Utc; } @@ -59,7 +59,7 @@ namespace Bit.Admin.Jobs new Tuple(typeof(DatabaseRebuildlIndexesJob), everySundayAtMidnightTrigger) }; - if(!_globalSettings.SelfHosted) + if (!_globalSettings.SelfHosted) { jobs.Add(new Tuple(typeof(AliveJob), everyTopOfTheHourTrigger)); } @@ -70,7 +70,7 @@ namespace Bit.Admin.Jobs public static void AddJobsServices(IServiceCollection services, bool selfHosted) { - if(!selfHosted) + if (!selfHosted) { services.AddTransient(); } diff --git a/src/Admin/Models/ChargeBraintreeModel.cs b/src/Admin/Models/ChargeBraintreeModel.cs index a9d45a9ac2..5b3a94f161 100644 --- a/src/Admin/Models/ChargeBraintreeModel.cs +++ b/src/Admin/Models/ChargeBraintreeModel.cs @@ -17,9 +17,9 @@ namespace Bit.Admin.Models public IEnumerable Validate(ValidationContext validationContext) { - if(Id != null) + if (Id != null) { - if(Id.Length != 36 || (Id[0] != 'o' && Id[0] != 'u') || + if (Id.Length != 36 || (Id[0] != 'o' && Id[0] != 'u') || !Guid.TryParse(Id.Substring(1, 32), out var guid)) { yield return new ValidationResult("Customer Id is not a valid format."); diff --git a/src/Admin/Models/CreateUpdateTransactionModel.cs b/src/Admin/Models/CreateUpdateTransactionModel.cs index 7f35b01142..ed2f5116c5 100644 --- a/src/Admin/Models/CreateUpdateTransactionModel.cs +++ b/src/Admin/Models/CreateUpdateTransactionModel.cs @@ -52,7 +52,7 @@ namespace Bit.Admin.Models public IEnumerable Validate(ValidationContext validationContext) { - if((!UserId.HasValue && !OrganizationId.HasValue) || (UserId.HasValue && OrganizationId.HasValue)) + if ((!UserId.HasValue && !OrganizationId.HasValue) || (UserId.HasValue && OrganizationId.HasValue)) { yield return new ValidationResult("Must provide either User Id, or Organization Id."); } diff --git a/src/Admin/Models/LogModel.cs b/src/Admin/Models/LogModel.cs index 94a4f81909..16f90b5df8 100644 --- a/src/Admin/Models/LogModel.cs +++ b/src/Admin/Models/LogModel.cs @@ -21,30 +21,30 @@ namespace Bit.Admin.Models public string ExceptionToString(JObject e) { - if(e == null) + if (e == null) { return null; } var val = string.Empty; - if(e["Message"] != null && e["Message"].ToObject() != null) + if (e["Message"] != null && e["Message"].ToObject() != null) { val += "Message:\n"; val += e["Message"] + "\n"; } - if(e["StackTrace"] != null && e["StackTrace"].ToObject() != null) + if (e["StackTrace"] != null && e["StackTrace"].ToObject() != null) { val += "\nStack Trace:\n"; val += e["StackTrace"]; } - else if(e["StackTraceString"] != null && e["StackTraceString"].ToObject() != null) + else if (e["StackTraceString"] != null && e["StackTraceString"].ToObject() != null) { val += "\nStack Trace String:\n"; val += e["StackTraceString"]; } - if(e["InnerException"] != null && e["InnerException"].ToObject() != null) + if (e["InnerException"] != null && e["InnerException"].ToObject() != null) { val += "\n\n=== Inner Exception ===\n\n"; val += ExceptionToString(e["InnerException"].ToObject()); diff --git a/src/Admin/Program.cs b/src/Admin/Program.cs index 69a5dba44c..1c650b4e53 100644 --- a/src/Admin/Program.cs +++ b/src/Admin/Program.cs @@ -22,7 +22,7 @@ namespace Bit.Admin logging.AddSerilog(hostingContext, e => { var context = e.Properties["SourceContext"].ToString(); - if(e.Properties.ContainsKey("RequestPath") && + if (e.Properties.ContainsKey("RequestPath") && !string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) && (context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer"))) { diff --git a/src/Admin/Startup.cs b/src/Admin/Startup.cs index c154ecc9fd..11c79be641 100644 --- a/src/Admin/Startup.cs +++ b/src/Admin/Startup.cs @@ -53,7 +53,7 @@ namespace Bit.Admin { options.ValidationInterval = TimeSpan.FromMinutes(5); }); - if(globalSettings.SelfHosted) + if (globalSettings.SelfHosted) { services.ConfigureApplicationCookie(options => { @@ -75,17 +75,17 @@ namespace Bit.Admin // Jobs service Jobs.JobsHostedService.AddJobsServices(services, globalSettings.SelfHosted); services.AddHostedService(); - if(globalSettings.SelfHosted) + if (globalSettings.SelfHosted) { services.AddHostedService(); } else { - if(CoreHelpers.SettingHasValue(globalSettings.Storage.ConnectionString)) + if (CoreHelpers.SettingHasValue(globalSettings.Storage.ConnectionString)) { services.AddHostedService(); } - else if(CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret)) + else if (CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret)) { services.AddHostedService(); } @@ -100,13 +100,13 @@ namespace Bit.Admin { app.UseSerilog(env, appLifetime, globalSettings); - if(globalSettings.SelfHosted) + if (globalSettings.SelfHosted) { app.UsePathBase("/admin"); app.UseForwardedHeaders(globalSettings); } - if(env.IsDevelopment()) + if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } diff --git a/src/Admin/TagHelpers/ActivePageTagHelper.cs b/src/Admin/TagHelpers/ActivePageTagHelper.cs index 897c5e5faa..208c19dfff 100644 --- a/src/Admin/TagHelpers/ActivePageTagHelper.cs +++ b/src/Admin/TagHelpers/ActivePageTagHelper.cs @@ -31,33 +31,33 @@ namespace Bit.Admin.TagHelpers public override void Process(TagHelperContext context, TagHelperOutput output) { - if(context == null) + if (context == null) { throw new ArgumentNullException(nameof(context)); } - if(output == null) + if (output == null) { throw new ArgumentNullException(nameof(output)); } - if(ActiveAction == null && ActiveController == null) + if (ActiveAction == null && ActiveController == null) { return; } var descriptor = ViewContext.ActionDescriptor as ControllerActionDescriptor; - if(descriptor == null) + if (descriptor == null) { return; } var controllerMatch = ActiveMatch(ActiveController, descriptor.ControllerName); var actionMatch = ActiveMatch(ActiveAction, descriptor.ActionName); - if(controllerMatch && actionMatch) + if (controllerMatch && actionMatch) { var classValue = "active"; - if(output.Attributes["class"] != null) + if (output.Attributes["class"] != null) { classValue += " " + output.Attributes["class"].Value; output.Attributes.Remove(output.Attributes["class"]); diff --git a/src/Admin/TagHelpers/OptionSelectedTagHelper.cs b/src/Admin/TagHelpers/OptionSelectedTagHelper.cs index 4bab1be244..fa696fed46 100644 --- a/src/Admin/TagHelpers/OptionSelectedTagHelper.cs +++ b/src/Admin/TagHelpers/OptionSelectedTagHelper.cs @@ -21,17 +21,17 @@ namespace Bit.Admin.TagHelpers public override void Process(TagHelperContext context, TagHelperOutput output) { - if(context == null) + if (context == null) { throw new ArgumentNullException(nameof(context)); } - if(output == null) + if (output == null) { throw new ArgumentNullException(nameof(output)); } - if(Selected) + if (Selected) { output.Attributes.Add("selected", "selected"); } diff --git a/src/Api/Controllers/AccountsController.cs b/src/Api/Controllers/AccountsController.cs index bfc71e6ec9..b060482384 100644 --- a/src/Api/Controllers/AccountsController.cs +++ b/src/Api/Controllers/AccountsController.cs @@ -53,7 +53,7 @@ namespace Bit.Api.Controllers public async Task PostPrelogin([FromBody]PreloginRequestModel model) { var kdfInformation = await _userRepository.GetKdfInformationByEmailAsync(model.Email); - if(kdfInformation == null) + if (kdfInformation == null) { kdfInformation = new UserKdfInformation { @@ -70,12 +70,12 @@ namespace Bit.Api.Controllers { var result = await _userService.RegisterUserAsync(model.ToUser(), model.MasterPasswordHash, model.Token, model.OrganizationUserId); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors.Where(e => e.Code != "DuplicateUserName")) + foreach (var error in result.Errors.Where(e => e.Code != "DuplicateUserName")) { ModelState.AddModelError(string.Empty, error.Description); } @@ -95,12 +95,12 @@ namespace Bit.Api.Controllers public async Task PostEmailToken([FromBody]EmailTokenRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) + if (!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) { await Task.Delay(2000); throw new BadRequestException("MasterPasswordHash", "Invalid password."); @@ -113,19 +113,19 @@ namespace Bit.Api.Controllers public async Task PostEmail([FromBody]EmailRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var result = await _userService.ChangeEmailAsync(user, model.MasterPasswordHash, model.NewEmail, model.NewMasterPasswordHash, model.Token, model.Key); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -138,7 +138,7 @@ namespace Bit.Api.Controllers public async Task PostVerifyEmail() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -151,17 +151,17 @@ namespace Bit.Api.Controllers public async Task PostVerifyEmailToken([FromBody]VerifyEmailRequestModel model) { var user = await _userService.GetUserByIdAsync(new Guid(model.UserId)); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var result = await _userService.ConfirmEmailAsync(user, model.Token); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -174,19 +174,19 @@ namespace Bit.Api.Controllers public async Task PostPassword([FromBody]PasswordRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var result = await _userService.ChangePasswordAsync(user, model.MasterPasswordHash, model.NewMasterPasswordHash, model.Key); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -199,19 +199,19 @@ namespace Bit.Api.Controllers public async Task PostKdf([FromBody]KdfRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var result = await _userService.ChangeKdfAsync(user, model.MasterPasswordHash, model.NewMasterPasswordHash, model.Key, model.Kdf.Value, model.KdfIterations.Value); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -224,7 +224,7 @@ namespace Bit.Api.Controllers public async Task PostKey([FromBody]UpdateKeyRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -232,9 +232,9 @@ namespace Bit.Api.Controllers var existingCiphers = await _cipherRepository.GetManyByUserIdAsync(user.Id); var ciphersDict = model.Ciphers?.ToDictionary(c => c.Id.Value); var ciphers = new List(); - if(existingCiphers.Any() && ciphersDict != null) + if (existingCiphers.Any() && ciphersDict != null) { - foreach(var cipher in existingCiphers.Where(c => ciphersDict.ContainsKey(c.Id))) + foreach (var cipher in existingCiphers.Where(c => ciphersDict.ContainsKey(c.Id))) { ciphers.Add(ciphersDict[cipher.Id].ToCipher(cipher)); } @@ -243,9 +243,9 @@ namespace Bit.Api.Controllers var existingFolders = await _folderRepository.GetManyByUserIdAsync(user.Id); var foldersDict = model.Folders?.ToDictionary(f => f.Id); var folders = new List(); - if(existingFolders.Any() && foldersDict != null) + if (existingFolders.Any() && foldersDict != null) { - foreach(var folder in existingFolders.Where(f => foldersDict.ContainsKey(f.Id))) + foreach (var folder in existingFolders.Where(f => foldersDict.ContainsKey(f.Id))) { folders.Add(foldersDict[folder.Id].ToFolder(folder)); } @@ -259,12 +259,12 @@ namespace Bit.Api.Controllers ciphers, folders); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -277,18 +277,18 @@ namespace Bit.Api.Controllers public async Task PostSecurityStamp([FromBody]SecurityStampRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var result = await _userService.RefreshSecurityStampAsync(user, model.MasterPasswordHash); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -301,7 +301,7 @@ namespace Bit.Api.Controllers public async Task GetProfile() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -328,7 +328,7 @@ namespace Bit.Api.Controllers public async Task PutProfile([FromBody]UpdateProfileRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -343,7 +343,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User); long? revisionDate = null; - if(userId.HasValue) + if (userId.HasValue) { var date = await _userService.GetAccountRevisionDateByIdAsync(userId.Value); revisionDate = CoreHelpers.ToEpocMilliseconds(date); @@ -356,7 +356,7 @@ namespace Bit.Api.Controllers public async Task PostKeys([FromBody]KeysRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -369,7 +369,7 @@ namespace Bit.Api.Controllers public async Task GetKeys() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -382,12 +382,12 @@ namespace Bit.Api.Controllers public async Task Delete([FromBody]DeleteAccountRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) + if (!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) { ModelState.AddModelError("MasterPasswordHash", "Invalid password."); await Task.Delay(2000); @@ -395,12 +395,12 @@ namespace Bit.Api.Controllers else { var result = await _userService.DeleteAsync(user); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -421,18 +421,18 @@ namespace Bit.Api.Controllers public async Task PostDeleteRecoverToken([FromBody]VerifyDeleteRecoverRequestModel model) { var user = await _userService.GetUserByIdAsync(new Guid(model.UserId)); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var result = await _userService.DeleteAsync(user, model.Token); - if(result.Succeeded) + if (result.Succeeded) { return; } - foreach(var error in result.Errors) + foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } @@ -445,7 +445,7 @@ namespace Bit.Api.Controllers public async Task PostIapCheck([FromBody]IapCheckRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -456,19 +456,19 @@ namespace Bit.Api.Controllers public async Task PostPremium(PremiumRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var valid = model.Validate(_globalSettings); UserLicense license = null; - if(valid && _globalSettings.SelfHosted) + if (valid && _globalSettings.SelfHosted) { license = await ApiHelpers.ReadJsonFileFromBody(HttpContext, model.License); } - if(!valid || (_globalSettings.SelfHosted && license == null)) + if (!valid || (_globalSettings.SelfHosted && license == null)) { throw new BadRequestException("Invalid license."); } @@ -489,7 +489,7 @@ namespace Bit.Api.Controllers public async Task GetBilling() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -502,18 +502,18 @@ namespace Bit.Api.Controllers public async Task GetSubscription() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!_globalSettings.SelfHosted && user.Gateway != null) + if (!_globalSettings.SelfHosted && user.Gateway != null) { var subscriptionInfo = await _paymentService.GetSubscriptionAsync(user); var license = await _userService.GenerateLicenseAsync(user, subscriptionInfo); return new SubscriptionResponseModel(user, subscriptionInfo, license); } - else if(!_globalSettings.SelfHosted) + else if (!_globalSettings.SelfHosted) { var license = await _userService.GenerateLicenseAsync(user); return new SubscriptionResponseModel(user, license); @@ -529,7 +529,7 @@ namespace Bit.Api.Controllers public async Task PostPayment([FromBody]PaymentRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -542,7 +542,7 @@ namespace Bit.Api.Controllers public async Task PostStorage([FromBody]StorageRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -560,13 +560,13 @@ namespace Bit.Api.Controllers public async Task PostLicense(LicenseRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var license = await ApiHelpers.ReadJsonFileFromBody(HttpContext, model.License); - if(license == null) + if (license == null) { throw new BadRequestException("Invalid license"); } @@ -579,7 +579,7 @@ namespace Bit.Api.Controllers public async Task PostCancel() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -592,7 +592,7 @@ namespace Bit.Api.Controllers public async Task PostReinstate() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } diff --git a/src/Api/Controllers/CiphersController.cs b/src/Api/Controllers/CiphersController.cs index 778fb57696..eb0bed8828 100644 --- a/src/Api/Controllers/CiphersController.cs +++ b/src/Api/Controllers/CiphersController.cs @@ -47,7 +47,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId); - if(cipher == null) + if (cipher == null) { throw new NotFoundException(); } @@ -59,7 +59,7 @@ namespace Bit.Api.Controllers public async Task GetAdmin(string id) { var cipher = await _cipherRepository.GetOrganizationDetailsByIdAsync(new Guid(id)); - if(cipher == null || !cipher.OrganizationId.HasValue || + if (cipher == null || !cipher.OrganizationId.HasValue || !_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) { throw new NotFoundException(); @@ -75,7 +75,7 @@ namespace Bit.Api.Controllers var userId = _userService.GetProperUserId(User).Value; var cipherId = new Guid(id); var cipher = await _cipherRepository.GetByIdAsync(cipherId, userId); - if(cipher == null) + if (cipher == null) { throw new NotFoundException(); } @@ -92,7 +92,7 @@ namespace Bit.Api.Controllers // TODO: Use hasOrgs proper for cipher listing here? var ciphers = await _cipherRepository.GetManyByUserIdAsync(userId, true || hasOrgs); Dictionary> collectionCiphersGroupDict = null; - if(hasOrgs) + if (hasOrgs) { var collectionCiphers = await _collectionCipherRepository.GetManyByUserIdAsync(userId); collectionCiphersGroupDict = collectionCiphers.GroupBy(c => c.CipherId).ToDictionary(s => s.Key); @@ -108,7 +108,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = model.ToCipherDetails(userId); - if(cipher.OrganizationId.HasValue && !_currentContext.OrganizationUser(cipher.OrganizationId.Value)) + if (cipher.OrganizationId.HasValue && !_currentContext.OrganizationUser(cipher.OrganizationId.Value)) { throw new NotFoundException(); } @@ -123,7 +123,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = model.Cipher.ToCipherDetails(userId); - if(cipher.OrganizationId.HasValue && !_currentContext.OrganizationUser(cipher.OrganizationId.Value)) + if (cipher.OrganizationId.HasValue && !_currentContext.OrganizationUser(cipher.OrganizationId.Value)) { throw new NotFoundException(); } @@ -137,7 +137,7 @@ namespace Bit.Api.Controllers public async Task PostAdmin([FromBody]CipherCreateRequestModel model) { var cipher = model.Cipher.ToOrganizationCipher(); - if(!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) + if (!_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) { throw new NotFoundException(); } @@ -155,14 +155,14 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId); - if(cipher == null) + if (cipher == null) { throw new NotFoundException(); } var modelOrgId = string.IsNullOrWhiteSpace(model.OrganizationId) ? (Guid?)null : new Guid(model.OrganizationId); - if(cipher.OrganizationId != modelOrgId) + if (cipher.OrganizationId != modelOrgId) { throw new BadRequestException("Organization mismatch. Re-sync if you recently shared this item, " + "then try again."); @@ -180,7 +180,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetOrganizationDetailsByIdAsync(new Guid(id)); - if(cipher == null || !cipher.OrganizationId.HasValue || + if (cipher == null || !cipher.OrganizationId.HasValue || !_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) { throw new NotFoundException(); @@ -200,7 +200,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var orgIdGuid = new Guid(organizationId); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } @@ -218,7 +218,7 @@ namespace Bit.Api.Controllers [HttpPost("import")] public async Task PostImport([FromBody]ImportCiphersRequestModel model) { - if(!_globalSettings.SelfHosted && + if (!_globalSettings.SelfHosted && (model.Ciphers.Count() > 6000 || model.FolderRelationships.Count() > 6000 || model.Folders.Count() > 1000)) { @@ -235,7 +235,7 @@ namespace Bit.Api.Controllers public async Task PostImport([FromQuery]string organizationId, [FromBody]ImportOrganizationCiphersRequestModel model) { - if(!_globalSettings.SelfHosted && + if (!_globalSettings.SelfHosted && (model.Ciphers.Count() > 6000 || model.CollectionRelationships.Count() > 12000 || model.Collections.Count() > 1000)) { @@ -243,7 +243,7 @@ namespace Bit.Api.Controllers } var orgId = new Guid(organizationId); - if(!_currentContext.OrganizationAdmin(orgId)) + if (!_currentContext.OrganizationAdmin(orgId)) { throw new NotFoundException(); } @@ -270,7 +270,7 @@ namespace Bit.Api.Controllers var userId = _userService.GetProperUserId(User).Value; var cipherId = new Guid(id); var cipher = await _cipherRepository.GetByIdAsync(cipherId); - if(cipher == null || cipher.UserId != userId || + if (cipher == null || cipher.UserId != userId || !_currentContext.OrganizationUser(new Guid(model.Cipher.OrganizationId))) { throw new NotFoundException(); @@ -291,7 +291,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId); - if(cipher == null || !cipher.OrganizationId.HasValue || + if (cipher == null || !cipher.OrganizationId.HasValue || !_currentContext.OrganizationUser(cipher.OrganizationId.Value)) { throw new NotFoundException(); @@ -307,7 +307,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(new Guid(id)); - if(cipher == null || !cipher.OrganizationId.HasValue || + if (cipher == null || !cipher.OrganizationId.HasValue || !_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) { throw new NotFoundException(); @@ -323,7 +323,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(new Guid(id), userId); - if(cipher == null) + if (cipher == null) { throw new NotFoundException(); } @@ -337,7 +337,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(new Guid(id)); - if(cipher == null || !cipher.OrganizationId.HasValue || + if (cipher == null || !cipher.OrganizationId.HasValue || !_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) { throw new NotFoundException(); @@ -350,7 +350,7 @@ namespace Bit.Api.Controllers [HttpPost("delete")] public async Task DeleteMany([FromBody]CipherBulkDeleteRequestModel model) { - if(!_globalSettings.SelfHosted && model.Ids.Count() > 500) + if (!_globalSettings.SelfHosted && model.Ids.Count() > 500) { throw new BadRequestException("You can only delete up to 500 items at a time. " + "Consider using the \"Purge Vault\" option instead."); @@ -364,7 +364,7 @@ namespace Bit.Api.Controllers [HttpPost("move")] public async Task MoveMany([FromBody]CipherBulkMoveRequestModel model) { - if(!_globalSettings.SelfHosted && model.Ids.Count() > 500) + if (!_globalSettings.SelfHosted && model.Ids.Count() > 500) { throw new BadRequestException("You can only move up to 500 items at a time."); } @@ -379,7 +379,7 @@ namespace Bit.Api.Controllers public async Task PutShareMany([FromBody]CipherBulkShareRequestModel model) { var organizationId = new Guid(model.Ciphers.First().OrganizationId); - if(!_currentContext.OrganizationUser(organizationId)) + if (!_currentContext.OrganizationUser(organizationId)) { throw new NotFoundException(); } @@ -389,9 +389,9 @@ namespace Bit.Api.Controllers var ciphersDict = ciphers.ToDictionary(c => c.Id); var shareCiphers = new List(); - foreach(var cipher in model.Ciphers) + foreach (var cipher in model.Ciphers) { - if(!ciphersDict.ContainsKey(cipher.Id.Value)) + if (!ciphersDict.ContainsKey(cipher.Id.Value)) { throw new BadRequestException("Trying to share ciphers that you do not own."); } @@ -407,26 +407,26 @@ namespace Bit.Api.Controllers public async Task PostPurge([FromBody]CipherPurgeRequestModel model, string organizationId = null) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) + if (!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) { ModelState.AddModelError("MasterPasswordHash", "Invalid password."); await Task.Delay(2000); throw new BadRequestException(ModelState); } - if(string.IsNullOrWhiteSpace(organizationId)) + if (string.IsNullOrWhiteSpace(organizationId)) { await _cipherRepository.DeleteByUserIdAsync(user.Id); } else { var orgId = new Guid(organizationId); - if(!_currentContext.OrganizationAdmin(orgId)) + if (!_currentContext.OrganizationAdmin(orgId)) { throw new NotFoundException(); } @@ -444,7 +444,7 @@ namespace Bit.Api.Controllers var idGuid = new Guid(id); var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(idGuid, userId); - if(cipher == null) + if (cipher == null) { throw new NotFoundException(); } @@ -468,7 +468,7 @@ namespace Bit.Api.Controllers var idGuid = new Guid(id); var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetOrganizationDetailsByIdAsync(idGuid); - if(cipher == null || !cipher.OrganizationId.HasValue || + if (cipher == null || !cipher.OrganizationId.HasValue || !_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) { throw new NotFoundException(); @@ -492,7 +492,7 @@ namespace Bit.Api.Controllers var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(new Guid(id)); - if(cipher == null || cipher.UserId != userId || !_currentContext.OrganizationUser(organizationId)) + if (cipher == null || cipher.UserId != userId || !_currentContext.OrganizationUser(organizationId)) { throw new NotFoundException(); } @@ -511,7 +511,7 @@ namespace Bit.Api.Controllers var idGuid = new Guid(id); var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(idGuid, userId); - if(cipher == null) + if (cipher == null) { throw new NotFoundException(); } @@ -526,7 +526,7 @@ namespace Bit.Api.Controllers var idGuid = new Guid(id); var userId = _userService.GetProperUserId(User).Value; var cipher = await _cipherRepository.GetByIdAsync(idGuid); - if(cipher == null || !cipher.OrganizationId.HasValue || + if (cipher == null || !cipher.OrganizationId.HasValue || !_currentContext.OrganizationAdmin(cipher.OrganizationId.Value)) { throw new NotFoundException(); @@ -537,12 +537,12 @@ namespace Bit.Api.Controllers private void ValidateAttachment() { - if(!Request?.ContentType.Contains("multipart/") ?? true) + if (!Request?.ContentType.Contains("multipart/") ?? true) { throw new BadRequestException("Invalid content."); } - if(Request.ContentLength > 105906176) // 101 MB, give em' 1 extra MB for cushion + if (Request.ContentLength > 105906176) // 101 MB, give em' 1 extra MB for cushion { throw new BadRequestException("Max file size is 100 MB."); } diff --git a/src/Api/Controllers/CollectionsController.cs b/src/Api/Controllers/CollectionsController.cs index f60925d3f7..b2479cbfce 100644 --- a/src/Api/Controllers/CollectionsController.cs +++ b/src/Api/Controllers/CollectionsController.cs @@ -45,16 +45,16 @@ namespace Bit.Api.Controllers public async Task GetDetails(string orgId, string id) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationManager(orgIdGuid)) + if (!_currentContext.OrganizationManager(orgIdGuid)) { throw new NotFoundException(); } var idGuid = new Guid(id); - if(_currentContext.OrganizationAdmin(orgIdGuid)) + if (_currentContext.OrganizationAdmin(orgIdGuid)) { var collectionDetails = await _collectionRepository.GetByIdWithGroupsAsync(idGuid); - if(collectionDetails?.Item1 == null || collectionDetails.Item1.OrganizationId != orgIdGuid) + if (collectionDetails?.Item1 == null || collectionDetails.Item1.OrganizationId != orgIdGuid) { throw new NotFoundException(); } @@ -64,7 +64,7 @@ namespace Bit.Api.Controllers { var collectionDetails = await _collectionRepository.GetByIdWithGroupsAsync(idGuid, _currentContext.UserId.Value); - if(collectionDetails?.Item1 == null || collectionDetails.Item1.OrganizationId != orgIdGuid) + if (collectionDetails?.Item1 == null || collectionDetails.Item1.OrganizationId != orgIdGuid) { throw new NotFoundException(); } @@ -76,7 +76,7 @@ namespace Bit.Api.Controllers public async Task> Get(string orgId) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } @@ -108,7 +108,7 @@ namespace Bit.Api.Controllers public async Task Post(string orgId, [FromBody]CollectionRequestModel model) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationManager(orgIdGuid)) + if (!_currentContext.OrganizationManager(orgIdGuid)) { throw new NotFoundException(); } @@ -154,7 +154,7 @@ namespace Bit.Api.Controllers private async Task GetCollectionAsync(Guid id, Guid orgId) { - if(!_currentContext.OrganizationManager(orgId)) + if (!_currentContext.OrganizationManager(orgId)) { throw new NotFoundException(); } @@ -162,7 +162,7 @@ namespace Bit.Api.Controllers var collection = _currentContext.OrganizationAdmin(orgId) ? await _collectionRepository.GetByIdAsync(id) : await _collectionRepository.GetByIdAsync(id, _currentContext.UserId.Value); - if(collection == null || collection.OrganizationId != orgId) + if (collection == null || collection.OrganizationId != orgId) { throw new NotFoundException(); } diff --git a/src/Api/Controllers/DevicesController.cs b/src/Api/Controllers/DevicesController.cs index fe8ee9e0ca..977216ca14 100644 --- a/src/Api/Controllers/DevicesController.cs +++ b/src/Api/Controllers/DevicesController.cs @@ -34,7 +34,7 @@ namespace Bit.Api.Controllers public async Task Get(string id) { var device = await _deviceRepository.GetByIdAsync(new Guid(id), _userService.GetProperUserId(User).Value); - if(device == null) + if (device == null) { throw new NotFoundException(); } @@ -47,7 +47,7 @@ namespace Bit.Api.Controllers public async Task GetByIdentifier(string identifier) { var device = await _deviceRepository.GetByIdentifierAsync(identifier, _userService.GetProperUserId(User).Value); - if(device == null) + if (device == null) { throw new NotFoundException(); } @@ -79,7 +79,7 @@ namespace Bit.Api.Controllers public async Task Put(string id, [FromBody]DeviceRequestModel model) { var device = await _deviceRepository.GetByIdAsync(new Guid(id), _userService.GetProperUserId(User).Value); - if(device == null) + if (device == null) { throw new NotFoundException(); } @@ -95,7 +95,7 @@ namespace Bit.Api.Controllers public async Task PutToken(string identifier, [FromBody]DeviceTokenRequestModel model) { var device = await _deviceRepository.GetByIdentifierAsync(identifier, _userService.GetProperUserId(User).Value); - if(device == null) + if (device == null) { throw new NotFoundException(); } @@ -109,7 +109,7 @@ namespace Bit.Api.Controllers public async Task PutClearToken(string identifier) { var device = await _deviceRepository.GetByIdentifierAsync(identifier); - if(device == null) + if (device == null) { throw new NotFoundException(); } @@ -122,7 +122,7 @@ namespace Bit.Api.Controllers public async Task Delete(string id) { var device = await _deviceRepository.GetByIdAsync(new Guid(id), _userService.GetProperUserId(User).Value); - if(device == null) + if (device == null) { throw new NotFoundException(); } diff --git a/src/Api/Controllers/EventsController.cs b/src/Api/Controllers/EventsController.cs index 53d53791ee..8f8ea599d4 100644 --- a/src/Api/Controllers/EventsController.cs +++ b/src/Api/Controllers/EventsController.cs @@ -53,23 +53,23 @@ namespace Bit.Api.Controllers [FromQuery]DateTime? start = null, [FromQuery]DateTime? end = null, [FromQuery]string continuationToken = null) { var cipher = await _cipherRepository.GetByIdAsync(new Guid(id)); - if(cipher == null) + if (cipher == null) { throw new NotFoundException(); } var canView = false; - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { canView = _currentContext.OrganizationAdmin(cipher.OrganizationId.Value); } - else if(cipher.UserId.HasValue) + else if (cipher.UserId.HasValue) { var userId = _userService.GetProperUserId(User).Value; canView = userId == cipher.UserId.Value; } - if(!canView) + if (!canView) { throw new NotFoundException(); } @@ -86,7 +86,7 @@ namespace Bit.Api.Controllers [FromQuery]DateTime? start = null, [FromQuery]DateTime? end = null, [FromQuery]string continuationToken = null) { var orgId = new Guid(id); - if(!_currentContext.OrganizationAdmin(orgId)) + if (!_currentContext.OrganizationAdmin(orgId)) { throw new NotFoundException(); } @@ -103,7 +103,7 @@ namespace Bit.Api.Controllers [FromQuery]DateTime? start = null, [FromQuery]DateTime? end = null, [FromQuery]string continuationToken = null) { var organizationUser = await _organizationUserRepository.GetByIdAsync(new Guid(id)); - if(organizationUser == null || !organizationUser.UserId.HasValue || + if (organizationUser == null || !organizationUser.UserId.HasValue || !_currentContext.OrganizationAdmin(organizationUser.OrganizationId)) { throw new NotFoundException(); @@ -119,19 +119,19 @@ namespace Bit.Api.Controllers private Tuple GetDateRange(DateTime? start, DateTime? end) { - if(!end.HasValue || !start.HasValue) + if (!end.HasValue || !start.HasValue) { end = DateTime.UtcNow.Date.AddDays(1).AddMilliseconds(-1); start = DateTime.UtcNow.Date.AddDays(-30); } - else if(start.Value > end.Value) + else if (start.Value > end.Value) { var newEnd = start; start = end; end = newEnd; } - if((end.Value - start.Value) > TimeSpan.FromDays(367)) + if ((end.Value - start.Value) > TimeSpan.FromDays(367)) { throw new BadRequestException("Range too large."); } diff --git a/src/Api/Controllers/FoldersController.cs b/src/Api/Controllers/FoldersController.cs index fd762ace78..a2c53e6d88 100644 --- a/src/Api/Controllers/FoldersController.cs +++ b/src/Api/Controllers/FoldersController.cs @@ -33,7 +33,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var folder = await _folderRepository.GetByIdAsync(new Guid(id), userId); - if(folder == null) + if (folder == null) { throw new NotFoundException(); } @@ -65,7 +65,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var folder = await _folderRepository.GetByIdAsync(new Guid(id), userId); - if(folder == null) + if (folder == null) { throw new NotFoundException(); } @@ -80,7 +80,7 @@ namespace Bit.Api.Controllers { var userId = _userService.GetProperUserId(User).Value; var folder = await _folderRepository.GetByIdAsync(new Guid(id), userId); - if(folder == null) + if (folder == null) { throw new NotFoundException(); } diff --git a/src/Api/Controllers/GroupsController.cs b/src/Api/Controllers/GroupsController.cs index a78209cef1..b771c23e4c 100644 --- a/src/Api/Controllers/GroupsController.cs +++ b/src/Api/Controllers/GroupsController.cs @@ -34,7 +34,7 @@ namespace Bit.Api.Controllers public async Task Get(string orgId, string id) { var group = await _groupRepository.GetByIdAsync(new Guid(id)); - if(group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) + if (group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) { throw new NotFoundException(); } @@ -46,7 +46,7 @@ namespace Bit.Api.Controllers public async Task GetDetails(string orgId, string id) { var groupDetails = await _groupRepository.GetByIdWithCollectionsAsync(new Guid(id)); - if(groupDetails?.Item1 == null || !_currentContext.OrganizationAdmin(groupDetails.Item1.OrganizationId)) + if (groupDetails?.Item1 == null || !_currentContext.OrganizationAdmin(groupDetails.Item1.OrganizationId)) { throw new NotFoundException(); } @@ -58,7 +58,7 @@ namespace Bit.Api.Controllers public async Task> Get(string orgId) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationManager(orgIdGuid)) + if (!_currentContext.OrganizationManager(orgIdGuid)) { throw new NotFoundException(); } @@ -73,7 +73,7 @@ namespace Bit.Api.Controllers { var idGuid = new Guid(id); var group = await _groupRepository.GetByIdAsync(idGuid); - if(group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) + if (group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) { throw new NotFoundException(); } @@ -86,7 +86,7 @@ namespace Bit.Api.Controllers public async Task Post(string orgId, [FromBody]GroupRequestModel model) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } @@ -101,7 +101,7 @@ namespace Bit.Api.Controllers public async Task Put(string orgId, string id, [FromBody]GroupRequestModel model) { var group = await _groupRepository.GetByIdAsync(new Guid(id)); - if(group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) + if (group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) { throw new NotFoundException(); } @@ -114,7 +114,7 @@ namespace Bit.Api.Controllers public async Task PutUsers(string orgId, string id, [FromBody]IEnumerable model) { var group = await _groupRepository.GetByIdAsync(new Guid(id)); - if(group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) + if (group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) { throw new NotFoundException(); } @@ -126,7 +126,7 @@ namespace Bit.Api.Controllers public async Task Delete(string orgId, string id) { var group = await _groupRepository.GetByIdAsync(new Guid(id)); - if(group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) + if (group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) { throw new NotFoundException(); } @@ -139,7 +139,7 @@ namespace Bit.Api.Controllers public async Task Delete(string orgId, string id, string orgUserId) { var group = await _groupRepository.GetByIdAsync(new Guid(id)); - if(group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) + if (group == null || !_currentContext.OrganizationAdmin(group.OrganizationId)) { throw new NotFoundException(); } diff --git a/src/Api/Controllers/HibpController.cs b/src/Api/Controllers/HibpController.cs index 2bf9222b75..9c61578f5d 100644 --- a/src/Api/Controllers/HibpController.cs +++ b/src/Api/Controllers/HibpController.cs @@ -50,7 +50,7 @@ namespace Bit.Api.Controllers private async Task SendAsync(string username, bool retry) { - if(!CoreHelpers.SettingHasValue(_globalSettings.HibpApiKey)) + if (!CoreHelpers.SettingHasValue(_globalSettings.HibpApiKey)) { throw new BadRequestException("HaveIBeenPwned API key not set."); } @@ -59,22 +59,22 @@ namespace Bit.Api.Controllers request.Headers.Add("hibp-client-id", GetClientId()); request.Headers.Add("User-Agent", _userAgent); var response = await _httpClient.SendAsync(request); - if(response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); return Content(data, "application/json"); } - else if(response.StatusCode == HttpStatusCode.NotFound) + else if (response.StatusCode == HttpStatusCode.NotFound) { return new NotFoundResult(); } - else if(response.StatusCode == HttpStatusCode.TooManyRequests && retry) + else if (response.StatusCode == HttpStatusCode.TooManyRequests && retry) { var delay = 2000; - if(response.Headers.Contains("retry-after")) + if (response.Headers.Contains("retry-after")) { var vals = response.Headers.GetValues("retry-after"); - if(vals.Any() && int.TryParse(vals.FirstOrDefault(), out var secDelay)) + if (vals.Any() && int.TryParse(vals.FirstOrDefault(), out var secDelay)) { delay = (secDelay * 1000) + 200; } @@ -91,7 +91,7 @@ namespace Bit.Api.Controllers private string GetClientId() { var userId = _userService.GetProperUserId(User).Value; - using(var sha256 = SHA256.Create()) + using (var sha256 = SHA256.Create()) { var hash = sha256.ComputeHash(userId.ToByteArray()); return Convert.ToBase64String(hash); diff --git a/src/Api/Controllers/InstallationsController.cs b/src/Api/Controllers/InstallationsController.cs index 6413f04f61..b51a8afe1e 100644 --- a/src/Api/Controllers/InstallationsController.cs +++ b/src/Api/Controllers/InstallationsController.cs @@ -26,7 +26,7 @@ namespace Bit.Api.Controllers public async Task Get(Guid id) { var installation = await _installationRepository.GetByIdAsync(id); - if(installation == null) + if (installation == null) { throw new NotFoundException(); } diff --git a/src/Api/Controllers/LicensesController.cs b/src/Api/Controllers/LicensesController.cs index 4d254b4c37..1b8f753437 100644 --- a/src/Api/Controllers/LicensesController.cs +++ b/src/Api/Controllers/LicensesController.cs @@ -43,11 +43,11 @@ namespace Bit.Api.Controllers public async Task GetUser(string id, [FromQuery]string key) { var user = await _userRepository.GetByIdAsync(new Guid(id)); - if(user == null) + if (user == null) { return null; } - else if(!user.LicenseKey.Equals(key)) + else if (!user.LicenseKey.Equals(key)) { await Task.Delay(2000); throw new BadRequestException("Invalid license key."); @@ -61,11 +61,11 @@ namespace Bit.Api.Controllers public async Task GetOrganization(string id, [FromQuery]string key) { var org = await _organizationRepository.GetByIdAsync(new Guid(id)); - if(org == null) + if (org == null) { return null; } - else if(!org.LicenseKey.Equals(key)) + else if (!org.LicenseKey.Equals(key)) { await Task.Delay(2000); throw new BadRequestException("Invalid license key."); diff --git a/src/Api/Controllers/OrganizationUsersController.cs b/src/Api/Controllers/OrganizationUsersController.cs index 86115cb137..60209dd228 100644 --- a/src/Api/Controllers/OrganizationUsersController.cs +++ b/src/Api/Controllers/OrganizationUsersController.cs @@ -46,7 +46,7 @@ namespace Bit.Api.Controllers public async Task Get(string orgId, string id) { var organizationUser = await _organizationUserRepository.GetByIdWithCollectionsAsync(new Guid(id)); - if(organizationUser == null || !_currentContext.OrganizationAdmin(organizationUser.Item1.OrganizationId)) + if (organizationUser == null || !_currentContext.OrganizationAdmin(organizationUser.Item1.OrganizationId)) { throw new NotFoundException(); } @@ -58,7 +58,7 @@ namespace Bit.Api.Controllers public async Task> Get(string orgId) { var orgGuidId = new Guid(orgId); - if(!_currentContext.OrganizationManager(orgGuidId)) + if (!_currentContext.OrganizationManager(orgGuidId)) { throw new NotFoundException(); } @@ -74,7 +74,7 @@ namespace Bit.Api.Controllers public async Task> GetGroups(string orgId, string id) { var organizationUser = await _organizationUserRepository.GetByIdAsync(new Guid(id)); - if(organizationUser == null || !_currentContext.OrganizationAdmin(organizationUser.OrganizationId)) + if (organizationUser == null || !_currentContext.OrganizationAdmin(organizationUser.OrganizationId)) { throw new NotFoundException(); } @@ -88,7 +88,7 @@ namespace Bit.Api.Controllers public async Task Invite(string orgId, [FromBody]OrganizationUserInviteRequestModel model) { var orgGuidId = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgGuidId)) + if (!_currentContext.OrganizationAdmin(orgGuidId)) { throw new NotFoundException(); } @@ -102,7 +102,7 @@ namespace Bit.Api.Controllers public async Task Reinvite(string orgId, string id) { var orgGuidId = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgGuidId)) + if (!_currentContext.OrganizationAdmin(orgGuidId)) { throw new NotFoundException(); } @@ -115,7 +115,7 @@ namespace Bit.Api.Controllers public async Task Accept(string orgId, string id, [FromBody]OrganizationUserAcceptRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -127,7 +127,7 @@ namespace Bit.Api.Controllers public async Task Confirm(string orgId, string id, [FromBody]OrganizationUserConfirmRequestModel model) { var orgGuidId = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgGuidId)) + if (!_currentContext.OrganizationAdmin(orgGuidId)) { throw new NotFoundException(); } @@ -142,13 +142,13 @@ namespace Bit.Api.Controllers public async Task Put(string orgId, string id, [FromBody]OrganizationUserUpdateRequestModel model) { var orgGuidId = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgGuidId)) + if (!_currentContext.OrganizationAdmin(orgGuidId)) { throw new NotFoundException(); } var organizationUser = await _organizationUserRepository.GetByIdAsync(new Guid(id)); - if(organizationUser == null || organizationUser.OrganizationId != orgGuidId) + if (organizationUser == null || organizationUser.OrganizationId != orgGuidId) { throw new NotFoundException(); } @@ -163,13 +163,13 @@ namespace Bit.Api.Controllers public async Task PutGroups(string orgId, string id, [FromBody]OrganizationUserUpdateGroupsRequestModel model) { var orgGuidId = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgGuidId)) + if (!_currentContext.OrganizationAdmin(orgGuidId)) { throw new NotFoundException(); } var organizationUser = await _organizationUserRepository.GetByIdAsync(new Guid(id)); - if(organizationUser == null || organizationUser.OrganizationId != orgGuidId) + if (organizationUser == null || organizationUser.OrganizationId != orgGuidId) { throw new NotFoundException(); } @@ -182,7 +182,7 @@ namespace Bit.Api.Controllers public async Task Delete(string orgId, string id) { var orgGuidId = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgGuidId)) + if (!_currentContext.OrganizationAdmin(orgGuidId)) { throw new NotFoundException(); } diff --git a/src/Api/Controllers/OrganizationsController.cs b/src/Api/Controllers/OrganizationsController.cs index 106f341249..d5e3adc2be 100644 --- a/src/Api/Controllers/OrganizationsController.cs +++ b/src/Api/Controllers/OrganizationsController.cs @@ -48,13 +48,13 @@ namespace Bit.Api.Controllers public async Task Get(string id) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -67,13 +67,13 @@ namespace Bit.Api.Controllers public async Task GetBilling(string id) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -86,21 +86,21 @@ namespace Bit.Api.Controllers public async Task GetSubscription(string id) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } - if(!_globalSettings.SelfHosted && organization.Gateway != null) + if (!_globalSettings.SelfHosted && organization.Gateway != null) { var subscriptionInfo = await _paymentService.GetSubscriptionAsync(organization); - if(subscriptionInfo == null) + if (subscriptionInfo == null) { throw new NotFoundException(); } @@ -117,13 +117,13 @@ namespace Bit.Api.Controllers public async Task GetLicense(string id, [FromQuery]Guid installationId) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var license = await _organizationService.GenerateLicenseAsync(orgIdGuid, installationId); - if(license == null) + if (license == null) { throw new NotFoundException(); } @@ -145,7 +145,7 @@ namespace Bit.Api.Controllers public async Task Post([FromBody]OrganizationCreateRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -160,13 +160,13 @@ namespace Bit.Api.Controllers public async Task PostLicense(OrganizationCreateLicenseRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } var license = await ApiHelpers.ReadJsonFileFromBody(HttpContext, model.License); - if(license == null) + if (license == null) { throw new BadRequestException("Invalid license"); } @@ -181,13 +181,13 @@ namespace Bit.Api.Controllers public async Task Put(string id, [FromBody]OrganizationUpdateRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -204,7 +204,7 @@ namespace Bit.Api.Controllers public async Task PostPayment(string id, [FromBody]PaymentRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } @@ -218,7 +218,7 @@ namespace Bit.Api.Controllers public async Task PostUpgrade(string id, [FromBody]OrganizationUpgradeRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } @@ -236,7 +236,7 @@ namespace Bit.Api.Controllers public async Task PostSeat(string id, [FromBody]OrganizationSeatRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } @@ -254,7 +254,7 @@ namespace Bit.Api.Controllers public async Task PostStorage(string id, [FromBody]StorageRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } @@ -272,7 +272,7 @@ namespace Bit.Api.Controllers public async Task PostVerifyBank(string id, [FromBody]OrganizationVerifyBankRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } @@ -285,7 +285,7 @@ namespace Bit.Api.Controllers public async Task PostCancel(string id) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } @@ -298,7 +298,7 @@ namespace Bit.Api.Controllers public async Task PostReinstate(string id) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } @@ -310,7 +310,7 @@ namespace Bit.Api.Controllers public async Task Leave(string id) { var orgGuidId = new Guid(id); - if(!_currentContext.OrganizationUser(orgGuidId)) + if (!_currentContext.OrganizationUser(orgGuidId)) { throw new NotFoundException(); } @@ -324,24 +324,24 @@ namespace Bit.Api.Controllers public async Task Delete(string id, [FromBody]OrganizationDeleteRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) + if (!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) { await Task.Delay(2000); throw new BadRequestException("MasterPasswordHash", "Invalid password."); @@ -357,13 +357,13 @@ namespace Bit.Api.Controllers public async Task PostLicense(string id, LicenseRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var license = await ApiHelpers.ReadJsonFileFromBody(HttpContext, model.License); - if(license == null) + if (license == null) { throw new BadRequestException("Invalid license"); } @@ -374,13 +374,13 @@ namespace Bit.Api.Controllers [HttpPost("{id}/import")] public async Task Import(string id, [FromBody]ImportOrganizationUsersRequestModel model) { - if(!_globalSettings.SelfHosted && (model.Groups.Count() > 200 || model.Users.Count() > 1000)) + if (!_globalSettings.SelfHosted && (model.Groups.Count() > 200 || model.Users.Count() > 1000)) { throw new BadRequestException("You cannot import this much data at once."); } var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } @@ -399,24 +399,24 @@ namespace Bit.Api.Controllers public async Task ApiKey(string id, [FromBody]ApiKeyRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) + if (!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) { await Task.Delay(2000); throw new BadRequestException("MasterPasswordHash", "Invalid password."); @@ -432,24 +432,24 @@ namespace Bit.Api.Controllers public async Task RotateApiKey(string id, [FromBody]ApiKeyRequestModel model) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationOwner(orgIdGuid)) + if (!_currentContext.OrganizationOwner(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) + if (!await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) { await Task.Delay(2000); throw new BadRequestException("MasterPasswordHash", "Invalid password."); diff --git a/src/Api/Controllers/PoliciesController.cs b/src/Api/Controllers/PoliciesController.cs index 1b137abd30..e7710117d6 100644 --- a/src/Api/Controllers/PoliciesController.cs +++ b/src/Api/Controllers/PoliciesController.cs @@ -52,12 +52,12 @@ namespace Bit.Api.Controllers public async Task Get(string orgId, int type) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } var policy = await _policyRepository.GetByOrganizationIdTypeAsync(orgIdGuid, (PolicyType)type); - if(policy == null) + if (policy == null) { throw new NotFoundException(); } @@ -69,7 +69,7 @@ namespace Bit.Api.Controllers public async Task> Get(string orgId) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationManager(orgIdGuid)) + if (!_currentContext.OrganizationManager(orgIdGuid)) { throw new NotFoundException(); } @@ -87,14 +87,14 @@ namespace Bit.Api.Controllers var orgUserId = new Guid(organizationUserId); var tokenValid = CoreHelpers.UserInviteTokenIsValid(_organizationServiceDataProtector, token, email, orgUserId, _globalSettings); - if(!tokenValid) + if (!tokenValid) { throw new NotFoundException(); } var orgIdGuid = new Guid(orgId); var orgUser = await _organizationUserRepository.GetByIdAsync(orgUserId); - if(orgUser == null || orgUser.OrganizationId != orgIdGuid) + if (orgUser == null || orgUser.OrganizationId != orgIdGuid) { throw new NotFoundException(); } @@ -108,12 +108,12 @@ namespace Bit.Api.Controllers public async Task Put(string orgId, int type, [FromBody]PolicyRequestModel model) { var orgIdGuid = new Guid(orgId); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } var policy = await _policyRepository.GetByOrganizationIdTypeAsync(new Guid(orgId), (PolicyType)type); - if(policy == null) + if (policy == null) { policy = model.ToPolicy(orgIdGuid); } diff --git a/src/Api/Controllers/PushController.cs b/src/Api/Controllers/PushController.cs index 528de7a9b9..860cf43ef9 100644 --- a/src/Api/Controllers/PushController.cs +++ b/src/Api/Controllers/PushController.cs @@ -74,12 +74,12 @@ namespace Bit.Api.Controllers { CheckUsage(); - if(!string.IsNullOrWhiteSpace(model.UserId)) + if (!string.IsNullOrWhiteSpace(model.UserId)) { await _pushNotificationService.SendPayloadToUserAsync(Prefix(model.UserId), model.Type.Value, model.Payload, Prefix(model.Identifier), Prefix(model.DeviceId)); } - else if(!string.IsNullOrWhiteSpace(model.OrganizationId)) + else if (!string.IsNullOrWhiteSpace(model.OrganizationId)) { await _pushNotificationService.SendPayloadToOrganizationAsync(Prefix(model.OrganizationId), model.Type.Value, model.Payload, Prefix(model.Identifier), Prefix(model.DeviceId)); @@ -88,7 +88,7 @@ namespace Bit.Api.Controllers private string Prefix(string value) { - if(string.IsNullOrWhiteSpace(value)) + if (string.IsNullOrWhiteSpace(value)) { return null; } @@ -98,7 +98,7 @@ namespace Bit.Api.Controllers private void CheckUsage() { - if(CanUse()) + if (CanUse()) { return; } @@ -108,7 +108,7 @@ namespace Bit.Api.Controllers private bool CanUse() { - if(_environment.IsDevelopment()) + if (_environment.IsDevelopment()) { return true; } diff --git a/src/Api/Controllers/SettingsController.cs b/src/Api/Controllers/SettingsController.cs index 01329f8aad..b999a582b5 100644 --- a/src/Api/Controllers/SettingsController.cs +++ b/src/Api/Controllers/SettingsController.cs @@ -23,7 +23,7 @@ namespace Bit.Api.Controllers public async Task GetDomains(bool excluded = true) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -37,7 +37,7 @@ namespace Bit.Api.Controllers public async Task PutDomains([FromBody]UpdateDomainsRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } diff --git a/src/Api/Controllers/SyncController.cs b/src/Api/Controllers/SyncController.cs index 436de3e42d..2f4e5d7ce5 100644 --- a/src/Api/Controllers/SyncController.cs +++ b/src/Api/Controllers/SyncController.cs @@ -52,7 +52,7 @@ namespace Bit.Api.Controllers public async Task Get([FromQuery]bool excludeDomains = false) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new BadRequestException("User not found."); } @@ -66,7 +66,7 @@ namespace Bit.Api.Controllers IEnumerable collections = null; IDictionary> collectionCiphersGroupDict = null; IEnumerable policies = null; - if(hasEnabledOrgs) + if (hasEnabledOrgs) { collections = await _collectionRepository.GetManyByUserIdAsync(user.Id); var collectionCiphers = await _collectionCipherRepository.GetManyByUserIdAsync(user.Id); diff --git a/src/Api/Controllers/TwoFactorController.cs b/src/Api/Controllers/TwoFactorController.cs index ed3fc12b36..e82a86d79d 100644 --- a/src/Api/Controllers/TwoFactorController.cs +++ b/src/Api/Controllers/TwoFactorController.cs @@ -47,7 +47,7 @@ namespace Bit.Api.Controllers public async Task> Get() { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } @@ -61,13 +61,13 @@ namespace Bit.Api.Controllers public async Task> GetOrganization(string id) { var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -93,7 +93,7 @@ namespace Bit.Api.Controllers var user = await CheckAsync(model.MasterPasswordHash, false); model.ToUser(user); - if(!await _userManager.VerifyTwoFactorTokenAsync(user, + if (!await _userManager.VerifyTwoFactorTokenAsync(user, CoreHelpers.CustomProviderName(TwoFactorProviderType.Authenticator), model.Token)) { await Task.Delay(2000); @@ -149,7 +149,7 @@ namespace Bit.Api.Controllers var duoApi = new DuoApi(model.IntegrationKey, model.SecretKey, model.Host); duoApi.JSONApiCall("GET", "/auth/v2/check"); } - catch(DuoException) + catch (DuoException) { throw new BadRequestException("Duo configuration settings are not valid. Please re-check the Duo Admin panel."); } @@ -167,13 +167,13 @@ namespace Bit.Api.Controllers var user = await CheckAsync(model.MasterPasswordHash, false); var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -190,13 +190,13 @@ namespace Bit.Api.Controllers var user = await CheckAsync(model.MasterPasswordHash, false); var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -206,7 +206,7 @@ namespace Bit.Api.Controllers var duoApi = new DuoApi(model.IntegrationKey, model.SecretKey, model.Host); duoApi.JSONApiCall("GET", "/auth/v2/check"); } - catch(DuoException) + catch (DuoException) { throw new BadRequestException("Duo configuration settings are not valid. Please re-check the Duo Admin panel."); } @@ -243,7 +243,7 @@ namespace Bit.Api.Controllers var user = await CheckAsync(model.MasterPasswordHash, true); var success = await _userService.CompleteU2fRegistrationAsync( user, model.Id.Value, model.Name, model.DeviceResponse); - if(!success) + if (!success) { throw new BadRequestException("Unable to complete U2F key registration."); } @@ -281,9 +281,9 @@ namespace Bit.Api.Controllers public async Task SendEmailLogin([FromBody]TwoFactorEmailRequestModel model) { var user = await _userManager.FindByEmailAsync(model.Email.ToLowerInvariant()); - if(user != null) + if (user != null) { - if(await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) + if (await _userService.CheckPasswordAsync(user, model.MasterPasswordHash)) { await _userService.SendTwoFactorEmailAsync(user); return; @@ -301,7 +301,7 @@ namespace Bit.Api.Controllers var user = await CheckAsync(model.MasterPasswordHash, false); model.ToUser(user); - if(!await _userManager.VerifyTwoFactorTokenAsync(user, + if (!await _userManager.VerifyTwoFactorTokenAsync(user, CoreHelpers.CustomProviderName(TwoFactorProviderType.Email), model.Token)) { await Task.Delay(2000); @@ -331,13 +331,13 @@ namespace Bit.Api.Controllers var user = await CheckAsync(model.MasterPasswordHash, false); var orgIdGuid = new Guid(id); - if(!_currentContext.OrganizationAdmin(orgIdGuid)) + if (!_currentContext.OrganizationAdmin(orgIdGuid)) { throw new NotFoundException(); } var organization = await _organizationRepository.GetByIdAsync(orgIdGuid); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -359,7 +359,7 @@ namespace Bit.Api.Controllers [AllowAnonymous] public async Task PostRecover([FromBody]TwoFactorRecoveryRequestModel model) { - if(!await _userService.RecoverTwoFactorAsync(model.Email, model.MasterPasswordHash, model.RecoveryCode, + if (!await _userService.RecoverTwoFactorAsync(model.Email, model.MasterPasswordHash, model.RecoveryCode, _organizationService)) { await Task.Delay(2000); @@ -370,18 +370,18 @@ namespace Bit.Api.Controllers private async Task CheckAsync(string masterPasswordHash, bool premium) { var user = await _userService.GetUserByPrincipalAsync(User); - if(user == null) + if (user == null) { throw new UnauthorizedAccessException(); } - if(!await _userService.CheckPasswordAsync(user, masterPasswordHash)) + if (!await _userService.CheckPasswordAsync(user, masterPasswordHash)) { await Task.Delay(2000); throw new BadRequestException("MasterPasswordHash", "Invalid password."); } - if(premium && !(await _userService.CanAccessPremium(user))) + if (premium && !(await _userService.CanAccessPremium(user))) { throw new BadRequestException("Premium status is required."); } @@ -391,12 +391,12 @@ namespace Bit.Api.Controllers private async Task ValidateYubiKeyAsync(User user, string name, string value) { - if(string.IsNullOrWhiteSpace(value) || value.Length == 12) + if (string.IsNullOrWhiteSpace(value) || value.Length == 12) { return; } - if(!await _userManager.VerifyTwoFactorTokenAsync(user, + if (!await _userManager.VerifyTwoFactorTokenAsync(user, CoreHelpers.CustomProviderName(TwoFactorProviderType.YubiKey), value)) { await Task.Delay(2000); diff --git a/src/Api/Controllers/UsersController.cs b/src/Api/Controllers/UsersController.cs index 605ddd2050..58a05a5c61 100644 --- a/src/Api/Controllers/UsersController.cs +++ b/src/Api/Controllers/UsersController.cs @@ -25,7 +25,7 @@ namespace Bit.Api.Controllers { var guidId = new Guid(id); var key = await _userRepository.GetPublicKeyAsync(guidId); - if(key == null) + if (key == null) { throw new NotFoundException(); } diff --git a/src/Api/Program.cs b/src/Api/Program.cs index 94aa38e8c6..4cb8ffbbb7 100644 --- a/src/Api/Program.cs +++ b/src/Api/Program.cs @@ -20,20 +20,20 @@ namespace Bit.Api logging.AddSerilog(hostingContext, e => { var context = e.Properties["SourceContext"].ToString(); - if(e.Exception != null && + if (e.Exception != null && (e.Exception.GetType() == typeof(SecurityTokenValidationException) || e.Exception.Message == "Bad security stamp.")) { return false; } - if(e.Level == LogEventLevel.Information && + if (e.Level == LogEventLevel.Information && context.Contains(typeof(IpRateLimitMiddleware).FullName)) { return true; } - if(context.Contains("IdentityServer4.Validation.TokenValidator") || + if (context.Contains("IdentityServer4.Validation.TokenValidator") || context.Contains("IdentityServer4.Validation.TokenRequestValidator")) { return e.Level > LogEventLevel.Error; diff --git a/src/Api/Public/Controllers/CollectionsController.cs b/src/Api/Public/Controllers/CollectionsController.cs index c5279bd6c6..62138fbbe0 100644 --- a/src/Api/Public/Controllers/CollectionsController.cs +++ b/src/Api/Public/Controllers/CollectionsController.cs @@ -44,7 +44,7 @@ namespace Bit.Api.Public.Controllers { var collectionWithGroups = await _collectionRepository.GetByIdWithGroupsAsync(id); var collection = collectionWithGroups?.Item1; - if(collection == null || collection.OrganizationId != _currentContext.OrganizationId) + if (collection == null || collection.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -87,7 +87,7 @@ namespace Bit.Api.Public.Controllers public async Task Put(Guid id, [FromBody]CollectionUpdateRequestModel model) { var existingCollection = await _collectionRepository.GetByIdAsync(id); - if(existingCollection == null || existingCollection.OrganizationId != _currentContext.OrganizationId) + if (existingCollection == null || existingCollection.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -111,7 +111,7 @@ namespace Bit.Api.Public.Controllers public async Task Delete(Guid id) { var collection = await _collectionRepository.GetByIdAsync(id); - if(collection == null || collection.OrganizationId != _currentContext.OrganizationId) + if (collection == null || collection.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } diff --git a/src/Api/Public/Controllers/EventsController.cs b/src/Api/Public/Controllers/EventsController.cs index 9e3b7727e1..ec75e0bce9 100644 --- a/src/Api/Public/Controllers/EventsController.cs +++ b/src/Api/Public/Controllers/EventsController.cs @@ -42,16 +42,16 @@ namespace Bit.Api.Public.Controllers { var dateRange = request.ToDateRange(); var result = new PagedResult(); - if(request.ActingUserId.HasValue) + if (request.ActingUserId.HasValue) { result = await _eventRepository.GetManyByOrganizationActingUserAsync( _currentContext.OrganizationId.Value, request.ActingUserId.Value, dateRange.Item1, dateRange.Item2, new PageOptions { ContinuationToken = request.ContinuationToken }); } - else if(request.ItemId.HasValue) + else if (request.ItemId.HasValue) { var cipher = await _cipherRepository.GetByIdAsync(request.ItemId.Value); - if(cipher != null && cipher.OrganizationId == _currentContext.OrganizationId.Value) + if (cipher != null && cipher.OrganizationId == _currentContext.OrganizationId.Value) { result = await _eventRepository.GetManyByCipherAsync( cipher, dateRange.Item1, dateRange.Item2, diff --git a/src/Api/Public/Controllers/GroupsController.cs b/src/Api/Public/Controllers/GroupsController.cs index 4b67b9e61c..39c8352868 100644 --- a/src/Api/Public/Controllers/GroupsController.cs +++ b/src/Api/Public/Controllers/GroupsController.cs @@ -45,7 +45,7 @@ namespace Bit.Api.Public.Controllers { var groupDetails = await _groupRepository.GetByIdWithCollectionsAsync(id); var group = groupDetails?.Item1; - if(group == null || group.OrganizationId != _currentContext.OrganizationId) + if (group == null || group.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -67,7 +67,7 @@ namespace Bit.Api.Public.Controllers public async Task GetMemberIds(Guid id) { var group = await _groupRepository.GetByIdAsync(id); - if(group == null || group.OrganizationId != _currentContext.OrganizationId) + if (group == null || group.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -128,7 +128,7 @@ namespace Bit.Api.Public.Controllers public async Task Put(Guid id, [FromBody]GroupCreateUpdateRequestModel model) { var existingGroup = await _groupRepository.GetByIdAsync(id); - if(existingGroup == null || existingGroup.OrganizationId != _currentContext.OrganizationId) + if (existingGroup == null || existingGroup.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -154,7 +154,7 @@ namespace Bit.Api.Public.Controllers public async Task PutMemberIds(Guid id, [FromBody]UpdateMemberIdsRequestModel model) { var existingGroup = await _groupRepository.GetByIdAsync(id); - if(existingGroup == null || existingGroup.OrganizationId != _currentContext.OrganizationId) + if (existingGroup == null || existingGroup.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -175,7 +175,7 @@ namespace Bit.Api.Public.Controllers public async Task Delete(Guid id) { var group = await _groupRepository.GetByIdAsync(id); - if(group == null || group.OrganizationId != _currentContext.OrganizationId) + if (group == null || group.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } diff --git a/src/Api/Public/Controllers/MembersController.cs b/src/Api/Public/Controllers/MembersController.cs index 882d8fc06e..e7cdd2ab24 100644 --- a/src/Api/Public/Controllers/MembersController.cs +++ b/src/Api/Public/Controllers/MembersController.cs @@ -51,7 +51,7 @@ namespace Bit.Api.Public.Controllers { var userDetails = await _organizationUserRepository.GetDetailsByIdWithCollectionsAsync(id); var orgUser = userDetails?.Item1; - if(orgUser == null || orgUser.OrganizationId != _currentContext.OrganizationId) + if (orgUser == null || orgUser.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -74,7 +74,7 @@ namespace Bit.Api.Public.Controllers public async Task GetGroupIds(Guid id) { var orgUser = await _organizationUserRepository.GetByIdAsync(id); - if(orgUser == null || orgUser.OrganizationId != _currentContext.OrganizationId) + if (orgUser == null || orgUser.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -138,7 +138,7 @@ namespace Bit.Api.Public.Controllers public async Task Put(Guid id, [FromBody]MemberUpdateRequestModel model) { var existingUser = await _organizationUserRepository.GetByIdAsync(id); - if(existingUser == null || existingUser.OrganizationId != _currentContext.OrganizationId) + if (existingUser == null || existingUser.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -146,7 +146,7 @@ namespace Bit.Api.Public.Controllers var associations = model.Collections?.Select(c => c.ToSelectionReadOnly()); await _organizationService.SaveUserAsync(updatedUser, null, associations); MemberResponseModel response = null; - if(existingUser.UserId.HasValue) + if (existingUser.UserId.HasValue) { var existingUserDetails = await _organizationUserRepository.GetDetailsByIdAsync(id); response = new MemberResponseModel(existingUserDetails, @@ -174,7 +174,7 @@ namespace Bit.Api.Public.Controllers public async Task PutGroupIds(Guid id, [FromBody]UpdateGroupIdsRequestModel model) { var existingUser = await _organizationUserRepository.GetByIdAsync(id); - if(existingUser == null || existingUser.OrganizationId != _currentContext.OrganizationId) + if (existingUser == null || existingUser.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -196,7 +196,7 @@ namespace Bit.Api.Public.Controllers public async Task Delete(Guid id) { var user = await _organizationUserRepository.GetByIdAsync(id); - if(user == null || user.OrganizationId != _currentContext.OrganizationId) + if (user == null || user.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } @@ -218,7 +218,7 @@ namespace Bit.Api.Public.Controllers public async Task PostReinvite(Guid id) { var existingUser = await _organizationUserRepository.GetByIdAsync(id); - if(existingUser == null || existingUser.OrganizationId != _currentContext.OrganizationId) + if (existingUser == null || existingUser.OrganizationId != _currentContext.OrganizationId) { return new NotFoundResult(); } diff --git a/src/Api/Public/Controllers/PoliciesController.cs b/src/Api/Public/Controllers/PoliciesController.cs index 819f7b423b..85660a4dcf 100644 --- a/src/Api/Public/Controllers/PoliciesController.cs +++ b/src/Api/Public/Controllers/PoliciesController.cs @@ -50,7 +50,7 @@ namespace Bit.Api.Public.Controllers { var policy = await _policyRepository.GetByOrganizationIdTypeAsync( _currentContext.OrganizationId.Value, type); - if(policy == null) + if (policy == null) { return new NotFoundResult(); } @@ -91,7 +91,7 @@ namespace Bit.Api.Public.Controllers { var policy = await _policyRepository.GetByOrganizationIdTypeAsync( _currentContext.OrganizationId.Value, type); - if(policy == null) + if (policy == null) { policy = model.ToPolicy(_currentContext.OrganizationId.Value); } diff --git a/src/Api/Startup.cs b/src/Api/Startup.cs index 066c683ff4..15e7879eba 100644 --- a/src/Api/Startup.cs +++ b/src/Api/Startup.cs @@ -40,7 +40,7 @@ namespace Bit.Api // Settings var globalSettings = services.AddGlobalSettingsServices(Configuration); - if(!globalSettings.SelfHosted) + if (!globalSettings.SelfHosted) { services.Configure(Configuration.GetSection("IpRateLimitOptions")); services.Configure(Configuration.GetSection("IpRateLimitPolicies")); @@ -64,7 +64,7 @@ namespace Bit.Api // BitPay services.AddSingleton(); - if(!globalSettings.SelfHosted) + if (!globalSettings.SelfHosted) { // Rate limiting services.AddSingleton(); @@ -118,7 +118,7 @@ namespace Bit.Api config.Conventions.Add(new PublicApiControllersModelConvention()); }).AddNewtonsoftJson(options => { - if(Environment.IsProduction() && Configuration["swaggerGen"] != "true") + if (Environment.IsProduction() && Configuration["swaggerGen"] != "true") { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); } @@ -126,13 +126,13 @@ namespace Bit.Api services.AddSwagger(globalSettings); - if(globalSettings.SelfHosted) + if (globalSettings.SelfHosted) { // Jobs service Jobs.JobsHostedService.AddJobsServices(services); services.AddHostedService(); } - if(CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && + if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName)) { services.AddHostedService(); @@ -152,7 +152,7 @@ namespace Bit.Api // Default Middleware app.UseDefaultMiddleware(env, globalSettings); - if(!globalSettings.SelfHosted) + if (!globalSettings.SelfHosted) { // Rate limiting app.UseMiddleware(); @@ -183,7 +183,7 @@ namespace Bit.Api app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute()); // Add Swagger - if(Environment.IsDevelopment() || globalSettings.SelfHosted) + if (Environment.IsDevelopment() || globalSettings.SelfHosted) { app.UseSwagger(config => { diff --git a/src/Api/Utilities/ApiHelpers.cs b/src/Api/Utilities/ApiHelpers.cs index 71586fdf20..8aef098b52 100644 --- a/src/Api/Utilities/ApiHelpers.cs +++ b/src/Api/Utilities/ApiHelpers.cs @@ -10,15 +10,15 @@ namespace Bit.Api.Utilities public async static Task ReadJsonFileFromBody(HttpContext httpContext, IFormFile file, long maxSize = 51200) { T obj = default(T); - if(file != null && httpContext.Request.ContentLength.HasValue && httpContext.Request.ContentLength.Value <= maxSize) + if (file != null && httpContext.Request.ContentLength.HasValue && httpContext.Request.ContentLength.Value <= maxSize) { try { - using(var stream = file.OpenReadStream()) - using(var reader = new StreamReader(stream)) + using (var stream = file.OpenReadStream()) + using (var reader = new StreamReader(stream)) { var s = await reader.ReadToEndAsync(); - if(!string.IsNullOrWhiteSpace(s)) + if (!string.IsNullOrWhiteSpace(s)) { obj = JsonConvert.DeserializeObject(s); } diff --git a/src/Api/Utilities/CamelCaseJsonResultFilterAttribute.cs b/src/Api/Utilities/CamelCaseJsonResultFilterAttribute.cs index 4865de6b0d..ec8aa640e3 100644 --- a/src/Api/Utilities/CamelCaseJsonResultFilterAttribute.cs +++ b/src/Api/Utilities/CamelCaseJsonResultFilterAttribute.cs @@ -20,7 +20,7 @@ namespace Bit.Api.Utilities public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { - if(context.Result is JsonResult jsonResult) + if (context.Result is JsonResult jsonResult) { context.Result = new JsonResult(jsonResult.Value, _jsonSerializerSettings); } diff --git a/src/Api/Utilities/ExceptionHandlerFilterAttribute.cs b/src/Api/Utilities/ExceptionHandlerFilterAttribute.cs index fe99d5fbfd..c414a6d38c 100644 --- a/src/Api/Utilities/ExceptionHandlerFilterAttribute.cs +++ b/src/Api/Utilities/ExceptionHandlerFilterAttribute.cs @@ -27,7 +27,7 @@ namespace Bit.Api.Utilities var errorMessage = "An error has occurred."; var exception = context.Exception; - if(exception == null) + if (exception == null) { // Should never happen. return; @@ -35,12 +35,12 @@ namespace Bit.Api.Utilities PublicApi.ErrorResponseModel publicErrorModel = null; InternalApi.ErrorResponseModel internalErrorModel = null; - if(exception is BadRequestException badRequestException) + if (exception is BadRequestException badRequestException) { context.HttpContext.Response.StatusCode = 400; - if(badRequestException.ModelState != null) + if (badRequestException.ModelState != null) { - if(_publicApi) + if (_publicApi) { publicErrorModel = new PublicApi.ErrorResponseModel(badRequestException.ModelState); } @@ -54,11 +54,11 @@ namespace Bit.Api.Utilities errorMessage = badRequestException.Message; } } - else if(exception is StripeException stripeException && + else if (exception is StripeException stripeException && stripeException?.StripeError?.ErrorType == "card_error") { context.HttpContext.Response.StatusCode = 400; - if(_publicApi) + if (_publicApi) { publicErrorModel = new PublicApi.ErrorResponseModel(stripeException.StripeError.Parameter, stripeException.Message); @@ -69,31 +69,31 @@ namespace Bit.Api.Utilities stripeException.Message); } } - else if(exception is GatewayException) + else if (exception is GatewayException) { errorMessage = exception.Message; context.HttpContext.Response.StatusCode = 400; } - else if(exception is NotSupportedException && !string.IsNullOrWhiteSpace(exception.Message)) + else if (exception is NotSupportedException && !string.IsNullOrWhiteSpace(exception.Message)) { errorMessage = exception.Message; context.HttpContext.Response.StatusCode = 400; } - else if(exception is ApplicationException) + else if (exception is ApplicationException) { context.HttpContext.Response.StatusCode = 402; } - else if(exception is NotFoundException) + else if (exception is NotFoundException) { errorMessage = "Resource not found."; context.HttpContext.Response.StatusCode = 404; } - else if(exception is SecurityTokenValidationException) + else if (exception is SecurityTokenValidationException) { errorMessage = "Invalid token."; context.HttpContext.Response.StatusCode = 403; } - else if(exception is UnauthorizedAccessException) + else if (exception is UnauthorizedAccessException) { errorMessage = "Unauthorized."; context.HttpContext.Response.StatusCode = 401; @@ -106,7 +106,7 @@ namespace Bit.Api.Utilities context.HttpContext.Response.StatusCode = 500; } - if(_publicApi) + if (_publicApi) { var errorModel = publicErrorModel ?? new PublicApi.ErrorResponseModel(errorMessage); context.Result = new ObjectResult(errorModel); @@ -115,7 +115,7 @@ namespace Bit.Api.Utilities { var errorModel = internalErrorModel ?? new InternalApi.ErrorResponseModel(errorMessage); var env = context.HttpContext.RequestServices.GetRequiredService(); - if(env.IsDevelopment()) + if (env.IsDevelopment()) { errorModel.ExceptionMessage = exception.Message; errorModel.ExceptionStackTrace = exception.StackTrace; diff --git a/src/Api/Utilities/ModelStateValidationFilterAttribute.cs b/src/Api/Utilities/ModelStateValidationFilterAttribute.cs index f8f602d2b3..e93d954431 100644 --- a/src/Api/Utilities/ModelStateValidationFilterAttribute.cs +++ b/src/Api/Utilities/ModelStateValidationFilterAttribute.cs @@ -18,14 +18,14 @@ namespace Bit.Api.Utilities public override void OnActionExecuting(ActionExecutingContext context) { var model = context.ActionArguments.FirstOrDefault(a => a.Key == "model"); - if(model.Key == "model" && model.Value == null) + if (model.Key == "model" && model.Value == null) { context.ModelState.AddModelError(string.Empty, "Body is empty."); } - if(!context.ModelState.IsValid) + if (!context.ModelState.IsValid) { - if(_publicApi) + if (_publicApi) { context.Result = new BadRequestObjectResult(new PublicApi.ErrorResponseModel(context.ModelState)); } diff --git a/src/Api/Utilities/MultipartFormDataHelper.cs b/src/Api/Utilities/MultipartFormDataHelper.cs index e9ef945b67..cfe03209cb 100644 --- a/src/Api/Utilities/MultipartFormDataHelper.cs +++ b/src/Api/Utilities/MultipartFormDataHelper.cs @@ -20,36 +20,36 @@ namespace Bit.Api.Utilities var reader = new MultipartReader(boundary, request.Body); var firstSection = await reader.ReadNextSectionAsync(); - if(firstSection != null) + if (firstSection != null) { - if(ContentDispositionHeaderValue.TryParse(firstSection.ContentDisposition, out var firstContent)) + if (ContentDispositionHeaderValue.TryParse(firstSection.ContentDisposition, out var firstContent)) { - if(HasFileContentDisposition(firstContent)) + if (HasFileContentDisposition(firstContent)) { // Old style with just data var fileName = HeaderUtilities.RemoveQuotes(firstContent.FileName).ToString(); - using(firstSection.Body) + using (firstSection.Body) { await callback(firstSection.Body, fileName, null); } } - else if(HasKeyDisposition(firstContent)) + else if (HasKeyDisposition(firstContent)) { // New style with key, then data string key = null; - using(var sr = new StreamReader(firstSection.Body)) + using (var sr = new StreamReader(firstSection.Body)) { key = await sr.ReadToEndAsync(); } var secondSection = await reader.ReadNextSectionAsync(); - if(secondSection != null) + if (secondSection != null) { - if(ContentDispositionHeaderValue.TryParse(secondSection.ContentDisposition, + if (ContentDispositionHeaderValue.TryParse(secondSection.ContentDisposition, out var secondContent) && HasFileContentDisposition(secondContent)) { var fileName = HeaderUtilities.RemoveQuotes(secondContent.FileName).ToString(); - using(secondSection.Body) + using (secondSection.Body) { await callback(secondSection.Body, fileName, key); } @@ -67,12 +67,12 @@ namespace Bit.Api.Utilities private static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit) { var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary); - if(StringSegment.IsNullOrEmpty(boundary)) + if (StringSegment.IsNullOrEmpty(boundary)) { throw new InvalidDataException("Missing content-type boundary."); } - if(boundary.Length > lengthLimit) + if (boundary.Length > lengthLimit) { throw new InvalidDataException($"Multipart boundary length limit {lengthLimit} exceeded."); } diff --git a/src/Api/Utilities/PublicApiControllersModelConvention.cs b/src/Api/Utilities/PublicApiControllersModelConvention.cs index 08f417ad5d..6689354259 100644 --- a/src/Api/Utilities/PublicApiControllersModelConvention.cs +++ b/src/Api/Utilities/PublicApiControllersModelConvention.cs @@ -8,7 +8,7 @@ namespace Bit.Api.Utilities { var controllerNamespace = controller.ControllerType.Namespace; var publicApi = controllerNamespace.Contains(".Public."); - if(publicApi) + if (publicApi) { controller.Filters.Add(new CamelCaseJsonResultFilterAttribute()); } diff --git a/src/Billing/Controllers/AppleController.cs b/src/Billing/Controllers/AppleController.cs index 5577869ca6..c6d29f27fe 100644 --- a/src/Billing/Controllers/AppleController.cs +++ b/src/Billing/Controllers/AppleController.cs @@ -27,25 +27,25 @@ namespace Bit.Billing.Controllers [HttpPost("iap")] public async Task PostIap() { - if(HttpContext?.Request?.Query == null) + if (HttpContext?.Request?.Query == null) { return new BadRequestResult(); } var key = HttpContext.Request.Query.ContainsKey("key") ? HttpContext.Request.Query["key"].ToString() : null; - if(key != _billingSettings.AppleWebhookKey) + if (key != _billingSettings.AppleWebhookKey) { return new BadRequestResult(); } string body = null; - using(var reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8)) + using (var reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8)) { body = await reader.ReadToEndAsync(); } - if(string.IsNullOrWhiteSpace(body)) + if (string.IsNullOrWhiteSpace(body)) { return new BadRequestResult(); } @@ -56,7 +56,7 @@ namespace Bit.Billing.Controllers _logger.LogInformation(Constants.BypassFiltersEventId, "Apple IAP Notification:\n\n{0}", json); return new OkResult(); } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Error processing IAP status notification."); return new BadRequestResult(); diff --git a/src/Billing/Controllers/BitPayController.cs b/src/Billing/Controllers/BitPayController.cs index 54903cb813..bb94fb8e80 100644 --- a/src/Billing/Controllers/BitPayController.cs +++ b/src/Billing/Controllers/BitPayController.cs @@ -49,31 +49,31 @@ namespace Bit.Billing.Controllers [HttpPost("ipn")] public async Task PostIpn([FromBody] BitPayEventModel model, [FromQuery] string key) { - if(key != _billingSettings.BitPayWebhookKey) + if (key != _billingSettings.BitPayWebhookKey) { return new BadRequestResult(); } - if(model == null || string.IsNullOrWhiteSpace(model.Data?.Id) || + if (model == null || string.IsNullOrWhiteSpace(model.Data?.Id) || string.IsNullOrWhiteSpace(model.Event?.Name)) { return new BadRequestResult(); } - if(model.Event.Name != "invoice_confirmed") + if (model.Event.Name != "invoice_confirmed") { // Only processing confirmed invoice events for now. return new OkResult(); } var invoice = await _bitPayClient.GetInvoiceAsync(model.Data.Id); - if(invoice == null || invoice.Status != "confirmed") + if (invoice == null || invoice.Status != "confirmed") { // Request forged...? _logger.LogWarning("Forged invoice detected. #" + model.Data.Id); return new BadRequestResult(); } - if(invoice.Currency != "USD") + if (invoice.Currency != "USD") { // Only process USD payments _logger.LogWarning("Non USD payment received. #" + invoice.Id); @@ -81,13 +81,13 @@ namespace Bit.Billing.Controllers } var ids = GetIdsFromPosData(invoice); - if(!ids.Item1.HasValue && !ids.Item2.HasValue) + if (!ids.Item1.HasValue && !ids.Item2.HasValue) { return new OkResult(); } var isAccountCredit = IsAccountCredit(invoice); - if(!isAccountCredit) + if (!isAccountCredit) { // Only processing credits _logger.LogWarning("Non-credit payment received. #" + invoice.Id); @@ -95,7 +95,7 @@ namespace Bit.Billing.Controllers } var transaction = await _transactionRepository.GetByGatewayIdAsync(GatewayType.BitPay, invoice.Id); - if(transaction != null) + if (transaction != null) { _logger.LogWarning("Already processed this confirmed invoice. #" + invoice.Id); return new OkResult(); @@ -117,16 +117,16 @@ namespace Bit.Billing.Controllers }; await _transactionRepository.CreateAsync(tx); - if(isAccountCredit) + if (isAccountCredit) { string billingEmail = null; - if(tx.OrganizationId.HasValue) + if (tx.OrganizationId.HasValue) { var org = await _organizationRepository.GetByIdAsync(tx.OrganizationId.Value); - if(org != null) + if (org != null) { billingEmail = org.BillingEmailAddress(); - if(await _paymentService.CreditAccountAsync(org, tx.Amount)) + if (await _paymentService.CreditAccountAsync(org, tx.Amount)) { await _organizationRepository.ReplaceAsync(org); } @@ -135,24 +135,24 @@ namespace Bit.Billing.Controllers else { var user = await _userRepository.GetByIdAsync(tx.UserId.Value); - if(user != null) + if (user != null) { billingEmail = user.BillingEmailAddress(); - if(await _paymentService.CreditAccountAsync(user, tx.Amount)) + if (await _paymentService.CreditAccountAsync(user, tx.Amount)) { await _userRepository.ReplaceAsync(user); } } } - if(!string.IsNullOrWhiteSpace(billingEmail)) + if (!string.IsNullOrWhiteSpace(billingEmail)) { await _mailService.SendAddedCreditAsync(billingEmail, tx.Amount); } } } // Catch foreign key violations because user/org could have been deleted. - catch(SqlException e) when(e.Number == 547) { } + catch (SqlException e) when(e.Number == 547) { } return new OkResult(); } @@ -166,7 +166,7 @@ namespace Bit.Billing.Controllers { var transactions = invoice.Transactions?.Where(t => t.Type == null && !string.IsNullOrWhiteSpace(t.Confirmations) && t.Confirmations != "0"); - if(transactions != null && transactions.Count() == 1) + if (transactions != null && transactions.Count() == 1) { return DateTime.Parse(transactions.First().ReceivedTime, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); @@ -179,19 +179,19 @@ namespace Bit.Billing.Controllers Guid? orgId = null; Guid? userId = null; - if(invoice != null && !string.IsNullOrWhiteSpace(invoice.PosData) && invoice.PosData.Contains(":")) + if (invoice != null && !string.IsNullOrWhiteSpace(invoice.PosData) && invoice.PosData.Contains(":")) { var mainParts = invoice.PosData.Split(','); - foreach(var mainPart in mainParts) + foreach (var mainPart in mainParts) { var parts = mainPart.Split(':'); - if(parts.Length > 1 && Guid.TryParse(parts[1], out var id)) + if (parts.Length > 1 && Guid.TryParse(parts[1], out var id)) { - if(parts[0] == "userId") + if (parts[0] == "userId") { userId = id; } - else if(parts[0] == "organizationId") + else if (parts[0] == "organizationId") { orgId = id; } diff --git a/src/Billing/Controllers/FreshdeskController.cs b/src/Billing/Controllers/FreshdeskController.cs index 2a88433943..6314815c9c 100644 --- a/src/Billing/Controllers/FreshdeskController.cs +++ b/src/Billing/Controllers/FreshdeskController.cs @@ -49,25 +49,25 @@ namespace Bit.Billing.Controllers [HttpPost("webhook")] public async Task PostWebhook() { - if(HttpContext?.Request?.Query == null) + if (HttpContext?.Request?.Query == null) { return new BadRequestResult(); } var key = HttpContext.Request.Query.ContainsKey("key") ? HttpContext.Request.Query["key"].ToString() : null; - if(key != _billingSettings.FreshdeskWebhookKey) + if (key != _billingSettings.FreshdeskWebhookKey) { return new BadRequestResult(); } string body = null; - using(var reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8)) + using (var reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8)) { body = await reader.ReadToEndAsync(); } - if(string.IsNullOrWhiteSpace(body)) + if (string.IsNullOrWhiteSpace(body)) { return new BadRequestResult(); } @@ -78,7 +78,7 @@ namespace Bit.Billing.Controllers string ticketId = data.ticket_id; string ticketContactEmail = data.ticket_contact_email; string ticketTags = data.ticket_tags; - if(string.IsNullOrWhiteSpace(ticketId) || string.IsNullOrWhiteSpace(ticketContactEmail)) + if (string.IsNullOrWhiteSpace(ticketId) || string.IsNullOrWhiteSpace(ticketContactEmail)) { return new BadRequestResult(); } @@ -86,32 +86,32 @@ namespace Bit.Billing.Controllers var updateBody = new Dictionary(); var note = string.Empty; var user = await _userRepository.GetByEmailAsync(ticketContactEmail); - if(user != null) + if (user != null) { note += $"
  • User, {user.Email}: {_globalSettings.BaseServiceUri.Admin}/users/edit/{user.Id}
  • "; var tags = new HashSet(); - if(user.Premium) + if (user.Premium) { tags.Add("Premium"); } var orgs = await _organizationRepository.GetManyByUserIdAsync(user.Id); - foreach(var org in orgs) + foreach (var org in orgs) { note += $"
  • Org, {org.Name}: " + $"{_globalSettings.BaseServiceUri.Admin}/organizations/edit/{org.Id}
  • "; var planName = GetAttribute(org.PlanType).Name.Split(" ").FirstOrDefault(); - if(!string.IsNullOrWhiteSpace(planName)) + if (!string.IsNullOrWhiteSpace(planName)) { tags.Add(string.Format("Org: {0}", planName)); } } - if(tags.Any()) + if (tags.Any()) { var tagsToUpdate = tags.ToList(); - if(!string.IsNullOrWhiteSpace(ticketTags)) + if (!string.IsNullOrWhiteSpace(ticketTags)) { var splitTicketTags = ticketTags.Split(','); - for(var i = 0; i < splitTicketTags.Length; i++) + for (var i = 0; i < splitTicketTags.Length; i++) { tagsToUpdate.Insert(i, splitTicketTags[i]); } @@ -139,7 +139,7 @@ namespace Bit.Billing.Controllers return new OkResult(); } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Error processing freshdesk webhook."); return new BadRequestResult(); @@ -152,14 +152,14 @@ namespace Bit.Billing.Controllers { request.Headers.Add("Authorization", _freshdeskAuthkey); var response = await _httpClient.SendAsync(request); - if(response.StatusCode != System.Net.HttpStatusCode.TooManyRequests || retriedCount > 3) + if (response.StatusCode != System.Net.HttpStatusCode.TooManyRequests || retriedCount > 3) { return response; } } catch { - if(retriedCount > 3) + if (retriedCount > 3) { throw; } diff --git a/src/Billing/Controllers/LoginController.cs b/src/Billing/Controllers/LoginController.cs index ecd5d76f74..c843fa54ab 100644 --- a/src/Billing/Controllers/LoginController.cs +++ b/src/Billing/Controllers/LoginController.cs @@ -26,11 +26,11 @@ namespace Billing.Controllers [ValidateAntiForgeryToken] public async Task Index(LoginModel model) { - if(ModelState.IsValid) + if (ModelState.IsValid) { var result = await _signInManager.PasswordlessSignInAsync(model.Email, Url.Action("Confirm", "Login", null, Request.Scheme)); - if(result.Succeeded) + if (result.Succeeded) { return RedirectToAction("Index", "Home"); } @@ -46,7 +46,7 @@ namespace Billing.Controllers public async Task Confirm(string email, string token) { var result = await _signInManager.PasswordlessSignInAsync(email, token, false); - if(!result.Succeeded) + if (!result.Succeeded) { return View("Error"); } diff --git a/src/Billing/Controllers/PayPalController.cs b/src/Billing/Controllers/PayPalController.cs index 63536101ae..6225a34890 100644 --- a/src/Billing/Controllers/PayPalController.cs +++ b/src/Billing/Controllers/PayPalController.cs @@ -48,64 +48,64 @@ namespace Bit.Billing.Controllers [HttpPost("ipn")] public async Task PostIpn() { - if(HttpContext?.Request?.Query == null) + if (HttpContext?.Request?.Query == null) { return new BadRequestResult(); } var key = HttpContext.Request.Query.ContainsKey("key") ? HttpContext.Request.Query["key"].ToString() : null; - if(key != _billingSettings.PayPal.WebhookKey) + if (key != _billingSettings.PayPal.WebhookKey) { return new BadRequestResult(); } string body = null; - using(var reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8)) + using (var reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8)) { body = await reader.ReadToEndAsync(); } - if(string.IsNullOrWhiteSpace(body)) + if (string.IsNullOrWhiteSpace(body)) { return new BadRequestResult(); } var verified = await _paypalIpnClient.VerifyIpnAsync(body); - if(!verified) + if (!verified) { _logger.LogWarning("Unverified IPN received."); return new BadRequestResult(); } var ipnTransaction = new PayPalIpnClient.IpnTransaction(body); - if(ipnTransaction.TxnType != "web_accept" && ipnTransaction.TxnType != "merch_pmt" && + if (ipnTransaction.TxnType != "web_accept" && ipnTransaction.TxnType != "merch_pmt" && ipnTransaction.PaymentStatus != "Refunded") { // Only processing billing agreement payments, buy now button payments, and refunds for now. return new OkResult(); } - if(ipnTransaction.ReceiverId != _billingSettings.PayPal.BusinessId) + if (ipnTransaction.ReceiverId != _billingSettings.PayPal.BusinessId) { _logger.LogWarning("Receiver was not proper business id. " + ipnTransaction.ReceiverId); return new BadRequestResult(); } - if(ipnTransaction.PaymentStatus == "Refunded" && ipnTransaction.ParentTxnId == null) + if (ipnTransaction.PaymentStatus == "Refunded" && ipnTransaction.ParentTxnId == null) { // Refunds require parent transaction return new OkResult(); } - if(ipnTransaction.PaymentType == "echeck" && ipnTransaction.PaymentStatus != "Refunded") + if (ipnTransaction.PaymentType == "echeck" && ipnTransaction.PaymentStatus != "Refunded") { // Not accepting eChecks, unless it is a refund _logger.LogWarning("Got an eCheck payment. " + ipnTransaction.TxnId); return new OkResult(); } - if(ipnTransaction.McCurrency != "USD") + if (ipnTransaction.McCurrency != "USD") { // Only process USD payments _logger.LogWarning("Received a payment not in USD. " + ipnTransaction.TxnId); @@ -113,16 +113,16 @@ namespace Bit.Billing.Controllers } var ids = ipnTransaction.GetIdsFromCustom(); - if(!ids.Item1.HasValue && !ids.Item2.HasValue) + if (!ids.Item1.HasValue && !ids.Item2.HasValue) { return new OkResult(); } - if(ipnTransaction.PaymentStatus == "Completed") + if (ipnTransaction.PaymentStatus == "Completed") { var transaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.PayPal, ipnTransaction.TxnId); - if(transaction != null) + if (transaction != null) { _logger.LogWarning("Already processed this completed transaction. #" + ipnTransaction.TxnId); return new OkResult(); @@ -145,16 +145,16 @@ namespace Bit.Billing.Controllers }; await _transactionRepository.CreateAsync(tx); - if(isAccountCredit) + if (isAccountCredit) { string billingEmail = null; - if(tx.OrganizationId.HasValue) + if (tx.OrganizationId.HasValue) { var org = await _organizationRepository.GetByIdAsync(tx.OrganizationId.Value); - if(org != null) + if (org != null) { billingEmail = org.BillingEmailAddress(); - if(await _paymentService.CreditAccountAsync(org, tx.Amount)) + if (await _paymentService.CreditAccountAsync(org, tx.Amount)) { await _organizationRepository.ReplaceAsync(org); } @@ -163,30 +163,30 @@ namespace Bit.Billing.Controllers else { var user = await _userRepository.GetByIdAsync(tx.UserId.Value); - if(user != null) + if (user != null) { billingEmail = user.BillingEmailAddress(); - if(await _paymentService.CreditAccountAsync(user, tx.Amount)) + if (await _paymentService.CreditAccountAsync(user, tx.Amount)) { await _userRepository.ReplaceAsync(user); } } } - if(!string.IsNullOrWhiteSpace(billingEmail)) + if (!string.IsNullOrWhiteSpace(billingEmail)) { await _mailService.SendAddedCreditAsync(billingEmail, tx.Amount); } } } // Catch foreign key violations because user/org could have been deleted. - catch(SqlException e) when(e.Number == 547) { } + catch (SqlException e) when(e.Number == 547) { } } - else if(ipnTransaction.PaymentStatus == "Refunded" || ipnTransaction.PaymentStatus == "Reversed") + else if (ipnTransaction.PaymentStatus == "Refunded" || ipnTransaction.PaymentStatus == "Reversed") { var refundTransaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.PayPal, ipnTransaction.TxnId); - if(refundTransaction != null) + if (refundTransaction != null) { _logger.LogWarning("Already processed this refunded transaction. #" + ipnTransaction.TxnId); return new OkResult(); @@ -194,7 +194,7 @@ namespace Bit.Billing.Controllers var parentTransaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.PayPal, ipnTransaction.ParentTxnId); - if(parentTransaction == null) + if (parentTransaction == null) { _logger.LogWarning("Parent transaction was not found. " + ipnTransaction.TxnId); return new BadRequestResult(); @@ -203,12 +203,12 @@ namespace Bit.Billing.Controllers var refundAmount = System.Math.Abs(ipnTransaction.McGross); var remainingAmount = parentTransaction.Amount - parentTransaction.RefundedAmount.GetValueOrDefault(); - if(refundAmount > 0 && !parentTransaction.Refunded.GetValueOrDefault() && + if (refundAmount > 0 && !parentTransaction.Refunded.GetValueOrDefault() && remainingAmount >= refundAmount) { parentTransaction.RefundedAmount = parentTransaction.RefundedAmount.GetValueOrDefault() + refundAmount; - if(parentTransaction.RefundedAmount == parentTransaction.Amount) + if (parentTransaction.RefundedAmount == parentTransaction.Amount) { parentTransaction.Refunded = true; } diff --git a/src/Billing/Controllers/StripeController.cs b/src/Billing/Controllers/StripeController.cs index ded3ffb026..b2bce09c97 100644 --- a/src/Billing/Controllers/StripeController.cs +++ b/src/Billing/Controllers/StripeController.cs @@ -69,26 +69,26 @@ namespace Bit.Billing.Controllers [HttpPost("webhook")] public async Task PostWebhook([FromQuery] string key) { - if(key != _billingSettings.StripeWebhookKey) + if (key != _billingSettings.StripeWebhookKey) { return new BadRequestResult(); } Stripe.Event parsedEvent; - using(var sr = new StreamReader(HttpContext.Request.Body)) + using (var sr = new StreamReader(HttpContext.Request.Body)) { var json = await sr.ReadToEndAsync(); parsedEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _billingSettings.StripeWebhookSecret); } - if(string.IsNullOrWhiteSpace(parsedEvent?.Id)) + if (string.IsNullOrWhiteSpace(parsedEvent?.Id)) { _logger.LogWarning("No event id."); return new BadRequestResult(); } - if(_hostingEnvironment.IsProduction() && !parsedEvent.Livemode) + if (_hostingEnvironment.IsProduction() && !parsedEvent.Livemode) { _logger.LogWarning("Getting test events in production."); return new BadRequestResult(); @@ -97,7 +97,7 @@ namespace Bit.Billing.Controllers var subDeleted = parsedEvent.Type.Equals("customer.subscription.deleted"); var subUpdated = parsedEvent.Type.Equals("customer.subscription.updated"); - if(subDeleted || subUpdated) + if (subDeleted || subUpdated) { var subscription = await GetSubscriptionAsync(parsedEvent, true); var ids = GetIdsFromMetaData(subscription.Metadata); @@ -106,42 +106,42 @@ namespace Bit.Billing.Controllers var subUnpaid = subUpdated && subscription.Status == "unpaid"; var subIncompleteExpired = subUpdated && subscription.Status == "incomplete_expired"; - if(subCanceled || subUnpaid || subIncompleteExpired) + if (subCanceled || subUnpaid || subIncompleteExpired) { // org - if(ids.Item1.HasValue) + if (ids.Item1.HasValue) { await _organizationService.DisableAsync(ids.Item1.Value, subscription.CurrentPeriodEnd); } // user - else if(ids.Item2.HasValue) + else if (ids.Item2.HasValue) { await _userService.DisablePremiumAsync(ids.Item2.Value, subscription.CurrentPeriodEnd); } } - if(subUpdated) + if (subUpdated) { // org - if(ids.Item1.HasValue) + if (ids.Item1.HasValue) { await _organizationService.UpdateExpirationDateAsync(ids.Item1.Value, subscription.CurrentPeriodEnd); } // user - else if(ids.Item2.HasValue) + else if (ids.Item2.HasValue) { await _userService.UpdatePremiumExpirationAsync(ids.Item2.Value, subscription.CurrentPeriodEnd); } } } - else if(parsedEvent.Type.Equals("invoice.upcoming")) + else if (parsedEvent.Type.Equals("invoice.upcoming")) { var invoice = await GetInvoiceAsync(parsedEvent); var subscriptionService = new SubscriptionService(); var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId); - if(subscription == null) + if (subscription == null) { throw new Exception("Invoice subscription is null. " + invoice.Id); } @@ -149,37 +149,37 @@ namespace Bit.Billing.Controllers string email = null; var ids = GetIdsFromMetaData(subscription.Metadata); // org - if(ids.Item1.HasValue) + if (ids.Item1.HasValue) { var org = await _organizationRepository.GetByIdAsync(ids.Item1.Value); - if(org != null && OrgPlanForInvoiceNotifications(org)) + if (org != null && OrgPlanForInvoiceNotifications(org)) { email = org.BillingEmail; } } // user - else if(ids.Item2.HasValue) + else if (ids.Item2.HasValue) { var user = await _userService.GetUserByIdAsync(ids.Item2.Value); - if(user.Premium) + if (user.Premium) { email = user.Email; } } - if(!string.IsNullOrWhiteSpace(email) && invoice.NextPaymentAttempt.HasValue) + if (!string.IsNullOrWhiteSpace(email) && invoice.NextPaymentAttempt.HasValue) { var items = invoice.Lines.Select(i => i.Description).ToList(); await _mailService.SendInvoiceUpcomingAsync(email, invoice.AmountDue / 100M, invoice.NextPaymentAttempt.Value, items, true); } } - else if(parsedEvent.Type.Equals("charge.succeeded")) + else if (parsedEvent.Type.Equals("charge.succeeded")) { var charge = await GetChargeAsync(parsedEvent); var chargeTransaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.Stripe, charge.Id); - if(chargeTransaction != null) + if (chargeTransaction != null) { _logger.LogWarning("Charge success already processed. " + charge.Id); return new OkResult(); @@ -189,29 +189,29 @@ namespace Bit.Billing.Controllers Subscription subscription = null; var subscriptionService = new SubscriptionService(); - if(charge.InvoiceId != null) + if (charge.InvoiceId != null) { var invoiceService = new InvoiceService(); var invoice = await invoiceService.GetAsync(charge.InvoiceId); - if(invoice?.SubscriptionId != null) + if (invoice?.SubscriptionId != null) { subscription = await subscriptionService.GetAsync(invoice.SubscriptionId); ids = GetIdsFromMetaData(subscription?.Metadata); } } - if(subscription == null || ids == null || (ids.Item1.HasValue && ids.Item2.HasValue)) + if (subscription == null || ids == null || (ids.Item1.HasValue && ids.Item2.HasValue)) { var subscriptions = await subscriptionService.ListAsync(new SubscriptionListOptions { CustomerId = charge.CustomerId }); - foreach(var sub in subscriptions) + foreach (var sub in subscriptions) { - if(sub.Status != "canceled" && sub.Status != "incomplete_expired") + if (sub.Status != "canceled" && sub.Status != "incomplete_expired") { ids = GetIdsFromMetaData(sub.Metadata); - if(ids.Item1.HasValue || ids.Item2.HasValue) + if (ids.Item1.HasValue || ids.Item2.HasValue) { subscription = sub; break; @@ -220,7 +220,7 @@ namespace Bit.Billing.Controllers } } - if(!ids.Item1.HasValue && !ids.Item2.HasValue) + if (!ids.Item1.HasValue && !ids.Item2.HasValue) { _logger.LogWarning("Charge success has no subscriber ids. " + charge.Id); return new BadRequestResult(); @@ -237,50 +237,50 @@ namespace Bit.Billing.Controllers GatewayId = charge.Id }; - if(charge.Source != null && charge.Source is Card card) + if (charge.Source != null && charge.Source is Card card) { tx.PaymentMethodType = PaymentMethodType.Card; tx.Details = $"{card.Brand}, *{card.Last4}"; } - else if(charge.Source != null && charge.Source is BankAccount bankAccount) + else if (charge.Source != null && charge.Source is BankAccount bankAccount) { tx.PaymentMethodType = PaymentMethodType.BankAccount; tx.Details = $"{bankAccount.BankName}, *{bankAccount.Last4}"; } - else if(charge.Source != null && charge.Source is Source source) + else if (charge.Source != null && charge.Source is Source source) { - if(source.Card != null) + if (source.Card != null) { tx.PaymentMethodType = PaymentMethodType.Card; tx.Details = $"{source.Card.Brand}, *{source.Card.Last4}"; } - else if(source.AchDebit != null) + else if (source.AchDebit != null) { tx.PaymentMethodType = PaymentMethodType.BankAccount; tx.Details = $"{source.AchDebit.BankName}, *{source.AchDebit.Last4}"; } - else if(source.AchCreditTransfer != null) + else if (source.AchCreditTransfer != null) { tx.PaymentMethodType = PaymentMethodType.BankAccount; tx.Details = $"ACH => {source.AchCreditTransfer.BankName}, " + $"{source.AchCreditTransfer.AccountNumber}"; } } - else if(charge.PaymentMethodDetails != null) + else if (charge.PaymentMethodDetails != null) { - if(charge.PaymentMethodDetails.Card != null) + if (charge.PaymentMethodDetails.Card != null) { tx.PaymentMethodType = PaymentMethodType.Card; tx.Details = $"{charge.PaymentMethodDetails.Card.Brand?.ToUpperInvariant()}, " + $"*{charge.PaymentMethodDetails.Card.Last4}"; } - else if(charge.PaymentMethodDetails.AchDebit != null) + else if (charge.PaymentMethodDetails.AchDebit != null) { tx.PaymentMethodType = PaymentMethodType.BankAccount; tx.Details = $"{charge.PaymentMethodDetails.AchDebit.BankName}, " + $"*{charge.PaymentMethodDetails.AchDebit.Last4}"; } - else if(charge.PaymentMethodDetails.AchCreditTransfer != null) + else if (charge.PaymentMethodDetails.AchCreditTransfer != null) { tx.PaymentMethodType = PaymentMethodType.BankAccount; tx.Details = $"ACH => {charge.PaymentMethodDetails.AchCreditTransfer.BankName}, " + @@ -288,7 +288,7 @@ namespace Bit.Billing.Controllers } } - if(!tx.PaymentMethodType.HasValue) + if (!tx.PaymentMethodType.HasValue) { _logger.LogWarning("Charge success from unsupported source/method. " + charge.Id); return new OkResult(); @@ -299,35 +299,35 @@ namespace Bit.Billing.Controllers await _transactionRepository.CreateAsync(tx); } // Catch foreign key violations because user/org could have been deleted. - catch(SqlException e) when(e.Number == 547) { } + catch (SqlException e) when(e.Number == 547) { } } - else if(parsedEvent.Type.Equals("charge.refunded")) + else if (parsedEvent.Type.Equals("charge.refunded")) { var charge = await GetChargeAsync(parsedEvent); var chargeTransaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.Stripe, charge.Id); - if(chargeTransaction == null) + if (chargeTransaction == null) { throw new Exception("Cannot find refunded charge. " + charge.Id); } var amountRefunded = charge.AmountRefunded / 100M; - if(!chargeTransaction.Refunded.GetValueOrDefault() && + if (!chargeTransaction.Refunded.GetValueOrDefault() && chargeTransaction.RefundedAmount.GetValueOrDefault() < amountRefunded) { chargeTransaction.RefundedAmount = amountRefunded; - if(charge.Refunded) + if (charge.Refunded) { chargeTransaction.Refunded = true; } await _transactionRepository.ReplaceAsync(chargeTransaction); - foreach(var refund in charge.Refunds) + foreach (var refund in charge.Refunds) { var refundTransaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.Stripe, refund.Id); - if(refundTransaction != null) + if (refundTransaction != null) { continue; } @@ -351,33 +351,33 @@ namespace Bit.Billing.Controllers _logger.LogWarning("Charge refund amount doesn't seem correct. " + charge.Id); } } - else if(parsedEvent.Type.Equals("invoice.payment_succeeded")) + else if (parsedEvent.Type.Equals("invoice.payment_succeeded")) { var invoice = await GetInvoiceAsync(parsedEvent, true); - if(invoice.Paid && invoice.BillingReason == "subscription_create") + if (invoice.Paid && invoice.BillingReason == "subscription_create") { var subscriptionService = new SubscriptionService(); var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId); - if(subscription?.Status == "active") + if (subscription?.Status == "active") { - if(DateTime.UtcNow - invoice.Created < TimeSpan.FromMinutes(1)) + if (DateTime.UtcNow - invoice.Created < TimeSpan.FromMinutes(1)) { await Task.Delay(5000); } var ids = GetIdsFromMetaData(subscription.Metadata); // org - if(ids.Item1.HasValue) + if (ids.Item1.HasValue) { - if(subscription.Items.Any(i => StaticStore.Plans.Any(p => p.StripePlanId == i.Plan.Id))) + if (subscription.Items.Any(i => StaticStore.Plans.Any(p => p.StripePlanId == i.Plan.Id))) { await _organizationService.EnableAsync(ids.Item1.Value, subscription.CurrentPeriodEnd); } } // user - else if(ids.Item2.HasValue) + else if (ids.Item2.HasValue) { - if(subscription.Items.Any(i => i.Plan.Id == "premium-annually")) + if (subscription.Items.Any(i => i.Plan.Id == "premium-annually")) { await _userService.EnablePremiumAsync(ids.Item2.Value, subscription.CurrentPeriodEnd); } @@ -385,18 +385,18 @@ namespace Bit.Billing.Controllers } } } - else if(parsedEvent.Type.Equals("invoice.payment_failed")) + else if (parsedEvent.Type.Equals("invoice.payment_failed")) { var invoice = await GetInvoiceAsync(parsedEvent, true); - if(!invoice.Paid && invoice.AttemptCount > 1 && UnpaidAutoChargeInvoiceForSubscriptionCycle(invoice)) + if (!invoice.Paid && invoice.AttemptCount > 1 && UnpaidAutoChargeInvoiceForSubscriptionCycle(invoice)) { await AttemptToPayInvoiceAsync(invoice); } } - else if(parsedEvent.Type.Equals("invoice.created")) + else if (parsedEvent.Type.Equals("invoice.created")) { var invoice = await GetInvoiceAsync(parsedEvent, true); - if(!invoice.Paid && UnpaidAutoChargeInvoiceForSubscriptionCycle(invoice)) + if (!invoice.Paid && UnpaidAutoChargeInvoiceForSubscriptionCycle(invoice)) { await AttemptToPayInvoiceAsync(invoice); } @@ -411,7 +411,7 @@ namespace Bit.Billing.Controllers private Tuple GetIdsFromMetaData(IDictionary metaData) { - if(metaData == null || !metaData.Any()) + if (metaData == null || !metaData.Any()) { return new Tuple(null, null); } @@ -419,26 +419,26 @@ namespace Bit.Billing.Controllers Guid? orgId = null; Guid? userId = null; - if(metaData.ContainsKey("organizationId")) + if (metaData.ContainsKey("organizationId")) { orgId = new Guid(metaData["organizationId"]); } - else if(metaData.ContainsKey("userId")) + else if (metaData.ContainsKey("userId")) { userId = new Guid(metaData["userId"]); } - if(userId == null && orgId == null) + if (userId == null && orgId == null) { var orgIdKey = metaData.Keys.FirstOrDefault(k => k.ToLowerInvariant() == "organizationid"); - if(!string.IsNullOrWhiteSpace(orgIdKey)) + if (!string.IsNullOrWhiteSpace(orgIdKey)) { orgId = new Guid(metaData[orgIdKey]); } else { var userIdKey = metaData.Keys.FirstOrDefault(k => k.ToLowerInvariant() == "userid"); - if(!string.IsNullOrWhiteSpace(userIdKey)) + if (!string.IsNullOrWhiteSpace(userIdKey)) { userId = new Guid(metaData[userIdKey]); } @@ -450,7 +450,7 @@ namespace Bit.Billing.Controllers private bool OrgPlanForInvoiceNotifications(Organization org) { - switch(org.PlanType) + switch (org.PlanType) { case PlanType.FamiliesAnnually: case PlanType.TeamsAnnually: @@ -465,11 +465,11 @@ namespace Bit.Billing.Controllers { var customerService = new CustomerService(); var customer = await customerService.GetAsync(invoice.CustomerId); - if(customer?.Metadata?.ContainsKey("appleReceipt") ?? false) + if (customer?.Metadata?.ContainsKey("appleReceipt") ?? false) { return await AttemptToPayInvoiceWithAppleReceiptAsync(invoice, customer); } - else if(customer?.Metadata?.ContainsKey("btCustomerId") ?? false) + else if (customer?.Metadata?.ContainsKey("btCustomerId") ?? false) { return await AttemptToPayInvoiceWithBraintreeAsync(invoice, customer); } @@ -478,14 +478,14 @@ namespace Bit.Billing.Controllers private async Task AttemptToPayInvoiceWithAppleReceiptAsync(Invoice invoice, Customer customer) { - if(!customer?.Metadata?.ContainsKey("appleReceipt") ?? true) + if (!customer?.Metadata?.ContainsKey("appleReceipt") ?? true) { return false; } var originalAppleReceiptTransactionId = customer.Metadata["appleReceipt"]; var appleReceiptRecord = await _appleIapService.GetReceiptAsync(originalAppleReceiptTransactionId); - if(string.IsNullOrWhiteSpace(appleReceiptRecord?.Item1) || !appleReceiptRecord.Item2.HasValue) + if (string.IsNullOrWhiteSpace(appleReceiptRecord?.Item1) || !appleReceiptRecord.Item2.HasValue) { return false; } @@ -493,13 +493,13 @@ namespace Bit.Billing.Controllers var subscriptionService = new SubscriptionService(); var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId); var ids = GetIdsFromMetaData(subscription?.Metadata); - if(!ids.Item2.HasValue) + if (!ids.Item2.HasValue) { // Apple receipt is only for user subscriptions return false; } - if(appleReceiptRecord.Item2.Value != ids.Item2.Value) + if (appleReceiptRecord.Item2.Value != ids.Item2.Value) { _logger.LogError("User Ids for Apple Receipt and subscription do not match: {0} != {1}.", appleReceiptRecord.Item2.Value, ids.Item2.Value); @@ -507,7 +507,7 @@ namespace Bit.Billing.Controllers } var appleReceiptStatus = await _appleIapService.GetVerifiedReceiptStatusAsync(appleReceiptRecord.Item1); - if(appleReceiptStatus == null) + if (appleReceiptStatus == null) { // TODO: cancel sub if receipt is cancelled? return false; @@ -515,7 +515,7 @@ namespace Bit.Billing.Controllers var receiptExpiration = appleReceiptStatus.GetLastExpiresDate().GetValueOrDefault(DateTime.MinValue); var invoiceDue = invoice.DueDate.GetValueOrDefault(DateTime.MinValue); - if(receiptExpiration <= invoiceDue) + if (receiptExpiration <= invoiceDue) { _logger.LogWarning("Apple receipt expiration is before invoice due date. {0} <= {1}", receiptExpiration, invoiceDue); @@ -525,7 +525,7 @@ namespace Bit.Billing.Controllers var receiptLastTransactionId = appleReceiptStatus.GetLastTransactionId(); var existingTransaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.AppStore, receiptLastTransactionId); - if(existingTransaction != null) + if (existingTransaction != null) { _logger.LogWarning("There is already an existing transaction for this Apple receipt.", receiptLastTransactionId); @@ -551,9 +551,9 @@ namespace Bit.Billing.Controllers await _transactionRepository.CreateAsync(appleTransaction); await invoiceService.PayAsync(invoice.Id, new InvoicePayOptions { PaidOutOfBand = true }); } - catch(Exception e) + catch (Exception e) { - if(e.Message.Contains("Invoice is already paid")) + if (e.Message.Contains("Invoice is already paid")) { await invoiceService.UpdateAsync(invoice.Id, new InvoiceUpdateOptions { @@ -571,7 +571,7 @@ namespace Bit.Billing.Controllers private async Task AttemptToPayInvoiceWithBraintreeAsync(Invoice invoice, Customer customer) { - if(!customer?.Metadata?.ContainsKey("btCustomerId") ?? true) + if (!customer?.Metadata?.ContainsKey("btCustomerId") ?? true) { return false; } @@ -579,7 +579,7 @@ namespace Bit.Billing.Controllers var subscriptionService = new SubscriptionService(); var subscription = await subscriptionService.GetAsync(invoice.SubscriptionId); var ids = GetIdsFromMetaData(subscription?.Metadata); - if(!ids.Item1.HasValue && !ids.Item2.HasValue) + if (!ids.Item1.HasValue && !ids.Item2.HasValue) { return false; } @@ -596,7 +596,7 @@ namespace Bit.Billing.Controllers var now = DateTime.UtcNow; var duplicateTransaction = existingTransactions? .FirstOrDefault(t => (now - t.CreationDate) < duplicateTimeSpan); - if(duplicateTransaction != null) + if (duplicateTransaction != null) { _logger.LogWarning("There is already a recent PayPal transaction ({0}). " + "Do not charge again to prevent possible duplicate.", duplicateTransaction.GatewayId); @@ -622,9 +622,9 @@ namespace Bit.Billing.Controllers } }); - if(!transactionResult.IsSuccess()) + if (!transactionResult.IsSuccess()) { - if(invoice.AttemptCount < 4) + if (invoice.AttemptCount < 4) { await _mailService.SendPaymentFailedAsync(customer.Email, btInvoiceAmount, true); } @@ -645,10 +645,10 @@ namespace Bit.Billing.Controllers }); await invoiceService.PayAsync(invoice.Id, new InvoicePayOptions { PaidOutOfBand = true }); } - catch(Exception e) + catch (Exception e) { await _btGateway.Transaction.RefundAsync(transactionResult.Target.Id); - if(e.Message.Contains("Invoice is already paid")) + if (e.Message.Contains("Invoice is already paid")) { await invoiceService.UpdateAsync(invoice.Id, new InvoiceUpdateOptions { @@ -672,17 +672,17 @@ namespace Bit.Billing.Controllers private async Task GetChargeAsync(Stripe.Event parsedEvent, bool fresh = false) { - if(!(parsedEvent.Data.Object is Charge eventCharge)) + if (!(parsedEvent.Data.Object is Charge eventCharge)) { throw new Exception("Charge is null (from parsed event). " + parsedEvent.Id); } - if(!fresh) + if (!fresh) { return eventCharge; } var chargeService = new ChargeService(); var charge = await chargeService.GetAsync(eventCharge.Id); - if(charge == null) + if (charge == null) { throw new Exception("Charge is null. " + eventCharge.Id); } @@ -691,17 +691,17 @@ namespace Bit.Billing.Controllers private async Task GetInvoiceAsync(Stripe.Event parsedEvent, bool fresh = false) { - if(!(parsedEvent.Data.Object is Invoice eventInvoice)) + if (!(parsedEvent.Data.Object is Invoice eventInvoice)) { throw new Exception("Invoice is null (from parsed event). " + parsedEvent.Id); } - if(!fresh) + if (!fresh) { return eventInvoice; } var invoiceService = new InvoiceService(); var invoice = await invoiceService.GetAsync(eventInvoice.Id); - if(invoice == null) + if (invoice == null) { throw new Exception("Invoice is null. " + eventInvoice.Id); } @@ -710,17 +710,17 @@ namespace Bit.Billing.Controllers private async Task GetSubscriptionAsync(Stripe.Event parsedEvent, bool fresh = false) { - if(!(parsedEvent.Data.Object is Subscription eventSubscription)) + if (!(parsedEvent.Data.Object is Subscription eventSubscription)) { throw new Exception("Subscription is null (from parsed event). " + parsedEvent.Id); } - if(!fresh) + if (!fresh) { return eventSubscription; } var subscriptionService = new SubscriptionService(); var subscription = await subscriptionService.GetAsync(eventSubscription.Id); - if(subscription == null) + if (subscription == null) { throw new Exception("Subscription is null. " + eventSubscription.Id); } diff --git a/src/Billing/Jobs/JobsHostedService.cs b/src/Billing/Jobs/JobsHostedService.cs index 82d159dfe1..4dc5d3b64b 100644 --- a/src/Billing/Jobs/JobsHostedService.cs +++ b/src/Billing/Jobs/JobsHostedService.cs @@ -29,7 +29,7 @@ namespace Bit.Billing.Jobs var timeZone = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") : TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); - if(_globalSettings.SelfHosted) + if (_globalSettings.SelfHosted) { timeZone = TimeZoneInfo.Utc; } diff --git a/src/Billing/Models/AppleReceiptNotification.cs b/src/Billing/Models/AppleReceiptNotification.cs index 454cbaad98..c71fa0eb19 100644 --- a/src/Billing/Models/AppleReceiptNotification.cs +++ b/src/Billing/Models/AppleReceiptNotification.cs @@ -29,7 +29,7 @@ namespace Bit.Billing.Models public string GetOriginalTransactionId() { - if(LatestReceiptInfo != null) + if (LatestReceiptInfo != null) { return LatestReceiptInfo.OriginalTransactionId; } @@ -38,7 +38,7 @@ namespace Bit.Billing.Models public string GetTransactionId() { - if(LatestReceiptInfo != null) + if (LatestReceiptInfo != null) { return LatestReceiptInfo.TransactionId; } @@ -47,7 +47,7 @@ namespace Bit.Billing.Models public DateTime? GetExpiresDate() { - if(LatestReceiptInfo != null) + if (LatestReceiptInfo != null) { return LatestReceiptInfo.ExpiresDate; } diff --git a/src/Billing/Program.cs b/src/Billing/Program.cs index 13a0bc3d01..1b2e0875a6 100644 --- a/src/Billing/Program.cs +++ b/src/Billing/Program.cs @@ -18,13 +18,13 @@ namespace Bit.Billing logging.AddSerilog(hostingContext, e => { var context = e.Properties["SourceContext"].ToString(); - if(e.Level == LogEventLevel.Information && + if (e.Level == LogEventLevel.Information && (context.StartsWith("\"Bit.Billing.Jobs") || context.StartsWith("\"Bit.Core.Jobs"))) { return true; } - if(e.Properties.ContainsKey("RequestPath") && + if (e.Properties.ContainsKey("RequestPath") && !string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) && (context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer"))) { diff --git a/src/Billing/Startup.cs b/src/Billing/Startup.cs index c45a88191a..70a3db0d7b 100644 --- a/src/Billing/Startup.cs +++ b/src/Billing/Startup.cs @@ -78,7 +78,7 @@ namespace Bit.Billing { app.UseSerilog(env, appLifetime, globalSettings); - if(env.IsDevelopment()) + if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } diff --git a/src/Billing/Utilities/PayPalIpnClient.cs b/src/Billing/Utilities/PayPalIpnClient.cs index 317f3bba8e..cd95e5a906 100644 --- a/src/Billing/Utilities/PayPalIpnClient.cs +++ b/src/Billing/Utilities/PayPalIpnClient.cs @@ -25,7 +25,7 @@ namespace Bit.Billing.Utilities public async Task VerifyIpnAsync(string ipnBody) { - if(ipnBody == null) + if (ipnBody == null) { throw new ArgumentException("No IPN body."); } @@ -38,16 +38,16 @@ namespace Bit.Billing.Utilities var cmdIpnBody = string.Concat("cmd=_notify-validate&", ipnBody); request.Content = new StringContent(cmdIpnBody, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await _httpClient.SendAsync(request); - if(!response.IsSuccessStatusCode) + if (!response.IsSuccessStatusCode) { throw new Exception("Failed to verify IPN, status: " + response.StatusCode); } var responseContent = await response.Content.ReadAsStringAsync(); - if(responseContent.Equals("VERIFIED")) + if (responseContent.Equals("VERIFIED")) { return true; } - else if(responseContent.Equals("INVALID")) + else if (responseContent.Equals("INVALID")) { return false; } @@ -67,7 +67,7 @@ namespace Bit.Billing.Utilities public IpnTransaction(string ipnFormData) { - if(string.IsNullOrWhiteSpace(ipnFormData)) + if (string.IsNullOrWhiteSpace(ipnFormData)) { return; } @@ -92,12 +92,12 @@ namespace Bit.Billing.Utilities PaymentDate = ConvertDate(GetDictValue(dataDict, "payment_date")); var mcGrossString = GetDictValue(dataDict, "mc_gross"); - if(!string.IsNullOrWhiteSpace(mcGrossString) && decimal.TryParse(mcGrossString, out var mcGross)) + if (!string.IsNullOrWhiteSpace(mcGrossString) && decimal.TryParse(mcGrossString, out var mcGross)) { McGross = mcGross; } var mcFeeString = GetDictValue(dataDict, "mc_fee"); - if(!string.IsNullOrWhiteSpace(mcFeeString) && decimal.TryParse(mcFeeString, out var mcFee)) + if (!string.IsNullOrWhiteSpace(mcFeeString) && decimal.TryParse(mcFeeString, out var mcFee)) { McFee = mcFee; } @@ -125,19 +125,19 @@ namespace Bit.Billing.Utilities Guid? orgId = null; Guid? userId = null; - if(!string.IsNullOrWhiteSpace(Custom) && Custom.Contains(":")) + if (!string.IsNullOrWhiteSpace(Custom) && Custom.Contains(":")) { var mainParts = Custom.Split(','); - foreach(var mainPart in mainParts) + foreach (var mainPart in mainParts) { var parts = mainPart.Split(':'); - if(parts.Length > 1 && Guid.TryParse(parts[1], out var id)) + if (parts.Length > 1 && Guid.TryParse(parts[1], out var id)) { - if(parts[0] == "user_id") + if (parts[0] == "user_id") { userId = id; } - else if(parts[0] == "organization_id") + else if (parts[0] == "organization_id") { orgId = id; } @@ -160,11 +160,11 @@ namespace Bit.Billing.Utilities private DateTime ConvertDate(string dateString) { - if(!string.IsNullOrWhiteSpace(dateString)) + if (!string.IsNullOrWhiteSpace(dateString)) { var parsed = DateTime.TryParseExact(dateString, _dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var paymentDate); - if(parsed) + if (parsed) { var pacificTime = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time") : diff --git a/src/Core/CurrentContext.cs b/src/Core/CurrentContext.cs index c217b55dc4..4fb53fb220 100644 --- a/src/Core/CurrentContext.cs +++ b/src/Core/CurrentContext.cs @@ -28,7 +28,7 @@ namespace Bit.Core public void Build(HttpContext httpContext, GlobalSettings globalSettings) { - if(_builtHttpContext) + if (_builtHttpContext) { return; } @@ -37,12 +37,12 @@ namespace Bit.Core HttpContext = httpContext; Build(httpContext.User, globalSettings); - if(DeviceIdentifier == null && httpContext.Request.Headers.ContainsKey("Device-Identifier")) + if (DeviceIdentifier == null && httpContext.Request.Headers.ContainsKey("Device-Identifier")) { DeviceIdentifier = httpContext.Request.Headers["Device-Identifier"]; } - if(httpContext.Request.Headers.ContainsKey("Device-Type") && + if (httpContext.Request.Headers.ContainsKey("Device-Type") && Enum.TryParse(httpContext.Request.Headers["Device-Type"].ToString(), out DeviceType dType)) { DeviceType = dType; @@ -51,14 +51,14 @@ namespace Bit.Core public void Build(ClaimsPrincipal user, GlobalSettings globalSettings) { - if(_builtClaimsPrincipal) + if (_builtClaimsPrincipal) { return; } _builtClaimsPrincipal = true; IpAddress = HttpContext.GetIpAddress(globalSettings); - if(user == null || !user.Claims.Any()) + if (user == null || !user.Claims.Any()) { return; } @@ -66,7 +66,7 @@ namespace Bit.Core var claimsDict = user.Claims.GroupBy(c => c.Type).ToDictionary(c => c.Key, c => c.Select(v => v)); var subject = GetClaimValue(claimsDict, "sub"); - if(Guid.TryParse(subject, out var subIdGuid)) + if (Guid.TryParse(subject, out var subIdGuid)) { UserId = subIdGuid; } @@ -74,18 +74,18 @@ namespace Bit.Core var clientId = GetClaimValue(claimsDict, "client_id"); var clientSubject = GetClaimValue(claimsDict, "client_sub"); var orgApi = false; - if(clientSubject != null) + if (clientSubject != null) { - if(clientId?.StartsWith("installation.") ?? false) + if (clientId?.StartsWith("installation.") ?? false) { - if(Guid.TryParse(clientSubject, out var idGuid)) + if (Guid.TryParse(clientSubject, out var idGuid)) { InstallationId = idGuid; } } - else if(clientId?.StartsWith("organization.") ?? false) + else if (clientId?.StartsWith("organization.") ?? false) { - if(Guid.TryParse(clientSubject, out var idGuid)) + if (Guid.TryParse(clientSubject, out var idGuid)) { OrganizationId = idGuid; orgApi = true; @@ -96,7 +96,7 @@ namespace Bit.Core DeviceIdentifier = GetClaimValue(claimsDict, "device"); Organizations = new List(); - if(claimsDict.ContainsKey("orgowner")) + if (claimsDict.ContainsKey("orgowner")) { Organizations.AddRange(claimsDict["orgowner"].Select(c => new CurrentContentOrganization @@ -105,7 +105,7 @@ namespace Bit.Core Type = OrganizationUserType.Owner })); } - else if(orgApi && OrganizationId.HasValue) + else if (orgApi && OrganizationId.HasValue) { Organizations.Add(new CurrentContentOrganization { @@ -114,7 +114,7 @@ namespace Bit.Core }); } - if(claimsDict.ContainsKey("orgadmin")) + if (claimsDict.ContainsKey("orgadmin")) { Organizations.AddRange(claimsDict["orgadmin"].Select(c => new CurrentContentOrganization @@ -124,7 +124,7 @@ namespace Bit.Core })); } - if(claimsDict.ContainsKey("orguser")) + if (claimsDict.ContainsKey("orguser")) { Organizations.AddRange(claimsDict["orguser"].Select(c => new CurrentContentOrganization @@ -134,7 +134,7 @@ namespace Bit.Core })); } - if(claimsDict.ContainsKey("orgmanager")) + if (claimsDict.ContainsKey("orgmanager")) { Organizations.AddRange(claimsDict["orgmanager"].Select(c => new CurrentContentOrganization @@ -171,7 +171,7 @@ namespace Bit.Core public async Task> OrganizationMembershipAsync( IOrganizationUserRepository organizationUserRepository, Guid userId) { - if(Organizations == null) + if (Organizations == null) { var userOrgs = await organizationUserRepository.GetManyByUserAsync(userId); Organizations = userOrgs.Where(ou => ou.Status == OrganizationUserStatusType.Confirmed) @@ -182,7 +182,7 @@ namespace Bit.Core private string GetClaimValue(Dictionary> claims, string type) { - if(!claims.ContainsKey(type)) + if (!claims.ContainsKey(type)) { return null; } diff --git a/src/Core/Exceptions/BadRequestException.cs b/src/Core/Exceptions/BadRequestException.cs index 13285c1647..bc9b3e2671 100644 --- a/src/Core/Exceptions/BadRequestException.cs +++ b/src/Core/Exceptions/BadRequestException.cs @@ -19,7 +19,7 @@ namespace Bit.Core.Exceptions public BadRequestException(ModelStateDictionary modelState) : base("The model state is invalid.") { - if(modelState.IsValid || modelState.ErrorCount == 0) + if (modelState.IsValid || modelState.ErrorCount == 0) { return; } diff --git a/src/Core/HostedServices/ApplicationCacheHostedService.cs b/src/Core/HostedServices/ApplicationCacheHostedService.cs index 38136aa345..d6b9bbe866 100644 --- a/src/Core/HostedServices/ApplicationCacheHostedService.cs +++ b/src/Core/HostedServices/ApplicationCacheHostedService.cs @@ -50,7 +50,7 @@ namespace Bit.Core.HostedServices EnableDeadLetteringOnMessageExpiration = true, }, new RuleDescription("default", new SqlFilter($"sys.Label != '{_subName}'"))); } - catch(MessagingEntityAlreadyExistsException) { } + catch (MessagingEntityAlreadyExistsException) { } _subscriptionClient.RegisterMessageHandler(ProcessMessageAsync, new MessageHandlerOptions(ExceptionReceivedHandlerAsync) { @@ -74,14 +74,14 @@ namespace Bit.Core.HostedServices private async Task ProcessMessageAsync(Message message, CancellationToken cancellationToken) { - if(message.Label != _subName && _applicationCacheService != null) + if (message.Label != _subName && _applicationCacheService != null) { - switch((ApplicationCacheMessageType)message.UserProperties["type"]) + switch ((ApplicationCacheMessageType)message.UserProperties["type"]) { case ApplicationCacheMessageType.UpsertOrganizationAbility: var upsertedOrgId = (Guid)message.UserProperties["id"]; var upsertedOrg = await _organizationRepository.GetByIdAsync(upsertedOrgId); - if(upsertedOrg != null) + if (upsertedOrg != null) { await _applicationCacheService.BaseUpsertOrganizationAbilityAsync(upsertedOrg); } @@ -94,7 +94,7 @@ namespace Bit.Core.HostedServices break; } } - if(!cancellationToken.IsCancellationRequested) + if (!cancellationToken.IsCancellationRequested) { await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken); } diff --git a/src/Core/Identity/AuthenticatorTokenProvider.cs b/src/Core/Identity/AuthenticatorTokenProvider.cs index bccfc9f713..d511e8ec61 100644 --- a/src/Core/Identity/AuthenticatorTokenProvider.cs +++ b/src/Core/Identity/AuthenticatorTokenProvider.cs @@ -21,7 +21,7 @@ namespace Bit.Core.Identity public async Task CanGenerateTwoFactorTokenAsync(UserManager manager, User user) { var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Authenticator); - if(string.IsNullOrWhiteSpace((string)provider?.MetaData["Key"])) + if (string.IsNullOrWhiteSpace((string)provider?.MetaData["Key"])) { return false; } diff --git a/src/Core/Identity/CustomIdentityServiceCollectionExtensions.cs b/src/Core/Identity/CustomIdentityServiceCollectionExtensions.cs index 103d263098..8965b621ce 100644 --- a/src/Core/Identity/CustomIdentityServiceCollectionExtensions.cs +++ b/src/Core/Identity/CustomIdentityServiceCollectionExtensions.cs @@ -41,7 +41,7 @@ namespace Microsoft.Extensions.DependencyInjection services.TryAddScoped>(); services.TryAddScoped>(); - if(setupAction != null) + if (setupAction != null) { services.Configure(setupAction); } diff --git a/src/Core/Identity/DuoWebTokenProvider.cs b/src/Core/Identity/DuoWebTokenProvider.cs index 49f858249b..d2b1c4dde4 100644 --- a/src/Core/Identity/DuoWebTokenProvider.cs +++ b/src/Core/Identity/DuoWebTokenProvider.cs @@ -26,13 +26,13 @@ namespace Bit.Core.Identity public async Task CanGenerateTwoFactorTokenAsync(UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user))) + if (!(await userService.CanAccessPremium(user))) { return false; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return false; } @@ -43,13 +43,13 @@ namespace Bit.Core.Identity public async Task GenerateAsync(string purpose, UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user))) + if (!(await userService.CanAccessPremium(user))) { return null; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return null; } @@ -62,13 +62,13 @@ namespace Bit.Core.Identity public async Task ValidateAsync(string purpose, string token, UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user))) + if (!(await userService.CanAccessPremium(user))) { return false; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Duo); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return false; } diff --git a/src/Core/Identity/EmailTokenProvider.cs b/src/Core/Identity/EmailTokenProvider.cs index c9b703bf61..fb874cf763 100644 --- a/src/Core/Identity/EmailTokenProvider.cs +++ b/src/Core/Identity/EmailTokenProvider.cs @@ -21,7 +21,7 @@ namespace Bit.Core.Identity public async Task CanGenerateTwoFactorTokenAsync(UserManager manager, User user) { var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Email); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return false; } @@ -33,7 +33,7 @@ namespace Bit.Core.Identity public Task GenerateAsync(string purpose, UserManager manager, User user) { var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Email); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return null; } @@ -57,11 +57,11 @@ namespace Bit.Core.Identity var emailParts = email.Split('@'); string shownPart = null; - if(emailParts[0].Length > 2 && emailParts[0].Length <= 4) + if (emailParts[0].Length > 2 && emailParts[0].Length <= 4) { shownPart = emailParts[0].Substring(0, 1); } - else if(emailParts[0].Length > 4) + else if (emailParts[0].Length > 4) { shownPart = emailParts[0].Substring(0, 2); } @@ -71,7 +71,7 @@ namespace Bit.Core.Identity } string redactedPart = null; - if(emailParts[0].Length > 4) + if (emailParts[0].Length > 4) { redactedPart = new string('*', emailParts[0].Length - 2); } diff --git a/src/Core/Identity/OrganizationDuoWebTokenProvider.cs b/src/Core/Identity/OrganizationDuoWebTokenProvider.cs index 02b0b99aad..74ecfccd09 100644 --- a/src/Core/Identity/OrganizationDuoWebTokenProvider.cs +++ b/src/Core/Identity/OrganizationDuoWebTokenProvider.cs @@ -19,7 +19,7 @@ namespace Bit.Core.Identity public Task CanGenerateTwoFactorTokenAsync(Organization organization) { - if(organization == null || !organization.Enabled || !organization.Use2fa) + if (organization == null || !organization.Enabled || !organization.Use2fa) { return Task.FromResult(false); } @@ -32,13 +32,13 @@ namespace Bit.Core.Identity public Task GenerateAsync(Organization organization, User user) { - if(organization == null || !organization.Enabled || !organization.Use2fa) + if (organization == null || !organization.Enabled || !organization.Use2fa) { return Task.FromResult(null); } var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return Task.FromResult(null); } @@ -50,13 +50,13 @@ namespace Bit.Core.Identity public Task ValidateAsync(string token, Organization organization, User user) { - if(organization == null || !organization.Enabled || !organization.Use2fa) + if (organization == null || !organization.Enabled || !organization.Use2fa) { return Task.FromResult(false); } var provider = organization.GetTwoFactorProvider(TwoFactorProviderType.OrganizationDuo); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return Task.FromResult(false); } diff --git a/src/Core/Identity/PasswordlessSignInManager.cs b/src/Core/Identity/PasswordlessSignInManager.cs index defcc37dcc..e69e248ea0 100644 --- a/src/Core/Identity/PasswordlessSignInManager.cs +++ b/src/Core/Identity/PasswordlessSignInManager.cs @@ -32,7 +32,7 @@ namespace Bit.Core.Identity public async Task PasswordlessSignInAsync(string email, string returnUrl) { var user = await UserManager.FindByEmailAsync(email); - if(user == null) + if (user == null) { return SignInResult.Failed; } @@ -45,7 +45,7 @@ namespace Bit.Core.Identity public async Task PasswordlessSignInAsync(TUser user, string token, bool isPersistent) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } @@ -58,7 +58,7 @@ namespace Bit.Core.Identity public async Task PasswordlessSignInAsync(string email, string token, bool isPersistent) { var user = await UserManager.FindByEmailAsync(email); - if(user == null) + if (user == null) { return SignInResult.Failed; } @@ -68,18 +68,18 @@ namespace Bit.Core.Identity public virtual async Task CheckPasswordlessSignInAsync(TUser user, string token) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } var error = await PreSignInCheck(user); - if(error != null) + if (error != null) { return error; } - if(await UserManager.VerifyUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, + if (await UserManager.VerifyUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, PasswordlessSignInPurpose, token)) { return SignInResult.Success; diff --git a/src/Core/Identity/ReadOnlyDatabaseIdentityUserStore.cs b/src/Core/Identity/ReadOnlyDatabaseIdentityUserStore.cs index 751477e23a..a4413af767 100644 --- a/src/Core/Identity/ReadOnlyDatabaseIdentityUserStore.cs +++ b/src/Core/Identity/ReadOnlyDatabaseIdentityUserStore.cs @@ -30,7 +30,7 @@ namespace Bit.Core.Identity public override async Task FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) { - if(!Guid.TryParse(userId, out var userIdGuid)) + if (!Guid.TryParse(userId, out var userIdGuid)) { return null; } diff --git a/src/Core/Identity/ReadOnlyEnvIdentityUserStore.cs b/src/Core/Identity/ReadOnlyEnvIdentityUserStore.cs index 827c657ac4..baa7e5c140 100644 --- a/src/Core/Identity/ReadOnlyEnvIdentityUserStore.cs +++ b/src/Core/Identity/ReadOnlyEnvIdentityUserStore.cs @@ -20,17 +20,17 @@ namespace Bit.Core.Identity CancellationToken cancellationToken = default(CancellationToken)) { var usersCsv = _configuration["adminSettings:admins"]; - if(!CoreHelpers.SettingHasValue(usersCsv)) + if (!CoreHelpers.SettingHasValue(usersCsv)) { return Task.FromResult(null); } var users = usersCsv.ToLowerInvariant().Split(','); var usersDict = new Dictionary(); - foreach(var u in users) + foreach (var u in users) { var parts = u.Split(':'); - if(parts.Length == 2) + if (parts.Length == 2) { var email = parts[0].Trim(); var stamp = parts[1].Trim(); @@ -44,7 +44,7 @@ namespace Bit.Core.Identity } var userStamp = usersDict.ContainsKey(normalizedEmail) ? usersDict[normalizedEmail] : null; - if(userStamp == null) + if (userStamp == null) { return Task.FromResult(null); } diff --git a/src/Core/Identity/U2fTokenProvider.cs b/src/Core/Identity/U2fTokenProvider.cs index 70d6872a1f..93162bc742 100644 --- a/src/Core/Identity/U2fTokenProvider.cs +++ b/src/Core/Identity/U2fTokenProvider.cs @@ -36,13 +36,13 @@ namespace Bit.Core.Identity public async Task CanGenerateTwoFactorTokenAsync(UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user))) + if (!(await userService.CanAccessPremium(user))) { return false; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.U2f); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return false; } @@ -53,14 +53,14 @@ namespace Bit.Core.Identity public async Task GenerateAsync(string purpose, UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user))) + if (!(await userService.CanAccessPremium(user))) { return null; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.U2f); var keys = LoadKeys(provider); - if(keys.Count == 0) + if (keys.Count == 0) { return null; } @@ -73,7 +73,7 @@ namespace Bit.Core.Identity var appId = Utilities.CoreHelpers.U2fAppIdUrl(_globalSettings); var oldChallenges = new List(); var challengeKeys = new List(); - foreach(var key in keys) + foreach (var key in keys) { var registration = new DeviceRegistration(key.Item2.KeyHandleBytes, key.Item2.PublicKeyBytes, key.Item2.CertificateBytes, key.Item2.Counter); @@ -115,7 +115,7 @@ namespace Bit.Core.Identity }); return $"{token}|{oldToken}"; } - catch(U2fException) + catch (U2fException) { return null; } @@ -124,14 +124,14 @@ namespace Bit.Core.Identity public async Task ValidateAsync(string purpose, string token, UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user)) || string.IsNullOrWhiteSpace(token)) + if (!(await userService.CanAccessPremium(user)) || string.IsNullOrWhiteSpace(token)) { return false; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.U2f); var keys = LoadKeys(provider); - if(keys.Count == 0) + if (keys.Count == 0) { return false; } @@ -139,13 +139,13 @@ namespace Bit.Core.Identity var authenticateResponse = BaseModel.FromJson(token); var key = keys.FirstOrDefault(f => f.Item2.KeyHandle == authenticateResponse.KeyHandle); - if(key == null) + if (key == null) { return false; } var challenges = await _u2fRepository.GetManyByUserIdAsync(user.Id); - if(challenges.Count == 0) + if (challenges.Count == 0) { return false; } @@ -153,7 +153,7 @@ namespace Bit.Core.Identity // User will have a authentication request for each device they have registered so get the one that matches // the device key handle var challenge = challenges.FirstOrDefault(c => c.KeyHandle == authenticateResponse.KeyHandle); - if(challenge == null) + if (challenge == null) { return false; } @@ -166,7 +166,7 @@ namespace Bit.Core.Identity var auth = new StartedAuthentication(challenge.Challenge, challenge.AppId, challenge.KeyHandle); U2fLib.FinishAuthentication(auth, authenticateResponse, registration); } - catch(U2fException) + catch (U2fException) { success = false; } @@ -174,7 +174,7 @@ namespace Bit.Core.Identity // Update database await _u2fRepository.DeleteManyByUserIdAsync(user.Id); key.Item2.Counter = registration.Counter; - if(key.Item2.Counter > 0) + if (key.Item2.Counter > 0) { key.Item2.Compromised = registration.IsCompromised; } @@ -195,19 +195,19 @@ namespace Bit.Core.Identity private List> LoadKeys(TwoFactorProvider provider) { var keys = new List>(); - if(!HasProperMetaData(provider)) + if (!HasProperMetaData(provider)) { return keys; } // Support up to 5 keys - for(var i = 1; i <= 5; i++) + for (var i = 1; i <= 5; i++) { var keyName = $"Key{i}"; - if(provider.MetaData.ContainsKey(keyName)) + if (provider.MetaData.ContainsKey(keyName)) { var key = new TwoFactorProvider.U2fMetaData((dynamic)provider.MetaData[keyName]); - if(!key?.Compromised ?? false) + if (!key?.Compromised ?? false) { keys.Add(new Tuple(keyName, key)); } diff --git a/src/Core/Identity/UserStore.cs b/src/Core/Identity/UserStore.cs index be0dab2002..354b9c7c81 100644 --- a/src/Core/Identity/UserStore.cs +++ b/src/Core/Identity/UserStore.cs @@ -46,7 +46,7 @@ namespace Bit.Core.Identity public async Task FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken = default(CancellationToken)) { - if(_currentContext?.User != null && _currentContext.User.Email == normalizedEmail) + if (_currentContext?.User != null && _currentContext.User.Email == normalizedEmail) { return _currentContext.User; } @@ -57,14 +57,14 @@ namespace Bit.Core.Identity public async Task FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) { - if(_currentContext?.User != null && + if (_currentContext?.User != null && string.Equals(_currentContext.User.Id.ToString(), userId, StringComparison.InvariantCultureIgnoreCase)) { return _currentContext.User; } Guid userIdGuid; - if(!Guid.TryParse(userId, out userIdGuid)) + if (!Guid.TryParse(userId, out userIdGuid)) { return null; } diff --git a/src/Core/Identity/YubicoOtpTokenProvider.cs b/src/Core/Identity/YubicoOtpTokenProvider.cs index 27a7883401..2aaaf484cb 100644 --- a/src/Core/Identity/YubicoOtpTokenProvider.cs +++ b/src/Core/Identity/YubicoOtpTokenProvider.cs @@ -26,13 +26,13 @@ namespace Bit.Core.Identity public async Task CanGenerateTwoFactorTokenAsync(UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user))) + if (!(await userService.CanAccessPremium(user))) { return false; } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.YubiKey); - if(!provider?.MetaData.Values.Any(v => !string.IsNullOrWhiteSpace((string)v)) ?? true) + if (!provider?.MetaData.Values.Any(v => !string.IsNullOrWhiteSpace((string)v)) ?? true) { return false; } @@ -48,12 +48,12 @@ namespace Bit.Core.Identity public async Task ValidateAsync(string purpose, string token, UserManager manager, User user) { var userService = _serviceProvider.GetRequiredService(); - if(!(await userService.CanAccessPremium(user))) + if (!(await userService.CanAccessPremium(user))) { return false; } - if(string.IsNullOrWhiteSpace(token) || token.Length < 32 || token.Length > 48) + if (string.IsNullOrWhiteSpace(token) || token.Length < 32 || token.Length > 48) { return false; } @@ -61,13 +61,13 @@ namespace Bit.Core.Identity var id = token.Substring(0, 12); var provider = user.GetTwoFactorProvider(TwoFactorProviderType.YubiKey); - if(!provider.MetaData.ContainsValue(id)) + if (!provider.MetaData.ContainsValue(id)) { return false; } var client = new YubicoClient(_globalSettings.Yubico.ClientId, _globalSettings.Yubico.Key); - if(_globalSettings.Yubico.ValidationUrls != null && _globalSettings.Yubico.ValidationUrls.Length > 0) + if (_globalSettings.Yubico.ValidationUrls != null && _globalSettings.Yubico.ValidationUrls.Length > 0) { client.SetUrls(_globalSettings.Yubico.ValidationUrls); } diff --git a/src/Core/IdentityServer/ClientStore.cs b/src/Core/IdentityServer/ClientStore.cs index 5b7895ccfa..6d596ebb16 100644 --- a/src/Core/IdentityServer/ClientStore.cs +++ b/src/Core/IdentityServer/ClientStore.cs @@ -30,13 +30,13 @@ namespace Bit.Core.IdentityServer public async Task FindClientByIdAsync(string clientId) { - if(!_globalSettings.SelfHosted && clientId.StartsWith("installation.")) + if (!_globalSettings.SelfHosted && clientId.StartsWith("installation.")) { var idParts = clientId.Split('.'); - if(idParts.Length > 1 && Guid.TryParse(idParts[1], out Guid id)) + if (idParts.Length > 1 && Guid.TryParse(idParts[1], out Guid id)) { var installation = await _installationRepository.GetByIdAsync(id); - if(installation != null) + if (installation != null) { return new Client { @@ -52,14 +52,14 @@ namespace Bit.Core.IdentityServer } } } - else if(_globalSettings.SelfHosted && clientId.StartsWith("internal.") && + else if (_globalSettings.SelfHosted && clientId.StartsWith("internal.") && CoreHelpers.SettingHasValue(_globalSettings.InternalIdentityKey)) { var idParts = clientId.Split('.'); - if(idParts.Length > 1) + if (idParts.Length > 1) { var id = idParts[1]; - if(!string.IsNullOrWhiteSpace(id)) + if (!string.IsNullOrWhiteSpace(id)) { return new Client { @@ -75,13 +75,13 @@ namespace Bit.Core.IdentityServer } } } - else if(clientId.StartsWith("organization.")) + else if (clientId.StartsWith("organization.")) { var idParts = clientId.Split('.'); - if(idParts.Length > 1 && Guid.TryParse(idParts[1], out var id)) + if (idParts.Length > 1 && Guid.TryParse(idParts[1], out var id)) { var org = await _organizationRepository.GetByIdAsync(id); - if(org != null) + if (org != null) { return new Client { diff --git a/src/Core/IdentityServer/PersistedGrantStore.cs b/src/Core/IdentityServer/PersistedGrantStore.cs index c3e97aadc0..20768f40cb 100644 --- a/src/Core/IdentityServer/PersistedGrantStore.cs +++ b/src/Core/IdentityServer/PersistedGrantStore.cs @@ -29,7 +29,7 @@ namespace Bit.Core.IdentityServer public async Task GetAsync(string key) { var grant = await _grantRepository.GetByKeyAsync(key); - if(grant == null) + if (grant == null) { return null; } diff --git a/src/Core/IdentityServer/ProfileService.cs b/src/Core/IdentityServer/ProfileService.cs index ad9589cbe0..3801414b5a 100644 --- a/src/Core/IdentityServer/ProfileService.cs +++ b/src/Core/IdentityServer/ProfileService.cs @@ -39,7 +39,7 @@ namespace Bit.Core.IdentityServer var newClaims = new List(); var user = await _userService.GetUserByPrincipalAsync(context.Subject); - if(user != null) + if (user != null) { var isPremium = await _licensingService.ValidateUserPremiumAsync(user); newClaims.AddRange(new List @@ -50,39 +50,39 @@ namespace Bit.Core.IdentityServer new Claim("sstamp", user.SecurityStamp) }); - if(!string.IsNullOrWhiteSpace(user.Name)) + if (!string.IsNullOrWhiteSpace(user.Name)) { newClaims.Add(new Claim(JwtClaimTypes.Name, user.Name)); } // Orgs that this user belongs to var orgs = await _currentContext.OrganizationMembershipAsync(_organizationUserRepository, user.Id); - if(orgs.Any()) + if (orgs.Any()) { - foreach(var group in orgs.GroupBy(o => o.Type)) + foreach (var group in orgs.GroupBy(o => o.Type)) { - switch(group.Key) + switch (group.Key) { case Enums.OrganizationUserType.Owner: - foreach(var org in group) + foreach (var org in group) { newClaims.Add(new Claim("orgowner", org.Id.ToString())); } break; case Enums.OrganizationUserType.Admin: - foreach(var org in group) + foreach (var org in group) { newClaims.Add(new Claim("orgadmin", org.Id.ToString())); } break; case Enums.OrganizationUserType.Manager: - foreach(var org in group) + foreach (var org in group) { newClaims.Add(new Claim("orgmanager", org.Id.ToString())); } break; case Enums.OrganizationUserType.User: - foreach(var org in group) + foreach (var org in group) { newClaims.Add(new Claim("orguser", org.Id.ToString())); } @@ -100,7 +100,7 @@ namespace Bit.Core.IdentityServer .ToList(); newClaims.AddRange(existingClaimsToKeep); - if(newClaims.Any()) + if (newClaims.Any()) { context.AddRequestedClaims(newClaims); } @@ -111,7 +111,7 @@ namespace Bit.Core.IdentityServer var securityTokenClaim = context.Subject?.Claims.FirstOrDefault(c => c.Type == "sstamp"); var user = await _userService.GetUserByPrincipalAsync(context.Subject); - if(user != null && securityTokenClaim != null) + if (user != null && securityTokenClaim != null) { context.IsActive = string.Equals(user.SecurityStamp, securityTokenClaim.Value, StringComparison.InvariantCultureIgnoreCase); diff --git a/src/Core/IdentityServer/ResourceOwnerPasswordValidator.cs b/src/Core/IdentityServer/ResourceOwnerPasswordValidator.cs index 1b8667eeaa..53aa2cb756 100644 --- a/src/Core/IdentityServer/ResourceOwnerPasswordValidator.cs +++ b/src/Core/IdentityServer/ResourceOwnerPasswordValidator.cs @@ -75,24 +75,24 @@ namespace Bit.Core.IdentityServer var twoFactorRequest = !string.IsNullOrWhiteSpace(twoFactorToken) && !string.IsNullOrWhiteSpace(twoFactorProvider); - if(string.IsNullOrWhiteSpace(context.UserName)) + if (string.IsNullOrWhiteSpace(context.UserName)) { await BuildErrorResultAsync(false, context, null); return; } var user = await _userManager.FindByEmailAsync(context.UserName.ToLowerInvariant()); - if(user == null || !await _userService.CheckPasswordAsync(user, context.Password)) + if (user == null || !await _userService.CheckPasswordAsync(user, context.Password)) { await BuildErrorResultAsync(false, context, user); return; } var twoFactorRequirement = await RequiresTwoFactorAsync(user); - if(twoFactorRequirement.Item1) + if (twoFactorRequirement.Item1) { var twoFactorProviderType = TwoFactorProviderType.Authenticator; // Just defaulting it - if(!twoFactorRequest || !Enum.TryParse(twoFactorProvider, out twoFactorProviderType)) + if (!twoFactorRequest || !Enum.TryParse(twoFactorProvider, out twoFactorProviderType)) { await BuildTwoFactorResultAsync(user, twoFactorRequirement.Item2, context); return; @@ -100,12 +100,12 @@ namespace Bit.Core.IdentityServer var verified = await VerifyTwoFactor(user, twoFactorRequirement.Item2, twoFactorProviderType, twoFactorToken); - if(!verified && twoFactorProviderType != TwoFactorProviderType.Remember) + if (!verified && twoFactorProviderType != TwoFactorProviderType.Remember) { await BuildErrorResultAsync(true, context, user); return; } - else if(!verified && twoFactorProviderType == TwoFactorProviderType.Remember) + else if (!verified && twoFactorProviderType == TwoFactorProviderType.Remember) { await Task.Delay(2000); // Delay for brute force. await BuildTwoFactorResultAsync(user, twoFactorRequirement.Item2, context); @@ -131,23 +131,23 @@ namespace Bit.Core.IdentityServer var claims = new List(); - if(device != null) + if (device != null) { claims.Add(new Claim("device", device.Identifier)); } var customResponse = new Dictionary(); - if(!string.IsNullOrWhiteSpace(user.PrivateKey)) + if (!string.IsNullOrWhiteSpace(user.PrivateKey)) { customResponse.Add("PrivateKey", user.PrivateKey); } - if(!string.IsNullOrWhiteSpace(user.Key)) + if (!string.IsNullOrWhiteSpace(user.Key)) { customResponse.Add("Key", user.Key); } - if(sendRememberToken) + if (sendRememberToken) { var token = await _userManager.GenerateTwoFactorTokenAsync(user, CoreHelpers.CustomProviderName(TwoFactorProviderType.Remember)); @@ -167,30 +167,30 @@ namespace Bit.Core.IdentityServer var providers = new Dictionary>(); var enabledProviders = new List>(); - if(organization?.GetTwoFactorProviders() != null) + if (organization?.GetTwoFactorProviders() != null) { enabledProviders.AddRange(organization.GetTwoFactorProviders().Where( p => organization.TwoFactorProviderIsEnabled(p.Key))); } - if(user.GetTwoFactorProviders() != null) + if (user.GetTwoFactorProviders() != null) { - foreach(var p in user.GetTwoFactorProviders()) + foreach (var p in user.GetTwoFactorProviders()) { - if(await _userService.TwoFactorProviderIsEnabledAsync(p.Key, user)) + if (await _userService.TwoFactorProviderIsEnabledAsync(p.Key, user)) { enabledProviders.Add(p); } } } - if(!enabledProviders.Any()) + if (!enabledProviders.Any()) { await BuildErrorResultAsync(false, context, user); return; } - foreach(var provider in enabledProviders) + foreach (var provider in enabledProviders) { providerKeys.Add((byte)provider.Key); var infoDict = await BuildTwoFactorParams(organization, user, provider.Key, provider.Value); @@ -204,7 +204,7 @@ namespace Bit.Core.IdentityServer { "TwoFactorProviders2", providers } }); - if(enabledProviders.Count() == 1 && enabledProviders.First().Key == TwoFactorProviderType.Email) + if (enabledProviders.Count() == 1 && enabledProviders.First().Key == TwoFactorProviderType.Email) { // Send email now if this is their only 2FA method await _userService.SendTwoFactorEmailAsync(user); @@ -214,13 +214,13 @@ namespace Bit.Core.IdentityServer private async Task BuildErrorResultAsync(bool twoFactorRequest, ResourceOwnerPasswordValidationContext context, User user) { - if(user != null) + if (user != null) { await _eventService.LogUserEventAsync(user.Id, twoFactorRequest ? EventType.User_FailedLogIn2fa : EventType.User_FailedLogIn); } - if(_globalSettings.SelfHosted) + if (_globalSettings.SelfHosted) { _logger.LogWarning(Constants.BypassFiltersEventId, string.Format("Failed login attempt{0}{1}", twoFactorRequest ? ", 2FA invalid." : ".", @@ -244,11 +244,11 @@ namespace Bit.Core.IdentityServer Organization firstEnabledOrg = null; var orgs = (await _currentContext.OrganizationMembershipAsync(_organizationUserRepository, user.Id)) .ToList(); - if(orgs.Any()) + if (orgs.Any()) { var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); var twoFactorOrgs = orgs.Where(o => OrgUsing2fa(orgAbilities, o.Id)); - if(twoFactorOrgs.Any()) + if (twoFactorOrgs.Any()) { var userOrgs = await _organizationRepository.GetManyByUserIdAsync(user.Id); firstEnabledOrg = userOrgs.FirstOrDefault( @@ -272,7 +272,7 @@ namespace Bit.Core.IdentityServer var deviceName = context.Request.Raw["DeviceName"]?.ToString(); var devicePushToken = context.Request.Raw["DevicePushToken"]?.ToString(); - if(string.IsNullOrWhiteSpace(deviceIdentifier) || string.IsNullOrWhiteSpace(deviceType) || + if (string.IsNullOrWhiteSpace(deviceIdentifier) || string.IsNullOrWhiteSpace(deviceType) || string.IsNullOrWhiteSpace(deviceName) || !Enum.TryParse(deviceType, out DeviceType type)) { return null; @@ -290,7 +290,7 @@ namespace Bit.Core.IdentityServer private async Task VerifyTwoFactor(User user, Organization organization, TwoFactorProviderType type, string token) { - switch(type) + switch (type) { case TwoFactorProviderType.Authenticator: case TwoFactorProviderType.Email: @@ -298,7 +298,7 @@ namespace Bit.Core.IdentityServer case TwoFactorProviderType.YubiKey: case TwoFactorProviderType.U2f: case TwoFactorProviderType.Remember: - if(type != TwoFactorProviderType.Remember && + if (type != TwoFactorProviderType.Remember && !(await _userService.TwoFactorProviderIsEnabledAsync(type, user))) { return false; @@ -306,7 +306,7 @@ namespace Bit.Core.IdentityServer return await _userManager.VerifyTwoFactorTokenAsync(user, CoreHelpers.CustomProviderName(type), token); case TwoFactorProviderType.OrganizationDuo: - if(!organization?.TwoFactorProviderIsEnabled(type) ?? true) + if (!organization?.TwoFactorProviderIsEnabled(type) ?? true) { return false; } @@ -320,20 +320,20 @@ namespace Bit.Core.IdentityServer private async Task> BuildTwoFactorParams(Organization organization, User user, TwoFactorProviderType type, TwoFactorProvider provider) { - switch(type) + switch (type) { case TwoFactorProviderType.Duo: case TwoFactorProviderType.U2f: case TwoFactorProviderType.Email: case TwoFactorProviderType.YubiKey: - if(!(await _userService.TwoFactorProviderIsEnabledAsync(type, user))) + if (!(await _userService.TwoFactorProviderIsEnabledAsync(type, user))) { return null; } var token = await _userManager.GenerateTwoFactorTokenAsync(user, CoreHelpers.CustomProviderName(type)); - if(type == TwoFactorProviderType.Duo) + if (type == TwoFactorProviderType.Duo) { return new Dictionary { @@ -341,7 +341,7 @@ namespace Bit.Core.IdentityServer ["Signature"] = token }; } - else if(type == TwoFactorProviderType.U2f) + else if (type == TwoFactorProviderType.U2f) { // TODO: Remove "Challenges" in a future update. Deprecated. var tokens = token?.Split('|'); @@ -351,14 +351,14 @@ namespace Bit.Core.IdentityServer ["Challenges"] = tokens != null && tokens.Length > 1 ? tokens[1] : null }; } - else if(type == TwoFactorProviderType.Email) + else if (type == TwoFactorProviderType.Email) { return new Dictionary { ["Email"] = token }; } - else if(type == TwoFactorProviderType.YubiKey) + else if (type == TwoFactorProviderType.YubiKey) { return new Dictionary { @@ -367,7 +367,7 @@ namespace Bit.Core.IdentityServer } return null; case TwoFactorProviderType.OrganizationDuo: - if(await _organizationDuoWebTokenProvider.CanGenerateTwoFactorTokenAsync(organization)) + if (await _organizationDuoWebTokenProvider.CanGenerateTwoFactorTokenAsync(organization)) { return new Dictionary { @@ -384,20 +384,20 @@ namespace Bit.Core.IdentityServer private async Task SaveDeviceAsync(User user, ResourceOwnerPasswordValidationContext context) { var device = GetDeviceFromRequest(context); - if(device != null) + if (device != null) { var existingDevice = await _deviceRepository.GetByIdentifierAsync(device.Identifier, user.Id); - if(existingDevice == null) + if (existingDevice == null) { device.UserId = user.Id; await _deviceService.SaveAsync(device); var now = DateTime.UtcNow; - if(now - user.CreationDate > TimeSpan.FromMinutes(10)) + if (now - user.CreationDate > TimeSpan.FromMinutes(10)) { var deviceType = device.Type.GetType().GetMember(device.Type.ToString()) .FirstOrDefault()?.GetCustomAttribute()?.GetName(); - if(!_globalSettings.DisableEmailNewDevice) + if (!_globalSettings.DisableEmailNewDevice) { await _mailService.SendNewDeviceLoggedInEmail(user.Email, deviceType, now, _currentContext.IpAddress); diff --git a/src/Core/IdentityServer/StaticClients.cs b/src/Core/IdentityServer/StaticClients.cs index 77701cdc07..81f7e895aa 100644 --- a/src/Core/IdentityServer/StaticClients.cs +++ b/src/Core/IdentityServer/StaticClients.cs @@ -38,7 +38,7 @@ namespace Bit.Core.IdentityServer AccessTokenLifetime = 3600 * accessTokenLifetimeHours; AllowOfflineAccess = true; - if(scopes == null) + if (scopes == null) { scopes = new string[] { "api" }; } diff --git a/src/Core/IdentityServer/TokenRetrieval.cs b/src/Core/IdentityServer/TokenRetrieval.cs index 8d82d28019..137162e79a 100644 --- a/src/Core/IdentityServer/TokenRetrieval.cs +++ b/src/Core/IdentityServer/TokenRetrieval.cs @@ -15,12 +15,12 @@ namespace Bit.Core.IdentityServer return (request) => { var authorization = request.Headers[_authHeader].FirstOrDefault(); - if(string.IsNullOrWhiteSpace(authorization)) + if (string.IsNullOrWhiteSpace(authorization)) { return request.Query[_queuryScheme].FirstOrDefault(); } - if(authorization.StartsWith(_headerScheme, StringComparison.OrdinalIgnoreCase)) + if (authorization.StartsWith(_headerScheme, StringComparison.OrdinalIgnoreCase)) { return authorization.Substring(_headerScheme.Length).Trim(); } diff --git a/src/Core/Jobs/BaseJob.cs b/src/Core/Jobs/BaseJob.cs index 0e4b206d40..2e198dfb29 100644 --- a/src/Core/Jobs/BaseJob.cs +++ b/src/Core/Jobs/BaseJob.cs @@ -20,7 +20,7 @@ namespace Bit.Core.Jobs { await ExecuteJobAsync(context); } - catch(Exception e) + catch (Exception e) { _logger.LogError(2, e, "Error performing {0}.", GetType().Name); } diff --git a/src/Core/Jobs/BaseJobsHostedService.cs b/src/Core/Jobs/BaseJobsHostedService.cs index 65c117d65d..18c2aed359 100644 --- a/src/Core/Jobs/BaseJobsHostedService.cs +++ b/src/Core/Jobs/BaseJobsHostedService.cs @@ -42,9 +42,9 @@ namespace Bit.Core.Jobs _scheduler.ListenerManager.AddJobListener(new JobListener(_listenerLogger), GroupMatcher.AnyGroup()); await _scheduler.Start(cancellationToken); - if(Jobs != null) + if (Jobs != null) { - foreach(var job in Jobs) + foreach (var job in Jobs) { var builtJob = JobBuilder.Create(job.Item1).Build(); await _scheduler.ScheduleJob(builtJob, job.Item2); diff --git a/src/Core/Models/Api/CipherLoginModel.cs b/src/Core/Models/Api/CipherLoginModel.cs index c50b4ea7a3..0e257395b6 100644 --- a/src/Core/Models/Api/CipherLoginModel.cs +++ b/src/Core/Models/Api/CipherLoginModel.cs @@ -15,7 +15,7 @@ namespace Bit.Core.Models.Api public CipherLoginModel(CipherLoginData data) { Uris = data.Uris?.Select(u => new CipherLoginUriModel(u))?.ToList(); - if(!Uris?.Any() ?? true) + if (!Uris?.Any() ?? true) { Uri = data.Uri; } @@ -33,12 +33,12 @@ namespace Bit.Core.Models.Api get => Uris?.FirstOrDefault()?.Uri; set { - if(string.IsNullOrWhiteSpace(value)) + if (string.IsNullOrWhiteSpace(value)) { return; } - if(Uris == null) + if (Uris == null) { Uris = new List(); } diff --git a/src/Core/Models/Api/Public/MemberBaseModel.cs b/src/Core/Models/Api/Public/MemberBaseModel.cs index 63bb46ea28..3786d0bd1b 100644 --- a/src/Core/Models/Api/Public/MemberBaseModel.cs +++ b/src/Core/Models/Api/Public/MemberBaseModel.cs @@ -12,7 +12,7 @@ namespace Bit.Core.Models.Api.Public public MemberBaseModel(OrganizationUser user) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } @@ -24,7 +24,7 @@ namespace Bit.Core.Models.Api.Public public MemberBaseModel(OrganizationUserUserDetails user) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } diff --git a/src/Core/Models/Api/Public/Request/EventFilterRequestModel.cs b/src/Core/Models/Api/Public/Request/EventFilterRequestModel.cs index 5d1f724568..c7a99d1d11 100644 --- a/src/Core/Models/Api/Public/Request/EventFilterRequestModel.cs +++ b/src/Core/Models/Api/Public/Request/EventFilterRequestModel.cs @@ -28,19 +28,19 @@ namespace Bit.Core.Models.Api.Public public Tuple ToDateRange() { - if(!End.HasValue || !Start.HasValue) + if (!End.HasValue || !Start.HasValue) { End = DateTime.UtcNow.Date.AddDays(1).AddMilliseconds(-1); Start = DateTime.UtcNow.Date.AddDays(-30); } - else if(Start.Value > End.Value) + else if (Start.Value > End.Value) { var newEnd = Start; Start = End; End = newEnd; } - if((End.Value - Start.Value) > TimeSpan.FromDays(367)) + if ((End.Value - Start.Value) > TimeSpan.FromDays(367)) { throw new BadRequestException("Date range must be < 367 days."); } diff --git a/src/Core/Models/Api/Public/Request/MemberCreateRequestModel.cs b/src/Core/Models/Api/Public/Request/MemberCreateRequestModel.cs index edc1bc3ab8..5ebd3f8664 100644 --- a/src/Core/Models/Api/Public/Request/MemberCreateRequestModel.cs +++ b/src/Core/Models/Api/Public/Request/MemberCreateRequestModel.cs @@ -22,12 +22,12 @@ namespace Bit.Core.Models.Api.Public public IEnumerable Validate(ValidationContext validationContext) { - if(Email.Contains(" ") || Email.Contains("<")) + if (Email.Contains(" ") || Email.Contains("<")) { yield return new ValidationResult($"Email is not valid.", new string[] { nameof(Email) }); } - else if(Email.Length > 50) + else if (Email.Length > 50) { yield return new ValidationResult($"Email is longer than 50 characters.", new string[] { nameof(Email) }); diff --git a/src/Core/Models/Api/Public/Response/AssociationWithPermissionsResponseModel.cs b/src/Core/Models/Api/Public/Response/AssociationWithPermissionsResponseModel.cs index 027cd257dc..635439a07e 100644 --- a/src/Core/Models/Api/Public/Response/AssociationWithPermissionsResponseModel.cs +++ b/src/Core/Models/Api/Public/Response/AssociationWithPermissionsResponseModel.cs @@ -7,7 +7,7 @@ namespace Bit.Core.Models.Api.Public { public AssociationWithPermissionsResponseModel(SelectionReadOnly selection) { - if(selection == null) + if (selection == null) { throw new ArgumentNullException(nameof(selection)); } diff --git a/src/Core/Models/Api/Public/Response/CollectionResponseModel.cs b/src/Core/Models/Api/Public/Response/CollectionResponseModel.cs index 690ac11d64..e66270367f 100644 --- a/src/Core/Models/Api/Public/Response/CollectionResponseModel.cs +++ b/src/Core/Models/Api/Public/Response/CollectionResponseModel.cs @@ -14,7 +14,7 @@ namespace Bit.Core.Models.Api.Public { public CollectionResponseModel(Collection collection, IEnumerable groups) { - if(collection == null) + if (collection == null) { throw new ArgumentNullException(nameof(collection)); } diff --git a/src/Core/Models/Api/Public/Response/ErrorResponseModel.cs b/src/Core/Models/Api/Public/Response/ErrorResponseModel.cs index 5f6234068d..e9edf13911 100644 --- a/src/Core/Models/Api/Public/Response/ErrorResponseModel.cs +++ b/src/Core/Models/Api/Public/Response/ErrorResponseModel.cs @@ -20,17 +20,17 @@ namespace Bit.Core.Models.Api.Public var keys = modelState.Keys.ToList(); var values = modelState.Values.ToList(); - for(var i = 0; i < values.Count; i++) + for (var i = 0; i < values.Count; i++) { var value = values[i]; - if(keys.Count <= i) + if (keys.Count <= i) { // Keys not available for some reason. break; } var key = keys[i]; - if(value.ValidationState != ModelValidationState.Invalid || value.Errors.Count == 0) + if (value.ValidationState != ModelValidationState.Invalid || value.Errors.Count == 0) { continue; } diff --git a/src/Core/Models/Api/Public/Response/EventResponseModel.cs b/src/Core/Models/Api/Public/Response/EventResponseModel.cs index 8d3ba5b33d..887e6cc075 100644 --- a/src/Core/Models/Api/Public/Response/EventResponseModel.cs +++ b/src/Core/Models/Api/Public/Response/EventResponseModel.cs @@ -12,7 +12,7 @@ namespace Bit.Core.Models.Api.Public { public EventResponseModel(IEvent ev) { - if(ev == null) + if (ev == null) { throw new ArgumentNullException(nameof(ev)); } diff --git a/src/Core/Models/Api/Public/Response/GroupResponseModel.cs b/src/Core/Models/Api/Public/Response/GroupResponseModel.cs index 2be85fb455..f3808c4a73 100644 --- a/src/Core/Models/Api/Public/Response/GroupResponseModel.cs +++ b/src/Core/Models/Api/Public/Response/GroupResponseModel.cs @@ -14,7 +14,7 @@ namespace Bit.Core.Models.Api.Public { public GroupResponseModel(Group group, IEnumerable collections) { - if(group == null) + if (group == null) { throw new ArgumentNullException(nameof(group)); } diff --git a/src/Core/Models/Api/Public/Response/MemberResponseModel.cs b/src/Core/Models/Api/Public/Response/MemberResponseModel.cs index d158b81c14..3cfbca75e3 100644 --- a/src/Core/Models/Api/Public/Response/MemberResponseModel.cs +++ b/src/Core/Models/Api/Public/Response/MemberResponseModel.cs @@ -16,7 +16,7 @@ namespace Bit.Core.Models.Api.Public public MemberResponseModel(OrganizationUser user, IEnumerable collections) : base(user) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } @@ -32,7 +32,7 @@ namespace Bit.Core.Models.Api.Public IEnumerable collections) : base(user) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } diff --git a/src/Core/Models/Api/Public/Response/PolicyResponseModel.cs b/src/Core/Models/Api/Public/Response/PolicyResponseModel.cs index b849f1a790..0321c52b4e 100644 --- a/src/Core/Models/Api/Public/Response/PolicyResponseModel.cs +++ b/src/Core/Models/Api/Public/Response/PolicyResponseModel.cs @@ -13,7 +13,7 @@ namespace Bit.Core.Models.Api.Public { public PolicyResponseModel(Policy policy) { - if(policy == null) + if (policy == null) { throw new ArgumentNullException(nameof(policy)); } @@ -21,7 +21,7 @@ namespace Bit.Core.Models.Api.Public Id = policy.Id; Type = policy.Type; Enabled = policy.Enabled; - if(!string.IsNullOrWhiteSpace(policy.Data)) + if (!string.IsNullOrWhiteSpace(policy.Data)) { Data = JsonConvert.DeserializeObject>(policy.Data); } diff --git a/src/Core/Models/Api/Request/Accounts/KdfRequestModel.cs b/src/Core/Models/Api/Request/Accounts/KdfRequestModel.cs index ae9591b955..aa68b2c0f9 100644 --- a/src/Core/Models/Api/Request/Accounts/KdfRequestModel.cs +++ b/src/Core/Models/Api/Request/Accounts/KdfRequestModel.cs @@ -14,12 +14,12 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(Kdf.HasValue && KdfIterations.HasValue) + if (Kdf.HasValue && KdfIterations.HasValue) { - switch(Kdf.Value) + switch (Kdf.Value) { case KdfType.PBKDF2_SHA256: - if(KdfIterations.Value < 5000 || KdfIterations.Value > 2_000_000) + if (KdfIterations.Value < 5000 || KdfIterations.Value > 2_000_000) { yield return new ValidationResult("KDF iterations must be between 5000 and 2000000."); } diff --git a/src/Core/Models/Api/Request/Accounts/KeysRequestModel.cs b/src/Core/Models/Api/Request/Accounts/KeysRequestModel.cs index b6fb5f7a09..0e69d389b7 100644 --- a/src/Core/Models/Api/Request/Accounts/KeysRequestModel.cs +++ b/src/Core/Models/Api/Request/Accounts/KeysRequestModel.cs @@ -11,12 +11,12 @@ namespace Bit.Core.Models.Api public User ToUser(User existingUser) { - if(string.IsNullOrWhiteSpace(existingUser.PublicKey) && !string.IsNullOrWhiteSpace(PublicKey)) + if (string.IsNullOrWhiteSpace(existingUser.PublicKey) && !string.IsNullOrWhiteSpace(PublicKey)) { existingUser.PublicKey = PublicKey; } - if(string.IsNullOrWhiteSpace(existingUser.PrivateKey)) + if (string.IsNullOrWhiteSpace(existingUser.PrivateKey)) { existingUser.PrivateKey = EncryptedPrivateKey; } diff --git a/src/Core/Models/Api/Request/Accounts/PremiumRequestModel.cs b/src/Core/Models/Api/Request/Accounts/PremiumRequestModel.cs index 0a755383ac..8fd4c6329d 100644 --- a/src/Core/Models/Api/Request/Accounts/PremiumRequestModel.cs +++ b/src/Core/Models/Api/Request/Accounts/PremiumRequestModel.cs @@ -23,7 +23,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { var creditType = PaymentMethodType.HasValue && PaymentMethodType.Value == Enums.PaymentMethodType.Credit; - if(string.IsNullOrWhiteSpace(PaymentToken) && !creditType && License == null) + if (string.IsNullOrWhiteSpace(PaymentToken) && !creditType && License == null) { yield return new ValidationResult("Payment token or license is required."); } diff --git a/src/Core/Models/Api/Request/Accounts/RegisterRequestModel.cs b/src/Core/Models/Api/Request/Accounts/RegisterRequestModel.cs index 193a9ba683..21e93754dd 100644 --- a/src/Core/Models/Api/Request/Accounts/RegisterRequestModel.cs +++ b/src/Core/Models/Api/Request/Accounts/RegisterRequestModel.cs @@ -37,12 +37,12 @@ namespace Bit.Core.Models.Api KdfIterations = KdfIterations.GetValueOrDefault(5000) }; - if(Key != null) + if (Key != null) { user.Key = Key; } - if(Keys != null) + if (Keys != null) { Keys.ToUser(user); } @@ -52,12 +52,12 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(Kdf.HasValue && KdfIterations.HasValue) + if (Kdf.HasValue && KdfIterations.HasValue) { - switch(Kdf.Value) + switch (Kdf.Value) { case KdfType.PBKDF2_SHA256: - if(KdfIterations.Value < 5000 || KdfIterations.Value > 1_000_000) + if (KdfIterations.Value < 5000 || KdfIterations.Value > 1_000_000) { yield return new ValidationResult("KDF iterations must be between 5000 and 1000000."); } diff --git a/src/Core/Models/Api/Request/Accounts/StorageRequestModel.cs b/src/Core/Models/Api/Request/Accounts/StorageRequestModel.cs index 5d72f7d9e4..dd17f78197 100644 --- a/src/Core/Models/Api/Request/Accounts/StorageRequestModel.cs +++ b/src/Core/Models/Api/Request/Accounts/StorageRequestModel.cs @@ -10,7 +10,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(StorageGbAdjustment == 0) + if (StorageGbAdjustment == 0) { yield return new ValidationResult("Storage adjustment cannot be 0.", new string[] { nameof(StorageGbAdjustment) }); diff --git a/src/Core/Models/Api/Request/BitPayInvoiceRequestModel.cs b/src/Core/Models/Api/Request/BitPayInvoiceRequestModel.cs index ec53ab6ef7..8587e3871e 100644 --- a/src/Core/Models/Api/Request/BitPayInvoiceRequestModel.cs +++ b/src/Core/Models/Api/Request/BitPayInvoiceRequestModel.cs @@ -33,16 +33,16 @@ namespace Bit.Core.Models.Api }; var posData = string.Empty; - if(UserId.HasValue) + if (UserId.HasValue) { posData = "userId:" + UserId.Value; } - else if(OrganizationId.HasValue) + else if (OrganizationId.HasValue) { posData = "organizationId:" + OrganizationId.Value; } - if(Credit) + if (Credit) { posData += ",accountCredit:1"; inv.ItemDesc = "Bitwarden Account Credit"; @@ -58,7 +58,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(!UserId.HasValue && !OrganizationId.HasValue) + if (!UserId.HasValue && !OrganizationId.HasValue) { yield return new ValidationResult("User or Ooganization is required."); } diff --git a/src/Core/Models/Api/Request/CipherRequestModel.cs b/src/Core/Models/Api/Request/CipherRequestModel.cs index 7b041073ce..6958334c2b 100644 --- a/src/Core/Models/Api/Request/CipherRequestModel.cs +++ b/src/Core/Models/Api/Request/CipherRequestModel.cs @@ -63,7 +63,7 @@ namespace Bit.Core.Models.Api public Cipher ToCipher(Cipher existingCipher) { - switch(existingCipher.Type) + switch (existingCipher.Type) { case CipherType.Login: var loginObj = JObject.FromObject(new CipherLoginData(this), @@ -90,29 +90,29 @@ namespace Bit.Core.Models.Api var hasAttachments2 = (Attachments2?.Count ?? 0) > 0; var hasAttachments = (Attachments?.Count ?? 0) > 0; - if(!hasAttachments2 && !hasAttachments) + if (!hasAttachments2 && !hasAttachments) { return existingCipher; } var attachments = existingCipher.GetAttachments(); - if((attachments?.Count ?? 0) == 0) + if ((attachments?.Count ?? 0) == 0) { return existingCipher; } - if(hasAttachments2) + if (hasAttachments2) { - foreach(var attachment in attachments.Where(a => Attachments2.ContainsKey(a.Key))) + foreach (var attachment in attachments.Where(a => Attachments2.ContainsKey(a.Key))) { var attachment2 = Attachments2[attachment.Key]; attachment.Value.FileName = attachment2.FileName; attachment.Value.Key = attachment2.Key; } } - else if(hasAttachments) + else if (hasAttachments) { - foreach(var attachment in attachments.Where(a => Attachments.ContainsKey(a.Key))) + foreach (var attachment in attachments.Where(a => Attachments.ContainsKey(a.Key))) { attachment.Value.FileName = Attachments[attachment.Key]; attachment.Value.Key = null; @@ -125,7 +125,7 @@ namespace Bit.Core.Models.Api public Cipher ToOrganizationCipher() { - if(string.IsNullOrWhiteSpace(OrganizationId)) + if (string.IsNullOrWhiteSpace(OrganizationId)) { throw new ArgumentNullException(nameof(OrganizationId)); } @@ -162,7 +162,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(!string.IsNullOrWhiteSpace(Cipher.OrganizationId) && (!CollectionIds?.Any() ?? true)) + if (!string.IsNullOrWhiteSpace(Cipher.OrganizationId) && (!CollectionIds?.Any() ?? true)) { yield return new ValidationResult("You must select at least one collection.", new string[] { nameof(CollectionIds) }); @@ -179,13 +179,13 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(string.IsNullOrWhiteSpace(Cipher.OrganizationId)) + if (string.IsNullOrWhiteSpace(Cipher.OrganizationId)) { yield return new ValidationResult("Cipher OrganizationId is required.", new string[] { nameof(Cipher.OrganizationId) }); } - if(!CollectionIds?.Any() ?? true) + if (!CollectionIds?.Any() ?? true) { yield return new ValidationResult("You must select at least one collection.", new string[] { nameof(CollectionIds) }); @@ -221,7 +221,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(!Ciphers?.Any() ?? true) + if (!Ciphers?.Any() ?? true) { yield return new ValidationResult("You must select at least one cipher.", new string[] { nameof(Ciphers) }); @@ -230,27 +230,27 @@ namespace Bit.Core.Models.Api { var allHaveIds = true; var organizationIds = new HashSet(); - foreach(var c in Ciphers) + foreach (var c in Ciphers) { organizationIds.Add(c.OrganizationId); - if(allHaveIds) + if (allHaveIds) { allHaveIds = !(!c.Id.HasValue || string.IsNullOrWhiteSpace(c.OrganizationId)); } } - if(!allHaveIds) + if (!allHaveIds) { yield return new ValidationResult("All Ciphers must have an Id and OrganizationId.", new string[] { nameof(Ciphers) }); } - else if(organizationIds.Count != 1) + else if (organizationIds.Count != 1) { yield return new ValidationResult("All ciphers must be for the same organization."); } } - if(!CollectionIds?.Any() ?? true) + if (!CollectionIds?.Any() ?? true) { yield return new ValidationResult("You must select at least one collection.", new string[] { nameof(CollectionIds) }); diff --git a/src/Core/Models/Api/Request/IapCheckRequestModel.cs b/src/Core/Models/Api/Request/IapCheckRequestModel.cs index c96a02486c..c1bc80dcdb 100644 --- a/src/Core/Models/Api/Request/IapCheckRequestModel.cs +++ b/src/Core/Models/Api/Request/IapCheckRequestModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(PaymentMethodType != Enums.PaymentMethodType.AppleInApp) + if (PaymentMethodType != Enums.PaymentMethodType.AppleInApp) { yield return new ValidationResult("Not a supported in-app purchase payment method.", new string[] { nameof(PaymentMethodType) }); diff --git a/src/Core/Models/Api/Request/Organizations/ImportOrganizationUsersRequestModel.cs b/src/Core/Models/Api/Request/Organizations/ImportOrganizationUsersRequestModel.cs index e9a421e15d..27d5280c84 100644 --- a/src/Core/Models/Api/Request/Organizations/ImportOrganizationUsersRequestModel.cs +++ b/src/Core/Models/Api/Request/Organizations/ImportOrganizationUsersRequestModel.cs @@ -62,7 +62,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(string.IsNullOrWhiteSpace(Email) && !Deleted) + if (string.IsNullOrWhiteSpace(Email) && !Deleted) { yield return new ValidationResult("Email is required for enabled users.", new string[] { nameof(Email) }); } diff --git a/src/Core/Models/Api/Request/Organizations/OrganizationCreateRequestModel.cs b/src/Core/Models/Api/Request/Organizations/OrganizationCreateRequestModel.cs index 798ab19dcc..7ee6992ed6 100644 --- a/src/Core/Models/Api/Request/Organizations/OrganizationCreateRequestModel.cs +++ b/src/Core/Models/Api/Request/Organizations/OrganizationCreateRequestModel.cs @@ -53,11 +53,11 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(PlanType != PlanType.Free && string.IsNullOrWhiteSpace(PaymentToken)) + if (PlanType != PlanType.Free && string.IsNullOrWhiteSpace(PaymentToken)) { yield return new ValidationResult("Payment required.", new string[] { nameof(PaymentToken) }); } - if(PlanType != PlanType.Free && !PaymentMethodType.HasValue) + if (PlanType != PlanType.Free && !PaymentMethodType.HasValue) { yield return new ValidationResult("Payment method type required.", new string[] { nameof(PaymentMethodType) }); diff --git a/src/Core/Models/Api/Request/Organizations/OrganizationSeatRequestModel.cs b/src/Core/Models/Api/Request/Organizations/OrganizationSeatRequestModel.cs index e2e5e827b1..a5ae303ae3 100644 --- a/src/Core/Models/Api/Request/Organizations/OrganizationSeatRequestModel.cs +++ b/src/Core/Models/Api/Request/Organizations/OrganizationSeatRequestModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(SeatAdjustment == 0) + if (SeatAdjustment == 0) { yield return new ValidationResult("Seat adjustment cannot be 0.", new string[] { nameof(SeatAdjustment) }); } diff --git a/src/Core/Models/Api/Request/Organizations/OrganizationUserRequestModels.cs b/src/Core/Models/Api/Request/Organizations/OrganizationUserRequestModels.cs index 2964cdec7d..39f0931196 100644 --- a/src/Core/Models/Api/Request/Organizations/OrganizationUserRequestModels.cs +++ b/src/Core/Models/Api/Request/Organizations/OrganizationUserRequestModels.cs @@ -17,26 +17,26 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(!Emails.Any()) + if (!Emails.Any()) { yield return new ValidationResult("An email is required."); } - if(Emails.Count() > 20) + if (Emails.Count() > 20) { yield return new ValidationResult("You can only invite up to 20 users at a time."); } var attr = new EmailAddressAttribute(); - for(var i = 0; i < Emails.Count(); i++) + for (var i = 0; i < Emails.Count(); i++) { var email = Emails.ElementAt(i); - if(!attr.IsValid(email) || email.Contains(" ") || email.Contains("<")) + if (!attr.IsValid(email) || email.Contains(" ") || email.Contains("<")) { yield return new ValidationResult($"Email #{i + 1} is not valid.", new string[] { nameof(Emails) }); } - else if(email.Length > 50) + else if (email.Length > 50) { yield return new ValidationResult($"Email #{i + 1} is longer than 50 characters.", new string[] { nameof(Emails) }); diff --git a/src/Core/Models/Api/Request/PushSendRequestModel.cs b/src/Core/Models/Api/Request/PushSendRequestModel.cs index 36ef816674..fc4f478668 100644 --- a/src/Core/Models/Api/Request/PushSendRequestModel.cs +++ b/src/Core/Models/Api/Request/PushSendRequestModel.cs @@ -17,7 +17,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(string.IsNullOrWhiteSpace(UserId) && string.IsNullOrWhiteSpace(OrganizationId)) + if (string.IsNullOrWhiteSpace(UserId) && string.IsNullOrWhiteSpace(OrganizationId)) { yield return new ValidationResult($"{nameof(UserId)} or {nameof(OrganizationId)} is required."); } diff --git a/src/Core/Models/Api/Request/TwoFactorRequestModels.cs b/src/Core/Models/Api/Request/TwoFactorRequestModels.cs index 5883f34e1c..5cd27a36f3 100644 --- a/src/Core/Models/Api/Request/TwoFactorRequestModels.cs +++ b/src/Core/Models/Api/Request/TwoFactorRequestModels.cs @@ -18,11 +18,11 @@ namespace Bit.Core.Models.Api public User ToUser(User extistingUser) { var providers = extistingUser.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { providers = new Dictionary(); } - else if(providers.ContainsKey(TwoFactorProviderType.Authenticator)) + else if (providers.ContainsKey(TwoFactorProviderType.Authenticator)) { providers.Remove(TwoFactorProviderType.Authenticator); } @@ -52,11 +52,11 @@ namespace Bit.Core.Models.Api public User ToUser(User extistingUser) { var providers = extistingUser.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { providers = new Dictionary(); } - else if(providers.ContainsKey(TwoFactorProviderType.Duo)) + else if (providers.ContainsKey(TwoFactorProviderType.Duo)) { providers.Remove(TwoFactorProviderType.Duo); } @@ -78,11 +78,11 @@ namespace Bit.Core.Models.Api public Organization ToOrganization(Organization extistingOrg) { var providers = extistingOrg.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { providers = new Dictionary(); } - else if(providers.ContainsKey(TwoFactorProviderType.OrganizationDuo)) + else if (providers.ContainsKey(TwoFactorProviderType.OrganizationDuo)) { providers.Remove(TwoFactorProviderType.OrganizationDuo); } @@ -103,7 +103,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(!Host.StartsWith("api-") || !Host.EndsWith(".duosecurity.com")) + if (!Host.StartsWith("api-") || !Host.EndsWith(".duosecurity.com")) { yield return new ValidationResult("Host is invalid.", new string[] { nameof(Host) }); } @@ -123,11 +123,11 @@ namespace Bit.Core.Models.Api public User ToUser(User extistingUser) { var providers = extistingUser.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { providers = new Dictionary(); } - else if(providers.ContainsKey(TwoFactorProviderType.YubiKey)) + else if (providers.ContainsKey(TwoFactorProviderType.YubiKey)) { providers.Remove(TwoFactorProviderType.YubiKey); } @@ -151,7 +151,7 @@ namespace Bit.Core.Models.Api private string FormatKey(string keyValue) { - if(string.IsNullOrWhiteSpace(keyValue)) + if (string.IsNullOrWhiteSpace(keyValue)) { return null; } @@ -161,33 +161,33 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(string.IsNullOrWhiteSpace(Key1) && string.IsNullOrWhiteSpace(Key2) && string.IsNullOrWhiteSpace(Key3) && + if (string.IsNullOrWhiteSpace(Key1) && string.IsNullOrWhiteSpace(Key2) && string.IsNullOrWhiteSpace(Key3) && string.IsNullOrWhiteSpace(Key4) && string.IsNullOrWhiteSpace(Key5)) { yield return new ValidationResult("A key is required.", new string[] { nameof(Key1) }); } - if(!string.IsNullOrWhiteSpace(Key1) && Key1.Length < 12) + if (!string.IsNullOrWhiteSpace(Key1) && Key1.Length < 12) { yield return new ValidationResult("Key 1 in invalid.", new string[] { nameof(Key1) }); } - if(!string.IsNullOrWhiteSpace(Key2) && Key2.Length < 12) + if (!string.IsNullOrWhiteSpace(Key2) && Key2.Length < 12) { yield return new ValidationResult("Key 2 in invalid.", new string[] { nameof(Key2) }); } - if(!string.IsNullOrWhiteSpace(Key3) && Key3.Length < 12) + if (!string.IsNullOrWhiteSpace(Key3) && Key3.Length < 12) { yield return new ValidationResult("Key 3 in invalid.", new string[] { nameof(Key3) }); } - if(!string.IsNullOrWhiteSpace(Key4) && Key4.Length < 12) + if (!string.IsNullOrWhiteSpace(Key4) && Key4.Length < 12) { yield return new ValidationResult("Key 4 in invalid.", new string[] { nameof(Key4) }); } - if(!string.IsNullOrWhiteSpace(Key5) && Key5.Length < 12) + if (!string.IsNullOrWhiteSpace(Key5) && Key5.Length < 12) { yield return new ValidationResult("Key 5 in invalid.", new string[] { nameof(Key5) }); } @@ -204,11 +204,11 @@ namespace Bit.Core.Models.Api public User ToUser(User extistingUser) { var providers = extistingUser.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { providers = new Dictionary(); } - else if(providers.ContainsKey(TwoFactorProviderType.Email)) + else if (providers.ContainsKey(TwoFactorProviderType.Email)) { providers.Remove(TwoFactorProviderType.Email); } @@ -237,7 +237,7 @@ namespace Bit.Core.Models.Api public IEnumerable Validate(ValidationContext validationContext) { - if(!Id.HasValue || Id < 0 || Id > 5) + if (!Id.HasValue || Id < 0 || Id > 5) { yield return new ValidationResult("Invalid Key Id", new string[] { nameof(Id) }); } diff --git a/src/Core/Models/Api/Response/ApiKeyResponseModel.cs b/src/Core/Models/Api/Response/ApiKeyResponseModel.cs index bd5caa5abb..0a69a7d342 100644 --- a/src/Core/Models/Api/Response/ApiKeyResponseModel.cs +++ b/src/Core/Models/Api/Response/ApiKeyResponseModel.cs @@ -8,7 +8,7 @@ namespace Bit.Core.Models.Api public ApiKeyResponseModel(Organization organization, string obj = "apiKey") : base(obj) { - if(organization == null) + if (organization == null) { throw new ArgumentNullException(nameof(organization)); } diff --git a/src/Core/Models/Api/Response/AttachmentResponseModel.cs b/src/Core/Models/Api/Response/AttachmentResponseModel.cs index 077d278c94..d10d96845c 100644 --- a/src/Core/Models/Api/Response/AttachmentResponseModel.cs +++ b/src/Core/Models/Api/Response/AttachmentResponseModel.cs @@ -29,7 +29,7 @@ namespace Bit.Core.Models.Api public static IEnumerable FromCipher(Cipher cipher, GlobalSettings globalSettings) { var attachments = cipher.GetAttachments(); - if(attachments == null) + if (attachments == null) { return null; } diff --git a/src/Core/Models/Api/Response/CipherResponseModel.cs b/src/Core/Models/Api/Response/CipherResponseModel.cs index 37d80867ae..2a632e4c4d 100644 --- a/src/Core/Models/Api/Response/CipherResponseModel.cs +++ b/src/Core/Models/Api/Response/CipherResponseModel.cs @@ -13,7 +13,7 @@ namespace Bit.Core.Models.Api public CipherMiniResponseModel(Cipher cipher, GlobalSettings globalSettings, bool orgUseTotp, string obj = "cipherMini") : base(obj) { - if(cipher == null) + if (cipher == null) { throw new ArgumentNullException(nameof(cipher)); } @@ -22,7 +22,7 @@ namespace Bit.Core.Models.Api Type = cipher.Type; CipherData cipherData; - switch(cipher.Type) + switch (cipher.Type) { case Enums.CipherType.Login: var loginData = JsonConvert.DeserializeObject(cipher.Data); @@ -100,7 +100,7 @@ namespace Bit.Core.Models.Api IDictionary> collectionCiphers, string obj = "cipherDetails") : base(cipher, globalSettings, obj) { - if(collectionCiphers?.ContainsKey(cipher.Id) ?? false) + if (collectionCiphers?.ContainsKey(cipher.Id) ?? false) { CollectionIds = collectionCiphers[cipher.Id].Select(c => c.CollectionId); } @@ -126,7 +126,7 @@ namespace Bit.Core.Models.Api IDictionary> collectionCiphers, string obj = "cipherMiniDetails") : base(cipher, globalSettings, false, obj) { - if(collectionCiphers?.ContainsKey(cipher.Id) ?? false) + if (collectionCiphers?.ContainsKey(cipher.Id) ?? false) { CollectionIds = collectionCiphers[cipher.Id].Select(c => c.CollectionId); } diff --git a/src/Core/Models/Api/Response/CollectionResponseModel.cs b/src/Core/Models/Api/Response/CollectionResponseModel.cs index ce2508660e..2161fbf9fb 100644 --- a/src/Core/Models/Api/Response/CollectionResponseModel.cs +++ b/src/Core/Models/Api/Response/CollectionResponseModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public CollectionResponseModel(Collection collection, string obj = "collection") : base(obj) { - if(collection == null) + if (collection == null) { throw new ArgumentNullException(nameof(collection)); } diff --git a/src/Core/Models/Api/Response/DeviceResponseModel.cs b/src/Core/Models/Api/Response/DeviceResponseModel.cs index 6110860324..aae273d83a 100644 --- a/src/Core/Models/Api/Response/DeviceResponseModel.cs +++ b/src/Core/Models/Api/Response/DeviceResponseModel.cs @@ -9,7 +9,7 @@ namespace Bit.Core.Models.Api public DeviceResponseModel(Device device) : base("device") { - if(device == null) + if (device == null) { throw new ArgumentNullException(nameof(device)); } diff --git a/src/Core/Models/Api/Response/DomainsResponseModel.cs b/src/Core/Models/Api/Response/DomainsResponseModel.cs index 383f7549a1..8debd8fa16 100644 --- a/src/Core/Models/Api/Response/DomainsResponseModel.cs +++ b/src/Core/Models/Api/Response/DomainsResponseModel.cs @@ -12,7 +12,7 @@ namespace Bit.Core.Models.Api public DomainsResponseModel(User user, bool excluded = true) : base("domains") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } @@ -26,7 +26,7 @@ namespace Bit.Core.Models.Api var globalDomains = new List(); var domainsToInclude = excluded ? Core.Utilities.StaticStore.GlobalDomains : Core.Utilities.StaticStore.GlobalDomains.Where(d => !excludedGlobalEquivalentDomains.Contains(d.Key)); - foreach(var domain in domainsToInclude) + foreach (var domain in domainsToInclude) { globalDomains.Add(new GlobalDomains(domain.Key, domain.Value, excludedGlobalEquivalentDomains, excluded)); } diff --git a/src/Core/Models/Api/Response/ErrorResponseModel.cs b/src/Core/Models/Api/Response/ErrorResponseModel.cs index 52e56d300a..bf56c97e3c 100644 --- a/src/Core/Models/Api/Response/ErrorResponseModel.cs +++ b/src/Core/Models/Api/Response/ErrorResponseModel.cs @@ -25,11 +25,11 @@ namespace Bit.Core.Models.Api var keys = modelState.Keys.ToList(); var values = modelState.Values.ToList(); - for(var i = 0; i < values.Count; i++) + for (var i = 0; i < values.Count; i++) { var value = values[i]; - if(keys.Count <= i) + if (keys.Count <= i) { // Keys not available for some reason. break; @@ -37,7 +37,7 @@ namespace Bit.Core.Models.Api var key = keys[i]; - if(value.ValidationState != ModelValidationState.Invalid || value.Errors.Count == 0) + if (value.ValidationState != ModelValidationState.Invalid || value.Errors.Count == 0) { continue; } diff --git a/src/Core/Models/Api/Response/EventResponseModel.cs b/src/Core/Models/Api/Response/EventResponseModel.cs index 6f15136eed..87802ce808 100644 --- a/src/Core/Models/Api/Response/EventResponseModel.cs +++ b/src/Core/Models/Api/Response/EventResponseModel.cs @@ -9,7 +9,7 @@ namespace Bit.Core.Models.Api public EventResponseModel(IEvent ev) : base("event") { - if(ev == null) + if (ev == null) { throw new ArgumentNullException(nameof(ev)); } diff --git a/src/Core/Models/Api/Response/FolderResponseModel.cs b/src/Core/Models/Api/Response/FolderResponseModel.cs index 5767bec310..3df1d8c2fb 100644 --- a/src/Core/Models/Api/Response/FolderResponseModel.cs +++ b/src/Core/Models/Api/Response/FolderResponseModel.cs @@ -8,7 +8,7 @@ namespace Bit.Core.Models.Api public FolderResponseModel(Folder folder) : base("folder") { - if(folder == null) + if (folder == null) { throw new ArgumentNullException(nameof(folder)); } diff --git a/src/Core/Models/Api/Response/GroupResponseModel.cs b/src/Core/Models/Api/Response/GroupResponseModel.cs index 71f9b5b26c..abf752a110 100644 --- a/src/Core/Models/Api/Response/GroupResponseModel.cs +++ b/src/Core/Models/Api/Response/GroupResponseModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public GroupResponseModel(Group group, string obj = "group") : base(obj) { - if(group == null) + if (group == null) { throw new ArgumentNullException(nameof(group)); } diff --git a/src/Core/Models/Api/Response/KeysResponseModel.cs b/src/Core/Models/Api/Response/KeysResponseModel.cs index c9a9b88c2b..6157147b34 100644 --- a/src/Core/Models/Api/Response/KeysResponseModel.cs +++ b/src/Core/Models/Api/Response/KeysResponseModel.cs @@ -8,7 +8,7 @@ namespace Bit.Core.Models.Api public KeysResponseModel(User user) : base("keys") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } diff --git a/src/Core/Models/Api/Response/OrganizationResponseModel.cs b/src/Core/Models/Api/Response/OrganizationResponseModel.cs index 6dfd3e86d8..e489be5571 100644 --- a/src/Core/Models/Api/Response/OrganizationResponseModel.cs +++ b/src/Core/Models/Api/Response/OrganizationResponseModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public OrganizationResponseModel(Organization organization, string obj = "organization") : base(obj) { - if(organization == null) + if (organization == null) { throw new ArgumentNullException(nameof(organization)); } @@ -71,7 +71,7 @@ namespace Bit.Core.Models.Api public OrganizationSubscriptionResponseModel(Organization organization, SubscriptionInfo subscription = null) : base(organization, "organizationSubscription") { - if(subscription != null) + if (subscription != null) { Subscription = subscription.Subscription != null ? new BillingSubscription(subscription.Subscription) : null; diff --git a/src/Core/Models/Api/Response/OrganizationUserResponseModel.cs b/src/Core/Models/Api/Response/OrganizationUserResponseModel.cs index dcb2236abd..a19fc9b844 100644 --- a/src/Core/Models/Api/Response/OrganizationUserResponseModel.cs +++ b/src/Core/Models/Api/Response/OrganizationUserResponseModel.cs @@ -12,7 +12,7 @@ namespace Bit.Core.Models.Api public OrganizationUserResponseModel(OrganizationUser organizationUser, string obj = "organizationUser") : base(obj) { - if(organizationUser == null) + if (organizationUser == null) { throw new ArgumentNullException(nameof(organizationUser)); } @@ -27,7 +27,7 @@ namespace Bit.Core.Models.Api public OrganizationUserResponseModel(OrganizationUserUserDetails organizationUser, string obj = "organizationUser") : base(obj) { - if(organizationUser == null) + if (organizationUser == null) { throw new ArgumentNullException(nameof(organizationUser)); } @@ -64,7 +64,7 @@ namespace Bit.Core.Models.Api bool twoFactorEnabled, string obj = "organizationUserUserDetails") : base(organizationUser, obj) { - if(organizationUser == null) + if (organizationUser == null) { throw new ArgumentNullException(nameof(organizationUser)); } diff --git a/src/Core/Models/Api/Response/PolicyResponseModel.cs b/src/Core/Models/Api/Response/PolicyResponseModel.cs index b1021f8bfc..4e4b36edf3 100644 --- a/src/Core/Models/Api/Response/PolicyResponseModel.cs +++ b/src/Core/Models/Api/Response/PolicyResponseModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public PolicyResponseModel(Policy policy, string obj = "policy") : base(obj) { - if(policy == null) + if (policy == null) { throw new ArgumentNullException(nameof(policy)); } @@ -20,7 +20,7 @@ namespace Bit.Core.Models.Api OrganizationId = policy.OrganizationId.ToString(); Type = policy.Type; Enabled = policy.Enabled; - if(!string.IsNullOrWhiteSpace(policy.Data)) + if (!string.IsNullOrWhiteSpace(policy.Data)) { Data = JsonConvert.DeserializeObject>(policy.Data); } diff --git a/src/Core/Models/Api/Response/ProfileResponseModel.cs b/src/Core/Models/Api/Response/ProfileResponseModel.cs index 20b8eac91c..3230871747 100644 --- a/src/Core/Models/Api/Response/ProfileResponseModel.cs +++ b/src/Core/Models/Api/Response/ProfileResponseModel.cs @@ -13,7 +13,7 @@ namespace Bit.Core.Models.Api IEnumerable organizationsUserDetails, bool twoFactorEnabled) : base("profile") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } diff --git a/src/Core/Models/Api/Response/ResponseModel.cs b/src/Core/Models/Api/Response/ResponseModel.cs index f215ccb86a..16a49f773d 100644 --- a/src/Core/Models/Api/Response/ResponseModel.cs +++ b/src/Core/Models/Api/Response/ResponseModel.cs @@ -7,7 +7,7 @@ namespace Bit.Core.Models.Api { public ResponseModel(string obj) { - if(string.IsNullOrWhiteSpace(obj)) + if (string.IsNullOrWhiteSpace(obj)) { throw new ArgumentNullException(nameof(obj)); } diff --git a/src/Core/Models/Api/Response/SelectionReadOnlyResponseModel.cs b/src/Core/Models/Api/Response/SelectionReadOnlyResponseModel.cs index dce5ffd456..35400ebac6 100644 --- a/src/Core/Models/Api/Response/SelectionReadOnlyResponseModel.cs +++ b/src/Core/Models/Api/Response/SelectionReadOnlyResponseModel.cs @@ -7,7 +7,7 @@ namespace Bit.Core.Models.Api { public SelectionReadOnlyResponseModel(SelectionReadOnly selection) { - if(selection == null) + if (selection == null) { throw new ArgumentNullException(nameof(selection)); } diff --git a/src/Core/Models/Api/Response/SubscriptionResponseModel.cs b/src/Core/Models/Api/Response/SubscriptionResponseModel.cs index a67a22b497..d18b3c1cbd 100644 --- a/src/Core/Models/Api/Response/SubscriptionResponseModel.cs +++ b/src/Core/Models/Api/Response/SubscriptionResponseModel.cs @@ -30,7 +30,7 @@ namespace Bit.Core.Models.Api MaxStorageGb = user.MaxStorageGb; Expiration = user.PremiumExpirationDate; - if(license != null) + if (license != null) { License = license; } @@ -58,7 +58,7 @@ namespace Bit.Core.Models.Api CancelledDate = sub.CancelledDate; CancelAtEndDate = sub.CancelAtEndDate; Cancelled = sub.Cancelled; - if(sub.Items != null) + if (sub.Items != null) { Items = sub.Items.Select(i => new BillingSubscriptionItem(i)); } diff --git a/src/Core/Models/Api/Response/TwoFactor/TwoFactorAuthenticatorResponseModel.cs b/src/Core/Models/Api/Response/TwoFactor/TwoFactorAuthenticatorResponseModel.cs index d973e046e5..6a2ac69e43 100644 --- a/src/Core/Models/Api/Response/TwoFactor/TwoFactorAuthenticatorResponseModel.cs +++ b/src/Core/Models/Api/Response/TwoFactor/TwoFactorAuthenticatorResponseModel.cs @@ -10,13 +10,13 @@ namespace Bit.Core.Models.Api public TwoFactorAuthenticatorResponseModel(User user) : base("twoFactorAuthenticator") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Authenticator); - if(provider?.MetaData?.ContainsKey("Key") ?? false) + if (provider?.MetaData?.ContainsKey("Key") ?? false) { Key = (string)provider.MetaData["Key"]; Enabled = provider.Enabled; diff --git a/src/Core/Models/Api/Response/TwoFactor/TwoFactorDuoResponseModel.cs b/src/Core/Models/Api/Response/TwoFactor/TwoFactorDuoResponseModel.cs index 7de73014aa..33ae08c973 100644 --- a/src/Core/Models/Api/Response/TwoFactor/TwoFactorDuoResponseModel.cs +++ b/src/Core/Models/Api/Response/TwoFactor/TwoFactorDuoResponseModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public TwoFactorDuoResponseModel(User user) : base(ResponseObj) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } @@ -23,7 +23,7 @@ namespace Bit.Core.Models.Api public TwoFactorDuoResponseModel(Organization org) : base(ResponseObj) { - if(org == null) + if (org == null) { throw new ArgumentNullException(nameof(org)); } @@ -39,19 +39,19 @@ namespace Bit.Core.Models.Api private void Build(TwoFactorProvider provider) { - if(provider?.MetaData != null && provider.MetaData.Count > 0) + if (provider?.MetaData != null && provider.MetaData.Count > 0) { Enabled = provider.Enabled; - if(provider.MetaData.ContainsKey("Host")) + if (provider.MetaData.ContainsKey("Host")) { Host = (string)provider.MetaData["Host"]; } - if(provider.MetaData.ContainsKey("SKey")) + if (provider.MetaData.ContainsKey("SKey")) { SecretKey = (string)provider.MetaData["SKey"]; } - if(provider.MetaData.ContainsKey("IKey")) + if (provider.MetaData.ContainsKey("IKey")) { IntegrationKey = (string)provider.MetaData["IKey"]; } diff --git a/src/Core/Models/Api/Response/TwoFactor/TwoFactorEmailResponseModel.cs b/src/Core/Models/Api/Response/TwoFactor/TwoFactorEmailResponseModel.cs index 9c61a26cbe..84ff76efd7 100644 --- a/src/Core/Models/Api/Response/TwoFactor/TwoFactorEmailResponseModel.cs +++ b/src/Core/Models/Api/Response/TwoFactor/TwoFactorEmailResponseModel.cs @@ -9,13 +9,13 @@ namespace Bit.Core.Models.Api public TwoFactorEmailResponseModel(User user) : base("twoFactorEmail") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Email); - if(provider?.MetaData?.ContainsKey("Email") ?? false) + if (provider?.MetaData?.ContainsKey("Email") ?? false) { Email = (string)provider.MetaData["Email"]; Enabled = provider.Enabled; diff --git a/src/Core/Models/Api/Response/TwoFactor/TwoFactorProviderResponseModel.cs b/src/Core/Models/Api/Response/TwoFactor/TwoFactorProviderResponseModel.cs index 15eec24ccc..e43c5424c5 100644 --- a/src/Core/Models/Api/Response/TwoFactor/TwoFactorProviderResponseModel.cs +++ b/src/Core/Models/Api/Response/TwoFactor/TwoFactorProviderResponseModel.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Models.Api public TwoFactorProviderResponseModel(TwoFactorProviderType type, TwoFactorProvider provider) : base(ResponseObj) { - if(provider == null) + if (provider == null) { throw new ArgumentNullException(nameof(provider)); } @@ -23,7 +23,7 @@ namespace Bit.Core.Models.Api public TwoFactorProviderResponseModel(TwoFactorProviderType type, User user) : base(ResponseObj) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } @@ -36,7 +36,7 @@ namespace Bit.Core.Models.Api public TwoFactorProviderResponseModel(TwoFactorProviderType type, Organization organization) : base(ResponseObj) { - if(organization == null) + if (organization == null) { throw new ArgumentNullException(nameof(organization)); } diff --git a/src/Core/Models/Api/Response/TwoFactor/TwoFactorRecoverResponseModel.cs b/src/Core/Models/Api/Response/TwoFactor/TwoFactorRecoverResponseModel.cs index 2c175fc539..baeed87e8d 100644 --- a/src/Core/Models/Api/Response/TwoFactor/TwoFactorRecoverResponseModel.cs +++ b/src/Core/Models/Api/Response/TwoFactor/TwoFactorRecoverResponseModel.cs @@ -8,7 +8,7 @@ namespace Bit.Core.Models.Api public TwoFactorRecoverResponseModel(User user) : base("twoFactorRecover") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } diff --git a/src/Core/Models/Api/Response/TwoFactor/TwoFactorU2fResponseModel.cs b/src/Core/Models/Api/Response/TwoFactor/TwoFactorU2fResponseModel.cs index 2f37b383ea..121be3d4be 100644 --- a/src/Core/Models/Api/Response/TwoFactor/TwoFactorU2fResponseModel.cs +++ b/src/Core/Models/Api/Response/TwoFactor/TwoFactorU2fResponseModel.cs @@ -12,7 +12,7 @@ namespace Bit.Core.Models.Api public TwoFactorU2fResponseModel(User user) : base("twoFactorU2f") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } diff --git a/src/Core/Models/Api/Response/TwoFactor/TwoFactorYubiKeyResponseModel.cs b/src/Core/Models/Api/Response/TwoFactor/TwoFactorYubiKeyResponseModel.cs index ecdb686b2d..56e15c5909 100644 --- a/src/Core/Models/Api/Response/TwoFactor/TwoFactorYubiKeyResponseModel.cs +++ b/src/Core/Models/Api/Response/TwoFactor/TwoFactorYubiKeyResponseModel.cs @@ -9,37 +9,37 @@ namespace Bit.Core.Models.Api public TwoFactorYubiKeyResponseModel(User user) : base("twoFactorYubiKey") { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.YubiKey); - if(provider?.MetaData != null && provider.MetaData.Count > 0) + if (provider?.MetaData != null && provider.MetaData.Count > 0) { Enabled = provider.Enabled; - if(provider.MetaData.ContainsKey("Key1")) + if (provider.MetaData.ContainsKey("Key1")) { Key1 = (string)provider.MetaData["Key1"]; } - if(provider.MetaData.ContainsKey("Key2")) + if (provider.MetaData.ContainsKey("Key2")) { Key2 = (string)provider.MetaData["Key2"]; } - if(provider.MetaData.ContainsKey("Key3")) + if (provider.MetaData.ContainsKey("Key3")) { Key3 = (string)provider.MetaData["Key3"]; } - if(provider.MetaData.ContainsKey("Key4")) + if (provider.MetaData.ContainsKey("Key4")) { Key4 = (string)provider.MetaData["Key4"]; } - if(provider.MetaData.ContainsKey("Key5")) + if (provider.MetaData.ContainsKey("Key5")) { Key5 = (string)provider.MetaData["Key5"]; } - if(provider.MetaData.ContainsKey("Nfc")) + if (provider.MetaData.ContainsKey("Nfc")) { Nfc = (bool)provider.MetaData["Nfc"]; } diff --git a/src/Core/Models/Business/AppleReceiptStatus.cs b/src/Core/Models/Business/AppleReceiptStatus.cs index 2fb179f025..80a049d1c3 100644 --- a/src/Core/Models/Business/AppleReceiptStatus.cs +++ b/src/Core/Models/Business/AppleReceiptStatus.cs @@ -58,7 +58,7 @@ namespace Bit.Billing.Models { var cancellationDate = GetLastCancellationDate(); var expiresDate = GetLastCancellationDate(); - if(cancellationDate.HasValue && expiresDate.HasValue) + if (cancellationDate.HasValue && expiresDate.HasValue) { return cancellationDate.Value <= expiresDate.Value; } diff --git a/src/Core/Models/Business/BillingInfo.cs b/src/Core/Models/Business/BillingInfo.cs index b94d44ba7b..46ea79f3d2 100644 --- a/src/Core/Models/Business/BillingInfo.cs +++ b/src/Core/Models/Business/BillingInfo.cs @@ -19,7 +19,7 @@ namespace Bit.Core.Models.Business public BillingSource(PaymentMethod method) { - if(method.Card != null) + if (method.Card != null) { Type = PaymentMethodType.Card; Description = $"{method.Card.Brand?.ToUpperInvariant()}, *{method.Card.Last4}, " + @@ -33,7 +33,7 @@ namespace Bit.Core.Models.Business public BillingSource(IPaymentSource source) { - if(source is BankAccount bankAccount) + if (source is BankAccount bankAccount) { Type = PaymentMethodType.BankAccount; Description = $"{bankAccount.BankName}, *{bankAccount.Last4} - " + @@ -42,7 +42,7 @@ namespace Bit.Core.Models.Business bankAccount.Status == "verification_failed" ? "verification failed" : "unverified"); NeedsVerification = bankAccount.Status == "new" || bankAccount.Status == "validated"; } - else if(source is Card card) + else if (source is Card card) { Type = PaymentMethodType.Card; Description = $"{card.Brand}, *{card.Last4}, " + @@ -52,7 +52,7 @@ namespace Bit.Core.Models.Business card.ExpYear); CardBrand = card.Brand; } - else if(source is Source src && src.Card != null) + else if (source is Source src && src.Card != null) { Type = PaymentMethodType.Card; Description = $"{src.Card.Brand}, *{src.Card.Last4}, " + @@ -66,12 +66,12 @@ namespace Bit.Core.Models.Business public BillingSource(Braintree.PaymentMethod method) { - if(method is Braintree.PayPalAccount paypal) + if (method is Braintree.PayPalAccount paypal) { Type = PaymentMethodType.PayPal; Description = paypal.Email; } - else if(method is Braintree.CreditCard card) + else if (method is Braintree.CreditCard card) { Type = PaymentMethodType.Card; Description = $"{card.CardType.ToString()}, *{card.LastFour}, " + @@ -81,7 +81,7 @@ namespace Bit.Core.Models.Business card.ExpirationYear); CardBrand = card.CardType.ToString(); } - else if(method is Braintree.UsBankAccount bank) + else if (method is Braintree.UsBankAccount bank) { Type = PaymentMethodType.BankAccount; Description = $"{bank.BankName}, *{bank.Last4}"; diff --git a/src/Core/Models/Business/OrganizationLicense.cs b/src/Core/Models/Business/OrganizationLicense.cs index 23d10160bb..d02dc79482 100644 --- a/src/Core/Models/Business/OrganizationLicense.cs +++ b/src/Core/Models/Business/OrganizationLicense.cs @@ -43,9 +43,9 @@ namespace Bit.Core.Models.Business UsersGetPremium = org.UsersGetPremium; Issued = DateTime.UtcNow; - if(subscriptionInfo?.Subscription == null) + if (subscriptionInfo?.Subscription == null) { - if(org.PlanType == PlanType.Custom && org.ExpirationDate.HasValue) + if (org.PlanType == PlanType.Custom && org.ExpirationDate.HasValue) { Expires = Refresh = org.ExpirationDate.Value; Trial = false; @@ -56,7 +56,7 @@ namespace Bit.Core.Models.Business Trial = true; } } - else if(subscriptionInfo.Subscription.TrialEndDate.HasValue && + else if (subscriptionInfo.Subscription.TrialEndDate.HasValue && subscriptionInfo.Subscription.TrialEndDate.Value > DateTime.UtcNow) { Expires = Refresh = subscriptionInfo.Subscription.TrialEndDate.Value; @@ -64,12 +64,12 @@ namespace Bit.Core.Models.Business } else { - if(org.ExpirationDate.HasValue && org.ExpirationDate.Value < DateTime.UtcNow) + if (org.ExpirationDate.HasValue && org.ExpirationDate.Value < DateTime.UtcNow) { // expired Expires = Refresh = org.ExpirationDate.Value; } - else if(subscriptionInfo?.Subscription?.PeriodDuration != null && + else if (subscriptionInfo?.Subscription?.PeriodDuration != null && subscriptionInfo.Subscription.PeriodDuration > TimeSpan.FromDays(180)) { Refresh = DateTime.UtcNow.AddDays(30); @@ -122,7 +122,7 @@ namespace Bit.Core.Models.Business public byte[] GetDataBytes(bool forHash = false) { string data = null; - if(Version >= 1 && Version <= 6) + if (Version >= 1 && Version <= 6) { var props = typeof(OrganizationLicense) .GetProperties(BindingFlags.Public | BindingFlags.Instance) @@ -162,7 +162,7 @@ namespace Bit.Core.Models.Business public byte[] ComputeHash() { - using(var alg = SHA256.Create()) + using (var alg = SHA256.Create()) { return alg.ComputeHash(GetDataBytes(true)); } @@ -170,12 +170,12 @@ namespace Bit.Core.Models.Business public bool CanUse(GlobalSettings globalSettings) { - if(!Enabled || Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) + if (!Enabled || Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) { return false; } - if(Version >= 1 && Version <= 6) + if (Version >= 1 && Version <= 6) { return InstallationId == globalSettings.Installation.Id && SelfHost; } @@ -187,12 +187,12 @@ namespace Bit.Core.Models.Business public bool VerifyData(Organization organization, GlobalSettings globalSettings) { - if(Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) + if (Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) { return false; } - if(Version >= 1 && Version <= 6) + if (Version >= 1 && Version <= 6) { var valid = globalSettings.Installation.Id == InstallationId && @@ -207,27 +207,27 @@ namespace Bit.Core.Models.Business organization.SelfHost == SelfHost && organization.Name.Equals(Name); - if(valid && Version >= 2) + if (valid && Version >= 2) { valid = organization.UsersGetPremium == UsersGetPremium; } - if(valid && Version >= 3) + if (valid && Version >= 3) { valid = organization.UseEvents == UseEvents; } - if(valid && Version >= 4) + if (valid && Version >= 4) { valid = organization.Use2fa == Use2fa; } - if(valid && Version >= 5) + if (valid && Version >= 5) { valid = organization.UseApi == UseApi; } - if(valid && Version >= 6) + if (valid && Version >= 6) { valid = organization.UsePolicies == UsePolicies; } @@ -242,7 +242,7 @@ namespace Bit.Core.Models.Business public bool VerifySignature(X509Certificate2 certificate) { - using(var rsa = certificate.GetRSAPublicKey()) + using (var rsa = certificate.GetRSAPublicKey()) { return rsa.VerifyData(GetDataBytes(), SignatureBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } @@ -250,12 +250,12 @@ namespace Bit.Core.Models.Business public byte[] Sign(X509Certificate2 certificate) { - if(!certificate.HasPrivateKey) + if (!certificate.HasPrivateKey) { throw new InvalidOperationException("You don't have the private key!"); } - using(var rsa = certificate.GetRSAPrivateKey()) + using (var rsa = certificate.GetRSAPrivateKey()) { return rsa.SignData(GetDataBytes(), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } diff --git a/src/Core/Models/Business/SubscriptionInfo.cs b/src/Core/Models/Business/SubscriptionInfo.cs index 7927d19426..2d39894502 100644 --- a/src/Core/Models/Business/SubscriptionInfo.cs +++ b/src/Core/Models/Business/SubscriptionInfo.cs @@ -23,7 +23,7 @@ namespace Bit.Core.Models.Business CancelledDate = sub.CanceledAt; CancelAtEndDate = sub.CancelAtPeriodEnd; Cancelled = sub.Status == "canceled" || sub.Status == "unpaid" || sub.Status == "incomplete_expired"; - if(sub.Items?.Data != null) + if (sub.Items?.Data != null) { Items = sub.Items.Data.Select(i => new BillingSubscriptionItem(i)); } @@ -44,7 +44,7 @@ namespace Bit.Core.Models.Business { public BillingSubscriptionItem(SubscriptionItem item) { - if(item.Plan != null) + if (item.Plan != null) { Name = item.Plan.Nickname; Amount = item.Plan.Amount.GetValueOrDefault() / 100M; @@ -74,7 +74,7 @@ namespace Bit.Core.Models.Business public BillingUpcomingInvoice(Braintree.Subscription sub) { Amount = sub.NextBillAmount.GetValueOrDefault() + sub.Balance.GetValueOrDefault(); - if(Amount < 0) + if (Amount < 0) { Amount = 0; } diff --git a/src/Core/Models/Business/UserLicense.cs b/src/Core/Models/Business/UserLicense.cs index 4d6ff3188e..ca7e257da2 100644 --- a/src/Core/Models/Business/UserLicense.cs +++ b/src/Core/Models/Business/UserLicense.cs @@ -71,7 +71,7 @@ namespace Bit.Core.Models.Business public byte[] GetDataBytes(bool forHash = false) { string data = null; - if(Version == 1) + if (Version == 1) { var props = typeof(UserLicense) .GetProperties(BindingFlags.Public | BindingFlags.Instance) @@ -101,7 +101,7 @@ namespace Bit.Core.Models.Business public byte[] ComputeHash() { - using(var alg = SHA256.Create()) + using (var alg = SHA256.Create()) { return alg.ComputeHash(GetDataBytes(true)); } @@ -109,12 +109,12 @@ namespace Bit.Core.Models.Business public bool CanUse(User user) { - if(Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) + if (Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) { return false; } - if(Version == 1) + if (Version == 1) { return user.EmailVerified && user.Email.Equals(Email, StringComparison.InvariantCultureIgnoreCase); } @@ -126,12 +126,12 @@ namespace Bit.Core.Models.Business public bool VerifyData(User user) { - if(Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) + if (Issued > DateTime.UtcNow || Expires < DateTime.UtcNow) { return false; } - if(Version == 1) + if (Version == 1) { return user.LicenseKey != null && user.LicenseKey.Equals(LicenseKey) && @@ -146,7 +146,7 @@ namespace Bit.Core.Models.Business public bool VerifySignature(X509Certificate2 certificate) { - using(var rsa = certificate.GetRSAPublicKey()) + using (var rsa = certificate.GetRSAPublicKey()) { return rsa.VerifyData(GetDataBytes(), SignatureBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } @@ -154,12 +154,12 @@ namespace Bit.Core.Models.Business public byte[] Sign(X509Certificate2 certificate) { - if(!certificate.HasPrivateKey) + if (!certificate.HasPrivateKey) { throw new InvalidOperationException("You don't have the private key!"); } - using(var rsa = certificate.GetRSAPrivateKey()) + using (var rsa = certificate.GetRSAPrivateKey()) { return rsa.SignData(GetDataBytes(), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } diff --git a/src/Core/Models/Data/EventTableEntity.cs b/src/Core/Models/Data/EventTableEntity.cs index a7a8d3219e..f881e1cdf9 100644 --- a/src/Core/Models/Data/EventTableEntity.cs +++ b/src/Core/Models/Data/EventTableEntity.cs @@ -44,7 +44,7 @@ namespace Bit.Core.Models.Data var result = base.WriteEntity(operationContext); var typeName = nameof(Type); - if(result.ContainsKey(typeName)) + if (result.ContainsKey(typeName)) { result[typeName] = new EntityProperty((int)Type); } @@ -54,7 +54,7 @@ namespace Bit.Core.Models.Data } var deviceTypeName = nameof(DeviceType); - if(result.ContainsKey(deviceTypeName)) + if (result.ContainsKey(deviceTypeName)) { result[deviceTypeName] = new EntityProperty((int?)DeviceType); } @@ -72,13 +72,13 @@ namespace Bit.Core.Models.Data base.ReadEntity(properties, operationContext); var typeName = nameof(Type); - if(properties.ContainsKey(typeName) && properties[typeName].Int32Value.HasValue) + if (properties.ContainsKey(typeName) && properties[typeName].Int32Value.HasValue) { Type = (EventType)properties[typeName].Int32Value.Value; } var deviceTypeName = nameof(DeviceType); - if(properties.ContainsKey(deviceTypeName) && properties[deviceTypeName].Int32Value.HasValue) + if (properties.ContainsKey(deviceTypeName) && properties[deviceTypeName].Int32Value.HasValue) { DeviceType = (DeviceType)properties[deviceTypeName].Int32Value.Value; } @@ -99,7 +99,7 @@ namespace Bit.Core.Models.Data } }; - if(e.OrganizationId.HasValue && e.ActingUserId.HasValue) + if (e.OrganizationId.HasValue && e.ActingUserId.HasValue) { entities.Add(new EventTableEntity(e) { @@ -109,7 +109,7 @@ namespace Bit.Core.Models.Data }); } - if(e.CipherId.HasValue) + if (e.CipherId.HasValue) { entities.Add(new EventTableEntity(e) { diff --git a/src/Core/Models/Data/InstallationDeviceEntity.cs b/src/Core/Models/Data/InstallationDeviceEntity.cs index 973c5c897c..76d0b4a23f 100644 --- a/src/Core/Models/Data/InstallationDeviceEntity.cs +++ b/src/Core/Models/Data/InstallationDeviceEntity.cs @@ -16,11 +16,11 @@ namespace Bit.Core.Models.Data public InstallationDeviceEntity(string prefixedDeviceId) { var parts = prefixedDeviceId.Split("_"); - if(parts.Length < 2) + if (parts.Length < 2) { throw new ArgumentException("Not enough parts."); } - if(!Guid.TryParse(parts[0], out var installationId) || !Guid.TryParse(parts[1], out var deviceId)) + if (!Guid.TryParse(parts[0], out var installationId) || !Guid.TryParse(parts[1], out var deviceId)) { throw new ArgumentException("Could not parse parts."); } diff --git a/src/Core/Models/Data/OrganizationUserUserDetails.cs b/src/Core/Models/Data/OrganizationUserUserDetails.cs index be341d4764..26190b3937 100644 --- a/src/Core/Models/Data/OrganizationUserUserDetails.cs +++ b/src/Core/Models/Data/OrganizationUserUserDetails.cs @@ -23,14 +23,14 @@ namespace Bit.Core.Models.Data public Dictionary GetTwoFactorProviders() { - if(string.IsNullOrWhiteSpace(TwoFactorProviders)) + if (string.IsNullOrWhiteSpace(TwoFactorProviders)) { return null; } try { - if(_twoFactorProviders == null) + if (_twoFactorProviders == null) { _twoFactorProviders = JsonConvert.DeserializeObject>( @@ -39,7 +39,7 @@ namespace Bit.Core.Models.Data return _twoFactorProviders; } - catch(JsonSerializationException) + catch (JsonSerializationException) { return null; } diff --git a/src/Core/Models/Mail/BaseMailModel.cs b/src/Core/Models/Mail/BaseMailModel.cs index 8f0ca3daf0..c1c439706c 100644 --- a/src/Core/Models/Mail/BaseMailModel.cs +++ b/src/Core/Models/Mail/BaseMailModel.cs @@ -10,7 +10,7 @@ namespace Bit.Core.Models.Mail { get { - if(Uri.TryCreate(WebVaultUrl, UriKind.Absolute, out Uri uri)) + if (Uri.TryCreate(WebVaultUrl, UriKind.Absolute, out Uri uri)) { return uri.Host; } diff --git a/src/Core/Models/Table/Cipher.cs b/src/Core/Models/Table/Cipher.cs index 07fe909876..68b637cdbb 100644 --- a/src/Core/Models/Table/Cipher.cs +++ b/src/Core/Models/Table/Cipher.cs @@ -28,12 +28,12 @@ namespace Bit.Core.Models.Table public Dictionary GetAttachments() { - if(string.IsNullOrWhiteSpace(Attachments)) + if (string.IsNullOrWhiteSpace(Attachments)) { return null; } - if(_attachmentData != null) + if (_attachmentData != null) { return _attachmentData; } @@ -51,7 +51,7 @@ namespace Bit.Core.Models.Table public void SetAttachments(Dictionary data) { - if(data == null || data.Count == 0) + if (data == null || data.Count == 0) { _attachmentData = null; Attachments = null; @@ -65,7 +65,7 @@ namespace Bit.Core.Models.Table public void AddAttachment(string id, CipherAttachment.MetaData data) { var attachments = GetAttachments(); - if(attachments == null) + if (attachments == null) { attachments = new Dictionary(); } @@ -77,7 +77,7 @@ namespace Bit.Core.Models.Table public void DeleteAttachment(string id) { var attachments = GetAttachments(); - if(!attachments?.ContainsKey(id) ?? true) + if (!attachments?.ContainsKey(id) ?? true) { return; } diff --git a/src/Core/Models/Table/Organization.cs b/src/Core/Models/Table/Organization.cs index be61289213..1573516f2b 100644 --- a/src/Core/Models/Table/Organization.cs +++ b/src/Core/Models/Table/Organization.cs @@ -48,7 +48,7 @@ namespace Bit.Core.Models.Table public void SetNewId() { - if(Id == default(Guid)) + if (Id == default(Guid)) { Id = CoreHelpers.GenerateComb(); } @@ -86,7 +86,7 @@ namespace Bit.Core.Models.Table public long StorageBytesRemaining() { - if(!MaxStorageGb.HasValue) + if (!MaxStorageGb.HasValue) { return 0; } @@ -97,7 +97,7 @@ namespace Bit.Core.Models.Table public long StorageBytesRemaining(short maxStorageGb) { var maxStorageBytes = maxStorageGb * 1073741824L; - if(!Storage.HasValue) + if (!Storage.HasValue) { return maxStorageBytes; } @@ -107,14 +107,14 @@ namespace Bit.Core.Models.Table public Dictionary GetTwoFactorProviders() { - if(string.IsNullOrWhiteSpace(TwoFactorProviders)) + if (string.IsNullOrWhiteSpace(TwoFactorProviders)) { return null; } try { - if(_twoFactorProviders == null) + if (_twoFactorProviders == null) { _twoFactorProviders = JsonConvert.DeserializeObject>( @@ -123,7 +123,7 @@ namespace Bit.Core.Models.Table return _twoFactorProviders; } - catch(JsonSerializationException) + catch (JsonSerializationException) { return null; } @@ -131,7 +131,7 @@ namespace Bit.Core.Models.Table public void SetTwoFactorProviders(Dictionary providers) { - if(!providers.Any()) + if (!providers.Any()) { TwoFactorProviders = null; _twoFactorProviders = null; @@ -148,7 +148,7 @@ namespace Bit.Core.Models.Table public bool TwoFactorProviderIsEnabled(TwoFactorProviderType provider) { var providers = GetTwoFactorProviders(); - if(providers == null || !providers.ContainsKey(provider)) + if (providers == null || !providers.ContainsKey(provider)) { return false; } @@ -159,7 +159,7 @@ namespace Bit.Core.Models.Table public bool TwoFactorIsEnabled() { var providers = GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { return false; } @@ -170,7 +170,7 @@ namespace Bit.Core.Models.Table public TwoFactorProvider GetTwoFactorProvider(TwoFactorProviderType provider) { var providers = GetTwoFactorProviders(); - if(providers == null || !providers.ContainsKey(provider)) + if (providers == null || !providers.ContainsKey(provider)) { return null; } diff --git a/src/Core/Models/Table/User.cs b/src/Core/Models/Table/User.cs index 570927132f..fe8af43b5d 100644 --- a/src/Core/Models/Table/User.cs +++ b/src/Core/Models/Table/User.cs @@ -80,14 +80,14 @@ namespace Bit.Core.Models.Table public Dictionary GetTwoFactorProviders() { - if(string.IsNullOrWhiteSpace(TwoFactorProviders)) + if (string.IsNullOrWhiteSpace(TwoFactorProviders)) { return null; } try { - if(_twoFactorProviders == null) + if (_twoFactorProviders == null) { _twoFactorProviders = JsonConvert.DeserializeObject>( @@ -96,7 +96,7 @@ namespace Bit.Core.Models.Table return _twoFactorProviders; } - catch(JsonSerializationException) + catch (JsonSerializationException) { return null; } @@ -124,7 +124,7 @@ namespace Bit.Core.Models.Table public TwoFactorProvider GetTwoFactorProvider(TwoFactorProviderType provider) { var providers = GetTwoFactorProviders(); - if(providers == null || !providers.ContainsKey(provider)) + if (providers == null || !providers.ContainsKey(provider)) { return null; } @@ -134,7 +134,7 @@ namespace Bit.Core.Models.Table public long StorageBytesRemaining() { - if(!MaxStorageGb.HasValue) + if (!MaxStorageGb.HasValue) { return 0; } @@ -145,7 +145,7 @@ namespace Bit.Core.Models.Table public long StorageBytesRemaining(short maxStorageGb) { var maxStorageBytes = maxStorageGb * 1073741824L; - if(!Storage.HasValue) + if (!Storage.HasValue) { return maxStorageBytes; } diff --git a/src/Core/Models/TwoFactorProvider.cs b/src/Core/Models/TwoFactorProvider.cs index c5c49d6710..8d51a8c02c 100644 --- a/src/Core/Models/TwoFactorProvider.cs +++ b/src/Core/Models/TwoFactorProvider.cs @@ -43,7 +43,7 @@ namespace Bit.Core.Models public static bool RequiresPremium(TwoFactorProviderType type) { - switch(type) + switch (type) { case TwoFactorProviderType.Duo: case TwoFactorProviderType.YubiKey: diff --git a/src/Core/Repositories/BaseRepository.cs b/src/Core/Repositories/BaseRepository.cs index 86bff6a29b..ab996ae710 100644 --- a/src/Core/Repositories/BaseRepository.cs +++ b/src/Core/Repositories/BaseRepository.cs @@ -12,11 +12,11 @@ namespace Bit.Core.Repositories public BaseRepository(string connectionString, string readOnlyConnectionString) { - if(string.IsNullOrWhiteSpace(connectionString)) + if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentNullException(nameof(connectionString)); } - if(string.IsNullOrWhiteSpace(readOnlyConnectionString)) + if (string.IsNullOrWhiteSpace(readOnlyConnectionString)) { throw new ArgumentNullException(nameof(readOnlyConnectionString)); } diff --git a/src/Core/Repositories/EntityFramework/OrganizationRepository.cs b/src/Core/Repositories/EntityFramework/OrganizationRepository.cs index 09ad7bf93b..9db92f8278 100644 --- a/src/Core/Repositories/EntityFramework/OrganizationRepository.cs +++ b/src/Core/Repositories/EntityFramework/OrganizationRepository.cs @@ -19,7 +19,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task> GetManyByEnabledAsync() { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var organizations = await GetDbSet(dbContext).Where(e => e.Enabled).ToListAsync(); @@ -36,7 +36,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task> SearchAsync(string name, string userEmail, bool? paid, int skip, int take) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); // TODO: more filters @@ -51,7 +51,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task UpdateStorageAsync(Guid id) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var ciphers = await dbContext.Ciphers @@ -75,7 +75,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task> GetManyAbilitiesAsync() { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); return await GetDbSet(dbContext) diff --git a/src/Core/Repositories/EntityFramework/Repository.cs b/src/Core/Repositories/EntityFramework/Repository.cs index fc85a332e9..b8158065b8 100644 --- a/src/Core/Repositories/EntityFramework/Repository.cs +++ b/src/Core/Repositories/EntityFramework/Repository.cs @@ -22,7 +22,7 @@ namespace Bit.Core.Repositories.EntityFramework public virtual async Task GetByIdAsync(TId id) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var entity = await GetDbSet(dbContext).FindAsync(id); @@ -32,7 +32,7 @@ namespace Bit.Core.Repositories.EntityFramework public virtual async Task CreateAsync(T obj) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var entity = Mapper.Map(obj); @@ -44,11 +44,11 @@ namespace Bit.Core.Repositories.EntityFramework public virtual async Task ReplaceAsync(T obj) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var entity = await GetDbSet(dbContext).FindAsync(obj.Id); - if(entity != null) + if (entity != null) { var mappedEntity = Mapper.Map(obj); dbContext.Entry(entity).CurrentValues.SetValues(mappedEntity); @@ -59,7 +59,7 @@ namespace Bit.Core.Repositories.EntityFramework public virtual async Task UpsertAsync(T obj) { - if(obj.Id.Equals(default(T))) + if (obj.Id.Equals(default(T))) { await CreateAsync(obj); } @@ -71,7 +71,7 @@ namespace Bit.Core.Repositories.EntityFramework public virtual async Task DeleteAsync(T obj) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var entity = Mapper.Map(obj); diff --git a/src/Core/Repositories/EntityFramework/UserRepository.cs b/src/Core/Repositories/EntityFramework/UserRepository.cs index 770176cad1..4d19428bdc 100644 --- a/src/Core/Repositories/EntityFramework/UserRepository.cs +++ b/src/Core/Repositories/EntityFramework/UserRepository.cs @@ -19,7 +19,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task GetByEmailAsync(string email) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); return await GetDbSet(dbContext).FirstOrDefaultAsync(e => e.Email == email); @@ -28,7 +28,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task GetKdfInformationByEmailAsync(string email) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); return await GetDbSet(dbContext).Where(e => e.Email == email) @@ -42,7 +42,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task> SearchAsync(string email, int skip, int take) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var users = await GetDbSet(dbContext) @@ -56,7 +56,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task> GetManyByPremiumAsync(bool premium) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var users = await GetDbSet(dbContext).Where(e => e.Premium == premium).ToListAsync(); @@ -66,7 +66,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task GetPublicKeyAsync(Guid id) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); return await GetDbSet(dbContext).Where(e => e.Id == id).Select(e => e.PublicKey).SingleOrDefaultAsync(); @@ -75,7 +75,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task GetAccountRevisionDateAsync(Guid id) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); return await GetDbSet(dbContext).Where(e => e.Id == id).Select(e => e.AccountRevisionDate) @@ -85,7 +85,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task UpdateStorageAsync(Guid id) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var ciphers = await dbContext.Ciphers.Where(e => e.UserId == id).ToListAsync(); @@ -108,7 +108,7 @@ namespace Bit.Core.Repositories.EntityFramework public async Task UpdateRenewalReminderDateAsync(Guid id, DateTime renewalReminderDate) { - using(var scope = ServiceScopeFactory.CreateScope()) + using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var user = new EFModel.User diff --git a/src/Core/Repositories/PostgreSql/BasePostgreSqlRepository.cs b/src/Core/Repositories/PostgreSql/BasePostgreSqlRepository.cs index cb698f250b..956d6fb977 100644 --- a/src/Core/Repositories/PostgreSql/BasePostgreSqlRepository.cs +++ b/src/Core/Repositories/PostgreSql/BasePostgreSqlRepository.cs @@ -17,7 +17,7 @@ namespace Bit.Core.Repositories.PostgreSql protected static string SnakeCase(string input) { - if(string.IsNullOrWhiteSpace(input)) + if (string.IsNullOrWhiteSpace(input)) { return input; } @@ -29,7 +29,7 @@ namespace Bit.Core.Repositories.PostgreSql { var dp = new DynamicParameters(); var properties = typeof(T).GetProperties(); - foreach(var property in properties) + foreach (var property in properties) { dp.Add($"_{SnakeCase(property.Name)}", property.GetValue(obj)); } diff --git a/src/Core/Repositories/PostgreSql/Repository.cs b/src/Core/Repositories/PostgreSql/Repository.cs index 051e2bf8b9..1c9053c114 100644 --- a/src/Core/Repositories/PostgreSql/Repository.cs +++ b/src/Core/Repositories/PostgreSql/Repository.cs @@ -15,7 +15,7 @@ namespace Bit.Core.Repositories.PostgreSql public Repository(string connectionString, string readOnlyConnectionString, string table = null) : base(connectionString, readOnlyConnectionString) { - if(!string.IsNullOrWhiteSpace(table)) + if (!string.IsNullOrWhiteSpace(table)) { Table = table; } @@ -29,7 +29,7 @@ namespace Bit.Core.Repositories.PostgreSql public virtual async Task GetByIdAsync(TId id) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"{Table}_read_by_id", @@ -43,7 +43,7 @@ namespace Bit.Core.Repositories.PostgreSql public virtual async Task CreateAsync(T obj) { obj.SetNewId(); - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"{Table}_create", @@ -54,7 +54,7 @@ namespace Bit.Core.Repositories.PostgreSql public virtual async Task ReplaceAsync(T obj) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"{Table}_update", @@ -65,7 +65,7 @@ namespace Bit.Core.Repositories.PostgreSql public virtual async Task UpsertAsync(T obj) { - if(obj.Id.Equals(default(TId))) + if (obj.Id.Equals(default(TId))) { await CreateAsync(obj); } @@ -77,7 +77,7 @@ namespace Bit.Core.Repositories.PostgreSql public virtual async Task DeleteAsync(T obj) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"{Table}_delete_by_id", diff --git a/src/Core/Repositories/PostgreSql/UserRepository.cs b/src/Core/Repositories/PostgreSql/UserRepository.cs index fca3a86252..f65b80dff5 100644 --- a/src/Core/Repositories/PostgreSql/UserRepository.cs +++ b/src/Core/Repositories/PostgreSql/UserRepository.cs @@ -27,7 +27,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task GetByEmailAsync(string email) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "user_read_by_email", @@ -40,7 +40,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task GetKdfInformationByEmailAsync(string email) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "user_read_kdf_by_email", @@ -53,7 +53,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task> SearchAsync(string email, int skip, int take) { - using(var connection = new NpgsqlConnection(ReadOnlyConnectionString)) + using (var connection = new NpgsqlConnection(ReadOnlyConnectionString)) { var results = await connection.QueryAsync( "user_search", @@ -67,7 +67,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task> GetManyByPremiumAsync(bool premium) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "user_read_by_premium", @@ -80,7 +80,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task> GetManyByPremiumRenewalAsync() { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "user_read_by_premium_renewal", @@ -92,7 +92,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task GetPublicKeyAsync(Guid id) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "user_read_public_key_by_id", @@ -105,7 +105,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task GetAccountRevisionDateAsync(Guid id) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "user_read_account_revision_date_by_id", @@ -123,7 +123,7 @@ namespace Bit.Core.Repositories.PostgreSql public override async Task DeleteAsync(User user) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"user_delete_by_id", @@ -135,7 +135,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task UpdateStorageAsync(Guid id) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { await connection.ExecuteAsync( "user_update_storage", @@ -147,7 +147,7 @@ namespace Bit.Core.Repositories.PostgreSql public async Task UpdateRenewalReminderDateAsync(Guid id, DateTime renewalReminderDate) { - using(var connection = new NpgsqlConnection(ConnectionString)) + using (var connection = new NpgsqlConnection(ConnectionString)) { await connection.ExecuteAsync( "user_update_renewal_reminder_date", diff --git a/src/Core/Repositories/SqlServer/CipherRepository.cs b/src/Core/Repositories/SqlServer/CipherRepository.cs index 83cb1c3b13..e5cf98649b 100644 --- a/src/Core/Repositories/SqlServer/CipherRepository.cs +++ b/src/Core/Repositories/SqlServer/CipherRepository.cs @@ -25,7 +25,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByIdAsync(Guid id, Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[CipherDetails_ReadByIdUserId]", @@ -38,7 +38,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetOrganizationDetailsByIdAsync(Guid id, bool deleted = false) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[CipherOrganizationDetails_ReadById]", @@ -51,7 +51,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetCanEditByIdAsync(Guid userId, Guid cipherId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var result = await connection.QueryFirstOrDefaultAsync( $"[{Schema}].[Cipher_ReadCanEditByIdUserId]", @@ -65,7 +65,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId, bool withOrganizations = true, bool deleted = false) { string sprocName = null; - if(withOrganizations) + if (withOrganizations) { sprocName = $"[{Schema}].[CipherDetails_ReadByUserId]"; } @@ -74,7 +74,7 @@ namespace Bit.Core.Repositories.SqlServer sprocName = $"[{Schema}].[CipherDetails_ReadWithoutOrganizationsByUserId]"; } - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( sprocName, @@ -90,7 +90,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByOrganizationIdAsync(Guid organizationId, bool deleted = false) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Cipher_ReadByOrganizationId]", @@ -107,7 +107,7 @@ namespace Bit.Core.Repositories.SqlServer var objWithCollections = JsonConvert.DeserializeObject( JsonConvert.SerializeObject(cipher)); objWithCollections.CollectionIds = collectionIds.ToGuidIdArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_CreateWithCollections]", @@ -119,7 +119,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task CreateAsync(CipherDetails cipher) { cipher.SetNewId(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[CipherDetails_Create]", @@ -134,7 +134,7 @@ namespace Bit.Core.Repositories.SqlServer var objWithCollections = JsonConvert.DeserializeObject( JsonConvert.SerializeObject(cipher)); objWithCollections.CollectionIds = collectionIds.ToGuidIdArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[CipherDetails_CreateWithCollections]", @@ -145,7 +145,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task ReplaceAsync(CipherDetails obj) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[CipherDetails_Update]", @@ -156,7 +156,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpsertAsync(CipherDetails cipher) { - if(cipher.Id.Equals(default(Guid))) + if (cipher.Id.Equals(default(Guid))) { await CreateAsync(cipher); } @@ -172,7 +172,7 @@ namespace Bit.Core.Repositories.SqlServer JsonConvert.SerializeObject(obj)); objWithCollections.CollectionIds = collectionIds.ToGuidIdArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var result = await connection.ExecuteScalarAsync( $"[{Schema}].[Cipher_UpdateWithCollections]", @@ -184,7 +184,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdatePartialAsync(Guid id, Guid userId, Guid? folderId, bool favorite) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_UpdatePartial]", @@ -195,7 +195,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateAttachmentAsync(CipherAttachment attachment) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_UpdateAttachment]", @@ -206,7 +206,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteAttachmentAsync(Guid cipherId, string attachmentId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_DeleteAttachment]", @@ -217,7 +217,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteAsync(Cipher obj, bool permanent = true) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_DeleteById]", @@ -228,7 +228,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteAsync(IEnumerable ids, Guid userId, bool permanent = true) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_Delete]", @@ -239,7 +239,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task MoveAsync(IEnumerable ids, Guid? folderId, Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_Move]", @@ -250,7 +250,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_DeleteByUserId]", @@ -261,7 +261,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Cipher_DeleteByOrganizationId]", @@ -272,24 +272,24 @@ namespace Bit.Core.Repositories.SqlServer public Task UpdateUserKeysAndCiphersAsync(User user, IEnumerable ciphers, IEnumerable folders) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { connection.Open(); - using(var transaction = connection.BeginTransaction()) + using (var transaction = connection.BeginTransaction()) { try { // 1. Update user. - using(var cmd = new SqlCommand("[dbo].[User_UpdateKeys]", connection, transaction)) + using (var cmd = new SqlCommand("[dbo].[User_UpdateKeys]", connection, transaction)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Id", SqlDbType.UniqueIdentifier).Value = user.Id; cmd.Parameters.Add("@SecurityStamp", SqlDbType.NVarChar).Value = user.SecurityStamp; cmd.Parameters.Add("@Key", SqlDbType.VarChar).Value = user.Key; - if(string.IsNullOrWhiteSpace(user.PrivateKey)) + if (string.IsNullOrWhiteSpace(user.PrivateKey)) { cmd.Parameters.Add("@PrivateKey", SqlDbType.VarChar).Value = DBNull.Value; } @@ -313,16 +313,16 @@ namespace Bit.Core.Repositories.SqlServer INTO #TempFolder FROM [dbo].[Folder]"; - using(var cmd = new SqlCommand(sqlCreateTemp, connection, transaction)) + using (var cmd = new SqlCommand(sqlCreateTemp, connection, transaction)) { cmd.ExecuteNonQuery(); } // 3. Bulk copy into temp tables. - if(ciphers.Any()) + if (ciphers.Any()) { - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "#TempCipher"; var dataTable = BuildCiphersTable(bulkCopy, ciphers); @@ -330,9 +330,9 @@ namespace Bit.Core.Repositories.SqlServer } } - if(folders.Any()) + if (folders.Any()) { - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "#TempFolder"; var dataTable = BuildFoldersTable(bulkCopy, folders); @@ -344,7 +344,7 @@ namespace Bit.Core.Repositories.SqlServer var sql = string.Empty; - if(ciphers.Any()) + if (ciphers.Any()) { sql += @" UPDATE @@ -361,7 +361,7 @@ namespace Bit.Core.Repositories.SqlServer C.[UserId] = @UserId"; } - if(folders.Any()) + if (folders.Any()) { sql += @" UPDATE @@ -381,7 +381,7 @@ namespace Bit.Core.Repositories.SqlServer DROP TABLE #TempCipher DROP TABLE #TempFolder"; - using(var cmd = new SqlCommand(sql, connection, transaction)) + using (var cmd = new SqlCommand(sql, connection, transaction)) { cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = user.Id; cmd.ExecuteNonQuery(); @@ -402,16 +402,16 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateCiphersAsync(Guid userId, IEnumerable ciphers) { - if(!ciphers.Any()) + if (!ciphers.Any()) { return; } - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { connection.Open(); - using(var transaction = connection.BeginTransaction()) + using (var transaction = connection.BeginTransaction()) { try { @@ -422,13 +422,13 @@ namespace Bit.Core.Repositories.SqlServer INTO #TempCipher FROM [dbo].[Cipher]"; - using(var cmd = new SqlCommand(sqlCreateTemp, connection, transaction)) + using (var cmd = new SqlCommand(sqlCreateTemp, connection, transaction)) { cmd.ExecuteNonQuery(); } // 2. Bulk copy into temp tables. - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "#TempCipher"; var dataTable = BuildCiphersTable(bulkCopy, ciphers); @@ -458,7 +458,7 @@ namespace Bit.Core.Repositories.SqlServer DROP TABLE #TempCipher"; - using(var cmd = new SqlCommand(sql, connection, transaction)) + using (var cmd = new SqlCommand(sql, connection, transaction)) { cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = userId; cmd.ExecuteNonQuery(); @@ -482,22 +482,22 @@ namespace Bit.Core.Repositories.SqlServer public async Task CreateAsync(IEnumerable ciphers, IEnumerable folders) { - if(!ciphers.Any()) + if (!ciphers.Any()) { return; } - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { connection.Open(); - using(var transaction = connection.BeginTransaction()) + using (var transaction = connection.BeginTransaction()) { try { - if(folders.Any()) + if (folders.Any()) { - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "[dbo].[Folder]"; var dataTable = BuildFoldersTable(bulkCopy, folders); @@ -505,7 +505,7 @@ namespace Bit.Core.Repositories.SqlServer } } - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "[dbo].[Cipher]"; var dataTable = BuildCiphersTable(bulkCopy, ciphers); @@ -531,38 +531,38 @@ namespace Bit.Core.Repositories.SqlServer public async Task CreateAsync(IEnumerable ciphers, IEnumerable collections, IEnumerable collectionCiphers) { - if(!ciphers.Any()) + if (!ciphers.Any()) { return; } - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { connection.Open(); - using(var transaction = connection.BeginTransaction()) + using (var transaction = connection.BeginTransaction()) { try { - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "[dbo].[Cipher]"; var dataTable = BuildCiphersTable(bulkCopy, ciphers); bulkCopy.WriteToServer(dataTable); } - if(collections.Any()) + if (collections.Any()) { - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "[dbo].[Collection]"; var dataTable = BuildCollectionsTable(bulkCopy, collections); bulkCopy.WriteToServer(dataTable); } - if(collectionCiphers.Any()) + if (collectionCiphers.Any()) { - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy.DestinationTableName = "[dbo].[CollectionCipher]"; var dataTable = BuildCollectionCiphersTable(bulkCopy, collectionCiphers); @@ -590,7 +590,7 @@ namespace Bit.Core.Repositories.SqlServer private DataTable BuildCiphersTable(SqlBulkCopy bulkCopy, IEnumerable ciphers) { var c = ciphers.FirstOrDefault(); - if(c == null) + if (c == null) { throw new ApplicationException("Must have some ciphers to bulk import."); } @@ -618,7 +618,7 @@ namespace Bit.Core.Repositories.SqlServer var revisionDateColumn = new DataColumn(nameof(c.RevisionDate), c.RevisionDate.GetType()); ciphersTable.Columns.Add(revisionDateColumn); - foreach(DataColumn col in ciphersTable.Columns) + foreach (DataColumn col in ciphersTable.Columns) { bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName); } @@ -627,7 +627,7 @@ namespace Bit.Core.Repositories.SqlServer keys[0] = idColumn; ciphersTable.PrimaryKey = keys; - foreach(var cipher in ciphers) + foreach (var cipher in ciphers) { var row = ciphersTable.NewRow(); @@ -651,7 +651,7 @@ namespace Bit.Core.Repositories.SqlServer private DataTable BuildFoldersTable(SqlBulkCopy bulkCopy, IEnumerable folders) { var f = folders.FirstOrDefault(); - if(f == null) + if (f == null) { throw new ApplicationException("Must have some folders to bulk import."); } @@ -669,7 +669,7 @@ namespace Bit.Core.Repositories.SqlServer var revisionDateColumn = new DataColumn(nameof(f.RevisionDate), f.RevisionDate.GetType()); foldersTable.Columns.Add(revisionDateColumn); - foreach(DataColumn col in foldersTable.Columns) + foreach (DataColumn col in foldersTable.Columns) { bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName); } @@ -678,7 +678,7 @@ namespace Bit.Core.Repositories.SqlServer keys[0] = idColumn; foldersTable.PrimaryKey = keys; - foreach(var folder in folders) + foreach (var folder in folders) { var row = foldersTable.NewRow(); @@ -697,7 +697,7 @@ namespace Bit.Core.Repositories.SqlServer private DataTable BuildCollectionsTable(SqlBulkCopy bulkCopy, IEnumerable collections) { var c = collections.FirstOrDefault(); - if(c == null) + if (c == null) { throw new ApplicationException("Must have some collections to bulk import."); } @@ -715,7 +715,7 @@ namespace Bit.Core.Repositories.SqlServer var revisionDateColumn = new DataColumn(nameof(c.RevisionDate), c.RevisionDate.GetType()); collectionsTable.Columns.Add(revisionDateColumn); - foreach(DataColumn col in collectionsTable.Columns) + foreach (DataColumn col in collectionsTable.Columns) { bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName); } @@ -724,7 +724,7 @@ namespace Bit.Core.Repositories.SqlServer keys[0] = idColumn; collectionsTable.PrimaryKey = keys; - foreach(var collection in collections) + foreach (var collection in collections) { var row = collectionsTable.NewRow(); @@ -743,7 +743,7 @@ namespace Bit.Core.Repositories.SqlServer private DataTable BuildCollectionCiphersTable(SqlBulkCopy bulkCopy, IEnumerable collectionCiphers) { var cc = collectionCiphers.FirstOrDefault(); - if(cc == null) + if (cc == null) { throw new ApplicationException("Must have some collectionCiphers to bulk import."); } @@ -755,7 +755,7 @@ namespace Bit.Core.Repositories.SqlServer var cipherIdColumn = new DataColumn(nameof(cc.CipherId), cc.CipherId.GetType()); collectionCiphersTable.Columns.Add(cipherIdColumn); - foreach(DataColumn col in collectionCiphersTable.Columns) + foreach (DataColumn col in collectionCiphersTable.Columns) { bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName); } @@ -765,7 +765,7 @@ namespace Bit.Core.Repositories.SqlServer keys[1] = cipherIdColumn; collectionCiphersTable.PrimaryKey = keys; - foreach(var collectionCipher in collectionCiphers) + foreach (var collectionCipher in collectionCiphers) { var row = collectionCiphersTable.NewRow(); diff --git a/src/Core/Repositories/SqlServer/CollectionCipherRepository.cs b/src/Core/Repositories/SqlServer/CollectionCipherRepository.cs index f04eace954..4711955604 100644 --- a/src/Core/Repositories/SqlServer/CollectionCipherRepository.cs +++ b/src/Core/Repositories/SqlServer/CollectionCipherRepository.cs @@ -22,7 +22,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[CollectionCipher_ReadByUserId]", @@ -35,7 +35,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[CollectionCipher_ReadByOrganizationId]", @@ -48,7 +48,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdCipherIdAsync(Guid userId, Guid cipherId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[CollectionCipher_ReadByUserIdCipherId]", @@ -61,7 +61,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateCollectionsAsync(Guid cipherId, Guid userId, IEnumerable collectionIds) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( "[dbo].[CollectionCipher_UpdateCollections]", @@ -72,7 +72,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateCollectionsForAdminAsync(Guid cipherId, Guid organizationId, IEnumerable collectionIds) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( "[dbo].[CollectionCipher_UpdateCollectionsAdmin]", @@ -84,7 +84,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateCollectionsForCiphersAsync(IEnumerable cipherIds, Guid userId, Guid organizationId, IEnumerable collectionIds) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( "[dbo].[CollectionCipher_UpdateCollectionsForCiphers]", diff --git a/src/Core/Repositories/SqlServer/CollectionRepository.cs b/src/Core/Repositories/SqlServer/CollectionRepository.cs index 25c54a1c7d..0e9b944458 100644 --- a/src/Core/Repositories/SqlServer/CollectionRepository.cs +++ b/src/Core/Repositories/SqlServer/CollectionRepository.cs @@ -24,7 +24,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetCountByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteScalarAsync( "[dbo].[Collection_ReadCountByOrganizationId]", @@ -37,7 +37,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task>> GetByIdWithGroupsAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryMultipleAsync( $"[{Schema}].[Collection_ReadWithGroupsById]", @@ -54,7 +54,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task>> GetByIdWithGroupsAsync( Guid id, Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryMultipleAsync( $"[{Schema}].[Collection_ReadWithGroupsByIdUserId]", @@ -70,7 +70,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByOrganizationId]", @@ -83,7 +83,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByIdAsync(Guid id, Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Collection_ReadByIdUserId]", @@ -96,7 +96,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Collection_ReadByUserId]", @@ -117,7 +117,7 @@ namespace Bit.Core.Repositories.SqlServer var objWithGroups = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj)); objWithGroups.Groups = groups.ToArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Collection_CreateWithGroups]", @@ -131,7 +131,7 @@ namespace Bit.Core.Repositories.SqlServer var objWithGroups = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj)); objWithGroups.Groups = groups.ToArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Collection_UpdateWithGroups]", @@ -142,7 +142,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task CreateUserAsync(Guid collectionId, Guid organizationUserId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[CollectionUser_Create]", @@ -153,7 +153,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteUserAsync(Guid collectionId, Guid organizationUserId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[CollectionUser_Delete]", @@ -164,7 +164,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateUsersAsync(Guid id, IEnumerable users) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[CollectionUser_UpdateUsers]", @@ -175,7 +175,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyUsersByIdAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[CollectionUser_ReadByCollectionId]", diff --git a/src/Core/Repositories/SqlServer/DeviceRepository.cs b/src/Core/Repositories/SqlServer/DeviceRepository.cs index 3c21f6487a..9301fe0711 100644 --- a/src/Core/Repositories/SqlServer/DeviceRepository.cs +++ b/src/Core/Repositories/SqlServer/DeviceRepository.cs @@ -22,7 +22,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByIdAsync(Guid id, Guid userId) { var device = await GetByIdAsync(id); - if(device == null || device.UserId != userId) + if (device == null || device.UserId != userId) { return null; } @@ -32,7 +32,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByIdentifierAsync(string identifier) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByIdentifier]", @@ -48,7 +48,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByIdentifierAsync(string identifier, Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByIdentifierUserId]", @@ -65,7 +65,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByUserId]", @@ -78,7 +78,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task ClearPushTokenAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"[{Schema}].[{Table}_ClearPushTokenById]", diff --git a/src/Core/Repositories/SqlServer/EventRepository.cs b/src/Core/Repositories/SqlServer/EventRepository.cs index 8bb9d88663..98e232f299 100644 --- a/src/Core/Repositories/SqlServer/EventRepository.cs +++ b/src/Core/Repositories/SqlServer/EventRepository.cs @@ -65,7 +65,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task CreateAsync(IEvent e) { - if(!(e is Event ev)) + if (!(e is Event ev)) { ev = new Event(e); } @@ -75,21 +75,21 @@ namespace Bit.Core.Repositories.SqlServer public async Task CreateManyAsync(IList entities) { - if(!entities?.Any() ?? true) + if (!entities?.Any() ?? true) { return; } - if(entities.Count == 1) + if (entities.Count == 1) { await CreateAsync(entities.First()); return; } - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { connection.Open(); - using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, null)) + using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, null)) { bulkCopy.DestinationTableName = "[dbo].[Event]"; var dataTable = BuildEventsTable(bulkCopy, entities.Select(e => e is Event ? e as Event : new Event(e))); @@ -102,7 +102,7 @@ namespace Bit.Core.Repositories.SqlServer IDictionary sprocParams, DateTime startDate, DateTime endDate, PageOptions pageOptions) { DateTime? beforeDate = null; - if(!string.IsNullOrWhiteSpace(pageOptions.ContinuationToken) && + if (!string.IsNullOrWhiteSpace(pageOptions.ContinuationToken) && long.TryParse(pageOptions.ContinuationToken, out var binaryDate)) { beforeDate = DateTime.SpecifyKind(DateTime.FromBinary(binaryDate), DateTimeKind.Utc); @@ -116,13 +116,13 @@ namespace Bit.Core.Repositories.SqlServer parameters.Add("@EndDate", endDate.ToUniversalTime(), DbType.DateTime2, null, 7); parameters.Add("@BeforeDate", beforeDate, DbType.DateTime2, null, 7); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var events = (await connection.QueryAsync(sprocName, parameters, commandType: CommandType.StoredProcedure)).ToList(); var result = new PagedResult(); - if(events.Any() && events.Count >= pageOptions.PageSize) + if (events.Any() && events.Count >= pageOptions.PageSize) { result.ContinuationToken = events.Last().Date.ToBinary().ToString(); } @@ -134,7 +134,7 @@ namespace Bit.Core.Repositories.SqlServer private DataTable BuildEventsTable(SqlBulkCopy bulkCopy, IEnumerable events) { var e = events.FirstOrDefault(); - if(e == null) + if (e == null) { throw new ApplicationException("Must have some events to bulk import."); } @@ -168,7 +168,7 @@ namespace Bit.Core.Repositories.SqlServer var dateColumn = new DataColumn(nameof(e.Date), e.Date.GetType()); eventsTable.Columns.Add(dateColumn); - foreach(DataColumn col in eventsTable.Columns) + foreach (DataColumn col in eventsTable.Columns) { bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName); } @@ -177,7 +177,7 @@ namespace Bit.Core.Repositories.SqlServer keys[0] = idColumn; eventsTable.PrimaryKey = keys; - foreach(var ev in events) + foreach (var ev in events) { ev.SetNewId(); diff --git a/src/Core/Repositories/SqlServer/FolderRepository.cs b/src/Core/Repositories/SqlServer/FolderRepository.cs index a8c3b202c9..835e9e6e39 100644 --- a/src/Core/Repositories/SqlServer/FolderRepository.cs +++ b/src/Core/Repositories/SqlServer/FolderRepository.cs @@ -22,7 +22,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByIdAsync(Guid id, Guid userId) { var folder = await GetByIdAsync(id); - if(folder == null || folder.UserId != userId) + if (folder == null || folder.UserId != userId) { return null; } @@ -32,7 +32,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Folder_ReadByUserId]", diff --git a/src/Core/Repositories/SqlServer/GrantRepository.cs b/src/Core/Repositories/SqlServer/GrantRepository.cs index 8ffe86a19b..39fe540fff 100644 --- a/src/Core/Repositories/SqlServer/GrantRepository.cs +++ b/src/Core/Repositories/SqlServer/GrantRepository.cs @@ -21,7 +21,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByKeyAsync(string key) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[Grant_ReadByKey]", @@ -34,7 +34,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyAsync(string subjectId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[Grant_ReadBySubjectId]", @@ -47,7 +47,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task SaveAsync(Grant obj) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( "[dbo].[Grant_Save]", @@ -58,7 +58,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteAsync(string key) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "[dbo].[Grant_DeleteByKey]", @@ -69,7 +69,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteAsync(string subjectId, string clientId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "[dbo].[Grant_DeleteBySubjectIdClientId]", @@ -80,7 +80,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteAsync(string subjectId, string clientId, string type) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "[dbo].[Grant_DeleteBySubjectIdClientIdType]", diff --git a/src/Core/Repositories/SqlServer/GroupRepository.cs b/src/Core/Repositories/SqlServer/GroupRepository.cs index 4639be33c1..c0b328c925 100644 --- a/src/Core/Repositories/SqlServer/GroupRepository.cs +++ b/src/Core/Repositories/SqlServer/GroupRepository.cs @@ -24,7 +24,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task>> GetByIdWithCollectionsAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryMultipleAsync( $"[{Schema}].[Group_ReadWithCollectionsById]", @@ -40,7 +40,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Group_ReadByOrganizationId]", @@ -53,7 +53,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyIdsByUserIdAsync(Guid organizationUserId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[GroupUser_ReadGroupIdsByOrganizationUserId]", @@ -66,7 +66,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyUserIdsByIdAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[GroupUser_ReadOrganizationUserIdsByGroupId]", @@ -79,7 +79,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyGroupUsersByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[GroupUser_ReadByOrganizationId]", @@ -96,7 +96,7 @@ namespace Bit.Core.Repositories.SqlServer var objWithCollections = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj)); objWithCollections.Collections = collections.ToArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Group_CreateWithCollections]", @@ -110,7 +110,7 @@ namespace Bit.Core.Repositories.SqlServer var objWithCollections = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj)); objWithCollections.Collections = collections.ToArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[Group_UpdateWithCollections]", @@ -121,7 +121,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteUserAsync(Guid groupId, Guid organizationUserId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[GroupUser_Delete]", @@ -132,7 +132,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateUsersAsync(Guid groupId, IEnumerable organizationUserIds) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( "[dbo].[GroupUser_UpdateUsers]", diff --git a/src/Core/Repositories/SqlServer/MaintenanceRepository.cs b/src/Core/Repositories/SqlServer/MaintenanceRepository.cs index a1b9af9fe2..fd0c2154d6 100644 --- a/src/Core/Repositories/SqlServer/MaintenanceRepository.cs +++ b/src/Core/Repositories/SqlServer/MaintenanceRepository.cs @@ -17,7 +17,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateStatisticsAsync() { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "[dbo].[AzureSQLMaintenance]", @@ -29,7 +29,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DisableCipherAutoStatsAsync() { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "sp_autostats", @@ -40,7 +40,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task RebuildIndexesAsync() { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "[dbo].[AzureSQLMaintenance]", @@ -52,7 +52,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteExpiredGrantsAsync() { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "[dbo].[Grant_DeleteExpired]", diff --git a/src/Core/Repositories/SqlServer/OrganizationRepository.cs b/src/Core/Repositories/SqlServer/OrganizationRepository.cs index 9201a481cd..528575d617 100644 --- a/src/Core/Repositories/SqlServer/OrganizationRepository.cs +++ b/src/Core/Repositories/SqlServer/OrganizationRepository.cs @@ -22,7 +22,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByEnabledAsync() { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[Organization_ReadByEnabled]", @@ -34,7 +34,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[Organization_ReadByUserId]", @@ -48,7 +48,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> SearchAsync(string name, string userEmail, bool? paid, int skip, int take) { - using(var connection = new SqlConnection(ReadOnlyConnectionString)) + using (var connection = new SqlConnection(ReadOnlyConnectionString)) { var results = await connection.QueryAsync( "[dbo].[Organization_Search]", @@ -62,7 +62,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateStorageAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( "[dbo].[Organization_UpdateStorage]", @@ -74,7 +74,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyAbilitiesAsync() { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[Organization_ReadAbilities]", diff --git a/src/Core/Repositories/SqlServer/OrganizationUserRepository.cs b/src/Core/Repositories/SqlServer/OrganizationUserRepository.cs index 16ef28903d..bfc6a494a1 100644 --- a/src/Core/Repositories/SqlServer/OrganizationUserRepository.cs +++ b/src/Core/Repositories/SqlServer/OrganizationUserRepository.cs @@ -25,7 +25,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetCountByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteScalarAsync( "[dbo].[OrganizationUser_ReadCountByOrganizationId]", @@ -38,7 +38,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetCountByFreeOrganizationAdminUserAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteScalarAsync( "[dbo].[OrganizationUser_ReadCountByFreeOrganizationAdminUser]", @@ -51,7 +51,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetCountByOnlyOwnerAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteScalarAsync( "[dbo].[OrganizationUser_ReadCountByOnlyOwner]", @@ -64,7 +64,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetCountByOrganizationAsync(Guid organizationId, string email, bool onlyRegisteredUsers) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var result = await connection.ExecuteScalarAsync( "[dbo].[OrganizationUser_ReadCountByOrganizationIdEmail]", @@ -77,7 +77,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByOrganizationAsync(Guid organizationId, Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[OrganizationUser_ReadByOrganizationIdUserId]", @@ -90,7 +90,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[OrganizationUser_ReadByUserId]", @@ -104,7 +104,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByOrganizationAsync(Guid organizationId, OrganizationUserType? type) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[OrganizationUser_ReadByOrganizationId]", @@ -117,7 +117,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task>> GetByIdWithCollectionsAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryMultipleAsync( "[dbo].[OrganizationUser_ReadWithCollectionsById]", @@ -132,7 +132,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetDetailsByIdAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[OrganizationUserUserDetails_ReadById]", @@ -145,7 +145,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task>> GetDetailsByIdWithCollectionsAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryMultipleAsync( "[dbo].[OrganizationUserUserDetails_ReadWithCollectionsById]", @@ -160,7 +160,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyDetailsByOrganizationAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[OrganizationUserUserDetails_ReadByOrganizationId]", @@ -174,7 +174,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyDetailsByUserAsync(Guid userId, OrganizationUserStatusType? status = null) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[OrganizationUserOrganizationDetails_ReadByUserIdStatus]", @@ -187,7 +187,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateGroupsAsync(Guid orgUserId, IEnumerable groupIds) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( "[dbo].[GroupUser_UpdateGroups]", @@ -203,7 +203,7 @@ namespace Bit.Core.Repositories.SqlServer JsonConvert.SerializeObject(obj)); objWithCollections.Collections = collections.ToArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[OrganizationUser_CreateWithCollections]", @@ -218,7 +218,7 @@ namespace Bit.Core.Repositories.SqlServer JsonConvert.SerializeObject(obj)); objWithCollections.Collections = collections.ToArrayTVP(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[OrganizationUser_UpdateWithCollections]", diff --git a/src/Core/Repositories/SqlServer/PolicyRepository.cs b/src/Core/Repositories/SqlServer/PolicyRepository.cs index c8843282f7..245656bb81 100644 --- a/src/Core/Repositories/SqlServer/PolicyRepository.cs +++ b/src/Core/Repositories/SqlServer/PolicyRepository.cs @@ -21,7 +21,7 @@ namespace Bit.Core.Repositories.SqlServer { } public async Task GetByOrganizationIdTypeAsync(Guid organizationId, PolicyType type) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByOrganizationIdType]", @@ -34,7 +34,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByOrganizationId]", @@ -47,7 +47,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByUserId]", diff --git a/src/Core/Repositories/SqlServer/Repository.cs b/src/Core/Repositories/SqlServer/Repository.cs index b6100f28bb..838fd70cb9 100644 --- a/src/Core/Repositories/SqlServer/Repository.cs +++ b/src/Core/Repositories/SqlServer/Repository.cs @@ -16,12 +16,12 @@ namespace Bit.Core.Repositories.SqlServer string schema = null, string table = null) : base(connectionString, readOnlyConnectionString) { - if(!string.IsNullOrWhiteSpace(table)) + if (!string.IsNullOrWhiteSpace(table)) { Table = table; } - if(!string.IsNullOrWhiteSpace(schema)) + if (!string.IsNullOrWhiteSpace(schema)) { Schema = schema; } @@ -32,7 +32,7 @@ namespace Bit.Core.Repositories.SqlServer public virtual async Task GetByIdAsync(TId id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadById]", @@ -46,7 +46,7 @@ namespace Bit.Core.Repositories.SqlServer public virtual async Task CreateAsync(T obj) { obj.SetNewId(); - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[{Table}_Create]", @@ -57,7 +57,7 @@ namespace Bit.Core.Repositories.SqlServer public virtual async Task ReplaceAsync(T obj) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.ExecuteAsync( $"[{Schema}].[{Table}_Update]", @@ -68,7 +68,7 @@ namespace Bit.Core.Repositories.SqlServer public virtual async Task UpsertAsync(T obj) { - if(obj.Id.Equals(default(TId))) + if (obj.Id.Equals(default(TId))) { await CreateAsync(obj); } @@ -80,7 +80,7 @@ namespace Bit.Core.Repositories.SqlServer public virtual async Task DeleteAsync(T obj) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"[{Schema}].[{Table}_DeleteById]", diff --git a/src/Core/Repositories/SqlServer/TransactionRepository.cs b/src/Core/Repositories/SqlServer/TransactionRepository.cs index 85f2ed35b5..90ba4af2fc 100644 --- a/src/Core/Repositories/SqlServer/TransactionRepository.cs +++ b/src/Core/Repositories/SqlServer/TransactionRepository.cs @@ -22,7 +22,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Transaction_ReadByUserId]", @@ -35,7 +35,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByOrganizationIdAsync(Guid organizationId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Transaction_ReadByOrganizationId]", @@ -48,7 +48,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByGatewayIdAsync(GatewayType gatewayType, string gatewayId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[Transaction_ReadByGatewayId]", diff --git a/src/Core/Repositories/SqlServer/U2fRepository.cs b/src/Core/Repositories/SqlServer/U2fRepository.cs index cd8570461d..3d8ea7f69b 100644 --- a/src/Core/Repositories/SqlServer/U2fRepository.cs +++ b/src/Core/Repositories/SqlServer/U2fRepository.cs @@ -21,7 +21,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[U2f_ReadByUserId]", @@ -34,7 +34,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task DeleteManyByUserIdAsync(Guid userId) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"[{Schema}].[U2f_DeleteByUserId]", diff --git a/src/Core/Repositories/SqlServer/UserRepository.cs b/src/Core/Repositories/SqlServer/UserRepository.cs index 4a296ca1cd..43a0c19911 100644 --- a/src/Core/Repositories/SqlServer/UserRepository.cs +++ b/src/Core/Repositories/SqlServer/UserRepository.cs @@ -27,7 +27,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetByEmailAsync(string email) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadByEmail]", @@ -40,7 +40,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetKdfInformationByEmailAsync(string email) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadKdfByEmail]", @@ -53,7 +53,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> SearchAsync(string email, int skip, int take) { - using(var connection = new SqlConnection(ReadOnlyConnectionString)) + using (var connection = new SqlConnection(ReadOnlyConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_Search]", @@ -67,7 +67,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task> GetManyByPremiumAsync(bool premium) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( "[dbo].[User_ReadByPremium]", @@ -80,7 +80,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetPublicKeyAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadPublicKeyById]", @@ -93,7 +93,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task GetAccountRevisionDateAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { var results = await connection.QueryAsync( $"[{Schema}].[{Table}_ReadAccountRevisionDateById]", @@ -111,7 +111,7 @@ namespace Bit.Core.Repositories.SqlServer public override async Task DeleteAsync(User user) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"[{Schema}].[{Table}_DeleteById]", @@ -123,7 +123,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateStorageAsync(Guid id) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"[{Schema}].[{Table}_UpdateStorage]", @@ -135,7 +135,7 @@ namespace Bit.Core.Repositories.SqlServer public async Task UpdateRenewalReminderDateAsync(Guid id, DateTime renewalReminderDate) { - using(var connection = new SqlConnection(ConnectionString)) + using (var connection = new SqlConnection(ConnectionString)) { await connection.ExecuteAsync( $"[{Schema}].[User_UpdateRenewalReminderDate]", diff --git a/src/Core/Repositories/TableStorage/EventRepository.cs b/src/Core/Repositories/TableStorage/EventRepository.cs index 12ebf57b42..49d87d2c6d 100644 --- a/src/Core/Repositories/TableStorage/EventRepository.cs +++ b/src/Core/Repositories/TableStorage/EventRepository.cs @@ -53,7 +53,7 @@ namespace Bit.Core.Repositories.TableStorage public async Task CreateAsync(IEvent e) { - if(!(e is EventTableEntity entity)) + if (!(e is EventTableEntity entity)) { throw new ArgumentException(nameof(e)); } @@ -63,12 +63,12 @@ namespace Bit.Core.Repositories.TableStorage public async Task CreateManyAsync(IList e) { - if(!e?.Any() ?? true) + if (!e?.Any() ?? true) { return; } - if(e.Count == 1) + if (e.Count == 1) { await CreateAsync(e.First()); return; @@ -76,10 +76,10 @@ namespace Bit.Core.Repositories.TableStorage var entities = e.Where(ev => ev is EventTableEntity).Select(ev => ev as EventTableEntity); var entityGroups = entities.GroupBy(ent => ent.PartitionKey); - foreach(var group in entityGroups) + foreach (var group in entityGroups) { var groupEntities = group.ToList(); - if(groupEntities.Count == 1) + if (groupEntities.Count == 1) { await CreateEntityAsync(groupEntities.First()); continue; @@ -87,16 +87,16 @@ namespace Bit.Core.Repositories.TableStorage // A batch insert can only contain 100 entities at a time var iterations = groupEntities.Count / 100; - for(var i = 0; i <= iterations; i++) + for (var i = 0; i <= iterations; i++) { var batch = new TableBatchOperation(); var batchEntities = groupEntities.Skip(i * 100).Take(100); - if(!batchEntities.Any()) + if (!batchEntities.Any()) { break; } - foreach(var entity in batchEntities) + foreach (var entity in batchEntities) { batch.InsertOrReplace(entity); } @@ -144,7 +144,7 @@ namespace Bit.Core.Repositories.TableStorage private string SerializeContinuationToken(TableContinuationToken token) { - if(token == null) + if (token == null) { return null; } @@ -155,13 +155,13 @@ namespace Bit.Core.Repositories.TableStorage private TableContinuationToken DeserializeContinuationToken(string token) { - if(string.IsNullOrWhiteSpace(token)) + if (string.IsNullOrWhiteSpace(token)) { return null; } var tokenParts = token.Split(new string[] { "__" }, StringSplitOptions.None); - if(tokenParts.Length < 4 || !Enum.TryParse(tokenParts[0], out StorageLocation tLoc)) + if (tokenParts.Length < 4 || !Enum.TryParse(tokenParts[0], out StorageLocation tLoc)) { return null; } diff --git a/src/Core/Repositories/TableStorage/InstallationDeviceRepository.cs b/src/Core/Repositories/TableStorage/InstallationDeviceRepository.cs index 71f95f67b5..0e7ea6c09c 100644 --- a/src/Core/Repositories/TableStorage/InstallationDeviceRepository.cs +++ b/src/Core/Repositories/TableStorage/InstallationDeviceRepository.cs @@ -29,22 +29,22 @@ namespace Bit.Core.Repositories.TableStorage public async Task UpsertManyAsync(IList entities) { - if(!entities?.Any() ?? true) + if (!entities?.Any() ?? true) { return; } - if(entities.Count == 1) + if (entities.Count == 1) { await UpsertAsync(entities.First()); return; } var entityGroups = entities.GroupBy(ent => ent.PartitionKey); - foreach(var group in entityGroups) + foreach (var group in entityGroups) { var groupEntities = group.ToList(); - if(groupEntities.Count == 1) + if (groupEntities.Count == 1) { await UpsertAsync(groupEntities.First()); continue; @@ -52,16 +52,16 @@ namespace Bit.Core.Repositories.TableStorage // A batch insert can only contain 100 entities at a time var iterations = groupEntities.Count / 100; - for(var i = 0; i <= iterations; i++) + for (var i = 0; i <= iterations; i++) { var batch = new TableBatchOperation(); var batchEntities = groupEntities.Skip(i * 100).Take(100); - if(!batchEntities.Any()) + if (!batchEntities.Any()) { break; } - foreach(var entity in batchEntities) + foreach (var entity in batchEntities) { batch.InsertOrReplace(entity); } @@ -78,9 +78,9 @@ namespace Bit.Core.Repositories.TableStorage entity.ETag = "*"; await _table.ExecuteAsync(TableOperation.Delete(entity)); } - catch(StorageException e) + catch (StorageException e) { - if(e.RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound) + if (e.RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound) { throw e; } diff --git a/src/Core/Repositories/TableStorage/MetaDataRepository.cs b/src/Core/Repositories/TableStorage/MetaDataRepository.cs index 6762fbbd13..4c083b93f9 100644 --- a/src/Core/Repositories/TableStorage/MetaDataRepository.cs +++ b/src/Core/Repositories/TableStorage/MetaDataRepository.cs @@ -33,7 +33,7 @@ namespace Bit.Core.Repositories.TableStorage public async Task GetAsync(string objectName, string id, string prop) { var dict = await GetAsync(objectName, id); - if(dict != null && dict.ContainsKey(prop)) + if (dict != null && dict.ContainsKey(prop)) { return dict[prop]; } @@ -46,7 +46,7 @@ namespace Bit.Core.Repositories.TableStorage TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, $"{objectName}_{id}")); var queryResults = await _table.ExecuteQuerySegmentedAsync(query, null); var entity = queryResults.Results.FirstOrDefault(); - if(entity == null) + if (entity == null) { entity = new DictionaryEntity { @@ -54,7 +54,7 @@ namespace Bit.Core.Repositories.TableStorage RowKey = string.Empty }; } - if(entity.ContainsKey(keyValuePair.Key)) + if (entity.ContainsKey(keyValuePair.Key)) { entity.Remove(keyValuePair.Key); } @@ -69,7 +69,7 @@ namespace Bit.Core.Repositories.TableStorage PartitionKey = $"{objectName}_{id}", RowKey = string.Empty }; - foreach(var item in dict) + foreach (var item in dict) { entity.Add(item.Key, item.Value); } @@ -87,9 +87,9 @@ namespace Bit.Core.Repositories.TableStorage ETag = "*" })); } - catch(StorageException e) + catch (StorageException e) { - if(e.RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound) + if (e.RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound) { throw e; } diff --git a/src/Core/Services/Implementations/AmazonSesMailDeliveryService.cs b/src/Core/Services/Implementations/AmazonSesMailDeliveryService.cs index 1d2977591d..451369821a 100644 --- a/src/Core/Services/Implementations/AmazonSesMailDeliveryService.cs +++ b/src/Core/Services/Implementations/AmazonSesMailDeliveryService.cs @@ -26,15 +26,15 @@ namespace Bit.Core.Services IWebHostEnvironment hostingEnvironment, ILogger logger) { - if(string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeyId)) + if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeyId)) { throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeyId)); } - if(string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeySecret)) + if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeySecret)) { throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeySecret)); } - if(string.IsNullOrWhiteSpace(globalSettings.Amazon?.Region)) + if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.Region)) { throw new ArgumentNullException(nameof(globalSettings.Amazon.Region)); } @@ -46,7 +46,7 @@ namespace Bit.Core.Services globalSettings.Amazon.AccessKeySecret, RegionEndpoint.GetBySystemName(globalSettings.Amazon.Region)); _source = $"\"{globalSettings.SiteName}\" <{globalSettings.Mail.ReplyToEmail}>"; _senderTag = $"Server_{globalSettings.ProjectName}"; - if(!string.IsNullOrWhiteSpace(_globalSettings.Mail.AmazonConfigSetName)) + if (!string.IsNullOrWhiteSpace(_globalSettings.Mail.AmazonConfigSetName)) { _configSetName = _globalSettings.Mail.AmazonConfigSetName; } @@ -91,12 +91,12 @@ namespace Bit.Core.Services } }; - if(message.BccEmails?.Any() ?? false) + if (message.BccEmails?.Any() ?? false) { request.Destination.BccAddresses = message.BccEmails.ToList(); } - if(!string.IsNullOrWhiteSpace(message.Category)) + if (!string.IsNullOrWhiteSpace(message.Category)) { request.Tags.Add(new MessageTag { Name = "Category", Value = message.Category }); } @@ -105,7 +105,7 @@ namespace Bit.Core.Services { await SendAsync(request, false); } - catch(Exception e) + catch (Exception e) { _logger.LogWarning(e, "Failed to send email. Re-retying..."); await SendAsync(request, true); @@ -115,7 +115,7 @@ namespace Bit.Core.Services private async Task SendAsync(SendEmailRequest request, bool retry) { - if(retry) + if (retry) { // wait and try again await Task.Delay(2000); diff --git a/src/Core/Services/Implementations/AmazonSqsBlockIpService.cs b/src/Core/Services/Implementations/AmazonSqsBlockIpService.cs index 9944f05f45..7090a753ba 100644 --- a/src/Core/Services/Implementations/AmazonSqsBlockIpService.cs +++ b/src/Core/Services/Implementations/AmazonSqsBlockIpService.cs @@ -16,15 +16,15 @@ namespace Bit.Core.Services public AmazonSqsBlockIpService( GlobalSettings globalSettings) { - if(string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeyId)) + if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeyId)) { throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeyId)); } - if(string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeySecret)) + if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.AccessKeySecret)) { throw new ArgumentNullException(nameof(globalSettings.Amazon.AccessKeySecret)); } - if(string.IsNullOrWhiteSpace(globalSettings.Amazon?.Region)) + if (string.IsNullOrWhiteSpace(globalSettings.Amazon?.Region)) { throw new ArgumentNullException(nameof(globalSettings.Amazon.Region)); } @@ -40,7 +40,7 @@ namespace Bit.Core.Services public async Task BlockIpAsync(string ipAddress, bool permanentBlock) { var now = DateTime.UtcNow; - if(_lastBlock != null && _lastBlock.Item1 == ipAddress && _lastBlock.Item2 == permanentBlock && + if (_lastBlock != null && _lastBlock.Item1 == ipAddress && _lastBlock.Item2 == permanentBlock && (now - _lastBlock.Item3) < TimeSpan.FromMinutes(1)) { // Already blocked this IP recently. @@ -49,7 +49,7 @@ namespace Bit.Core.Services _lastBlock = new Tuple(ipAddress, permanentBlock, now); await _client.SendMessageAsync(_blockIpQueueUrl, ipAddress); - if(!permanentBlock) + if (!permanentBlock) { await _client.SendMessageAsync(_unblockIpQueueUrl, ipAddress); } @@ -57,7 +57,7 @@ namespace Bit.Core.Services private async Task InitAsync() { - if(_didInit) + if (_didInit) { return; } diff --git a/src/Core/Services/Implementations/AppleIapService.cs b/src/Core/Services/Implementations/AppleIapService.cs index b070ac8946..8f460c0a4e 100644 --- a/src/Core/Services/Implementations/AppleIapService.cs +++ b/src/Core/Services/Implementations/AppleIapService.cs @@ -37,7 +37,7 @@ namespace Bit.Core.Services public async Task GetVerifiedReceiptStatusAsync(string receiptData) { var receiptStatus = await GetReceiptStatusAsync(receiptData); - if(receiptStatus?.Status != 0) + if (receiptStatus?.Status != 0) { return null; } @@ -51,7 +51,7 @@ namespace Bit.Core.Services receiptStatus.GetLastTransactionId() != null; var validTransaction = receiptStatus.GetLastExpiresDate() .GetValueOrDefault(DateTime.MinValue) > DateTime.UtcNow; - if(validEnvironment && validProductBundle && validProduct && validIds && validTransaction) + if (validEnvironment && validProductBundle && validProduct && validIds && validTransaction) { return receiptStatus; } @@ -61,7 +61,7 @@ namespace Bit.Core.Services public async Task SaveReceiptAsync(AppleReceiptStatus receiptStatus, Guid userId) { var originalTransactionId = receiptStatus.GetOriginalTransactionId(); - if(string.IsNullOrWhiteSpace(originalTransactionId)) + if (string.IsNullOrWhiteSpace(originalTransactionId)) { throw new Exception("OriginalTransactionId is null"); } @@ -76,7 +76,7 @@ namespace Bit.Core.Services public async Task> GetReceiptAsync(string originalTransactionId) { var receipt = await _metaDataRespository.GetAsync("AppleReceipt", originalTransactionId); - if(receipt == null) + if (receipt == null) { return null; } @@ -89,7 +89,7 @@ namespace Bit.Core.Services { try { - if(attempt > 4) + if (attempt > 4) { throw new Exception("Failed verifying Apple IAP after too many attempts. Last attempt status: " + lastReceiptStatus?.Status ?? "null"); @@ -100,15 +100,15 @@ namespace Bit.Core.Services new JProperty("password", _globalSettings.AppleIap.Password)).ToString(); var response = await _httpClient.PostAsync(url, new StringContent(json)); - if(response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode) { var responseJson = await response.Content.ReadAsStringAsync(); var receiptStatus = JsonConvert.DeserializeObject(responseJson); - if(receiptStatus.Status == 21007) + if (receiptStatus.Status == 21007) { return await GetReceiptStatusAsync(receiptData, false, attempt + 1, receiptStatus); } - else if(receiptStatus.Status == 21005) + else if (receiptStatus.Status == 21005) { await Task.Delay(2000); return await GetReceiptStatusAsync(receiptData, prod, attempt + 1, receiptStatus); @@ -116,7 +116,7 @@ namespace Bit.Core.Services return receiptStatus; } } - catch(Exception e) + catch (Exception e) { _logger.LogWarning(e, "Error verifying Apple IAP receipt."); } diff --git a/src/Core/Services/Implementations/AzureAttachmentStorageService.cs b/src/Core/Services/Implementations/AzureAttachmentStorageService.cs index 21e15a9b2f..5ad473566f 100644 --- a/src/Core/Services/Implementations/AzureAttachmentStorageService.cs +++ b/src/Core/Services/Implementations/AzureAttachmentStorageService.cs @@ -26,7 +26,7 @@ namespace Bit.Core.Services await InitAsync(); var blob = _attachmentsContainer.GetBlockBlobReference($"{cipher.Id}/{attachmentId}"); blob.Metadata.Add("cipherId", cipher.Id.ToString()); - if(cipher.UserId.HasValue) + if (cipher.UserId.HasValue) { blob.Metadata.Add("userId", cipher.UserId.Value.ToString()); } @@ -52,13 +52,13 @@ namespace Bit.Core.Services { await InitAsync(); var source = _attachmentsContainer.GetBlockBlobReference($"temp/{cipherId}/{organizationId}/{attachmentId}"); - if(!(await source.ExistsAsync())) + if (!(await source.ExistsAsync())) { return; } var dest = _attachmentsContainer.GetBlockBlobReference($"{cipherId}/{attachmentId}"); - if(!(await dest.ExistsAsync())) + if (!(await dest.ExistsAsync())) { return; } @@ -78,7 +78,7 @@ namespace Bit.Core.Services await source.DeleteIfExistsAsync(); var original = _attachmentsContainer.GetBlockBlobReference($"temp/{cipherId}/{attachmentId}"); - if(!(await original.ExistsAsync())) + if (!(await original.ExistsAsync())) { return; } @@ -103,17 +103,17 @@ namespace Bit.Core.Services var segment = await _attachmentsContainer.ListBlobsSegmentedAsync($"temp/{cipherId}", true, BlobListingDetails.None, 100, null, null, null); - while(true) + while (true) { - foreach(var blob in segment.Results) + foreach (var blob in segment.Results) { - if(blob is CloudBlockBlob blockBlob) + if (blob is CloudBlockBlob blockBlob) { await blockBlob.DeleteIfExistsAsync(); } } - if(segment.ContinuationToken == null) + if (segment.ContinuationToken == null) { break; } @@ -128,17 +128,17 @@ namespace Bit.Core.Services var segment = await _attachmentsContainer.ListBlobsSegmentedAsync(cipherId.ToString(), true, BlobListingDetails.None, 100, null, null, null); - while(true) + while (true) { - foreach(var blob in segment.Results) + foreach (var blob in segment.Results) { - if(blob is CloudBlockBlob blockBlob) + if (blob is CloudBlockBlob blockBlob) { await blockBlob.DeleteIfExistsAsync(); } } - if(segment.ContinuationToken == null) + if (segment.ContinuationToken == null) { break; } @@ -159,7 +159,7 @@ namespace Bit.Core.Services private async Task InitAsync() { - if(_attachmentsContainer == null) + if (_attachmentsContainer == null) { _attachmentsContainer = _blobClient.GetContainerReference(AttchmentContainerName); await _attachmentsContainer.CreateIfNotExistsAsync(BlobContainerPublicAccessType.Blob, null, null); diff --git a/src/Core/Services/Implementations/AzureQueueBlockIpService.cs b/src/Core/Services/Implementations/AzureQueueBlockIpService.cs index c51d1f6790..bceb6594ad 100644 --- a/src/Core/Services/Implementations/AzureQueueBlockIpService.cs +++ b/src/Core/Services/Implementations/AzureQueueBlockIpService.cs @@ -20,7 +20,7 @@ namespace Bit.Core.Services public async Task BlockIpAsync(string ipAddress, bool permanentBlock) { var now = DateTime.UtcNow; - if(_lastBlock != null && _lastBlock.Item1 == ipAddress && _lastBlock.Item2 == permanentBlock && + if (_lastBlock != null && _lastBlock.Item1 == ipAddress && _lastBlock.Item2 == permanentBlock && (now - _lastBlock.Item3) < TimeSpan.FromMinutes(1)) { // Already blocked this IP recently. @@ -29,7 +29,7 @@ namespace Bit.Core.Services _lastBlock = new Tuple(ipAddress, permanentBlock, now); await _blockIpQueueClient.SendMessageAsync(ipAddress); - if(!permanentBlock) + if (!permanentBlock) { await _unblockIpQueueClient.SendMessageAsync(ipAddress, new TimeSpan(0, 15, 0)); } diff --git a/src/Core/Services/Implementations/AzureQueuePushNotificationService.cs b/src/Core/Services/Implementations/AzureQueuePushNotificationService.cs index 28ef9120f1..0bfc860f2c 100644 --- a/src/Core/Services/Implementations/AzureQueuePushNotificationService.cs +++ b/src/Core/Services/Implementations/AzureQueuePushNotificationService.cs @@ -47,7 +47,7 @@ namespace Bit.Core.Services private async Task PushCipherAsync(Cipher cipher, PushType type, IEnumerable collectionIds) { - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { var message = new SyncCipherPushNotification { @@ -59,7 +59,7 @@ namespace Bit.Core.Services await SendMessageAsync(type, message, true); } - else if(cipher.UserId.HasValue) + else if (cipher.UserId.HasValue) { var message = new SyncCipherPushNotification { @@ -145,7 +145,7 @@ namespace Bit.Core.Services private string GetContextIdentifier(bool excludeCurrentContext) { - if(!excludeCurrentContext) + if (!excludeCurrentContext) { return null; } diff --git a/src/Core/Services/Implementations/BaseIdentityClientService.cs b/src/Core/Services/Implementations/BaseIdentityClientService.cs index 2859ef45e1..cfb5a172b3 100644 --- a/src/Core/Services/Implementations/BaseIdentityClientService.cs +++ b/src/Core/Services/Implementations/BaseIdentityClientService.cs @@ -55,7 +55,7 @@ namespace Bit.Core.Services protected async Task SendAsync(HttpMethod method, string path, object requestModel = null) { var tokenStateResponse = await HandleTokenStateAsync(); - if(!tokenStateResponse) + if (!tokenStateResponse) { return; } @@ -70,7 +70,7 @@ namespace Bit.Core.Services { var response = await Client.SendAsync(message); } - catch(Exception e) + catch (Exception e) { _logger.LogError(12334, e, "Failed to send to {0}.", message.RequestUri.ToString()); } @@ -78,13 +78,13 @@ namespace Bit.Core.Services protected async Task HandleTokenStateAsync() { - if(_nextAuthAttempt.HasValue && DateTime.UtcNow > _nextAuthAttempt.Value) + if (_nextAuthAttempt.HasValue && DateTime.UtcNow > _nextAuthAttempt.Value) { return false; } _nextAuthAttempt = null; - if(!string.IsNullOrWhiteSpace(AccessToken) && !TokenNeedsRefresh()) + if (!string.IsNullOrWhiteSpace(AccessToken) && !TokenNeedsRefresh()) { return true; } @@ -107,19 +107,19 @@ namespace Bit.Core.Services { response = await IdentityClient.SendAsync(requestMessage); } - catch(Exception e) + catch (Exception e) { _logger.LogError(12339, e, "Unable to authenticate with identity server."); } - if(response == null) + if (response == null) { return false; } - if(!response.IsSuccessStatusCode) + if (!response.IsSuccessStatusCode) { - if(response.StatusCode == HttpStatusCode.BadRequest) + if (response.StatusCode == HttpStatusCode.BadRequest) { _nextAuthAttempt = DateTime.UtcNow.AddDays(1); } @@ -143,7 +143,7 @@ namespace Bit.Core.Services public TokenHttpRequestMessage(object requestObject, string token) : this(token) { - if(requestObject != null) + if (requestObject != null) { var stringContent = JsonConvert.SerializeObject(requestObject); Content = new StringContent(stringContent, Encoding.UTF8, "application/json"); @@ -155,7 +155,7 @@ namespace Bit.Core.Services { var decoded = DecodeToken(); var exp = decoded?["exp"]; - if(exp == null) + if (exp == null) { throw new InvalidOperationException("No exp in token."); } @@ -166,24 +166,24 @@ namespace Bit.Core.Services protected JObject DecodeToken() { - if(_decodedToken != null) + if (_decodedToken != null) { return _decodedToken; } - if(AccessToken == null) + if (AccessToken == null) { throw new InvalidOperationException($"{nameof(AccessToken)} not found."); } var parts = AccessToken.Split('.'); - if(parts.Length != 3) + if (parts.Length != 3) { throw new InvalidOperationException($"{nameof(AccessToken)} must have 3 parts"); } var decodedBytes = CoreHelpers.Base64UrlDecode(parts[1]); - if(decodedBytes == null || decodedBytes.Length < 1) + if (decodedBytes == null || decodedBytes.Length < 1) { throw new InvalidOperationException($"{nameof(AccessToken)} must have 3 parts"); } diff --git a/src/Core/Services/Implementations/CipherService.cs b/src/Core/Services/Implementations/CipherService.cs index 3117ede509..fbd86c944e 100644 --- a/src/Core/Services/Implementations/CipherService.cs +++ b/src/Core/Services/Implementations/CipherService.cs @@ -60,16 +60,16 @@ namespace Bit.Core.Services public async Task SaveAsync(Cipher cipher, Guid savingUserId, IEnumerable collectionIds = null, bool skipPermissionCheck = false, bool limitCollectionScope = true) { - if(!skipPermissionCheck && !(await UserCanEditAsync(cipher, savingUserId))) + if (!skipPermissionCheck && !(await UserCanEditAsync(cipher, savingUserId))) { throw new BadRequestException("You do not have permissions to edit this."); } - if(cipher.Id == default(Guid)) + if (cipher.Id == default(Guid)) { - if(cipher.OrganizationId.HasValue && collectionIds != null) + if (cipher.OrganizationId.HasValue && collectionIds != null) { - if(limitCollectionScope) + if (limitCollectionScope) { // Set user ID to limit scope of collection ids in the create sproc cipher.UserId = savingUserId; @@ -87,7 +87,7 @@ namespace Bit.Core.Services } else { - if(collectionIds != null) + if (collectionIds != null) { throw new ArgumentException("Cannot create cipher with collection ids at the same time."); } @@ -103,15 +103,15 @@ namespace Bit.Core.Services public async Task SaveDetailsAsync(CipherDetails cipher, Guid savingUserId, IEnumerable collectionIds = null, bool skipPermissionCheck = false) { - if(!skipPermissionCheck && !(await UserCanEditAsync(cipher, savingUserId))) + if (!skipPermissionCheck && !(await UserCanEditAsync(cipher, savingUserId))) { throw new BadRequestException("You do not have permissions to edit this."); } cipher.UserId = savingUserId; - if(cipher.Id == default(Guid)) + if (cipher.Id == default(Guid)) { - if(cipher.OrganizationId.HasValue && collectionIds != null) + if (cipher.OrganizationId.HasValue && collectionIds != null) { await _cipherRepository.CreateAsync(cipher, collectionIds); } @@ -121,7 +121,7 @@ namespace Bit.Core.Services } await _eventService.LogCipherEventAsync(cipher, Enums.EventType.Cipher_Created); - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { var org = await _organizationRepository.GetByIdAsync(cipher.OrganizationId.Value); cipher.OrganizationUseTotp = org.UseTotp; @@ -132,7 +132,7 @@ namespace Bit.Core.Services } else { - if(collectionIds != null) + if (collectionIds != null) { throw new ArgumentException("Cannot create cipher with collection ids at the same time."); } @@ -148,26 +148,26 @@ namespace Bit.Core.Services public async Task CreateAttachmentAsync(Cipher cipher, Stream stream, string fileName, string key, long requestLength, Guid savingUserId, bool orgAdmin = false) { - if(!orgAdmin && !(await UserCanEditAsync(cipher, savingUserId))) + if (!orgAdmin && !(await UserCanEditAsync(cipher, savingUserId))) { throw new BadRequestException("You do not have permissions to edit this."); } - if(requestLength < 1) + if (requestLength < 1) { throw new BadRequestException("No data to attach."); } var storageBytesRemaining = 0L; - if(cipher.UserId.HasValue) + if (cipher.UserId.HasValue) { var user = await _userRepository.GetByIdAsync(cipher.UserId.Value); - if(!(await _userService.CanAccessPremium(user))) + if (!(await _userService.CanAccessPremium(user))) { throw new BadRequestException("You must have premium status to use attachments."); } - if(user.Premium) + if (user.Premium) { storageBytesRemaining = user.StorageBytesRemaining(); } @@ -179,10 +179,10 @@ namespace Bit.Core.Services _globalSettings.SelfHosted ? (short)10240 : (short)1); } } - else if(cipher.OrganizationId.HasValue) + else if (cipher.OrganizationId.HasValue) { var org = await _organizationRepository.GetByIdAsync(cipher.OrganizationId.Value); - if(!org.MaxStorageGb.HasValue) + if (!org.MaxStorageGb.HasValue) { throw new BadRequestException("This organization cannot use attachments."); } @@ -190,7 +190,7 @@ namespace Bit.Core.Services storageBytesRemaining = org.StorageBytesRemaining(); } - if(storageBytesRemaining < requestLength) + if (storageBytesRemaining < requestLength) { throw new BadRequestException("Not enough storage available."); } @@ -236,29 +236,29 @@ namespace Bit.Core.Services { try { - if(requestLength < 1) + if (requestLength < 1) { throw new BadRequestException("No data to attach."); } - if(cipher.Id == default(Guid)) + if (cipher.Id == default(Guid)) { throw new BadRequestException(nameof(cipher.Id)); } - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { throw new BadRequestException("Cipher belongs to an organization already."); } var org = await _organizationRepository.GetByIdAsync(organizationId); - if(org == null || !org.MaxStorageGb.HasValue) + if (org == null || !org.MaxStorageGb.HasValue) { throw new BadRequestException("This organization cannot use attachments."); } var storageBytesRemaining = org.StorageBytesRemaining(); - if(storageBytesRemaining < requestLength) + if (storageBytesRemaining < requestLength) { throw new BadRequestException("Not enough storage available for this organization."); } @@ -275,7 +275,7 @@ namespace Bit.Core.Services public async Task DeleteAsync(Cipher cipher, Guid deletingUserId, bool orgAdmin = false) { - if(!orgAdmin && !(await UserCanEditAsync(cipher, deletingUserId))) + if (!orgAdmin && !(await UserCanEditAsync(cipher, deletingUserId))) { throw new BadRequestException("You do not have permissions to delete this."); } @@ -298,7 +298,7 @@ namespace Bit.Core.Services var events = deletingCiphers.Select(c => new Tuple(c, EventType.Cipher_Deleted, null)); - foreach(var eventsBatch in events.Batch(100)) + foreach (var eventsBatch in events.Batch(100)) { await _eventService.LogCipherEventsAsync(eventsBatch); } @@ -310,12 +310,12 @@ namespace Bit.Core.Services public async Task DeleteAttachmentAsync(Cipher cipher, string attachmentId, Guid deletingUserId, bool orgAdmin = false) { - if(!orgAdmin && !(await UserCanEditAsync(cipher, deletingUserId))) + if (!orgAdmin && !(await UserCanEditAsync(cipher, deletingUserId))) { throw new BadRequestException("You do not have permissions to delete this."); } - if(!cipher.ContainsAttachment(attachmentId)) + if (!cipher.ContainsAttachment(attachmentId)) { throw new NotFoundException(); } @@ -332,7 +332,7 @@ namespace Bit.Core.Services public async Task PurgeAsync(Guid organizationId) { var org = await _organizationRepository.GetByIdAsync(organizationId); - if(org == null) + if (org == null) { throw new NotFoundException(); } @@ -342,10 +342,10 @@ namespace Bit.Core.Services public async Task MoveManyAsync(IEnumerable cipherIds, Guid? destinationFolderId, Guid movingUserId) { - if(destinationFolderId.HasValue) + if (destinationFolderId.HasValue) { var folder = await _folderRepository.GetByIdAsync(destinationFolderId.Value); - if(folder == null || folder.UserId != movingUserId) + if (folder == null || folder.UserId != movingUserId) { throw new BadRequestException("Invalid folder."); } @@ -358,7 +358,7 @@ namespace Bit.Core.Services public async Task SaveFolderAsync(Folder folder) { - if(folder.Id == default(Guid)) + if (folder.Id == default(Guid)) { await _folderRepository.CreateAsync(folder); @@ -394,29 +394,29 @@ namespace Bit.Core.Services try { - if(cipher.Id == default(Guid)) + if (cipher.Id == default(Guid)) { throw new BadRequestException(nameof(cipher.Id)); } - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { throw new BadRequestException("Already belongs to an organization."); } - if(!cipher.UserId.HasValue || cipher.UserId.Value != sharingUserId) + if (!cipher.UserId.HasValue || cipher.UserId.Value != sharingUserId) { throw new NotFoundException(); } var org = await _organizationRepository.GetByIdAsync(organizationId); - if(hasAttachments && !org.MaxStorageGb.HasValue) + if (hasAttachments && !org.MaxStorageGb.HasValue) { throw new BadRequestException("This organization cannot use attachments."); } var storageAdjustment = attachments?.Sum(a => a.Value.Size) ?? 0; - if(org.StorageBytesRemaining() < storageAdjustment) + if (org.StorageBytesRemaining() < storageAdjustment) { throw new BadRequestException("Not enough storage available for this organization."); } @@ -425,7 +425,7 @@ namespace Bit.Core.Services cipher.UserId = sharingUserId; cipher.OrganizationId = organizationId; cipher.RevisionDate = DateTime.UtcNow; - if(!await _cipherRepository.ReplaceAsync(cipher, collectionIds)) + if (!await _cipherRepository.ReplaceAsync(cipher, collectionIds)) { throw new BadRequestException("Unable to save."); } @@ -433,10 +433,10 @@ namespace Bit.Core.Services updatedCipher = true; await _eventService.LogCipherEventAsync(cipher, Enums.EventType.Cipher_Shared); - if(hasOldAttachments) + if (hasOldAttachments) { // migrate old attachments - foreach(var attachment in attachments.Where(a => a.Key == null)) + foreach (var attachment in attachments.Where(a => a.Key == null)) { await _attachmentStorageService.StartShareAttachmentAsync(cipher.Id, organizationId, attachment.Key); @@ -453,23 +453,23 @@ namespace Bit.Core.Services catch { // roll everything back - if(updatedCipher) + if (updatedCipher) { await _cipherRepository.ReplaceAsync(originalCipher); } - if(!hasOldAttachments || !migratedAttachments) + if (!hasOldAttachments || !migratedAttachments) { throw; } - if(updatedCipher) + if (updatedCipher) { await _userRepository.UpdateStorageAsync(sharingUserId); await _organizationRepository.UpdateStorageAsync(organizationId); } - foreach(var attachment in attachments.Where(a => a.Key == null)) + foreach (var attachment in attachments.Where(a => a.Key == null)) { await _attachmentStorageService.RollbackShareAttachmentAsync(cipher.Id, organizationId, attachment.Key); @@ -484,19 +484,19 @@ namespace Bit.Core.Services IEnumerable collectionIds, Guid sharingUserId) { var cipherIds = new List(); - foreach(var cipher in ciphers) + foreach (var cipher in ciphers) { - if(cipher.Id == default(Guid)) + if (cipher.Id == default(Guid)) { throw new BadRequestException("All ciphers must already exist."); } - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { throw new BadRequestException("One or more ciphers already belong to an organization."); } - if(!cipher.UserId.HasValue || cipher.UserId.Value != sharingUserId) + if (!cipher.UserId.HasValue || cipher.UserId.Value != sharingUserId) { throw new BadRequestException("One or more ciphers do not belong to you."); } @@ -513,7 +513,7 @@ namespace Bit.Core.Services var events = ciphers.Select(c => new Tuple(c, EventType.Cipher_Shared, null)); - foreach(var eventsBatch in events.Batch(100)) + foreach (var eventsBatch in events.Batch(100)) { await _eventService.LogCipherEventsAsync(eventsBatch); } @@ -525,12 +525,12 @@ namespace Bit.Core.Services public async Task SaveCollectionsAsync(Cipher cipher, IEnumerable collectionIds, Guid savingUserId, bool orgAdmin) { - if(cipher.Id == default(Guid)) + if (cipher.Id == default(Guid)) { throw new BadRequestException(nameof(cipher.Id)); } - if(!cipher.OrganizationId.HasValue) + if (!cipher.OrganizationId.HasValue) { throw new BadRequestException("Cipher must belong to an organization."); } @@ -539,14 +539,14 @@ namespace Bit.Core.Services // The sprocs will validate that all collections belong to this org/user and that they have // proper write permissions. - if(orgAdmin) + if (orgAdmin) { await _collectionCipherRepository.UpdateCollectionsForAdminAsync(cipher.Id, cipher.OrganizationId.Value, collectionIds); } else { - if(!(await UserCanEditAsync(cipher, savingUserId))) + if (!(await UserCanEditAsync(cipher, savingUserId))) { throw new BadRequestException("You do not have permissions to edit this."); } @@ -564,29 +564,29 @@ namespace Bit.Core.Services List ciphers, IEnumerable> folderRelationships) { - foreach(var cipher in ciphers) + foreach (var cipher in ciphers) { cipher.SetNewId(); - if(cipher.UserId.HasValue && cipher.Favorite) + if (cipher.UserId.HasValue && cipher.Favorite) { cipher.Favorites = $"{{\"{cipher.UserId.ToString().ToUpperInvariant()}\":\"true\"}}"; } } // Init. ids for folders - foreach(var folder in folders) + foreach (var folder in folders) { folder.SetNewId(); } // Create the folder associations based on the newly created folder ids - foreach(var relationship in folderRelationships) + foreach (var relationship in folderRelationships) { var cipher = ciphers.ElementAtOrDefault(relationship.Key); var folder = folders.ElementAtOrDefault(relationship.Value); - if(cipher == null || folder == null) + if (cipher == null || folder == null) { continue; } @@ -600,7 +600,7 @@ namespace Bit.Core.Services // push var userId = folders.FirstOrDefault()?.UserId ?? ciphers.FirstOrDefault()?.UserId; - if(userId.HasValue) + if (userId.HasValue) { await _pushService.PushSyncVaultAsync(userId.Value); } @@ -612,13 +612,13 @@ namespace Bit.Core.Services IEnumerable> collectionRelationships, Guid importingUserId) { - if(collections.Count > 0) + if (collections.Count > 0) { var org = await _organizationRepository.GetByIdAsync(collections[0].OrganizationId); - if(org != null && org.MaxCollections.HasValue) + if (org != null && org.MaxCollections.HasValue) { var collectionCount = await _collectionRepository.GetCountByOrganizationIdAsync(org.Id); - if(org.MaxCollections.Value < (collectionCount + collections.Count)) + if (org.MaxCollections.Value < (collectionCount + collections.Count)) { throw new BadRequestException("This organization can only have a maximum of " + $"{org.MaxCollections.Value} collections."); @@ -627,25 +627,25 @@ namespace Bit.Core.Services } // Init. ids for ciphers - foreach(var cipher in ciphers) + foreach (var cipher in ciphers) { cipher.SetNewId(); } // Init. ids for collections - foreach(var collection in collections) + foreach (var collection in collections) { collection.SetNewId(); } // Create associations based on the newly assigned ids var collectionCiphers = new List(); - foreach(var relationship in collectionRelationships) + foreach (var relationship in collectionRelationships) { var cipher = ciphers.ElementAtOrDefault(relationship.Key); var collection = collections.ElementAtOrDefault(relationship.Value); - if(cipher == null || collection == null) + if (cipher == null || collection == null) { continue; } @@ -666,7 +666,7 @@ namespace Bit.Core.Services private async Task UserCanEditAsync(Cipher cipher, Guid userId) { - if(!cipher.OrganizationId.HasValue && cipher.UserId.HasValue && cipher.UserId.Value == userId) + if (!cipher.OrganizationId.HasValue && cipher.UserId.HasValue && cipher.UserId.Value == userId) { return true; } diff --git a/src/Core/Services/Implementations/CollectionService.cs b/src/Core/Services/Implementations/CollectionService.cs index 3df6c444d8..e982aff587 100644 --- a/src/Core/Services/Implementations/CollectionService.cs +++ b/src/Core/Services/Implementations/CollectionService.cs @@ -37,24 +37,24 @@ namespace Bit.Core.Services Guid? assignUserId = null) { var org = await _organizationRepository.GetByIdAsync(collection.OrganizationId); - if(org == null) + if (org == null) { throw new BadRequestException("Organization not found"); } - if(collection.Id == default(Guid)) + if (collection.Id == default(Guid)) { - if(org.MaxCollections.HasValue) + if (org.MaxCollections.HasValue) { var collectionCount = await _collectionRepository.GetCountByOrganizationIdAsync(org.Id); - if(org.MaxCollections.Value <= collectionCount) + if (org.MaxCollections.Value <= collectionCount) { throw new BadRequestException("You have reached the maximum number of collections " + $"({org.MaxCollections.Value}) for this organization."); } } - if(groups == null || !org.UseGroups) + if (groups == null || !org.UseGroups) { await _collectionRepository.CreateAsync(collection); } @@ -64,10 +64,10 @@ namespace Bit.Core.Services } // Assign a user to the newly created collection. - if(assignUserId.HasValue) + if (assignUserId.HasValue) { var orgUser = await _organizationUserRepository.GetByOrganizationAsync(org.Id, assignUserId.Value); - if(orgUser != null && orgUser.Status == Enums.OrganizationUserStatusType.Confirmed) + if (orgUser != null && orgUser.Status == Enums.OrganizationUserStatusType.Confirmed) { await _collectionRepository.UpdateUsersAsync(collection.Id, new List { @@ -79,7 +79,7 @@ namespace Bit.Core.Services } else { - if(!org.UseGroups) + if (!org.UseGroups) { await _collectionRepository.ReplaceAsync(collection); } @@ -101,7 +101,7 @@ namespace Bit.Core.Services public async Task DeleteUserAsync(Collection collection, Guid organizationUserId) { var orgUser = await _organizationUserRepository.GetByIdAsync(organizationUserId); - if(orgUser == null || orgUser.OrganizationId != collection.OrganizationId) + if (orgUser == null || orgUser.OrganizationId != collection.OrganizationId) { throw new NotFoundException(); } diff --git a/src/Core/Services/Implementations/DeviceService.cs b/src/Core/Services/Implementations/DeviceService.cs index ca93af8a70..4bf177b4e0 100644 --- a/src/Core/Services/Implementations/DeviceService.cs +++ b/src/Core/Services/Implementations/DeviceService.cs @@ -20,7 +20,7 @@ namespace Bit.Core.Services public async Task SaveAsync(Device device) { - if(device.Id == default(Guid)) + if (device.Id == default(Guid)) { await _deviceRepository.CreateAsync(device); } diff --git a/src/Core/Services/Implementations/EventService.cs b/src/Core/Services/Implementations/EventService.cs index 6e62b0b09b..ab62f87e39 100644 --- a/src/Core/Services/Implementations/EventService.cs +++ b/src/Core/Services/Implementations/EventService.cs @@ -56,7 +56,7 @@ namespace Bit.Core.Services Date = DateTime.UtcNow }); - if(orgEvents.Any()) + if (orgEvents.Any()) { events.AddRange(orgEvents); await _eventWriteService.CreateManyAsync(events); @@ -70,7 +70,7 @@ namespace Bit.Core.Services public async Task LogCipherEventAsync(Cipher cipher, EventType type, DateTime? date = null) { var e = await BuildCipherEventMessageAsync(cipher, type, date); - if(e != null) + if (e != null) { await _eventWriteService.CreateAsync(e); } @@ -79,10 +79,10 @@ namespace Bit.Core.Services public async Task LogCipherEventsAsync(IEnumerable> events) { var cipherEvents = new List(); - foreach(var ev in events) + foreach (var ev in events) { var e = await BuildCipherEventMessageAsync(ev.Item1, ev.Item2, ev.Item3); - if(e != null) + if (e != null) { cipherEvents.Add(e); } @@ -93,15 +93,15 @@ namespace Bit.Core.Services private async Task BuildCipherEventMessageAsync(Cipher cipher, EventType type, DateTime? date = null) { // Only logging organization cipher events for now. - if(!cipher.OrganizationId.HasValue || (!_currentContext?.UserId.HasValue ?? true)) + if (!cipher.OrganizationId.HasValue || (!_currentContext?.UserId.HasValue ?? true)) { return null; } - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); - if(!CanUseEvents(orgAbilities, cipher.OrganizationId.Value)) + if (!CanUseEvents(orgAbilities, cipher.OrganizationId.Value)) { return null; } @@ -121,7 +121,7 @@ namespace Bit.Core.Services public async Task LogCollectionEventAsync(Collection collection, EventType type, DateTime? date = null) { var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); - if(!CanUseEvents(orgAbilities, collection.OrganizationId)) + if (!CanUseEvents(orgAbilities, collection.OrganizationId)) { return; } @@ -140,7 +140,7 @@ namespace Bit.Core.Services public async Task LogGroupEventAsync(Group group, EventType type, DateTime? date = null) { var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); - if(!CanUseEvents(orgAbilities, group.OrganizationId)) + if (!CanUseEvents(orgAbilities, group.OrganizationId)) { return; } @@ -159,7 +159,7 @@ namespace Bit.Core.Services public async Task LogPolicyEventAsync(Policy policy, EventType type, DateTime? date = null) { var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); - if(!CanUseEvents(orgAbilities, policy.OrganizationId)) + if (!CanUseEvents(orgAbilities, policy.OrganizationId)) { return; } @@ -179,7 +179,7 @@ namespace Bit.Core.Services DateTime? date = null) { var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); - if(!CanUseEvents(orgAbilities, organizationUser.OrganizationId)) + if (!CanUseEvents(orgAbilities, organizationUser.OrganizationId)) { return; } @@ -198,7 +198,7 @@ namespace Bit.Core.Services public async Task LogOrganizationEventAsync(Organization organization, EventType type, DateTime? date = null) { - if(!organization.Enabled || !organization.UseEvents) + if (!organization.Enabled || !organization.UseEvents) { return; } diff --git a/src/Core/Services/Implementations/GroupService.cs b/src/Core/Services/Implementations/GroupService.cs index 4a7618c444..1cb300443c 100644 --- a/src/Core/Services/Implementations/GroupService.cs +++ b/src/Core/Services/Implementations/GroupService.cs @@ -30,21 +30,21 @@ namespace Bit.Core.Services public async Task SaveAsync(Group group, IEnumerable collections = null) { var org = await _organizationRepository.GetByIdAsync(group.OrganizationId); - if(org == null) + if (org == null) { throw new BadRequestException("Organization not found"); } - if(!org.UseGroups) + if (!org.UseGroups) { throw new BadRequestException("This organization cannot use groups."); } - if(group.Id == default(Guid)) + if (group.Id == default(Guid)) { group.CreationDate = group.RevisionDate = DateTime.UtcNow; - if(collections == null) + if (collections == null) { await _groupRepository.CreateAsync(group); } @@ -72,7 +72,7 @@ namespace Bit.Core.Services public async Task DeleteUserAsync(Group group, Guid organizationUserId) { var orgUser = await _organizationUserRepository.GetByIdAsync(organizationUserId); - if(orgUser == null || orgUser.OrganizationId != group.OrganizationId) + if (orgUser == null || orgUser.OrganizationId != group.OrganizationId) { throw new NotFoundException(); } diff --git a/src/Core/Services/Implementations/HandlebarsMailService.cs b/src/Core/Services/Implementations/HandlebarsMailService.cs index 2bd6bcc84b..373995af88 100644 --- a/src/Core/Services/Implementations/HandlebarsMailService.cs +++ b/src/Core/Services/Implementations/HandlebarsMailService.cs @@ -338,10 +338,10 @@ namespace Bit.Core.Services private async Task RenderAsync(string templateName, T model) { await RegisterHelpersAndPartialsAsync(); - if(!_templateCache.TryGetValue(templateName, out var template)) + if (!_templateCache.TryGetValue(templateName, out var template)) { var source = await ReadSourceAsync(templateName); - if(source != null) + if (source != null) { template = Handlebars.Compile(source); _templateCache.Add(templateName, template); @@ -354,12 +354,12 @@ namespace Bit.Core.Services { var assembly = typeof(HandlebarsMailService).GetTypeInfo().Assembly; var fullTemplateName = $"{Namespace}.{templateName}.hbs"; - if(!assembly.GetManifestResourceNames().Any(f => f == fullTemplateName)) + if (!assembly.GetManifestResourceNames().Any(f => f == fullTemplateName)) { return null; } - using(var s = assembly.GetManifestResourceStream(fullTemplateName)) - using(var sr = new StreamReader(s)) + using (var s = assembly.GetManifestResourceStream(fullTemplateName)) + using (var sr = new StreamReader(s)) { return await sr.ReadToEndAsync(); } @@ -367,7 +367,7 @@ namespace Bit.Core.Services private async Task RegisterHelpersAndPartialsAsync() { - if(_registeredHelpersAndPartials) + if (_registeredHelpersAndPartials) { return; } @@ -384,12 +384,12 @@ namespace Bit.Core.Services Handlebars.RegisterHelper("date", (writer, context, parameters) => { - if(parameters.Length == 0 || !(parameters[0] is DateTime)) + if (parameters.Length == 0 || !(parameters[0] is DateTime)) { writer.WriteSafeString(string.Empty); return; } - if(parameters.Length > 0 && parameters[1] is string) + if (parameters.Length > 0 && parameters[1] is string) { writer.WriteSafeString(((DateTime)parameters[0]).ToString(parameters[1].ToString())); } @@ -401,7 +401,7 @@ namespace Bit.Core.Services Handlebars.RegisterHelper("usd", (writer, context, parameters) => { - if(parameters.Length == 0 || !(parameters[0] is decimal)) + if (parameters.Length == 0 || !(parameters[0] is decimal)) { writer.WriteSafeString(string.Empty); return; @@ -411,7 +411,7 @@ namespace Bit.Core.Services Handlebars.RegisterHelper("link", (writer, context, parameters) => { - if(parameters.Length == 0) + if (parameters.Length == 0) { writer.WriteSafeString(string.Empty); return; @@ -420,12 +420,12 @@ namespace Bit.Core.Services var text = parameters[0].ToString(); var href = text; var clickTrackingOff = false; - if(parameters.Length == 2) + if (parameters.Length == 2) { - if(parameters[1] is string) + if (parameters[1] is string) { var p1 = parameters[1].ToString(); - if(p1 == "true" || p1 == "false") + if (p1 == "true" || p1 == "false") { clickTrackingOff = p1 == "true"; } @@ -434,26 +434,26 @@ namespace Bit.Core.Services href = p1; } } - else if(parameters[1] is bool) + else if (parameters[1] is bool) { clickTrackingOff = (bool)parameters[1]; } } - else if(parameters.Length > 2) + else if (parameters.Length > 2) { - if(parameters[1] is string) + if (parameters[1] is string) { href = parameters[1].ToString(); } - if(parameters[2] is string) + if (parameters[2] is string) { var p2 = parameters[2].ToString(); - if(p2 == "true" || p2 == "false") + if (p2 == "true" || p2 == "false") { clickTrackingOff = p2 == "true"; } } - else if(parameters[2] is bool) + else if (parameters[2] is bool) { clickTrackingOff = (bool)parameters[2]; } diff --git a/src/Core/Services/Implementations/InMemoryApplicationCacheService.cs b/src/Core/Services/Implementations/InMemoryApplicationCacheService.cs index 7190866423..0c61b1fb47 100644 --- a/src/Core/Services/Implementations/InMemoryApplicationCacheService.cs +++ b/src/Core/Services/Implementations/InMemoryApplicationCacheService.cs @@ -32,7 +32,7 @@ namespace Bit.Core.Services await InitOrganizationAbilitiesAsync(); var newAbility = new OrganizationAbility(organization); - if(_orgAbilities.ContainsKey(organization.Id)) + if (_orgAbilities.ContainsKey(organization.Id)) { _orgAbilities[organization.Id] = newAbility; } @@ -44,7 +44,7 @@ namespace Bit.Core.Services public virtual Task DeleteOrganizationAbilityAsync(Guid organizationId) { - if(_orgAbilities != null && _orgAbilities.ContainsKey(organizationId)) + if (_orgAbilities != null && _orgAbilities.ContainsKey(organizationId)) { _orgAbilities.Remove(organizationId); } @@ -55,7 +55,7 @@ namespace Bit.Core.Services private async Task InitOrganizationAbilitiesAsync() { var now = DateTime.UtcNow; - if(_orgAbilities == null || (now - _lastOrgAbilityRefresh) > _orgAbilitiesRefreshInterval) + if (_orgAbilities == null || (now - _lastOrgAbilityRefresh) > _orgAbilitiesRefreshInterval) { var abilities = await _organizationRepository.GetManyAbilitiesAsync(); _orgAbilities = abilities.ToDictionary(a => a.Id); diff --git a/src/Core/Services/Implementations/LicensingService.cs b/src/Core/Services/Implementations/LicensingService.cs index 9c1266d3d3..5b41c6fcca 100644 --- a/src/Core/Services/Implementations/LicensingService.cs +++ b/src/Core/Services/Implementations/LicensingService.cs @@ -44,12 +44,12 @@ namespace Bit.Core.Services var certThumbprint = environment.IsDevelopment() ? "207E64A231E8AA32AAF68A61037C075EBEBD553F" : "‎B34876439FCDA2846505B2EFBBA6C4A951313EBE"; - if(_globalSettings.SelfHosted) + if (_globalSettings.SelfHosted) { _certificate = CoreHelpers.GetEmbeddedCertificateAsync("licensing.cer", null) .GetAwaiter().GetResult(); } - else if(CoreHelpers.SettingHasValue(_globalSettings.Storage?.ConnectionString) && + else if (CoreHelpers.SettingHasValue(_globalSettings.Storage?.ConnectionString) && CoreHelpers.SettingHasValue(_globalSettings.LicenseCertificatePassword)) { var storageAccount = CloudStorageAccount.Parse(globalSettings.Storage.ConnectionString); @@ -62,13 +62,13 @@ namespace Bit.Core.Services _certificate = CoreHelpers.GetCertificate(certThumbprint); } - if(_certificate == null || !_certificate.Thumbprint.Equals(CoreHelpers.CleanCertificateThumbprint(certThumbprint), + if (_certificate == null || !_certificate.Thumbprint.Equals(CoreHelpers.CleanCertificateThumbprint(certThumbprint), StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Invalid licensing certificate."); } - if(_globalSettings.SelfHosted && !CoreHelpers.SettingHasValue(_globalSettings.LicenseDirectory)) + if (_globalSettings.SelfHosted && !CoreHelpers.SettingHasValue(_globalSettings.LicenseDirectory)) { throw new InvalidOperationException("No license directory."); } @@ -76,7 +76,7 @@ namespace Bit.Core.Services public async Task ValidateOrganizationsAsync() { - if(!_globalSettings.SelfHosted) + if (!_globalSettings.SelfHosted) { return; } @@ -85,29 +85,29 @@ namespace Bit.Core.Services _logger.LogInformation(Constants.BypassFiltersEventId, null, "Validating licenses for {0} organizations.", enabledOrgs.Count); - foreach(var org in enabledOrgs) + foreach (var org in enabledOrgs) { var license = ReadOrganizationLicense(org); - if(license == null) + if (license == null) { await DisableOrganizationAsync(org, null, "No license file."); continue; } var totalLicensedOrgs = enabledOrgs.Count(o => o.LicenseKey.Equals(license.LicenseKey)); - if(totalLicensedOrgs > 1) + if (totalLicensedOrgs > 1) { await DisableOrganizationAsync(org, license, "Multiple organizations."); continue; } - if(!license.VerifyData(org, _globalSettings)) + if (!license.VerifyData(org, _globalSettings)) { await DisableOrganizationAsync(org, license, "Invalid data."); continue; } - if(!license.VerifySignature(_certificate)) + if (!license.VerifySignature(_certificate)) { await DisableOrganizationAsync(org, license, "Invalid signature."); continue; @@ -128,7 +128,7 @@ namespace Bit.Core.Services public async Task ValidateUsersAsync() { - if(!_globalSettings.SelfHosted) + if (!_globalSettings.SelfHosted) { return; } @@ -137,7 +137,7 @@ namespace Bit.Core.Services _logger.LogInformation(Constants.BypassFiltersEventId, null, "Validating premium for {0} users.", premiumUsers.Count); - foreach(var user in premiumUsers) + foreach (var user in premiumUsers) { await ProcessUserValidationAsync(user); } @@ -145,22 +145,22 @@ namespace Bit.Core.Services public async Task ValidateUserPremiumAsync(User user) { - if(!_globalSettings.SelfHosted) + if (!_globalSettings.SelfHosted) { return user.Premium; } - if(!user.Premium) + if (!user.Premium) { return false; } // Only check once per day var now = DateTime.UtcNow; - if(_userCheckCache.ContainsKey(user.Id)) + if (_userCheckCache.ContainsKey(user.Id)) { var lastCheck = _userCheckCache[user.Id]; - if(lastCheck < now && now - lastCheck < TimeSpan.FromDays(1)) + if (lastCheck < now && now - lastCheck < TimeSpan.FromDays(1)) { return user.Premium; } @@ -182,19 +182,19 @@ namespace Bit.Core.Services private async Task ProcessUserValidationAsync(User user) { var license = ReadUserLicense(user); - if(license == null) + if (license == null) { await DisablePremiumAsync(user, null, "No license file."); return false; } - if(!license.VerifyData(user)) + if (!license.VerifyData(user)) { await DisablePremiumAsync(user, license, "Invalid data."); return false; } - if(!license.VerifySignature(_certificate)) + if (!license.VerifySignature(_certificate)) { await DisablePremiumAsync(user, license, "Invalid signature."); return false; @@ -222,7 +222,7 @@ namespace Bit.Core.Services public byte[] SignLicense(ILicense license) { - if(_globalSettings.SelfHosted || !_certificate.HasPrivateKey) + if (_globalSettings.SelfHosted || !_certificate.HasPrivateKey) { throw new InvalidOperationException("Cannot sign licenses."); } @@ -233,7 +233,7 @@ namespace Bit.Core.Services private UserLicense ReadUserLicense(User user) { var filePath = $"{_globalSettings.LicenseDirectory}/user/{user.Id}.json"; - if(!File.Exists(filePath)) + if (!File.Exists(filePath)) { return null; } @@ -245,7 +245,7 @@ namespace Bit.Core.Services private OrganizationLicense ReadOrganizationLicense(Organization organization) { var filePath = $"{_globalSettings.LicenseDirectory}/organization/{organization.Id}.json"; - if(!File.Exists(filePath)) + if (!File.Exists(filePath)) { return null; } diff --git a/src/Core/Services/Implementations/LocalAttachmentStorageService.cs b/src/Core/Services/Implementations/LocalAttachmentStorageService.cs index 79abf5de6a..7eb9eaf257 100644 --- a/src/Core/Services/Implementations/LocalAttachmentStorageService.cs +++ b/src/Core/Services/Implementations/LocalAttachmentStorageService.cs @@ -23,7 +23,7 @@ namespace Bit.Core.Services var cipherDirPath = $"{_baseDirPath}/{cipher.Id}"; CreateDirectoryIfNotExists(cipherDirPath); - using(var fs = File.Create($"{cipherDirPath}/{attachmentId}")) + using (var fs = File.Create($"{cipherDirPath}/{attachmentId}")) { stream.Seek(0, SeekOrigin.Begin); await stream.CopyToAsync(fs); @@ -36,7 +36,7 @@ namespace Bit.Core.Services var tempCipherOrgDirPath = $"{_baseTempDirPath}/{cipherId}/{organizationId}"; CreateDirectoryIfNotExists(tempCipherOrgDirPath); - using(var fs = File.Create($"{tempCipherOrgDirPath}/{attachmentId}")) + using (var fs = File.Create($"{tempCipherOrgDirPath}/{attachmentId}")) { stream.Seek(0, SeekOrigin.Begin); await stream.CopyToAsync(fs); @@ -47,13 +47,13 @@ namespace Bit.Core.Services { await InitAsync(); var sourceFilePath = $"{_baseTempDirPath}/{cipherId}/{organizationId}/{attachmentId}"; - if(!File.Exists(sourceFilePath)) + if (!File.Exists(sourceFilePath)) { return; } var destFilePath = $"{_baseDirPath}/{cipherId}/{attachmentId}"; - if(!File.Exists(destFilePath)) + if (!File.Exists(destFilePath)) { return; } @@ -73,7 +73,7 @@ namespace Bit.Core.Services DeleteFileIfExists($"{_baseTempDirPath}/{cipherId}/{organizationId}/{attachmentId}"); var originalFilePath = $"{_baseTempDirPath}/{cipherId}/{attachmentId}"; - if(!File.Exists(originalFilePath)) + if (!File.Exists(originalFilePath)) { return; } @@ -115,7 +115,7 @@ namespace Bit.Core.Services private void DeleteFileIfExists(string path) { - if(File.Exists(path)) + if (File.Exists(path)) { File.Delete(path); } @@ -123,7 +123,7 @@ namespace Bit.Core.Services private void DeleteDirectoryIfExists(string path) { - if(Directory.Exists(path)) + if (Directory.Exists(path)) { Directory.Delete(path, true); } @@ -131,7 +131,7 @@ namespace Bit.Core.Services private void CreateDirectoryIfNotExists(string path) { - if(!Directory.Exists(path)) + if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } @@ -139,12 +139,12 @@ namespace Bit.Core.Services private Task InitAsync() { - if(!Directory.Exists(_baseDirPath)) + if (!Directory.Exists(_baseDirPath)) { Directory.CreateDirectory(_baseDirPath); } - if(!Directory.Exists(_baseTempDirPath)) + if (!Directory.Exists(_baseTempDirPath)) { Directory.CreateDirectory(_baseTempDirPath); } diff --git a/src/Core/Services/Implementations/MailKitSmtpMailDeliveryService.cs b/src/Core/Services/Implementations/MailKitSmtpMailDeliveryService.cs index 7471f78cbd..22a806ef2a 100644 --- a/src/Core/Services/Implementations/MailKitSmtpMailDeliveryService.cs +++ b/src/Core/Services/Implementations/MailKitSmtpMailDeliveryService.cs @@ -17,11 +17,11 @@ namespace Bit.Core.Services GlobalSettings globalSettings, ILogger logger) { - if(globalSettings.Mail?.Smtp?.Host == null) + if (globalSettings.Mail?.Smtp?.Host == null) { throw new ArgumentNullException(nameof(globalSettings.Mail.Smtp.Host)); } - if(globalSettings.Mail?.ReplyToEmail?.Contains("@") ?? false) + if (globalSettings.Mail?.ReplyToEmail?.Contains("@") ?? false) { _replyDomain = globalSettings.Mail.ReplyToEmail.Split('@')[1]; } @@ -35,40 +35,40 @@ namespace Bit.Core.Services var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(_globalSettings.SiteName, _globalSettings.Mail.ReplyToEmail)); mimeMessage.Subject = message.Subject; - if(!string.IsNullOrWhiteSpace(_replyDomain)) + if (!string.IsNullOrWhiteSpace(_replyDomain)) { mimeMessage.MessageId = $"<{Guid.NewGuid()}@{_replyDomain}>"; } - foreach(var address in message.ToEmails) + foreach (var address in message.ToEmails) { mimeMessage.To.Add(new MailboxAddress(address)); } - if(message.BccEmails != null) + if (message.BccEmails != null) { - foreach(var address in message.BccEmails) + foreach (var address in message.BccEmails) { mimeMessage.Bcc.Add(new MailboxAddress(address)); } } var builder = new BodyBuilder(); - if(!string.IsNullOrWhiteSpace(message.TextContent)) + if (!string.IsNullOrWhiteSpace(message.TextContent)) { builder.TextBody = message.TextContent; } builder.HtmlBody = message.HtmlContent; mimeMessage.Body = builder.ToMessageBody(); - using(var client = new SmtpClient()) + using (var client = new SmtpClient()) { - if(_globalSettings.Mail.Smtp.TrustServer) + if (_globalSettings.Mail.Smtp.TrustServer) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; } - if(!_globalSettings.Mail.Smtp.StartTls && !_globalSettings.Mail.Smtp.Ssl && + if (!_globalSettings.Mail.Smtp.StartTls && !_globalSettings.Mail.Smtp.Ssl && _globalSettings.Mail.Smtp.Port == 25) { await client.ConnectAsync(_globalSettings.Mail.Smtp.Host, _globalSettings.Mail.Smtp.Port, @@ -81,7 +81,7 @@ namespace Bit.Core.Services await client.ConnectAsync(_globalSettings.Mail.Smtp.Host, _globalSettings.Mail.Smtp.Port, useSsl); } - if(CoreHelpers.SettingHasValue(_globalSettings.Mail.Smtp.Username) && + if (CoreHelpers.SettingHasValue(_globalSettings.Mail.Smtp.Username) && CoreHelpers.SettingHasValue(_globalSettings.Mail.Smtp.Password)) { await client.AuthenticateAsync(_globalSettings.Mail.Smtp.Username, diff --git a/src/Core/Services/Implementations/MultiServicePushNotificationService.cs b/src/Core/Services/Implementations/MultiServicePushNotificationService.cs index b925d265a1..40ce4fbf3a 100644 --- a/src/Core/Services/Implementations/MultiServicePushNotificationService.cs +++ b/src/Core/Services/Implementations/MultiServicePushNotificationService.cs @@ -24,16 +24,16 @@ namespace Bit.Core.Services ILogger relayLogger, ILogger hubLogger) { - if(globalSettings.SelfHosted) + if (globalSettings.SelfHosted) { - if(CoreHelpers.SettingHasValue(globalSettings.PushRelayBaseUri) && + if (CoreHelpers.SettingHasValue(globalSettings.PushRelayBaseUri) && globalSettings.Installation?.Id != null && CoreHelpers.SettingHasValue(globalSettings.Installation?.Key)) { _services.Add(new RelayPushNotificationService(deviceRepository, globalSettings, httpContextAccessor, relayLogger)); } - if(CoreHelpers.SettingHasValue(globalSettings.InternalIdentityKey) && + if (CoreHelpers.SettingHasValue(globalSettings.InternalIdentityKey) && CoreHelpers.SettingHasValue(globalSettings.BaseServiceUri.InternalNotifications)) { _services.Add(new NotificationsApiPushNotificationService( @@ -42,12 +42,12 @@ namespace Bit.Core.Services } else { - if(CoreHelpers.SettingHasValue(globalSettings.NotificationHub.ConnectionString)) + if (CoreHelpers.SettingHasValue(globalSettings.NotificationHub.ConnectionString)) { _services.Add(new NotificationHubPushNotificationService(installationDeviceRepository, globalSettings, httpContextAccessor)); } - if(CoreHelpers.SettingHasValue(globalSettings.Notifications?.ConnectionString)) + if (CoreHelpers.SettingHasValue(globalSettings.Notifications?.ConnectionString)) { _services.Add(new AzureQueuePushNotificationService(globalSettings, httpContextAccessor)); } @@ -138,9 +138,9 @@ namespace Bit.Core.Services private void PushToServices(Func pushFunc) { - if(_services != null) + if (_services != null) { - foreach(var service in _services) + foreach (var service in _services) { pushFunc(service); } diff --git a/src/Core/Services/Implementations/NotificationHubPushNotificationService.cs b/src/Core/Services/Implementations/NotificationHubPushNotificationService.cs index d43705de0f..e12a55baa0 100644 --- a/src/Core/Services/Implementations/NotificationHubPushNotificationService.cs +++ b/src/Core/Services/Implementations/NotificationHubPushNotificationService.cs @@ -50,7 +50,7 @@ namespace Bit.Core.Services private async Task PushCipherAsync(Cipher cipher, PushType type, IEnumerable collectionIds) { - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { // We cannot send org pushes since access logic is much more complicated than just the fact that they belong // to the organization. Potentially we could blindly send to just users that have the access all permission @@ -59,7 +59,7 @@ namespace Bit.Core.Services // await SendPayloadToOrganizationAsync(cipher.OrganizationId.Value, type, message, true); } - else if(cipher.UserId.HasValue) + else if (cipher.UserId.HasValue) { var message = new SyncCipherPushNotification { @@ -151,7 +151,7 @@ namespace Bit.Core.Services { var tag = BuildTag($"template:payload_userId:{userId}", identifier); await SendPayloadAsync(tag, type, payload); - if(InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) + if (InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) { await _installationDeviceRepository.UpsertAsync(new InstallationDeviceEntity(deviceId)); } @@ -162,7 +162,7 @@ namespace Bit.Core.Services { var tag = BuildTag($"template:payload && organizationId:{orgId}", identifier); await SendPayloadAsync(tag, type, payload); - if(InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) + if (InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) { await _installationDeviceRepository.UpsertAsync(new InstallationDeviceEntity(deviceId)); } @@ -170,7 +170,7 @@ namespace Bit.Core.Services private string GetContextIdentifier(bool excludeCurrentContext) { - if(!excludeCurrentContext) + if (!excludeCurrentContext) { return null; } @@ -182,7 +182,7 @@ namespace Bit.Core.Services private string BuildTag(string tag, string identifier) { - if(!string.IsNullOrWhiteSpace(identifier)) + if (!string.IsNullOrWhiteSpace(identifier)) { tag += $" && !deviceIdentifier:{identifier}"; } diff --git a/src/Core/Services/Implementations/NotificationHubPushRegistrationService.cs b/src/Core/Services/Implementations/NotificationHubPushRegistrationService.cs index f1c2b262f2..ff95cd5ad0 100644 --- a/src/Core/Services/Implementations/NotificationHubPushRegistrationService.cs +++ b/src/Core/Services/Implementations/NotificationHubPushRegistrationService.cs @@ -30,7 +30,7 @@ namespace Bit.Core.Services public async Task CreateOrUpdateRegistrationAsync(string pushToken, string deviceId, string userId, string identifier, DeviceType type) { - if(string.IsNullOrWhiteSpace(pushToken)) + if (string.IsNullOrWhiteSpace(pushToken)) { return; } @@ -47,13 +47,13 @@ namespace Bit.Core.Services $"userId:{userId}" }; - if(!string.IsNullOrWhiteSpace(identifier)) + if (!string.IsNullOrWhiteSpace(identifier)) { installation.Tags.Add("deviceIdentifier:" + identifier); } string payloadTemplate = null, messageTemplate = null, badgeMessageTemplate = null; - switch(type) + switch (type) { case DeviceType.Android: payloadTemplate = "{\"data\":{\"data\":{\"type\":\"#(type)\",\"payload\":\"$(payload)\"}}}"; @@ -88,7 +88,7 @@ namespace Bit.Core.Services userId, identifier); await _client.CreateOrUpdateInstallationAsync(installation); - if(InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) + if (InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) { await _installationDeviceRepository.UpsertAsync(new InstallationDeviceEntity(deviceId)); } @@ -97,7 +97,7 @@ namespace Bit.Core.Services private void BuildInstallationTemplate(Installation installation, string templateId, string templateBody, string userId, string identifier) { - if(templateBody == null) + if (templateBody == null) { return; } @@ -114,7 +114,7 @@ namespace Bit.Core.Services } }; - if(!string.IsNullOrWhiteSpace(identifier)) + if (!string.IsNullOrWhiteSpace(identifier)) { template.Tags.Add($"{fullTemplateId}_deviceIdentifier:{identifier}"); } @@ -127,14 +127,14 @@ namespace Bit.Core.Services try { await _client.DeleteInstallationAsync(deviceId); - if(InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) + if (InstallationDeviceEntity.IsInstallationDeviceId(deviceId)) { await _installationDeviceRepository.DeleteAsync(new InstallationDeviceEntity(deviceId)); } } - catch(Exception e) + catch (Exception e) { - if(e.InnerException == null || !e.InnerException.Message.Contains("(404) Not Found")) + if (e.InnerException == null || !e.InnerException.Message.Contains("(404) Not Found")) { throw e; } @@ -144,7 +144,7 @@ namespace Bit.Core.Services public async Task AddUserRegistrationOrganizationAsync(IEnumerable deviceIds, string organizationId) { await PatchTagsForUserDevicesAsync(deviceIds, UpdateOperationType.Add, $"organizationId:{organizationId}"); - if(deviceIds.Any() && InstallationDeviceEntity.IsInstallationDeviceId(deviceIds.First())) + if (deviceIds.Any() && InstallationDeviceEntity.IsInstallationDeviceId(deviceIds.First())) { var entities = deviceIds.Select(e => new InstallationDeviceEntity(e)); await _installationDeviceRepository.UpsertManyAsync(entities.ToList()); @@ -155,7 +155,7 @@ namespace Bit.Core.Services { await PatchTagsForUserDevicesAsync(deviceIds, UpdateOperationType.Remove, $"organizationId:{organizationId}"); - if(deviceIds.Any() && InstallationDeviceEntity.IsInstallationDeviceId(deviceIds.First())) + if (deviceIds.Any() && InstallationDeviceEntity.IsInstallationDeviceId(deviceIds.First())) { var entities = deviceIds.Select(e => new InstallationDeviceEntity(e)); await _installationDeviceRepository.UpsertManyAsync(entities.ToList()); @@ -165,7 +165,7 @@ namespace Bit.Core.Services private async Task PatchTagsForUserDevicesAsync(IEnumerable deviceIds, UpdateOperationType op, string tag) { - if(!deviceIds.Any()) + if (!deviceIds.Any()) { return; } @@ -176,24 +176,24 @@ namespace Bit.Core.Services Path = "/tags" }; - if(op == UpdateOperationType.Add) + if (op == UpdateOperationType.Add) { operation.Value = tag; } - else if(op == UpdateOperationType.Remove) + else if (op == UpdateOperationType.Remove) { operation.Path += $"/{tag}"; } - foreach(var id in deviceIds) + foreach (var id in deviceIds) { try { await _client.PatchInstallationAsync(id, new List { operation }); } - catch(Exception e) + catch (Exception e) { - if(e.InnerException == null || !e.InnerException.Message.Contains("(404) Not Found")) + if (e.InnerException == null || !e.InnerException.Message.Contains("(404) Not Found")) { throw e; } diff --git a/src/Core/Services/Implementations/NotificationsApiPushNotificationService.cs b/src/Core/Services/Implementations/NotificationsApiPushNotificationService.cs index 05cb139183..04f2240268 100644 --- a/src/Core/Services/Implementations/NotificationsApiPushNotificationService.cs +++ b/src/Core/Services/Implementations/NotificationsApiPushNotificationService.cs @@ -54,7 +54,7 @@ namespace Bit.Core.Services private async Task PushCipherAsync(Cipher cipher, PushType type, IEnumerable collectionIds) { - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { var message = new SyncCipherPushNotification { @@ -66,7 +66,7 @@ namespace Bit.Core.Services await SendMessageAsync(type, message, true); } - else if(cipher.UserId.HasValue) + else if (cipher.UserId.HasValue) { var message = new SyncCipherPushNotification { @@ -151,7 +151,7 @@ namespace Bit.Core.Services private string GetContextIdentifier(bool excludeCurrentContext) { - if(!excludeCurrentContext) + if (!excludeCurrentContext) { return null; } diff --git a/src/Core/Services/Implementations/OrganizationService.cs b/src/Core/Services/Implementations/OrganizationService.cs index 4c65dcfcb4..db0d3fcc32 100644 --- a/src/Core/Services/Implementations/OrganizationService.cs +++ b/src/Core/Services/Implementations/OrganizationService.cs @@ -78,14 +78,14 @@ namespace Bit.Core.Services PaymentMethodType paymentMethodType) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } var updated = await _paymentService.UpdatePaymentMethodAsync(organization, paymentMethodType, paymentToken); - if(updated) + if (updated) { await ReplaceAndUpdateCache(organization); } @@ -94,13 +94,13 @@ namespace Bit.Core.Services public async Task CancelSubscriptionAsync(Guid organizationId, bool? endOfPeriod = null) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } var eop = endOfPeriod.GetValueOrDefault(true); - if(!endOfPeriod.HasValue && organization.ExpirationDate.HasValue && + if (!endOfPeriod.HasValue && organization.ExpirationDate.HasValue && organization.ExpirationDate.Value < DateTime.UtcNow) { eop = false; @@ -112,7 +112,7 @@ namespace Bit.Core.Services public async Task ReinstateSubscriptionAsync(Guid organizationId) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } @@ -123,39 +123,39 @@ namespace Bit.Core.Services public async Task> UpgradePlanAsync(Guid organizationId, OrganizationUpgrade upgrade) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } - if(string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) + if (string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) { throw new BadRequestException("Your account has no payment method available."); } var existingPlan = StaticStore.Plans.FirstOrDefault(p => p.Type == organization.PlanType); - if(existingPlan == null) + if (existingPlan == null) { throw new BadRequestException("Existing plan not found."); } var newPlan = StaticStore.Plans.FirstOrDefault(p => p.Type == upgrade.Plan && !p.Disabled); - if(newPlan == null) + if (newPlan == null) { throw new BadRequestException("Plan not found."); } - if(existingPlan.Type == newPlan.Type) + if (existingPlan.Type == newPlan.Type) { throw new BadRequestException("Organization is already on this plan."); } - if(existingPlan.UpgradeSortOrder >= newPlan.UpgradeSortOrder) + if (existingPlan.UpgradeSortOrder >= newPlan.UpgradeSortOrder) { throw new BadRequestException("You cannot upgrade to this plan."); } - if(existingPlan.Type != PlanType.Free) + if (existingPlan.Type != PlanType.Free) { throw new BadRequestException("You can only upgrade from the free plan. Contact support."); } @@ -164,21 +164,21 @@ namespace Bit.Core.Services var newPlanSeats = (short)(newPlan.BaseSeats + (newPlan.CanBuyAdditionalSeats ? upgrade.AdditionalSeats : 0)); - if(!organization.Seats.HasValue || organization.Seats.Value > newPlanSeats) + if (!organization.Seats.HasValue || organization.Seats.Value > newPlanSeats) { var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organization.Id); - if(userCount > newPlanSeats) + if (userCount > newPlanSeats) { throw new BadRequestException($"Your organization currently has {userCount} seats filled. " + $"Your new plan only has ({newPlanSeats}) seats. Remove some users."); } } - if(newPlan.MaxCollections.HasValue && (!organization.MaxCollections.HasValue || + if (newPlan.MaxCollections.HasValue && (!organization.MaxCollections.HasValue || organization.MaxCollections.Value > newPlan.MaxCollections.Value)) { var collectionCount = await _collectionRepository.GetCountByOrganizationIdAsync(organization.Id); - if(collectionCount > newPlan.MaxCollections.Value) + if (collectionCount > newPlan.MaxCollections.Value) { throw new BadRequestException($"Your organization currently has {collectionCount} collections. " + $"Your new plan allows for a maximum of ({newPlan.MaxCollections.Value}) collections. " + @@ -186,20 +186,20 @@ namespace Bit.Core.Services } } - if(!newPlan.UseGroups && organization.UseGroups) + if (!newPlan.UseGroups && organization.UseGroups) { var groups = await _groupRepository.GetManyByOrganizationIdAsync(organization.Id); - if(groups.Any()) + if (groups.Any()) { throw new BadRequestException($"Your new plan does not allow the groups feature. " + $"Remove your groups."); } } - if(!newPlan.UsePolicies && organization.UsePolicies) + if (!newPlan.UsePolicies && organization.UsePolicies) { var policies = await _policyRepository.GetManyByOrganizationIdAsync(organization.Id); - if(policies.Any(p => p.Enabled)) + if (policies.Any(p => p.Enabled)) { throw new BadRequestException($"Your new plan does not allow the policies feature. " + $"Disable your policies."); @@ -210,7 +210,7 @@ namespace Bit.Core.Services string paymentIntentClientSecret = null; var success = true; - if(string.IsNullOrWhiteSpace(organization.GatewaySubscriptionId)) + if (string.IsNullOrWhiteSpace(organization.GatewaySubscriptionId)) { paymentIntentClientSecret = await _paymentService.UpgradeFreeOrganizationAsync(organization, newPlan, upgrade.AdditionalStorageGb, upgrade.AdditionalSeats, upgrade.PremiumAccessAddon); @@ -246,18 +246,18 @@ namespace Bit.Core.Services public async Task AdjustStorageAsync(Guid organizationId, short storageAdjustmentGb) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } var plan = StaticStore.Plans.FirstOrDefault(p => p.Type == organization.PlanType); - if(plan == null) + if (plan == null) { throw new BadRequestException("Existing plan not found."); } - if(!plan.MaxStorageGb.HasValue) + if (!plan.MaxStorageGb.HasValue) { throw new BadRequestException("Plan does not allow additional storage."); } @@ -271,54 +271,54 @@ namespace Bit.Core.Services public async Task AdjustSeatsAsync(Guid organizationId, int seatAdjustment) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } - if(string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) + if (string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) { throw new BadRequestException("No payment method found."); } - if(string.IsNullOrWhiteSpace(organization.GatewaySubscriptionId)) + if (string.IsNullOrWhiteSpace(organization.GatewaySubscriptionId)) { throw new BadRequestException("No subscription found."); } var plan = StaticStore.Plans.FirstOrDefault(p => p.Type == organization.PlanType); - if(plan == null) + if (plan == null) { throw new BadRequestException("Existing plan not found."); } - if(!plan.CanBuyAdditionalSeats) + if (!plan.CanBuyAdditionalSeats) { throw new BadRequestException("Plan does not allow additional seats."); } var newSeatTotal = organization.Seats + seatAdjustment; - if(plan.BaseSeats > newSeatTotal) + if (plan.BaseSeats > newSeatTotal) { throw new BadRequestException($"Plan has a minimum of {plan.BaseSeats} seats."); } - if(newSeatTotal <= 0) + if (newSeatTotal <= 0) { throw new BadRequestException("You must have at least 1 seat."); } var additionalSeats = newSeatTotal - plan.BaseSeats; - if(plan.MaxAdditionalSeats.HasValue && additionalSeats > plan.MaxAdditionalSeats.Value) + if (plan.MaxAdditionalSeats.HasValue && additionalSeats > plan.MaxAdditionalSeats.Value) { throw new BadRequestException($"Organization plan allows a maximum of " + $"{plan.MaxAdditionalSeats.Value} additional seats."); } - if(!organization.Seats.HasValue || organization.Seats.Value > newSeatTotal) + if (!organization.Seats.HasValue || organization.Seats.Value > newSeatTotal) { var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organization.Id); - if(userCount > newSeatTotal) + if (userCount > newSeatTotal) { throw new BadRequestException($"Your organization currently has {userCount} seats filled. " + $"Your new plan only has ({newSeatTotal}) seats. Remove some users."); @@ -328,7 +328,7 @@ namespace Bit.Core.Services var subscriptionItemService = new SubscriptionItemService(); var subscriptionService = new SubscriptionService(); var sub = await subscriptionService.GetAsync(organization.GatewaySubscriptionId); - if(sub == null) + if (sub == null) { throw new BadRequestException("Subscription not found."); } @@ -343,7 +343,7 @@ namespace Bit.Core.Services Quantity = i.Quantity, }).ToList(); - if(additionalSeats > 0 && seatItem == null) + if (additionalSeats > 0 && seatItem == null) { subItemOptions.Add(new InvoiceSubscriptionItemOptions { @@ -359,7 +359,7 @@ namespace Bit.Core.Services SubscriptionId = sub.Id }); } - else if(additionalSeats > 0 && seatItem != null) + else if (additionalSeats > 0 && seatItem != null) { subItemOptions.Add(new InvoiceSubscriptionItemOptions { @@ -375,7 +375,7 @@ namespace Bit.Core.Services Prorate = prorate }); } - else if(seatItem != null && additionalSeats == 0) + else if (seatItem != null && additionalSeats == 0) { subItemOptions.Add(new InvoiceSubscriptionItemOptions { @@ -387,7 +387,7 @@ namespace Bit.Core.Services string paymentIntentClientSecret = null; var invoicedNow = false; - if(additionalSeats > 0) + if (additionalSeats > 0) { var result = await (_paymentService as StripePaymentService).PreviewUpcomingInvoiceAndPayAsync( organization, plan.StripeSeatPlanId, subItemOptions, 500); @@ -404,12 +404,12 @@ namespace Bit.Core.Services public async Task VerifyBankAsync(Guid organizationId, int amount1, int amount2) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } - if(string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) + if (string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) { throw new GatewayException("Not a gateway customer."); } @@ -417,14 +417,14 @@ namespace Bit.Core.Services var bankService = new BankAccountService(); var customerService = new CustomerService(); var customer = await customerService.GetAsync(organization.GatewayCustomerId); - if(customer == null) + if (customer == null) { throw new GatewayException("Cannot find customer."); } var bankAccount = customer.Sources .FirstOrDefault(s => s is BankAccount && ((BankAccount)s).Status != "verified") as BankAccount; - if(bankAccount == null) + if (bankAccount == null) { throw new GatewayException("Cannot find an unverified bank account."); } @@ -433,12 +433,12 @@ namespace Bit.Core.Services { var result = await bankService.VerifyAsync(organization.GatewayCustomerId, bankAccount.Id, new BankAccountVerifyOptions { Amounts = new List { amount1, amount2 } }); - if(result.Status != "verified") + if (result.Status != "verified") { throw new GatewayException("Unable to verify account."); } } - catch(StripeException e) + catch (StripeException e) { throw new GatewayException(e.Message); } @@ -447,7 +447,7 @@ namespace Bit.Core.Services public async Task> SignUpAsync(OrganizationSignup signup) { var plan = StaticStore.Plans.FirstOrDefault(p => p.Type == signup.Plan && !p.Disabled); - if(plan == null) + if (plan == null) { throw new BadRequestException("Plan not found."); } @@ -484,11 +484,11 @@ namespace Bit.Core.Services RevisionDate = DateTime.UtcNow }; - if(plan.Type == PlanType.Free) + if (plan.Type == PlanType.Free) { var adminCount = await _organizationUserRepository.GetCountByFreeOrganizationAdminUserAsync(signup.Owner.Id); - if(adminCount > 0) + if (adminCount > 0) { throw new BadRequestException("You can only be an admin of one free organization."); } @@ -506,25 +506,25 @@ namespace Bit.Core.Services public async Task> SignUpAsync( OrganizationLicense license, User owner, string ownerKey, string collectionName) { - if(license == null || !_licensingService.VerifyLicense(license)) + if (license == null || !_licensingService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } - if(!license.CanUse(_globalSettings)) + if (!license.CanUse(_globalSettings)) { throw new BadRequestException("Invalid license. Make sure your license allows for on-premise " + "hosting of organizations and that the installation id matches your current installation."); } - if(license.PlanType != PlanType.Custom && + if (license.PlanType != PlanType.Custom && StaticStore.Plans.FirstOrDefault(p => p.Type == license.PlanType && !p.Disabled) == null) { throw new BadRequestException("Plan not found."); } var enabledOrgs = await _organizationRepository.GetManyByEnabledAsync(); - if(enabledOrgs.Any(o => o.LicenseKey.Equals(license.LicenseKey))) + if (enabledOrgs.Any(o => o.LicenseKey.Equals(license.LicenseKey))) { throw new BadRequestException("License is already in use by another organization."); } @@ -590,7 +590,7 @@ namespace Bit.Core.Services await _organizationUserRepository.CreateAsync(orgUser); - if(!string.IsNullOrWhiteSpace(collectionName)) + if (!string.IsNullOrWhiteSpace(collectionName)) { var defaultCollection = new Collection { @@ -612,12 +612,12 @@ namespace Bit.Core.Services } catch { - if(withPayment) + if (withPayment) { await _paymentService.CancelAndRecoverChargesAsync(organization); } - if(organization.Id != default(Guid)) + if (organization.Id != default(Guid)) { await _organizationRepository.DeleteAsync(organization); await _applicationCacheService.DeleteOrganizationAbilityAsync(organization.Id); @@ -630,49 +630,49 @@ namespace Bit.Core.Services public async Task UpdateLicenseAsync(Guid organizationId, OrganizationLicense license) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } - if(!_globalSettings.SelfHosted) + if (!_globalSettings.SelfHosted) { throw new InvalidOperationException("Licenses require self hosting."); } - if(license == null || !_licensingService.VerifyLicense(license)) + if (license == null || !_licensingService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } - if(!license.CanUse(_globalSettings)) + if (!license.CanUse(_globalSettings)) { throw new BadRequestException("Invalid license. Make sure your license allows for on-premise " + "hosting of organizations and that the installation id matches your current installation."); } var enabledOrgs = await _organizationRepository.GetManyByEnabledAsync(); - if(enabledOrgs.Any(o => o.LicenseKey.Equals(license.LicenseKey) && o.Id != organizationId)) + if (enabledOrgs.Any(o => o.LicenseKey.Equals(license.LicenseKey) && o.Id != organizationId)) { throw new BadRequestException("License is already in use by another organization."); } - if(license.Seats.HasValue && + if (license.Seats.HasValue && (!organization.Seats.HasValue || organization.Seats.Value > license.Seats.Value)) { var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organization.Id); - if(userCount > license.Seats.Value) + if (userCount > license.Seats.Value) { throw new BadRequestException($"Your organization currently has {userCount} seats filled. " + $"Your new license only has ({ license.Seats.Value}) seats. Remove some users."); } } - if(license.MaxCollections.HasValue && (!organization.MaxCollections.HasValue || + if (license.MaxCollections.HasValue && (!organization.MaxCollections.HasValue || organization.MaxCollections.Value > license.MaxCollections.Value)) { var collectionCount = await _collectionRepository.GetCountByOrganizationIdAsync(organization.Id); - if(collectionCount > license.MaxCollections.Value) + if (collectionCount > license.MaxCollections.Value) { throw new BadRequestException($"Your organization currently has {collectionCount} collections. " + $"Your new license allows for a maximum of ({license.MaxCollections.Value}) collections. " + @@ -680,20 +680,20 @@ namespace Bit.Core.Services } } - if(!license.UseGroups && organization.UseGroups) + if (!license.UseGroups && organization.UseGroups) { var groups = await _groupRepository.GetManyByOrganizationIdAsync(organization.Id); - if(groups.Count > 0) + if (groups.Count > 0) { throw new BadRequestException($"Your organization currently has {groups.Count} groups. " + $"Your new license does not allow for the use of groups. Remove all groups."); } } - if(!license.UsePolicies && organization.UsePolicies) + if (!license.UsePolicies && organization.UsePolicies) { var policies = await _policyRepository.GetManyByOrganizationIdAsync(organization.Id); - if(policies.Any(p => p.Enabled)) + if (policies.Any(p => p.Enabled)) { throw new BadRequestException($"Your organization currently has {policies.Count} enabled " + $"policies. Your new license does not allow for the use of policies. Disable all policies."); @@ -730,7 +730,7 @@ namespace Bit.Core.Services public async Task DeleteAsync(Organization organization) { - if(!string.IsNullOrWhiteSpace(organization.GatewaySubscriptionId)) + if (!string.IsNullOrWhiteSpace(organization.GatewaySubscriptionId)) { try { @@ -738,7 +738,7 @@ namespace Bit.Core.Services organization.ExpirationDate.Value >= DateTime.UtcNow; await _paymentService.CancelSubscriptionAsync(organization, eop); } - catch(GatewayException) { } + catch (GatewayException) { } } await _organizationRepository.DeleteAsync(organization); @@ -748,7 +748,7 @@ namespace Bit.Core.Services public async Task EnableAsync(Guid organizationId, DateTime? expirationDate) { var org = await GetOrgById(organizationId); - if(org != null && !org.Enabled && org.Gateway.HasValue) + if (org != null && !org.Enabled && org.Gateway.HasValue) { org.Enabled = true; org.ExpirationDate = expirationDate; @@ -760,7 +760,7 @@ namespace Bit.Core.Services public async Task DisableAsync(Guid organizationId, DateTime? expirationDate) { var org = await GetOrgById(organizationId); - if(org != null && org.Enabled) + if (org != null && org.Enabled) { org.Enabled = false; org.ExpirationDate = expirationDate; @@ -774,7 +774,7 @@ namespace Bit.Core.Services public async Task UpdateExpirationDateAsync(Guid organizationId, DateTime? expirationDate) { var org = await GetOrgById(organizationId); - if(org != null) + if (org != null) { org.ExpirationDate = expirationDate; org.RevisionDate = DateTime.UtcNow; @@ -785,7 +785,7 @@ namespace Bit.Core.Services public async Task EnableAsync(Guid organizationId) { var org = await GetOrgById(organizationId); - if(org != null && !org.Enabled) + if (org != null && !org.Enabled) { org.Enabled = true; await ReplaceAndUpdateCache(org); @@ -794,14 +794,14 @@ namespace Bit.Core.Services public async Task UpdateAsync(Organization organization, bool updateBilling = false) { - if(organization.Id == default(Guid)) + if (organization.Id == default(Guid)) { throw new ApplicationException("Cannot create org this way. Call SignUpAsync."); } await ReplaceAndUpdateCache(organization, EventType.Organization_Updated); - if(updateBilling && !string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) + if (updateBilling && !string.IsNullOrWhiteSpace(organization.GatewayCustomerId)) { var customerService = new CustomerService(); await customerService.UpdateAsync(organization.GatewayCustomerId, new CustomerUpdateOptions @@ -814,18 +814,18 @@ namespace Bit.Core.Services public async Task UpdateTwoFactorProviderAsync(Organization organization, TwoFactorProviderType type) { - if(!type.ToString().Contains("Organization")) + if (!type.ToString().Contains("Organization")) { throw new ArgumentException("Not an organization provider type."); } - if(!organization.Use2fa) + if (!organization.Use2fa) { throw new BadRequestException("Organization cannot use 2FA."); } var providers = organization.GetTwoFactorProviders(); - if(!providers?.ContainsKey(type) ?? true) + if (!providers?.ContainsKey(type) ?? true) { return; } @@ -837,13 +837,13 @@ namespace Bit.Core.Services public async Task DisableTwoFactorProviderAsync(Organization organization, TwoFactorProviderType type) { - if(!type.ToString().Contains("Organization")) + if (!type.ToString().Contains("Organization")) { throw new ArgumentException("Not an organization provider type."); } var providers = organization.GetTwoFactorProviders(); - if(!providers?.ContainsKey(type) ?? true) + if (!providers?.ContainsKey(type) ?? true) { return; } @@ -859,7 +859,7 @@ namespace Bit.Core.Services var results = await InviteUserAsync(organizationId, invitingUserId, new List { email }, type, accessAll, externalId, collections); var result = results.FirstOrDefault(); - if(result == null) + if (result == null) { throw new BadRequestException("This user has already been invited."); } @@ -871,27 +871,27 @@ namespace Bit.Core.Services IEnumerable collections) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } - if(type == OrganizationUserType.Owner && invitingUserId.HasValue) + if (type == OrganizationUserType.Owner && invitingUserId.HasValue) { var invitingUserOrgs = await _organizationUserRepository.GetManyByUserAsync(invitingUserId.Value); var anyOwners = invitingUserOrgs.Any( u => u.OrganizationId == organizationId && u.Type == OrganizationUserType.Owner); - if(!anyOwners) + if (!anyOwners) { throw new BadRequestException("Only owners can invite new owners."); } } - if(organization.Seats.HasValue) + if (organization.Seats.HasValue) { var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organizationId); var availableSeats = organization.Seats.Value - userCount; - if(availableSeats < emails.Count()) + if (availableSeats < emails.Count()) { throw new BadRequestException("You have reached the maximum number of users " + $"({organization.Seats.Value}) for this organization."); @@ -899,12 +899,12 @@ namespace Bit.Core.Services } var orgUsers = new List(); - foreach(var email in emails) + foreach (var email in emails) { // Make sure user is not already invited var existingOrgUserCount = await _organizationUserRepository.GetCountByOrganizationAsync( organizationId, email, false); - if(existingOrgUserCount > 0) + if (existingOrgUserCount > 0) { continue; } @@ -923,7 +923,7 @@ namespace Bit.Core.Services RevisionDate = DateTime.UtcNow }; - if(!orgUser.AccessAll && collections.Any()) + if (!orgUser.AccessAll && collections.Any()) { await _organizationUserRepository.CreateAsync(orgUser, collections); } @@ -943,7 +943,7 @@ namespace Bit.Core.Services public async Task ResendInviteAsync(Guid organizationId, Guid? invitingUserId, Guid organizationUserId) { var orgUser = await _organizationUserRepository.GetByIdAsync(organizationUserId); - if(orgUser == null || orgUser.OrganizationId != organizationId || + if (orgUser == null || orgUser.OrganizationId != organizationId || orgUser.Status != OrganizationUserStatusType.Invited) { throw new BadRequestException("User invalid."); @@ -965,30 +965,30 @@ namespace Bit.Core.Services IUserService userService) { var orgUser = await _organizationUserRepository.GetByIdAsync(organizationUserId); - if(orgUser == null) + if (orgUser == null) { throw new BadRequestException("User invalid."); } - if(orgUser.Status != OrganizationUserStatusType.Invited) + if (orgUser.Status != OrganizationUserStatusType.Invited) { throw new BadRequestException("Already accepted."); } - if(string.IsNullOrWhiteSpace(orgUser.Email) || + if (string.IsNullOrWhiteSpace(orgUser.Email) || !orgUser.Email.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)) { throw new BadRequestException("User email does not match invite."); } - if(orgUser.Type == OrganizationUserType.Owner || orgUser.Type == OrganizationUserType.Admin) + if (orgUser.Type == OrganizationUserType.Owner || orgUser.Type == OrganizationUserType.Admin) { var org = await GetOrgById(orgUser.OrganizationId); - if(org.PlanType == PlanType.Free) + if (org.PlanType == PlanType.Free) { var adminCount = await _organizationUserRepository.GetCountByFreeOrganizationAdminUserAsync( user.Id); - if(adminCount > 0) + if (adminCount > 0) { throw new BadRequestException("You can only be an admin of one free organization."); } @@ -997,20 +997,20 @@ namespace Bit.Core.Services var existingOrgUserCount = await _organizationUserRepository.GetCountByOrganizationAsync( orgUser.OrganizationId, user.Email, true); - if(existingOrgUserCount > 0) + if (existingOrgUserCount > 0) { throw new BadRequestException("You are already part of this organization."); } - if(!CoreHelpers.UserInviteTokenIsValid(_dataProtector, token, user.Email, orgUser.Id, _globalSettings)) + if (!CoreHelpers.UserInviteTokenIsValid(_dataProtector, token, user.Email, orgUser.Id, _globalSettings)) { throw new BadRequestException("Invalid token."); } - if(!await userService.TwoFactorIsEnabledAsync(user)) + if (!await userService.TwoFactorIsEnabledAsync(user)) { var policies = await _policyRepository.GetManyByOrganizationIdAsync(orgUser.OrganizationId); - if(policies.Any(p => p.Type == PolicyType.TwoFactorAuthentication && p.Enabled)) + if (policies.Any(p => p.Type == PolicyType.TwoFactorAuthentication && p.Enabled)) { throw new BadRequestException("You cannot join this organization until you enable " + "two-step login on your user account."); @@ -1031,19 +1031,19 @@ namespace Bit.Core.Services Guid confirmingUserId, IUserService userService) { var orgUser = await _organizationUserRepository.GetByIdAsync(organizationUserId); - if(orgUser == null || orgUser.Status != OrganizationUserStatusType.Accepted || + if (orgUser == null || orgUser.Status != OrganizationUserStatusType.Accepted || orgUser.OrganizationId != organizationId) { throw new BadRequestException("User not valid."); } var org = await GetOrgById(organizationId); - if(org.PlanType == PlanType.Free && + if (org.PlanType == PlanType.Free && (orgUser.Type == OrganizationUserType.Admin || orgUser.Type == OrganizationUserType.Owner)) { var adminCount = await _organizationUserRepository.GetCountByFreeOrganizationAdminUserAsync( orgUser.UserId.Value); - if(adminCount > 0) + if (adminCount > 0) { throw new BadRequestException("User can only be an admin of one free organization."); } @@ -1052,7 +1052,7 @@ namespace Bit.Core.Services var user = await _userRepository.GetByIdAsync(orgUser.UserId.Value); var policies = await _policyRepository.GetManyByOrganizationIdAsync(organizationId); var usingTwoFactorPolicy = policies.Any(p => p.Type == PolicyType.TwoFactorAuthentication && p.Enabled); - if(usingTwoFactorPolicy && !(await userService.TwoFactorIsEnabledAsync(user))) + if (usingTwoFactorPolicy && !(await userService.TwoFactorIsEnabledAsync(user))) { throw new BadRequestException("User does not have two-step login enabled."); } @@ -1075,22 +1075,22 @@ namespace Bit.Core.Services public async Task SaveUserAsync(OrganizationUser user, Guid? savingUserId, IEnumerable collections) { - if(user.Id.Equals(default(Guid))) + if (user.Id.Equals(default(Guid))) { throw new BadRequestException("Invite the user first."); } - if(savingUserId.HasValue) + if (savingUserId.HasValue) { var savingUserOrgs = await _organizationUserRepository.GetManyByUserAsync(savingUserId.Value); var savingUserIsOrgOwner = savingUserOrgs .Any(u => u.OrganizationId == user.OrganizationId && u.Type == OrganizationUserType.Owner); - if(!savingUserIsOrgOwner) + if (!savingUserIsOrgOwner) { var originalUser = await _organizationUserRepository.GetByIdAsync(user.Id); var isOwner = originalUser.Type == OrganizationUserType.Owner; var nowOwner = user.Type == OrganizationUserType.Owner; - if((isOwner && !nowOwner) || (!isOwner && nowOwner)) + if ((isOwner && !nowOwner) || (!isOwner && nowOwner)) { throw new BadRequestException("Only an owner can change the user type of another owner."); } @@ -1098,13 +1098,13 @@ namespace Bit.Core.Services } var confirmedOwners = (await GetConfirmedOwnersAsync(user.OrganizationId)).ToList(); - if(user.Type != OrganizationUserType.Owner && + if (user.Type != OrganizationUserType.Owner && confirmedOwners.Count == 1 && confirmedOwners[0].Id == user.Id) { throw new BadRequestException("Organization must have at least one confirmed owner."); } - if(user.AccessAll) + if (user.AccessAll) { // We don't need any collections if we're flagged to have all access. collections = new List(); @@ -1116,29 +1116,29 @@ namespace Bit.Core.Services public async Task DeleteUserAsync(Guid organizationId, Guid organizationUserId, Guid? deletingUserId) { var orgUser = await _organizationUserRepository.GetByIdAsync(organizationUserId); - if(orgUser == null || orgUser.OrganizationId != organizationId) + if (orgUser == null || orgUser.OrganizationId != organizationId) { throw new BadRequestException("User not valid."); } - if(deletingUserId.HasValue && orgUser.UserId == deletingUserId.Value) + if (deletingUserId.HasValue && orgUser.UserId == deletingUserId.Value) { throw new BadRequestException("You cannot remove yourself."); } - if(orgUser.Type == OrganizationUserType.Owner && deletingUserId.HasValue) + if (orgUser.Type == OrganizationUserType.Owner && deletingUserId.HasValue) { var deletingUserOrgs = await _organizationUserRepository.GetManyByUserAsync(deletingUserId.Value); var anyOwners = deletingUserOrgs.Any( u => u.OrganizationId == organizationId && u.Type == OrganizationUserType.Owner); - if(!anyOwners) + if (!anyOwners) { throw new BadRequestException("Only owners can delete other owners."); } } var confirmedOwners = (await GetConfirmedOwnersAsync(organizationId)).ToList(); - if(confirmedOwners.Count == 1 && confirmedOwners[0].Id == organizationUserId) + if (confirmedOwners.Count == 1 && confirmedOwners[0].Id == organizationUserId) { throw new BadRequestException("Organization must have at least one confirmed owner."); } @@ -1146,7 +1146,7 @@ namespace Bit.Core.Services await _organizationUserRepository.DeleteAsync(orgUser); await _eventService.LogOrganizationUserEventAsync(orgUser, EventType.OrganizationUser_Removed); - if(orgUser.UserId.HasValue) + if (orgUser.UserId.HasValue) { // push var deviceIds = await GetUserDeviceIdsAsync(orgUser.UserId.Value); @@ -1159,13 +1159,13 @@ namespace Bit.Core.Services public async Task DeleteUserAsync(Guid organizationId, Guid userId) { var orgUser = await _organizationUserRepository.GetByOrganizationAsync(organizationId, userId); - if(orgUser == null) + if (orgUser == null) { throw new NotFoundException(); } var confirmedOwners = (await GetConfirmedOwnersAsync(organizationId)).ToList(); - if(confirmedOwners.Count == 1 && confirmedOwners[0].Id == orgUser.Id) + if (confirmedOwners.Count == 1 && confirmedOwners[0].Id == orgUser.Id) { throw new BadRequestException("Organization must have at least one confirmed owner."); } @@ -1173,7 +1173,7 @@ namespace Bit.Core.Services await _organizationUserRepository.DeleteAsync(orgUser); await _eventService.LogOrganizationUserEventAsync(orgUser, EventType.OrganizationUser_Removed); - if(orgUser.UserId.HasValue) + if (orgUser.UserId.HasValue) { // push var deviceIds = await GetUserDeviceIdsAsync(orgUser.UserId.Value); @@ -1198,13 +1198,13 @@ namespace Bit.Core.Services public async Task GenerateLicenseAsync(Organization organization, Guid installationId) { - if(organization == null) + if (organization == null) { throw new NotFoundException(); } var installation = await _installationRepository.GetByIdAsync(installationId); - if(installation == null || !installation.Enabled) + if (installation == null || !installation.Enabled) { throw new BadRequestException("Invalid installation id"); } @@ -1221,12 +1221,12 @@ namespace Bit.Core.Services bool overwriteExisting) { var organization = await GetOrgById(organizationId); - if(organization == null) + if (organization == null) { throw new NotFoundException(); } - if(!organization.UseDirectory) + if (!organization.UseDirectory) { throw new BadRequestException("Organization cannot use directory syncing."); } @@ -1239,7 +1239,7 @@ namespace Bit.Core.Services // Users // Remove Users - if(removeUserExternalIds?.Any() ?? false) + if (removeUserExternalIds?.Any() ?? false) { var removeUsersSet = new HashSet(removeUserExternalIds); var existingUsersDict = existingExternalUsers.ToDictionary(u => u.ExternalId); @@ -1249,9 +1249,9 @@ namespace Bit.Core.Services .Where(ru => existingUsersDict.ContainsKey(ru)) .Select(ru => existingUsersDict[ru]); - foreach(var user in usersToRemove) + foreach (var user in usersToRemove) { - if(user.Type != OrganizationUserType.Owner) + if (user.Type != OrganizationUserType.Owner) { await _organizationUserRepository.DeleteAsync(new OrganizationUser { Id = user.Id }); existingExternalUsersIdDict.Remove(user.ExternalId); @@ -1259,12 +1259,12 @@ namespace Bit.Core.Services } } - if(overwriteExisting) + if (overwriteExisting) { // Remove existing external users that are not in new user set - foreach(var user in existingExternalUsers) + foreach (var user in existingExternalUsers) { - if(user.Type != OrganizationUserType.Owner && !newUsersSet.Contains(user.ExternalId) && + if (user.Type != OrganizationUserType.Owner && !newUsersSet.Contains(user.ExternalId) && existingExternalUsersIdDict.ContainsKey(user.ExternalId)) { await _organizationUserRepository.DeleteAsync(new OrganizationUser { Id = user.Id }); @@ -1273,7 +1273,7 @@ namespace Bit.Core.Services } } - if(newUsers?.Any() ?? false) + if (newUsers?.Any() ?? false) { // Marry existing users var existingUsersEmailsDict = existingUsers @@ -1281,11 +1281,11 @@ namespace Bit.Core.Services .ToDictionary(u => u.Email); var newUsersEmailsDict = newUsers.ToDictionary(u => u.Email); var usersToAttach = existingUsersEmailsDict.Keys.Intersect(newUsersEmailsDict.Keys).ToList(); - foreach(var user in usersToAttach) + foreach (var user in usersToAttach) { var orgUserDetails = existingUsersEmailsDict[user]; var orgUser = await _organizationUserRepository.GetByIdAsync(orgUserDetails.Id); - if(orgUser != null) + if (orgUser != null) { orgUser.ExternalId = newUsersEmailsDict[user].ExternalId; await _organizationUserRepository.UpsertAsync(orgUser); @@ -1299,18 +1299,18 @@ namespace Bit.Core.Services var seatsAvailable = int.MaxValue; var enoughSeatsAvailable = true; - if(organization.Seats.HasValue) + if (organization.Seats.HasValue) { var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organizationId); seatsAvailable = organization.Seats.Value - userCount; enoughSeatsAvailable = seatsAvailable >= usersToAdd.Count; } - if(enoughSeatsAvailable) + if (enoughSeatsAvailable) { - foreach(var user in newUsers) + foreach (var user in newUsers) { - if(!usersToAdd.Contains(user.ExternalId) || string.IsNullOrWhiteSpace(user.Email)) + if (!usersToAdd.Contains(user.ExternalId) || string.IsNullOrWhiteSpace(user.Email)) { continue; } @@ -1321,7 +1321,7 @@ namespace Bit.Core.Services OrganizationUserType.User, false, user.ExternalId, new List()); existingExternalUsersIdDict.Add(newUser.ExternalId, newUser.Id); } - catch(BadRequestException) + catch (BadRequestException) { continue; } @@ -1331,9 +1331,9 @@ namespace Bit.Core.Services // Groups - if(groups?.Any() ?? false) + if (groups?.Any() ?? false) { - if(!organization.UseGroups) + if (!organization.UseGroups) { throw new BadRequestException("Organization cannot use groups."); } @@ -1348,7 +1348,7 @@ namespace Bit.Core.Services .Where(g => !existingExternalGroupsDict.ContainsKey(g.Group.ExternalId)) .Select(g => g.Group); - foreach(var group in newGroups) + foreach (var group in newGroups) { group.CreationDate = group.RevisionDate = DateTime.UtcNow; @@ -1361,17 +1361,17 @@ namespace Bit.Core.Services .Where(g => groupsDict.ContainsKey(g.ExternalId)) .ToList(); - if(updateGroups.Any()) + if (updateGroups.Any()) { var groupUsers = await _groupRepository.GetManyGroupUsersByOrganizationIdAsync(organizationId); var existingGroupUsers = groupUsers .GroupBy(gu => gu.GroupId) .ToDictionary(g => g.Key, g => new HashSet(g.Select(gr => gr.OrganizationUserId))); - foreach(var group in updateGroups) + foreach (var group in updateGroups) { var updatedGroup = groupsDict[group.ExternalId].Group; - if(group.Name != updatedGroup.Name) + if (group.Name != updatedGroup.Name) { group.RevisionDate = DateTime.UtcNow; group.Name = updatedGroup.Name; @@ -1399,7 +1399,7 @@ namespace Bit.Core.Services { var availableUsers = groupUsers.Intersect(existingUsersIdDict.Keys); var users = new HashSet(availableUsers.Select(u => existingUsersIdDict[u])); - if(existingUsers != null && existingUsers.Count == users.Count && users.SetEquals(existingUsers)) + if (existingUsers != null && existingUsers.Count == users.Count && users.SetEquals(existingUsers)) { return; } @@ -1425,7 +1425,7 @@ namespace Bit.Core.Services await _organizationRepository.ReplaceAsync(org); await _applicationCacheService.UpsertOrganizationAbilityAsync(org); - if(orgEvent.HasValue) + if (orgEvent.HasValue) { await _eventService.LogOrganizationEventAsync(org, orgEvent.Value); } @@ -1438,37 +1438,37 @@ namespace Bit.Core.Services private void ValidateOrganizationUpgradeParameters(Models.StaticStore.Plan plan, OrganizationUpgrade upgrade) { - if(!plan.MaxStorageGb.HasValue && upgrade.AdditionalStorageGb > 0) + if (!plan.MaxStorageGb.HasValue && upgrade.AdditionalStorageGb > 0) { throw new BadRequestException("Plan does not allow additional storage."); } - if(upgrade.AdditionalStorageGb < 0) + if (upgrade.AdditionalStorageGb < 0) { throw new BadRequestException("You can't subtract storage!"); } - if(!plan.CanBuyPremiumAccessAddon && upgrade.PremiumAccessAddon) + if (!plan.CanBuyPremiumAccessAddon && upgrade.PremiumAccessAddon) { throw new BadRequestException("This plan does not allow you to buy the premium access addon."); } - if(plan.BaseSeats + upgrade.AdditionalSeats <= 0) + if (plan.BaseSeats + upgrade.AdditionalSeats <= 0) { throw new BadRequestException("You do not have any seats!"); } - if(upgrade.AdditionalSeats < 0) + if (upgrade.AdditionalSeats < 0) { throw new BadRequestException("You can't subtract seats!"); } - if(!plan.CanBuyAdditionalSeats && upgrade.AdditionalSeats > 0) + if (!plan.CanBuyAdditionalSeats && upgrade.AdditionalSeats > 0) { throw new BadRequestException("Plan does not allow additional users."); } - if(plan.CanBuyAdditionalSeats && plan.MaxAdditionalSeats.HasValue && + if (plan.CanBuyAdditionalSeats && plan.MaxAdditionalSeats.HasValue && upgrade.AdditionalSeats > plan.MaxAdditionalSeats.Value) { throw new BadRequestException($"Selected plan allows a maximum of " + diff --git a/src/Core/Services/Implementations/PolicyService.cs b/src/Core/Services/Implementations/PolicyService.cs index fa2c5164b2..8d0fb9b4dd 100644 --- a/src/Core/Services/Implementations/PolicyService.cs +++ b/src/Core/Services/Implementations/PolicyService.cs @@ -33,38 +33,38 @@ namespace Bit.Core.Services Guid? savingUserId) { var org = await _organizationRepository.GetByIdAsync(policy.OrganizationId); - if(org == null) + if (org == null) { throw new BadRequestException("Organization not found"); } - if(!org.UsePolicies) + if (!org.UsePolicies) { throw new BadRequestException("This organization cannot use policies."); } var now = DateTime.UtcNow; - if(policy.Id == default(Guid)) + if (policy.Id == default(Guid)) { policy.CreationDate = now; } - else if(policy.Enabled) + else if (policy.Enabled) { var currentPolicy = await _policyRepository.GetByIdAsync(policy.Id); - if(!currentPolicy?.Enabled ?? true) + if (!currentPolicy?.Enabled ?? true) { - if(currentPolicy.Type == Enums.PolicyType.TwoFactorAuthentication) + if (currentPolicy.Type == Enums.PolicyType.TwoFactorAuthentication) { Organization organization = null; var orgUsers = await _organizationUserRepository.GetManyDetailsByOrganizationAsync( policy.OrganizationId); - foreach(var orgUser in orgUsers.Where(ou => + foreach (var orgUser in orgUsers.Where(ou => ou.Status != Enums.OrganizationUserStatusType.Invited && ou.Type != Enums.OrganizationUserType.Owner)) { - if(orgUser.UserId != savingUserId && !await userService.TwoFactorIsEnabledAsync(orgUser)) + if (orgUser.UserId != savingUserId && !await userService.TwoFactorIsEnabledAsync(orgUser)) { - if(organization == null) + if (organization == null) { organization = await _organizationRepository.GetByIdAsync(policy.OrganizationId); } diff --git a/src/Core/Services/Implementations/RelayPushNotificationService.cs b/src/Core/Services/Implementations/RelayPushNotificationService.cs index b913ab3082..d17e71f21c 100644 --- a/src/Core/Services/Implementations/RelayPushNotificationService.cs +++ b/src/Core/Services/Implementations/RelayPushNotificationService.cs @@ -53,7 +53,7 @@ namespace Bit.Core.Services private async Task PushCipherAsync(Cipher cipher, PushType type, IEnumerable collectionIds) { - if(cipher.OrganizationId.HasValue) + if (cipher.OrganizationId.HasValue) { // We cannot send org pushes since access logic is much more complicated than just the fact that they belong // to the organization. Potentially we could blindly send to just users that have the access all permission @@ -62,7 +62,7 @@ namespace Bit.Core.Services // await SendPayloadToOrganizationAsync(cipher.OrganizationId.Value, type, message, true); } - else if(cipher.UserId.HasValue) + else if (cipher.UserId.HasValue) { var message = new SyncCipherPushNotification { @@ -169,14 +169,14 @@ namespace Bit.Core.Services { var currentContext = _httpContextAccessor?.HttpContext?. RequestServices.GetService(typeof(CurrentContext)) as CurrentContext; - if(!string.IsNullOrWhiteSpace(currentContext?.DeviceIdentifier)) + if (!string.IsNullOrWhiteSpace(currentContext?.DeviceIdentifier)) { var device = await _deviceRepository.GetByIdentifierAsync(currentContext.DeviceIdentifier); - if(device != null) + if (device != null) { request.DeviceId = device.Id.ToString(); } - if(addIdentifier) + if (addIdentifier) { request.Identifier = currentContext.DeviceIdentifier; } diff --git a/src/Core/Services/Implementations/RelayPushRegistrationService.cs b/src/Core/Services/Implementations/RelayPushRegistrationService.cs index ee18815cdb..dbe160e921 100644 --- a/src/Core/Services/Implementations/RelayPushRegistrationService.cs +++ b/src/Core/Services/Implementations/RelayPushRegistrationService.cs @@ -47,7 +47,7 @@ namespace Bit.Core.Services public async Task AddUserRegistrationOrganizationAsync(IEnumerable deviceIds, string organizationId) { - if(!deviceIds.Any()) + if (!deviceIds.Any()) { return; } @@ -58,7 +58,7 @@ namespace Bit.Core.Services public async Task DeleteUserRegistrationOrganizationAsync(IEnumerable deviceIds, string organizationId) { - if(!deviceIds.Any()) + if (!deviceIds.Any()) { return; } diff --git a/src/Core/Services/Implementations/StripePaymentService.cs b/src/Core/Services/Implementations/StripePaymentService.cs index 4ad28b1ed5..9ae2f3037d 100644 --- a/src/Core/Services/Implementations/StripePaymentService.cs +++ b/src/Core/Services/Implementations/StripePaymentService.cs @@ -60,9 +60,9 @@ namespace Bit.Core.Services var stripePaymentMethod = paymentMethodType == PaymentMethodType.Card || paymentMethodType == PaymentMethodType.BankAccount; - if(stripePaymentMethod && !string.IsNullOrWhiteSpace(paymentToken)) + if (stripePaymentMethod && !string.IsNullOrWhiteSpace(paymentToken)) { - if(paymentToken.StartsWith("pm_")) + if (paymentToken.StartsWith("pm_")) { stipeCustomerPaymentMethodId = paymentToken; } @@ -71,7 +71,7 @@ namespace Bit.Core.Services stipeCustomerSourceToken = paymentToken; } } - else if(paymentMethodType == PaymentMethodType.PayPal) + else if (paymentMethodType == PaymentMethodType.PayPal) { var randomSuffix = Utilities.CoreHelpers.RandomString(3, upper: false, numeric: false); var customerResult = await _btGateway.Customer.CreateAsync(new Braintree.CustomerRequest @@ -85,7 +85,7 @@ namespace Bit.Core.Services } }); - if(!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) + if (!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) { throw new GatewayException("Failed to create PayPal customer record."); } @@ -109,7 +109,7 @@ namespace Bit.Core.Services } }; - if(plan.StripePlanId != null) + if (plan.StripePlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -118,7 +118,7 @@ namespace Bit.Core.Services }); } - if(additionalSeats > 0 && plan.StripeSeatPlanId != null) + if (additionalSeats > 0 && plan.StripeSeatPlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -127,7 +127,7 @@ namespace Bit.Core.Services }); } - if(additionalStorageGb > 0) + if (additionalStorageGb > 0) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -136,7 +136,7 @@ namespace Bit.Core.Services }); } - if(premiumAccessAddon && plan.StripePremiumAccessPlanId != null) + if (premiumAccessAddon && plan.StripePremiumAccessPlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -165,22 +165,22 @@ namespace Bit.Core.Services subCreateOptions.CustomerId = customer.Id; var subscriptionService = new SubscriptionService(); subscription = await subscriptionService.CreateAsync(subCreateOptions); - if(subscription.Status == "incomplete" && subscription.LatestInvoice?.PaymentIntent != null) + if (subscription.Status == "incomplete" && subscription.LatestInvoice?.PaymentIntent != null) { - if(subscription.LatestInvoice.PaymentIntent.Status == "requires_payment_method") + if (subscription.LatestInvoice.PaymentIntent.Status == "requires_payment_method") { await subscriptionService.CancelAsync(subscription.Id, new SubscriptionCancelOptions()); throw new GatewayException("Payment method was declined."); } } } - catch(Exception e) + catch (Exception e) { - if(customer != null) + if (customer != null) { await customerService.DeleteAsync(customer.Id); } - if(braintreeCustomer != null) + if (braintreeCustomer != null) { await _btGateway.Customer.DeleteAsync(braintreeCustomer.Id); } @@ -191,7 +191,7 @@ namespace Bit.Core.Services org.GatewayCustomerId = customer.Id; org.GatewaySubscriptionId = subscription.Id; - if(subscription.Status == "incomplete" && + if (subscription.Status == "incomplete" && subscription.LatestInvoice?.PaymentIntent?.Status == "requires_action") { org.Enabled = false; @@ -208,7 +208,7 @@ namespace Bit.Core.Services public async Task UpgradeFreeOrganizationAsync(Organization org, Models.StaticStore.Plan plan, short additionalStorageGb, short additionalSeats, bool premiumAccessAddon) { - if(!string.IsNullOrWhiteSpace(org.GatewaySubscriptionId)) + if (!string.IsNullOrWhiteSpace(org.GatewaySubscriptionId)) { throw new BadRequestException("Organization already has a subscription."); } @@ -218,7 +218,7 @@ namespace Bit.Core.Services customerOptions.AddExpand("default_source"); customerOptions.AddExpand("invoice_settings.default_payment_method"); var customer = await customerService.GetAsync(org.GatewayCustomerId, customerOptions); - if(customer == null) + if (customer == null) { throw new GatewayException("Could not find customer payment profile."); } @@ -233,7 +233,7 @@ namespace Bit.Core.Services } }; - if(plan.StripePlanId != null) + if (plan.StripePlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -242,7 +242,7 @@ namespace Bit.Core.Services }); } - if(additionalSeats > 0 && plan.StripeSeatPlanId != null) + if (additionalSeats > 0 && plan.StripeSeatPlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -251,7 +251,7 @@ namespace Bit.Core.Services }); } - if(additionalStorageGb > 0) + if (additionalStorageGb > 0) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -260,7 +260,7 @@ namespace Bit.Core.Services }); } - if(premiumAccessAddon && plan.StripePremiumAccessPlanId != null) + if (premiumAccessAddon && plan.StripePremiumAccessPlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -272,25 +272,25 @@ namespace Bit.Core.Services var stripePaymentMethod = false; var paymentMethodType = PaymentMethodType.Credit; var hasBtCustomerId = customer.Metadata.ContainsKey("btCustomerId"); - if(hasBtCustomerId) + if (hasBtCustomerId) { paymentMethodType = PaymentMethodType.PayPal; } else { - if(customer.InvoiceSettings?.DefaultPaymentMethod?.Type == "card") + if (customer.InvoiceSettings?.DefaultPaymentMethod?.Type == "card") { paymentMethodType = PaymentMethodType.Card; stripePaymentMethod = true; } - else if(customer.DefaultSource != null) + else if (customer.DefaultSource != null) { - if(customer.DefaultSource is Card || customer.DefaultSource is SourceCard) + if (customer.DefaultSource is Card || customer.DefaultSource is SourceCard) { paymentMethodType = PaymentMethodType.Card; stripePaymentMethod = true; } - else if(customer.DefaultSource is BankAccount || customer.DefaultSource is SourceAchDebit) + else if (customer.DefaultSource is BankAccount || customer.DefaultSource is SourceAchDebit) { paymentMethodType = PaymentMethodType.BankAccount; stripePaymentMethod = true; @@ -299,7 +299,7 @@ namespace Bit.Core.Services else { var paymentMethod = GetLatestCardPaymentMethod(customer.Id); - if(paymentMethod != null) + if (paymentMethod != null) { paymentMethodType = PaymentMethodType.Card; stripePaymentMethod = true; @@ -312,7 +312,7 @@ namespace Bit.Core.Services stripePaymentMethod, paymentMethodType, subCreateOptions, null); org.GatewaySubscriptionId = subscription.Id; - if(subscription.Status == "incomplete" && + if (subscription.Status == "incomplete" && subscription.LatestInvoice?.PaymentIntent?.Status == "requires_action") { org.Enabled = false; @@ -329,20 +329,20 @@ namespace Bit.Core.Services public async Task PurchasePremiumAsync(User user, PaymentMethodType paymentMethodType, string paymentToken, short additionalStorageGb) { - if(paymentMethodType != PaymentMethodType.Credit && string.IsNullOrWhiteSpace(paymentToken)) + if (paymentMethodType != PaymentMethodType.Credit && string.IsNullOrWhiteSpace(paymentToken)) { throw new BadRequestException("Payment token is required."); } - if(paymentMethodType == PaymentMethodType.Credit && + if (paymentMethodType == PaymentMethodType.Credit && (user.Gateway != GatewayType.Stripe || string.IsNullOrWhiteSpace(user.GatewayCustomerId))) { throw new BadRequestException("Your account does not have any credit available."); } - if(paymentMethodType == PaymentMethodType.BankAccount || paymentMethodType == PaymentMethodType.GoogleInApp) + if (paymentMethodType == PaymentMethodType.BankAccount || paymentMethodType == PaymentMethodType.GoogleInApp) { throw new GatewayException("Payment method is not supported at this time."); } - if((paymentMethodType == PaymentMethodType.GoogleInApp || + if ((paymentMethodType == PaymentMethodType.GoogleInApp || paymentMethodType == PaymentMethodType.AppleInApp) && additionalStorageGb > 0) { throw new BadRequestException("You cannot add storage with this payment method."); @@ -357,9 +357,9 @@ namespace Bit.Core.Services string stipeCustomerPaymentMethodId = null; string stipeCustomerSourceToken = null; - if(stripePaymentMethod && !string.IsNullOrWhiteSpace(paymentToken)) + if (stripePaymentMethod && !string.IsNullOrWhiteSpace(paymentToken)) { - if(paymentToken.StartsWith("pm_")) + if (paymentToken.StartsWith("pm_")) { stipeCustomerPaymentMethodId = paymentToken; } @@ -369,18 +369,18 @@ namespace Bit.Core.Services } } - if(user.Gateway == GatewayType.Stripe && !string.IsNullOrWhiteSpace(user.GatewayCustomerId)) + if (user.Gateway == GatewayType.Stripe && !string.IsNullOrWhiteSpace(user.GatewayCustomerId)) { - if(!string.IsNullOrWhiteSpace(paymentToken)) + if (!string.IsNullOrWhiteSpace(paymentToken)) { try { await UpdatePaymentMethodAsync(user, paymentMethodType, paymentToken, true); } - catch(Exception e) + catch (Exception e) { var message = e.Message.ToLowerInvariant(); - if(message.Contains("apple") || message.Contains("in-app")) + if (message.Contains("apple") || message.Contains("in-app")) { throw e; } @@ -393,10 +393,10 @@ namespace Bit.Core.Services catch { } } - if(customer == null && !string.IsNullOrWhiteSpace(paymentToken)) + if (customer == null && !string.IsNullOrWhiteSpace(paymentToken)) { var stripeCustomerMetadata = new Dictionary(); - if(paymentMethodType == PaymentMethodType.PayPal) + if (paymentMethodType == PaymentMethodType.PayPal) { var randomSuffix = Utilities.CoreHelpers.RandomString(3, upper: false, numeric: false); var customerResult = await _btGateway.Customer.CreateAsync(new Braintree.CustomerRequest @@ -410,7 +410,7 @@ namespace Bit.Core.Services } }); - if(!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) + if (!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) { throw new GatewayException("Failed to create PayPal customer record."); } @@ -418,10 +418,10 @@ namespace Bit.Core.Services braintreeCustomer = customerResult.Target; stripeCustomerMetadata.Add("btCustomerId", braintreeCustomer.Id); } - else if(paymentMethodType == PaymentMethodType.AppleInApp) + else if (paymentMethodType == PaymentMethodType.AppleInApp) { var verifiedReceiptStatus = await _appleIapService.GetVerifiedReceiptStatusAsync(paymentToken); - if(verifiedReceiptStatus == null) + if (verifiedReceiptStatus == null) { throw new GatewayException("Cannot verify apple in-app purchase."); } @@ -430,7 +430,7 @@ namespace Bit.Core.Services await _appleIapService.SaveReceiptAsync(verifiedReceiptStatus, user.Id); stripeCustomerMetadata.Add("appleReceipt", receiptOriginalTransactionId); } - else if(!stripePaymentMethod) + else if (!stripePaymentMethod) { throw new GatewayException("Payment method is not supported at this time."); } @@ -450,7 +450,7 @@ namespace Bit.Core.Services createdStripeCustomer = true; } - if(customer == null) + if (customer == null) { throw new GatewayException("Could not set up customer payment profile."); } @@ -471,7 +471,7 @@ namespace Bit.Core.Services Quantity = 1, }); - if(additionalStorageGb > 0) + if (additionalStorageGb > 0) { subCreateOptions.Items.Add(new SubscriptionItemOption { @@ -487,7 +487,7 @@ namespace Bit.Core.Services user.GatewayCustomerId = customer.Id; user.GatewaySubscriptionId = subscription.Id; - if(subscription.Status == "incomplete" && + if (subscription.Status == "incomplete" && subscription.LatestInvoice?.PaymentIntent?.Status == "requires_action") { return subscription.LatestInvoice.PaymentIntent.ClientSecret; @@ -514,7 +514,7 @@ namespace Bit.Core.Services Subscription subscription = null; try { - if(!stripePaymentMethod) + if (!stripePaymentMethod) { var previewInvoice = await invoiceService.UpcomingAsync(new UpcomingInvoiceOptions { @@ -522,15 +522,15 @@ namespace Bit.Core.Services SubscriptionItems = ToInvoiceSubscriptionItemOptions(subCreateOptions.Items) }); - if(previewInvoice.AmountDue > 0) + if (previewInvoice.AmountDue > 0) { var appleReceiptOrigTransactionId = customer.Metadata != null && customer.Metadata.ContainsKey("appleReceipt") ? customer.Metadata["appleReceipt"] : null; var braintreeCustomerId = customer.Metadata != null && customer.Metadata.ContainsKey("btCustomerId") ? customer.Metadata["btCustomerId"] : null; - if(!string.IsNullOrWhiteSpace(appleReceiptOrigTransactionId)) + if (!string.IsNullOrWhiteSpace(appleReceiptOrigTransactionId)) { - if(!subcriber.IsUser()) + if (!subcriber.IsUser()) { throw new GatewayException("In-app purchase is only allowed for users."); } @@ -539,7 +539,7 @@ namespace Bit.Core.Services appleReceiptOrigTransactionId); var verifiedAppleReceipt = await _appleIapService.GetVerifiedReceiptStatusAsync( appleReceipt.Item1); - if(verifiedAppleReceipt == null) + if (verifiedAppleReceipt == null) { throw new GatewayException("Failed to get Apple in-app purchase receipt data."); } @@ -548,7 +548,7 @@ namespace Bit.Core.Services subInvoiceMetadata.Add("appleReceiptTransactionId", lastTransactionId); var existingTransaction = await _transactionRepository.GetByGatewayIdAsync( GatewayType.AppStore, lastTransactionId); - if(existingTransaction == null) + if (existingTransaction == null) { appleTransaction = verifiedAppleReceipt.BuildTransactionFromLastTransaction( PremiumPlanAppleIapPrice, subcriber.Id); @@ -556,7 +556,7 @@ namespace Bit.Core.Services await _transactionRepository.CreateAsync(appleTransaction); } } - else if(!string.IsNullOrWhiteSpace(braintreeCustomerId)) + else if (!string.IsNullOrWhiteSpace(braintreeCustomerId)) { var btInvoiceAmount = (previewInvoice.AmountDue / 100M); var transactionResult = await _btGateway.Transaction.SaleAsync( @@ -578,7 +578,7 @@ namespace Bit.Core.Services } }); - if(!transactionResult.IsSuccess()) + if (!transactionResult.IsSuccess()) { throw new GatewayException("Failed to charge PayPal customer."); } @@ -600,14 +600,14 @@ namespace Bit.Core.Services addedCreditToStripeCustomer = true; } } - else if(paymentMethodType == PaymentMethodType.Credit) + else if (paymentMethodType == PaymentMethodType.Credit) { var previewInvoice = await invoiceService.UpcomingAsync(new UpcomingInvoiceOptions { CustomerId = customer.Id, SubscriptionItems = ToInvoiceSubscriptionItemOptions(subCreateOptions.Items) }); - if(previewInvoice.AmountDue > 0) + if (previewInvoice.AmountDue > 0) { throw new GatewayException("Your account does not have enough credit available."); } @@ -617,16 +617,16 @@ namespace Bit.Core.Services subCreateOptions.AddExpand("latest_invoice.payment_intent"); var subscriptionService = new SubscriptionService(); subscription = await subscriptionService.CreateAsync(subCreateOptions); - if(subscription.Status == "incomplete" && subscription.LatestInvoice?.PaymentIntent != null) + if (subscription.Status == "incomplete" && subscription.LatestInvoice?.PaymentIntent != null) { - if(subscription.LatestInvoice.PaymentIntent.Status == "requires_payment_method") + if (subscription.LatestInvoice.PaymentIntent.Status == "requires_payment_method") { await subscriptionService.CancelAsync(subscription.Id, new SubscriptionCancelOptions()); throw new GatewayException("Payment method was declined."); } } - if(!stripePaymentMethod && subInvoiceMetadata.Any()) + if (!stripePaymentMethod && subInvoiceMetadata.Any()) { var invoices = await invoiceService.ListAsync(new InvoiceListOptions { @@ -634,7 +634,7 @@ namespace Bit.Core.Services }); var invoice = invoices?.FirstOrDefault(); - if(invoice == null) + if (invoice == null) { throw new GatewayException("Invoice not found."); } @@ -647,15 +647,15 @@ namespace Bit.Core.Services return subscription; } - catch(Exception e) + catch (Exception e) { - if(customer != null) + if (customer != null) { - if(createdStripeCustomer) + if (createdStripeCustomer) { await customerService.DeleteAsync(customer.Id); } - else if(addedCreditToStripeCustomer || customer.Balance < 0) + else if (addedCreditToStripeCustomer || customer.Balance < 0) { await customerService.UpdateAsync(customer.Id, new CustomerUpdateOptions { @@ -663,20 +663,20 @@ namespace Bit.Core.Services }); } } - if(braintreeTransaction != null) + if (braintreeTransaction != null) { await _btGateway.Transaction.RefundAsync(braintreeTransaction.Id); } - if(braintreeCustomer != null) + if (braintreeCustomer != null) { await _btGateway.Customer.DeleteAsync(braintreeCustomer.Id); } - if(appleTransaction != null) + if (appleTransaction != null) { await _transactionRepository.DeleteAsync(appleTransaction); } - if(e is StripeException strEx && + if (e is StripeException strEx && (strEx.StripeError?.Message?.Contains("cannot be used because it is not verified") ?? false)) { throw new GatewayException("Bank account is not yet verified."); @@ -702,7 +702,7 @@ namespace Bit.Core.Services var subscriptionItemService = new SubscriptionItemService(); var subscriptionService = new SubscriptionService(); var sub = await subscriptionService.GetAsync(storableSubscriber.GatewaySubscriptionId); - if(sub == null) + if (sub == null) { throw new GatewayException("Subscription not found."); } @@ -717,7 +717,7 @@ namespace Bit.Core.Services Quantity = i.Quantity, }).ToList(); - if(additionalStorage > 0 && storageItem == null) + if (additionalStorage > 0 && storageItem == null) { subItemOptions.Add(new InvoiceSubscriptionItemOptions { @@ -733,7 +733,7 @@ namespace Bit.Core.Services Prorate = prorate }); } - else if(additionalStorage > 0 && storageItem != null) + else if (additionalStorage > 0 && storageItem != null) { subItemOptions.Add(new InvoiceSubscriptionItemOptions { @@ -749,7 +749,7 @@ namespace Bit.Core.Services Prorate = prorate }); } - else if(additionalStorage == 0 && storageItem != null) + else if (additionalStorage == 0 && storageItem != null) { subItemOptions.Add(new InvoiceSubscriptionItemOptions { @@ -761,7 +761,7 @@ namespace Bit.Core.Services string paymentIntentClientSecret = null; var invoicedNow = false; - if(additionalStorage > 0) + if (additionalStorage > 0) { var result = await PreviewUpcomingInvoiceAndPayAsync( storableSubscriber, storagePlanId, subItemOptions, 400); @@ -769,7 +769,7 @@ namespace Bit.Core.Services paymentIntentClientSecret = result.Item2; } - if(subUpdateAction != null) + if (subUpdateAction != null) { await subUpdateAction(!invoicedNow); } @@ -778,35 +778,35 @@ namespace Bit.Core.Services public async Task CancelAndRecoverChargesAsync(ISubscriber subscriber) { - if(!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) + if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) { var subscriptionService = new SubscriptionService(); await subscriptionService.CancelAsync(subscriber.GatewaySubscriptionId, new SubscriptionCancelOptions()); } - if(string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) + if (string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { return; } var customerService = new CustomerService(); var customer = await customerService.GetAsync(subscriber.GatewayCustomerId); - if(customer == null) + if (customer == null) { return; } - if(customer.Metadata.ContainsKey("btCustomerId")) + if (customer.Metadata.ContainsKey("btCustomerId")) { var transactionRequest = new Braintree.TransactionSearchRequest() .CustomerId.Is(customer.Metadata["btCustomerId"]); var transactions = _btGateway.Transaction.Search(transactionRequest); - if((transactions?.MaximumCount ?? 0) > 0) + if ((transactions?.MaximumCount ?? 0) > 0) { var txs = transactions.Cast().Where(c => c.RefundedTransactionId == null); - foreach(var transaction in txs) + foreach (var transaction in txs) { await _btGateway.Transaction.RefundAsync(transaction.Id); } @@ -822,10 +822,10 @@ namespace Bit.Core.Services CustomerId = subscriber.GatewayCustomerId }); - if(charges?.Data != null) + if (charges?.Data != null) { var refundService = new RefundService(); - foreach(var charge in charges.Data.Where(c => c.Captured.GetValueOrDefault() && !c.Refunded)) + foreach (var charge in charges.Data.Where(c => c.Captured.GetValueOrDefault() && !c.Refunded)) { await refundService.CreateAsync(new RefundCreateOptions { ChargeId = charge.Id }); } @@ -844,7 +844,7 @@ namespace Bit.Core.Services customerOptions.AddExpand("invoice_settings.default_payment_method"); var customer = await customerService.GetAsync(subscriber.GatewayCustomerId, customerOptions); var usingInAppPaymentMethod = customer.Metadata.ContainsKey("appleReceipt"); - if(usingInAppPaymentMethod) + if (usingInAppPaymentMethod) { throw new BadRequestException("Cannot perform this action with in-app purchase payment method. " + "Contact support."); @@ -871,22 +871,22 @@ namespace Bit.Core.Services .Where(i => pendingInvoiceItemsDict.ContainsKey(i.Id) || (i.Plan.Id == planId && i.Proration)); var invoiceAmount = itemsForInvoice?.Sum(i => i.Amount) ?? 0; var invoiceNow = invoiceAmount >= prorateThreshold; - if(invoiceNow) + if (invoiceNow) { // Owes more than prorateThreshold on next invoice. // Invoice them and pay now instead of waiting until next billing cycle. string cardPaymentMethodId = null; var invoiceAmountDue = upcomingPreview.StartingBalance + invoiceAmount; - if(invoiceAmountDue > 0 && !customer.Metadata.ContainsKey("btCustomerId")) + if (invoiceAmountDue > 0 && !customer.Metadata.ContainsKey("btCustomerId")) { var hasDefaultCardPaymentMethod = customer.InvoiceSettings?.DefaultPaymentMethod?.Type == "card"; var hasDefaultValidSource = customer.DefaultSource != null && (customer.DefaultSource is Card || customer.DefaultSource is BankAccount); - if(!hasDefaultCardPaymentMethod && !hasDefaultValidSource) + if (!hasDefaultCardPaymentMethod && !hasDefaultValidSource) { cardPaymentMethodId = GetLatestCardPaymentMethod(customer.Id)?.Id; - if(cardPaymentMethodId == null) + if (cardPaymentMethodId == null) { throw new BadRequestException("No payment method is available."); } @@ -898,9 +898,9 @@ namespace Bit.Core.Services Braintree.Transaction braintreeTransaction = null; try { - foreach(var ii in itemsForInvoice) + foreach (var ii in itemsForInvoice) { - if(pendingInvoiceItemsDict.ContainsKey(ii.Id)) + if (pendingInvoiceItemsDict.ContainsKey(ii.Id)) { continue; } @@ -926,9 +926,9 @@ namespace Bit.Core.Services }); var invoicePayOptions = new InvoicePayOptions(); - if(invoice.AmountDue > 0) + if (invoice.AmountDue > 0) { - if(customer?.Metadata?.ContainsKey("btCustomerId") ?? false) + if (customer?.Metadata?.ContainsKey("btCustomerId") ?? false) { invoicePayOptions.PaidOutOfBand = true; var btInvoiceAmount = (invoice.AmountDue / 100M); @@ -951,7 +951,7 @@ namespace Bit.Core.Services } }); - if(!transactionResult.IsSuccess()) + if (!transactionResult.IsSuccess()) { throw new GatewayException("Failed to charge PayPal customer."); } @@ -978,9 +978,9 @@ namespace Bit.Core.Services { await invoiceService.PayAsync(invoice.Id, invoicePayOptions); } - catch(StripeException e) + catch (StripeException e) { - if(e.HttpStatusCode == System.Net.HttpStatusCode.PaymentRequired && + if (e.HttpStatusCode == System.Net.HttpStatusCode.PaymentRequired && e.StripeError?.Code == "invoice_payment_intent_requires_action") { // SCA required, get intent client secret @@ -995,16 +995,16 @@ namespace Bit.Core.Services } } } - catch(Exception e) + catch (Exception e) { - if(braintreeTransaction != null) + if (braintreeTransaction != null) { await _btGateway.Transaction.RefundAsync(braintreeTransaction.Id); } - if(invoice != null) + if (invoice != null) { await invoiceService.VoidInvoiceAsync(invoice.Id, new InvoiceVoidOptions()); - if(invoice.StartingBalance != 0) + if (invoice.StartingBalance != 0) { await customerService.UpdateAsync(customer.Id, new CustomerUpdateOptions { @@ -1013,7 +1013,7 @@ namespace Bit.Core.Services } // Restore invoice items that were brought in - foreach(var item in pendingInvoiceItems) + foreach (var item in pendingInvoiceItems) { var i = new InvoiceItemCreateOptions { @@ -1031,13 +1031,13 @@ namespace Bit.Core.Services } else { - foreach(var ii in createdInvoiceItems) + foreach (var ii in createdInvoiceItems) { await invoiceItemService.DeleteAsync(ii.Id); } } - if(e is StripeException strEx && + if (e is StripeException strEx && (strEx.StripeError?.Message?.Contains("cannot be used because it is not verified") ?? false)) { throw new GatewayException("Bank account is not yet verified."); @@ -1052,21 +1052,21 @@ namespace Bit.Core.Services public async Task CancelSubscriptionAsync(ISubscriber subscriber, bool endOfPeriod = false, bool skipInAppPurchaseCheck = false) { - if(subscriber == null) + if (subscriber == null) { throw new ArgumentNullException(nameof(subscriber)); } - if(string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) + if (string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) { throw new GatewayException("No subscription."); } - if(!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId) && !skipInAppPurchaseCheck) + if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId) && !skipInAppPurchaseCheck) { var customerService = new CustomerService(); var customer = await customerService.GetAsync(subscriber.GatewayCustomerId); - if(customer.Metadata.ContainsKey("appleReceipt")) + if (customer.Metadata.ContainsKey("appleReceipt")) { throw new BadRequestException("You are required to manage your subscription from the app store."); } @@ -1074,12 +1074,12 @@ namespace Bit.Core.Services var subscriptionService = new SubscriptionService(); var sub = await subscriptionService.GetAsync(subscriber.GatewaySubscriptionId); - if(sub == null) + if (sub == null) { throw new GatewayException("Subscription was not found."); } - if(sub.CanceledAt.HasValue || sub.Status == "canceled" || sub.Status == "unpaid" || + if (sub.CanceledAt.HasValue || sub.Status == "canceled" || sub.Status == "unpaid" || sub.Status == "incomplete_expired") { // Already canceled @@ -1092,14 +1092,14 @@ namespace Bit.Core.Services await subscriptionService.UpdateAsync(sub.Id, new SubscriptionUpdateOptions { CancelAtPeriodEnd = true }) : await subscriptionService.CancelAsync(sub.Id, new SubscriptionCancelOptions()); - if(!canceledSub.CanceledAt.HasValue) + if (!canceledSub.CanceledAt.HasValue) { throw new GatewayException("Unable to cancel subscription."); } } - catch(StripeException e) + catch (StripeException e) { - if(e.Message != $"No such subscription: {subscriber.GatewaySubscriptionId}") + if (e.Message != $"No such subscription: {subscriber.GatewaySubscriptionId}") { throw e; } @@ -1108,24 +1108,24 @@ namespace Bit.Core.Services public async Task ReinstateSubscriptionAsync(ISubscriber subscriber) { - if(subscriber == null) + if (subscriber == null) { throw new ArgumentNullException(nameof(subscriber)); } - if(string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) + if (string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) { throw new GatewayException("No subscription."); } var subscriptionService = new SubscriptionService(); var sub = await subscriptionService.GetAsync(subscriber.GatewaySubscriptionId); - if(sub == null) + if (sub == null) { throw new GatewayException("Subscription was not found."); } - if((sub.Status != "active" && sub.Status != "trialing" && !sub.Status.StartsWith("incomplete")) || + if ((sub.Status != "active" && sub.Status != "trialing" && !sub.Status.StartsWith("incomplete")) || !sub.CanceledAt.HasValue) { throw new GatewayException("Subscription is not marked for cancellation."); @@ -1133,7 +1133,7 @@ namespace Bit.Core.Services var updatedSub = await subscriptionService.UpdateAsync(sub.Id, new SubscriptionUpdateOptions { CancelAtPeriodEnd = false }); - if(updatedSub.CanceledAt.HasValue) + if (updatedSub.CanceledAt.HasValue) { throw new GatewayException("Unable to reinstate subscription."); } @@ -1142,12 +1142,12 @@ namespace Bit.Core.Services public async Task UpdatePaymentMethodAsync(ISubscriber subscriber, PaymentMethodType paymentMethodType, string paymentToken, bool allowInAppPurchases = false) { - if(subscriber == null) + if (subscriber == null) { throw new ArgumentNullException(nameof(subscriber)); } - if(subscriber.Gateway.HasValue && subscriber.Gateway.Value != GatewayType.Stripe) + if (subscriber.Gateway.HasValue && subscriber.Gateway.Value != GatewayType.Stripe) { throw new GatewayException("Switching from one payment type to another is not supported. " + "Contact us for assistance."); @@ -1170,39 +1170,39 @@ namespace Bit.Core.Services var paymentMethodService = new PaymentMethodService(); Customer customer = null; - if(!allowInAppPurchases && inAppPurchase) + if (!allowInAppPurchases && inAppPurchase) { throw new GatewayException("In-app purchase payment method is not allowed."); } - if(!subscriber.IsUser() && inAppPurchase) + if (!subscriber.IsUser() && inAppPurchase) { throw new GatewayException("In-app purchase payment method is only allowed for users."); } - if(!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) + if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { customer = await customerService.GetAsync(subscriber.GatewayCustomerId); - if(customer.Metadata?.Any() ?? false) + if (customer.Metadata?.Any() ?? false) { stripeCustomerMetadata = customer.Metadata; } } - if(inAppPurchase && customer != null && customer.Balance != 0) + if (inAppPurchase && customer != null && customer.Balance != 0) { throw new GatewayException("Customer balance cannot exist when using in-app purchases."); } - if(!inAppPurchase && customer != null && stripeCustomerMetadata.ContainsKey("appleReceipt")) + if (!inAppPurchase && customer != null && stripeCustomerMetadata.ContainsKey("appleReceipt")) { throw new GatewayException("Cannot change from in-app payment method. Contact support."); } var hadBtCustomer = stripeCustomerMetadata.ContainsKey("btCustomerId"); - if(stripePaymentMethod) + if (stripePaymentMethod) { - if(paymentToken.StartsWith("pm_")) + if (paymentToken.StartsWith("pm_")) { stipeCustomerPaymentMethodId = paymentToken; } @@ -1211,9 +1211,9 @@ namespace Bit.Core.Services stipeCustomerSourceToken = paymentToken; } } - else if(paymentMethodType == PaymentMethodType.PayPal) + else if (paymentMethodType == PaymentMethodType.PayPal) { - if(hadBtCustomer) + if (hadBtCustomer) { var pmResult = await _btGateway.PaymentMethod.CreateAsync(new Braintree.PaymentMethodRequest { @@ -1221,7 +1221,7 @@ namespace Bit.Core.Services PaymentMethodNonce = paymentToken }); - if(pmResult.IsSuccess()) + if (pmResult.IsSuccess()) { var customerResult = await _btGateway.Customer.UpdateAsync( stripeCustomerMetadata["btCustomerId"], new Braintree.CustomerRequest @@ -1229,7 +1229,7 @@ namespace Bit.Core.Services DefaultPaymentMethodToken = pmResult.Target.Token }); - if(customerResult.IsSuccess() && customerResult.Target.PaymentMethods.Length > 0) + if (customerResult.IsSuccess() && customerResult.Target.PaymentMethods.Length > 0) { braintreeCustomer = customerResult.Target; } @@ -1245,7 +1245,7 @@ namespace Bit.Core.Services } } - if(!hadBtCustomer) + if (!hadBtCustomer) { var customerResult = await _btGateway.Customer.CreateAsync(new Braintree.CustomerRequest { @@ -1259,7 +1259,7 @@ namespace Bit.Core.Services } }); - if(!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) + if (!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) { throw new GatewayException("Failed to create PayPal customer record."); } @@ -1267,10 +1267,10 @@ namespace Bit.Core.Services braintreeCustomer = customerResult.Target; } } - else if(paymentMethodType == PaymentMethodType.AppleInApp) + else if (paymentMethodType == PaymentMethodType.AppleInApp) { appleReceiptStatus = await _appleIapService.GetVerifiedReceiptStatusAsync(paymentToken); - if(appleReceiptStatus == null) + if (appleReceiptStatus == null) { throw new GatewayException("Cannot verify Apple in-app purchase."); } @@ -1281,26 +1281,26 @@ namespace Bit.Core.Services throw new GatewayException("Payment method is not supported at this time."); } - if(stripeCustomerMetadata.ContainsKey("btCustomerId")) + if (stripeCustomerMetadata.ContainsKey("btCustomerId")) { - if(braintreeCustomer?.Id != stripeCustomerMetadata["btCustomerId"]) + if (braintreeCustomer?.Id != stripeCustomerMetadata["btCustomerId"]) { var nowSec = Utilities.CoreHelpers.ToEpocSeconds(DateTime.UtcNow); stripeCustomerMetadata.Add($"btCustomerId_{nowSec}", stripeCustomerMetadata["btCustomerId"]); } stripeCustomerMetadata["btCustomerId"] = braintreeCustomer?.Id; } - else if(!string.IsNullOrWhiteSpace(braintreeCustomer?.Id)) + else if (!string.IsNullOrWhiteSpace(braintreeCustomer?.Id)) { stripeCustomerMetadata.Add("btCustomerId", braintreeCustomer.Id); } - if(appleReceiptStatus != null) + if (appleReceiptStatus != null) { var originalTransactionId = appleReceiptStatus.GetOriginalTransactionId(); - if(stripeCustomerMetadata.ContainsKey("appleReceipt")) + if (stripeCustomerMetadata.ContainsKey("appleReceipt")) { - if(originalTransactionId != stripeCustomerMetadata["appleReceipt"]) + if (originalTransactionId != stripeCustomerMetadata["appleReceipt"]) { var nowSec = Utilities.CoreHelpers.ToEpocSeconds(DateTime.UtcNow); stripeCustomerMetadata.Add($"appleReceipt_{nowSec}", stripeCustomerMetadata["appleReceipt"]); @@ -1316,7 +1316,7 @@ namespace Bit.Core.Services try { - if(customer == null) + if (customer == null) { customer = await customerService.CreateAsync(new CustomerCreateOptions { @@ -1336,13 +1336,13 @@ namespace Bit.Core.Services createdCustomer = true; } - if(!createdCustomer) + if (!createdCustomer) { string defaultSourceId = null; string defaultPaymentMethodId = null; - if(stripePaymentMethod) + if (stripePaymentMethod) { - if(!string.IsNullOrWhiteSpace(stipeCustomerSourceToken) && paymentToken.StartsWith("btok_")) + if (!string.IsNullOrWhiteSpace(stipeCustomerSourceToken) && paymentToken.StartsWith("btok_")) { var bankAccount = await bankSerice.CreateAsync(customer.Id, new BankAccountCreateOptions { @@ -1350,7 +1350,7 @@ namespace Bit.Core.Services }); defaultSourceId = bankAccount.Id; } - else if(!string.IsNullOrWhiteSpace(stipeCustomerPaymentMethodId)) + else if (!string.IsNullOrWhiteSpace(stipeCustomerPaymentMethodId)) { await paymentMethodService.AttachAsync(stipeCustomerPaymentMethodId, new PaymentMethodAttachOptions { CustomerId = customer.Id }); @@ -1358,13 +1358,13 @@ namespace Bit.Core.Services } } - foreach(var source in customer.Sources.Where(s => s.Id != defaultSourceId)) + foreach (var source in customer.Sources.Where(s => s.Id != defaultSourceId)) { - if(source is BankAccount) + if (source is BankAccount) { await bankSerice.DeleteAsync(customer.Id, source.Id); } - else if(source is Card) + else if (source is Card) { await cardService.DeleteAsync(customer.Id, source.Id); } @@ -1375,7 +1375,7 @@ namespace Bit.Core.Services CustomerId = customer.Id, Type = "card" }); - foreach(var cardMethod in cardPaymentMethods.Where(m => m.Id != defaultPaymentMethodId)) + foreach (var cardMethod in cardPaymentMethods.Where(m => m.Id != defaultPaymentMethodId)) { await paymentMethodService.DetachAsync(cardMethod.Id, new PaymentMethodDetachOptions()); } @@ -1391,9 +1391,9 @@ namespace Bit.Core.Services }); } } - catch(Exception e) + catch (Exception e) { - if(braintreeCustomer != null && !hadBtCustomer) + if (braintreeCustomer != null && !hadBtCustomer) { await _btGateway.Customer.DeleteAsync(braintreeCustomer.Id); } @@ -1409,7 +1409,7 @@ namespace Bit.Core.Services Customer customer = null; var customerExists = subscriber.Gateway == GatewayType.Stripe && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId); - if(customerExists) + if (customerExists) { customer = await customerService.GetAsync(subscriber.GatewayCustomerId); } @@ -1435,15 +1435,15 @@ namespace Bit.Core.Services var billingInfo = new BillingInfo(); ICollection transactions = null; - if(subscriber is User) + if (subscriber is User) { transactions = await _transactionRepository.GetManyByUserIdAsync(subscriber.Id); } - else if(subscriber is Organization) + else if (subscriber is Organization) { transactions = await _transactionRepository.GetManyByOrganizationIdAsync(subscriber.Id); } - if(transactions != null) + if (transactions != null) { billingInfo.Transactions = transactions?.OrderByDescending(i => i.CreationDate) .Select(t => new BillingInfo.BillingTransaction(t)); @@ -1452,7 +1452,7 @@ namespace Bit.Core.Services var customerService = new CustomerService(); var invoiceService = new InvoiceService(); - if(!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) + if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { Customer customer = null; try @@ -1462,46 +1462,46 @@ namespace Bit.Core.Services customerOptions.AddExpand("invoice_settings.default_payment_method"); customer = await customerService.GetAsync(subscriber.GatewayCustomerId, customerOptions); } - catch(StripeException) { } - if(customer != null) + catch (StripeException) { } + if (customer != null) { billingInfo.Balance = customer.Balance / 100M; - if(customer.Metadata?.ContainsKey("appleReceipt") ?? false) + if (customer.Metadata?.ContainsKey("appleReceipt") ?? false) { billingInfo.PaymentSource = new BillingInfo.BillingSource { Type = PaymentMethodType.AppleInApp }; } - else if(customer.Metadata?.ContainsKey("btCustomerId") ?? false) + else if (customer.Metadata?.ContainsKey("btCustomerId") ?? false) { try { var braintreeCustomer = await _btGateway.Customer.FindAsync( customer.Metadata["btCustomerId"]); - if(braintreeCustomer?.DefaultPaymentMethod != null) + if (braintreeCustomer?.DefaultPaymentMethod != null) { billingInfo.PaymentSource = new BillingInfo.BillingSource( braintreeCustomer.DefaultPaymentMethod); } } - catch(Braintree.Exceptions.NotFoundException) { } + catch (Braintree.Exceptions.NotFoundException) { } } - else if(customer.InvoiceSettings?.DefaultPaymentMethod?.Type == "card") + else if (customer.InvoiceSettings?.DefaultPaymentMethod?.Type == "card") { billingInfo.PaymentSource = new BillingInfo.BillingSource( customer.InvoiceSettings.DefaultPaymentMethod); } - else if(customer.DefaultSource != null && + else if (customer.DefaultSource != null && (customer.DefaultSource is Card || customer.DefaultSource is BankAccount)) { billingInfo.PaymentSource = new BillingInfo.BillingSource(customer.DefaultSource); } - if(billingInfo.PaymentSource == null) + if (billingInfo.PaymentSource == null) { var paymentMethod = GetLatestCardPaymentMethod(customer.Id); - if(paymentMethod != null) + if (paymentMethod != null) { billingInfo.PaymentSource = new BillingInfo.BillingSource(paymentMethod); } @@ -1524,37 +1524,37 @@ namespace Bit.Core.Services { var subscriptionInfo = new SubscriptionInfo(); - if(subscriber.IsUser() && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) + if (subscriber.IsUser() && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { var customerService = new CustomerService(); var customer = await customerService.GetAsync(subscriber.GatewayCustomerId); subscriptionInfo.UsingInAppPurchase = customer.Metadata.ContainsKey("appleReceipt"); } - if(!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) + if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) { var subscriptionService = new SubscriptionService(); var invoiceService = new InvoiceService(); var sub = await subscriptionService.GetAsync(subscriber.GatewaySubscriptionId); - if(sub != null) + if (sub != null) { subscriptionInfo.Subscription = new SubscriptionInfo.BillingSubscription(sub); } - if(!sub.CanceledAt.HasValue && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) + if (!sub.CanceledAt.HasValue && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { try { var upcomingInvoice = await invoiceService.UpcomingAsync( new UpcomingInvoiceOptions { CustomerId = subscriber.GatewayCustomerId }); - if(upcomingInvoice != null) + if (upcomingInvoice != null) { subscriptionInfo.UpcomingInvoice = new SubscriptionInfo.BillingUpcomingInvoice(upcomingInvoice); } } - catch(StripeException) { } + catch (StripeException) { } } } @@ -1572,10 +1572,10 @@ namespace Bit.Core.Services private async Task VerifyAppleReceiptNotInUseAsync(string receiptOriginalTransactionId, ISubscriber subscriber) { var existingReceipt = await _appleIapService.GetReceiptAsync(receiptOriginalTransactionId); - if(existingReceipt != null && existingReceipt.Item2.HasValue && existingReceipt.Item2 != subscriber.Id) + if (existingReceipt != null && existingReceipt.Item2.HasValue && existingReceipt.Item2 != subscriber.Id) { var existingUser = await _userRepository.GetByIdAsync(existingReceipt.Item2.Value); - if(existingUser != null) + if (existingUser != null) { throw new GatewayException("Apple receipt already in use by another user."); } diff --git a/src/Core/Services/Implementations/UserService.cs b/src/Core/Services/Implementations/UserService.cs index 089239e8ef..bdf008d81f 100644 --- a/src/Core/Services/Implementations/UserService.cs +++ b/src/Core/Services/Implementations/UserService.cs @@ -108,7 +108,7 @@ namespace Bit.Core.Services public Guid? GetProperUserId(ClaimsPrincipal principal) { - if(!Guid.TryParse(GetUserId(principal), out var userIdGuid)) + if (!Guid.TryParse(GetUserId(principal), out var userIdGuid)) { return null; } @@ -118,13 +118,13 @@ namespace Bit.Core.Services public async Task GetUserByIdAsync(string userId) { - if(_currentContext?.User != null && + if (_currentContext?.User != null && string.Equals(_currentContext.User.Id.ToString(), userId, StringComparison.InvariantCultureIgnoreCase)) { return _currentContext.User; } - if(!Guid.TryParse(userId, out var userIdGuid)) + if (!Guid.TryParse(userId, out var userIdGuid)) { return null; } @@ -135,7 +135,7 @@ namespace Bit.Core.Services public async Task GetUserByIdAsync(Guid userId) { - if(_currentContext?.User != null && _currentContext.User.Id == userId) + if (_currentContext?.User != null && _currentContext.User.Id == userId) { return _currentContext.User; } @@ -147,7 +147,7 @@ namespace Bit.Core.Services public async Task GetUserByPrincipalAsync(ClaimsPrincipal principal) { var userId = GetProperUserId(principal); - if(!userId.HasValue) + if (!userId.HasValue) { return null; } @@ -162,7 +162,7 @@ namespace Bit.Core.Services public async Task SaveUserAsync(User user, bool push = false) { - if(user.Id == default(Guid)) + if (user.Id == default(Guid)) { throw new ApplicationException("Use register method to create a new user."); } @@ -170,7 +170,7 @@ namespace Bit.Core.Services user.RevisionDate = user.AccountRevisionDate = DateTime.UtcNow; await _userRepository.ReplaceAsync(user); - if(push) + if (push) { // push await _pushService.PushSyncSettingsAsync(user.Id); @@ -181,18 +181,18 @@ namespace Bit.Core.Services { // Check if user is the only owner of any organizations. var onlyOwnerCount = await _organizationUserRepository.GetCountByOnlyOwnerAsync(user.Id); - if(onlyOwnerCount > 0) + if (onlyOwnerCount > 0) { var deletedOrg = false; var orgs = await _organizationUserRepository.GetManyDetailsByUserAsync(user.Id, OrganizationUserStatusType.Confirmed); - if(orgs.Count == 1) + if (orgs.Count == 1) { var org = await _organizationRepository.GetByIdAsync(orgs.First().OrganizationId); - if(org != null && (!org.Enabled || string.IsNullOrWhiteSpace(org.GatewaySubscriptionId))) + if (org != null && (!org.Enabled || string.IsNullOrWhiteSpace(org.GatewaySubscriptionId))) { var orgCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(org.Id); - if(orgCount <= 1) + if (orgCount <= 1) { await _organizationRepository.DeleteAsync(org); deletedOrg = true; @@ -200,7 +200,7 @@ namespace Bit.Core.Services } } - if(!deletedOrg) + if (!deletedOrg) { return IdentityResult.Failed(new IdentityError { @@ -209,13 +209,13 @@ namespace Bit.Core.Services } } - if(!string.IsNullOrWhiteSpace(user.GatewaySubscriptionId)) + if (!string.IsNullOrWhiteSpace(user.GatewaySubscriptionId)) { try { await CancelPremiumAsync(user, null, true); } - catch(GatewayException) { } + catch (GatewayException) { } } await _userRepository.DeleteAsync(user); @@ -225,7 +225,7 @@ namespace Bit.Core.Services public async Task DeleteAsync(User user, string token) { - if(!(await VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, "DeleteAccount", token))) + if (!(await VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, "DeleteAccount", token))) { return IdentityResult.Failed(ErrorDescriber.InvalidToken()); } @@ -236,7 +236,7 @@ namespace Bit.Core.Services public async Task SendDeleteConfirmationAsync(string email) { var user = await _userRepository.GetByEmailAsync(email); - if(user == null) + if (user == null) { // No user exists. return; @@ -250,25 +250,25 @@ namespace Bit.Core.Services string token, Guid? orgUserId) { var tokenValid = false; - if(_globalSettings.DisableUserRegistration && !string.IsNullOrWhiteSpace(token) && orgUserId.HasValue) + if (_globalSettings.DisableUserRegistration && !string.IsNullOrWhiteSpace(token) && orgUserId.HasValue) { tokenValid = CoreHelpers.UserInviteTokenIsValid(_organizationServiceDataProtector, token, user.Email, orgUserId.Value, _globalSettings); } - if(_globalSettings.DisableUserRegistration && !tokenValid) + if (_globalSettings.DisableUserRegistration && !tokenValid) { throw new BadRequestException("Open registration has been disabled by the system administrator."); } - if(orgUserId.HasValue) + if (orgUserId.HasValue) { var orgUser = await _organizationUserRepository.GetByIdAsync(orgUserId.Value); - if(orgUser != null) + if (orgUser != null) { var twoFactorPolicy = await _policyRepository.GetByOrganizationIdTypeAsync(orgUser.OrganizationId, PolicyType.TwoFactorAuthentication); - if(twoFactorPolicy != null && twoFactorPolicy.Enabled) + if (twoFactorPolicy != null && twoFactorPolicy.Enabled) { user.SetTwoFactorProviders(new Dictionary { @@ -285,7 +285,7 @@ namespace Bit.Core.Services } var result = await base.CreateAsync(user, masterPassword); - if(result == IdentityResult.Success) + if (result == IdentityResult.Success) { await _mailService.SendWelcomeEmailAsync(user); } @@ -296,13 +296,13 @@ namespace Bit.Core.Services public async Task SendMasterPasswordHintAsync(string email) { var user = await _userRepository.GetByEmailAsync(email); - if(user == null) + if (user == null) { // No user exists. Do we want to send an email telling them this in the future? return; } - if(string.IsNullOrWhiteSpace(user.MasterPasswordHint)) + if (string.IsNullOrWhiteSpace(user.MasterPasswordHint)) { await _mailService.SendNoMasterPasswordHintEmailAsync(email); return; @@ -314,7 +314,7 @@ namespace Bit.Core.Services public async Task SendTwoFactorEmailAsync(User user) { var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Email); - if(provider == null || provider.MetaData == null || !provider.MetaData.ContainsKey("Email")) + if (provider == null || provider.MetaData == null || !provider.MetaData.ContainsKey("Email")) { throw new ArgumentNullException("No email."); } @@ -328,7 +328,7 @@ namespace Bit.Core.Services public async Task VerifyTwoFactorEmailAsync(User user, string token) { var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Email); - if(provider == null || provider.MetaData == null || !provider.MetaData.ContainsKey("Email")) + if (provider == null || provider.MetaData == null || !provider.MetaData.ContainsKey("Email")) { throw new ArgumentNullException("No email."); } @@ -361,13 +361,13 @@ namespace Bit.Core.Services public async Task CompleteU2fRegistrationAsync(User user, int id, string name, string deviceResponse) { - if(string.IsNullOrWhiteSpace(deviceResponse)) + if (string.IsNullOrWhiteSpace(deviceResponse)) { return false; } var challenges = await _u2fRepository.GetManyByUserIdAsync(user.Id); - if(!challenges?.Any() ?? true) + if (!challenges?.Any() ?? true) { return false; } @@ -384,28 +384,28 @@ namespace Bit.Core.Services // Add device var providers = user.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { providers = new Dictionary(); } var provider = user.GetTwoFactorProvider(TwoFactorProviderType.U2f); - if(provider == null) + if (provider == null) { provider = new TwoFactorProvider(); } - if(provider.MetaData == null) + if (provider.MetaData == null) { provider.MetaData = new Dictionary(); } - if(provider.MetaData.Count >= 5) + if (provider.MetaData.Count >= 5) { // Can only register up to 5 keys return false; } var keyId = $"Key{id}"; - if(provider.MetaData.ContainsKey(keyId)) + if (provider.MetaData.ContainsKey(keyId)) { provider.MetaData.Remove(keyId); } @@ -421,7 +421,7 @@ namespace Bit.Core.Services Counter = reg.Counter }); - if(providers.ContainsKey(TwoFactorProviderType.U2f)) + if (providers.ContainsKey(TwoFactorProviderType.U2f)) { providers.Remove(TwoFactorProviderType.U2f); } @@ -431,7 +431,7 @@ namespace Bit.Core.Services await UpdateTwoFactorProviderAsync(user, TwoFactorProviderType.U2f); return true; } - catch(U2fException e) + catch (U2fException e) { Logger.LogError(e, "Complete U2F registration error."); return false; @@ -441,19 +441,19 @@ namespace Bit.Core.Services public async Task DeleteU2fKeyAsync(User user, int id) { var providers = user.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { return false; } var keyName = $"Key{id}"; var provider = user.GetTwoFactorProvider(TwoFactorProviderType.U2f); - if(!provider?.MetaData?.ContainsKey(keyName) ?? true) + if (!provider?.MetaData?.ContainsKey(keyName) ?? true) { return false; } - if(provider.MetaData.Count < 2) + if (provider.MetaData.Count < 2) { return false; } @@ -467,7 +467,7 @@ namespace Bit.Core.Services public async Task SendEmailVerificationAsync(User user) { - if(user.EmailVerified) + if (user.EmailVerified) { throw new BadRequestException("Email already verified."); } @@ -479,7 +479,7 @@ namespace Bit.Core.Services public async Task InitiateEmailChangeAsync(User user, string newEmail) { var existingUser = await _userRepository.GetByEmailAsync(newEmail); - if(existingUser != null) + if (existingUser != null) { await _mailService.SendChangeEmailAlreadyExistsEmailAsync(user.Email, newEmail); return; @@ -493,25 +493,25 @@ namespace Bit.Core.Services string newMasterPassword, string token, string key) { var verifyPasswordResult = _passwordHasher.VerifyHashedPassword(user, user.MasterPassword, masterPassword); - if(verifyPasswordResult == PasswordVerificationResult.Failed) + if (verifyPasswordResult == PasswordVerificationResult.Failed) { return IdentityResult.Failed(_identityErrorDescriber.PasswordMismatch()); } - if(!await base.VerifyUserTokenAsync(user, _identityOptions.Tokens.ChangeEmailTokenProvider, + if (!await base.VerifyUserTokenAsync(user, _identityOptions.Tokens.ChangeEmailTokenProvider, GetChangeEmailTokenPurpose(newEmail), token)) { return IdentityResult.Failed(_identityErrorDescriber.InvalidToken()); } var existingUser = await _userRepository.GetByEmailAsync(newEmail); - if(existingUser != null && existingUser.Id != user.Id) + if (existingUser != null && existingUser.Id != user.Id) { return IdentityResult.Failed(_identityErrorDescriber.DuplicateEmail(newEmail)); } var result = await UpdatePasswordHash(user, newMasterPassword); - if(!result.Succeeded) + if (!result.Succeeded) { return result; } @@ -534,15 +534,15 @@ namespace Bit.Core.Services public async Task ChangePasswordAsync(User user, string masterPassword, string newMasterPassword, string key) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } - if(await CheckPasswordAsync(user, masterPassword)) + if (await CheckPasswordAsync(user, masterPassword)) { var result = await UpdatePasswordHash(user, newMasterPassword); - if(!result.Succeeded) + if (!result.Succeeded) { return result; } @@ -564,15 +564,15 @@ namespace Bit.Core.Services public async Task ChangeKdfAsync(User user, string masterPassword, string newMasterPassword, string key, KdfType kdf, int kdfIterations) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } - if(await CheckPasswordAsync(user, masterPassword)) + if (await CheckPasswordAsync(user, masterPassword)) { var result = await UpdatePasswordHash(user, newMasterPassword); - if(!result.Succeeded) + if (!result.Succeeded) { return result; } @@ -593,18 +593,18 @@ namespace Bit.Core.Services public async Task UpdateKeyAsync(User user, string masterPassword, string key, string privateKey, IEnumerable ciphers, IEnumerable folders) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } - if(await CheckPasswordAsync(user, masterPassword)) + if (await CheckPasswordAsync(user, masterPassword)) { user.RevisionDate = user.AccountRevisionDate = DateTime.UtcNow; user.SecurityStamp = Guid.NewGuid().ToString(); user.Key = key; user.PrivateKey = privateKey; - if(ciphers.Any() || folders.Any()) + if (ciphers.Any() || folders.Any()) { await _cipherRepository.UpdateUserKeysAndCiphersAsync(user, ciphers, folders); } @@ -623,15 +623,15 @@ namespace Bit.Core.Services public async Task RefreshSecurityStampAsync(User user, string masterPassword) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } - if(await CheckPasswordAsync(user, masterPassword)) + if (await CheckPasswordAsync(user, masterPassword)) { var result = await base.UpdateSecurityStampAsync(user); - if(!result.Succeeded) + if (!result.Succeeded) { return result; } @@ -656,7 +656,7 @@ namespace Bit.Core.Services IOrganizationService organizationService) { var providers = user.GetTwoFactorProviders(); - if(!providers?.ContainsKey(type) ?? true) + if (!providers?.ContainsKey(type) ?? true) { return; } @@ -666,7 +666,7 @@ namespace Bit.Core.Services await SaveUserAsync(user); await _eventService.LogUserEventAsync(user.Id, EventType.User_Disabled2fa); - if(!await TwoFactorIsEnabledAsync(user)) + if (!await TwoFactorIsEnabledAsync(user)) { await CheckPoliciesOnTwoFactorRemovalAsync(user, organizationService); } @@ -676,18 +676,18 @@ namespace Bit.Core.Services IOrganizationService organizationService) { var user = await _userRepository.GetByEmailAsync(email); - if(user == null) + if (user == null) { // No user exists. Do we want to send an email telling them this in the future? return false; } - if(!await CheckPasswordAsync(user, masterPassword)) + if (!await CheckPasswordAsync(user, masterPassword)) { return false; } - if(string.Compare(user.TwoFactorRecoveryCode, recoveryCode, true) != 0) + if (string.Compare(user.TwoFactorRecoveryCode, recoveryCode, true) != 0) { return false; } @@ -705,17 +705,17 @@ namespace Bit.Core.Services public async Task> SignUpPremiumAsync(User user, string paymentToken, PaymentMethodType paymentMethodType, short additionalStorageGb, UserLicense license) { - if(user.Premium) + if (user.Premium) { throw new BadRequestException("Already a premium user."); } - if(additionalStorageGb < 0) + if (additionalStorageGb < 0) { throw new BadRequestException("You can't subtract storage!"); } - if((paymentMethodType == PaymentMethodType.GoogleInApp || + if ((paymentMethodType == PaymentMethodType.GoogleInApp || paymentMethodType == PaymentMethodType.AppleInApp) && additionalStorageGb > 0) { throw new BadRequestException("You cannot add storage with this payment method."); @@ -723,14 +723,14 @@ namespace Bit.Core.Services string paymentIntentClientSecret = null; IPaymentService paymentService = null; - if(_globalSettings.SelfHosted) + if (_globalSettings.SelfHosted) { - if(license == null || !_licenseService.VerifyLicense(license)) + if (license == null || !_licenseService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } - if(!license.CanUse(user)) + if (!license.CanUse(user)) { throw new BadRequestException("This license is not valid for this user."); } @@ -748,7 +748,7 @@ namespace Bit.Core.Services user.Premium = true; user.RevisionDate = DateTime.UtcNow; - if(_globalSettings.SelfHosted) + if (_globalSettings.SelfHosted) { user.MaxStorageGb = 10240; // 10 TB user.LicenseKey = license.LicenseKey; @@ -776,21 +776,21 @@ namespace Bit.Core.Services public async Task IapCheckAsync(User user, PaymentMethodType paymentMethodType) { - if(paymentMethodType != PaymentMethodType.AppleInApp) + if (paymentMethodType != PaymentMethodType.AppleInApp) { throw new BadRequestException("Payment method not supported for in-app purchases."); } - if(user.Premium) + if (user.Premium) { throw new BadRequestException("Already a premium user."); } - if(!string.IsNullOrWhiteSpace(user.GatewayCustomerId)) + if (!string.IsNullOrWhiteSpace(user.GatewayCustomerId)) { var customerService = new Stripe.CustomerService(); var customer = await customerService.GetAsync(user.GatewayCustomerId); - if(customer != null && customer.Balance != 0) + if (customer != null && customer.Balance != 0) { throw new BadRequestException("Customer balance cannot exist when using in-app purchases."); } @@ -799,17 +799,17 @@ namespace Bit.Core.Services public async Task UpdateLicenseAsync(User user, UserLicense license) { - if(!_globalSettings.SelfHosted) + if (!_globalSettings.SelfHosted) { throw new InvalidOperationException("Licenses require self hosting."); } - if(license == null || !_licenseService.VerifyLicense(license)) + if (license == null || !_licenseService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } - if(!license.CanUse(user)) + if (!license.CanUse(user)) { throw new BadRequestException("This license is not valid for this user."); } @@ -828,12 +828,12 @@ namespace Bit.Core.Services public async Task AdjustStorageAsync(User user, short storageAdjustmentGb) { - if(user == null) + if (user == null) { throw new ArgumentNullException(nameof(user)); } - if(!user.Premium) + if (!user.Premium) { throw new BadRequestException("Not a premium user."); } @@ -846,13 +846,13 @@ namespace Bit.Core.Services public async Task ReplacePaymentMethodAsync(User user, string paymentToken, PaymentMethodType paymentMethodType) { - if(paymentToken.StartsWith("btok_")) + if (paymentToken.StartsWith("btok_")) { throw new BadRequestException("Invalid token."); } var updated = await _paymentService.UpdatePaymentMethodAsync(user, paymentMethodType, paymentToken); - if(updated) + if (updated) { await SaveUserAsync(user); } @@ -861,7 +861,7 @@ namespace Bit.Core.Services public async Task CancelPremiumAsync(User user, bool? endOfPeriod = null, bool accountDelete = false) { var eop = endOfPeriod.GetValueOrDefault(true); - if(!endOfPeriod.HasValue && user.PremiumExpirationDate.HasValue && + if (!endOfPeriod.HasValue && user.PremiumExpirationDate.HasValue && user.PremiumExpirationDate.Value < DateTime.UtcNow) { eop = false; @@ -882,7 +882,7 @@ namespace Bit.Core.Services public async Task EnablePremiumAsync(User user, DateTime? expirationDate) { - if(user != null && !user.Premium && user.Gateway.HasValue) + if (user != null && !user.Premium && user.Gateway.HasValue) { user.Premium = true; user.PremiumExpirationDate = expirationDate; @@ -899,7 +899,7 @@ namespace Bit.Core.Services public async Task DisablePremiumAsync(User user, DateTime? expirationDate) { - if(user != null && user.Premium) + if (user != null && user.Premium) { user.Premium = false; user.PremiumExpirationDate = expirationDate; @@ -911,7 +911,7 @@ namespace Bit.Core.Services public async Task UpdatePremiumExpirationAsync(Guid userId, DateTime? expirationDate) { var user = await _userRepository.GetByIdAsync(userId); - if(user != null) + if (user != null) { user.PremiumExpirationDate = expirationDate; user.RevisionDate = DateTime.UtcNow; @@ -921,12 +921,12 @@ namespace Bit.Core.Services public async Task GenerateLicenseAsync(User user, SubscriptionInfo subscriptionInfo = null) { - if(user == null) + if (user == null) { throw new NotFoundException(); } - if(subscriptionInfo == null && user.Gateway != null) + if (subscriptionInfo == null && user.Gateway != null) { subscriptionInfo = await _paymentService.GetSubscriptionAsync(user); } @@ -937,13 +937,13 @@ namespace Bit.Core.Services public override async Task CheckPasswordAsync(User user, string password) { - if(user == null) + if (user == null) { return false; } var result = await base.VerifyPasswordAsync(Store as IUserPasswordStore, user, password); - if(result == PasswordVerificationResult.SuccessRehashNeeded) + if (result == PasswordVerificationResult.SuccessRehashNeeded) { await UpdatePasswordHash(user, password, false, false); user.RevisionDate = DateTime.UtcNow; @@ -951,7 +951,7 @@ namespace Bit.Core.Services } var success = result != PasswordVerificationResult.Failed; - if(!success) + if (!success) { Logger.LogWarning(0, "Invalid password for user {userId}.", user.Id); } @@ -961,16 +961,16 @@ namespace Bit.Core.Services public async Task CanAccessPremium(ITwoFactorProvidersUser user) { var userId = user.GetUserId(); - if(!userId.HasValue) + if (!userId.HasValue) { return false; } - if(user.GetPremium()) + if (user.GetPremium()) { return true; } var orgs = await _currentContext.OrganizationMembershipAsync(_organizationUserRepository, userId.Value); - if(!orgs.Any()) + if (!orgs.Any()) { return false; } @@ -982,20 +982,20 @@ namespace Bit.Core.Services public async Task TwoFactorIsEnabledAsync(ITwoFactorProvidersUser user) { var providers = user.GetTwoFactorProviders(); - if(providers == null) + if (providers == null) { return false; } - foreach(var p in providers) + foreach (var p in providers) { - if(p.Value?.Enabled ?? false) + if (p.Value?.Enabled ?? false) { - if(!TwoFactorProvider.RequiresPremium(p.Key)) + if (!TwoFactorProvider.RequiresPremium(p.Key)) { return true; } - if(await CanAccessPremium(user)) + if (await CanAccessPremium(user)) { return true; } @@ -1007,12 +1007,12 @@ namespace Bit.Core.Services public async Task TwoFactorProviderIsEnabledAsync(TwoFactorProviderType provider, ITwoFactorProvidersUser user) { var providers = user.GetTwoFactorProviders(); - if(providers == null || !providers.ContainsKey(provider) || !providers[provider].Enabled) + if (providers == null || !providers.ContainsKey(provider) || !providers[provider].Enabled) { return false; } - if(!TwoFactorProvider.RequiresPremium(provider)) + if (!TwoFactorProvider.RequiresPremium(provider)) { return true; } @@ -1023,17 +1023,17 @@ namespace Bit.Core.Services private async Task UpdatePasswordHash(User user, string newPassword, bool validatePassword = true, bool refreshStamp = true) { - if(validatePassword) + if (validatePassword) { var validate = await ValidatePasswordInternal(user, newPassword); - if(!validate.Succeeded) + if (!validate.Succeeded) { return validate; } } user.MasterPassword = _passwordHasher.HashPassword(user, newPassword); - if(refreshStamp) + if (refreshStamp) { user.SecurityStamp = Guid.NewGuid().ToString(); } @@ -1044,16 +1044,16 @@ namespace Bit.Core.Services private async Task ValidatePasswordInternal(User user, string password) { var errors = new List(); - foreach(var v in _passwordValidators) + foreach (var v in _passwordValidators) { var result = await v.ValidateAsync(this, user, password); - if(!result.Succeeded) + if (!result.Succeeded) { errors.AddRange(result.Errors); } } - if(errors.Count > 0) + if (errors.Count > 0) { Logger.LogWarning("User {userId} password validation failed: {errors}.", await GetUserIdAsync(user), string.Join(";", errors.Select(e => e.Code))); @@ -1066,7 +1066,7 @@ namespace Bit.Core.Services public void SetTwoFactorProvider(User user, TwoFactorProviderType type) { var providers = user.GetTwoFactorProviders(); - if(!providers?.ContainsKey(type) ?? true) + if (!providers?.ContainsKey(type) ?? true) { return; } @@ -1074,7 +1074,7 @@ namespace Bit.Core.Services providers[type].Enabled = true; user.SetTwoFactorProviders(providers); - if(string.IsNullOrWhiteSpace(user.TwoFactorRecoveryCode)) + if (string.IsNullOrWhiteSpace(user.TwoFactorRecoveryCode)) { user.TwoFactorRecoveryCode = CoreHelpers.SecureRandomString(32, upper: false, special: false); } @@ -1084,14 +1084,14 @@ namespace Bit.Core.Services { var policies = await _policyRepository.GetManyByUserIdAsync(user.Id); var twoFactorPolicies = policies.Where(p => p.Type == PolicyType.TwoFactorAuthentication && p.Enabled); - if(twoFactorPolicies.Any()) + if (twoFactorPolicies.Any()) { var userOrgs = await _organizationUserRepository.GetManyByUserAsync(user.Id); var ownerOrgs = userOrgs.Where(o => o.Type == OrganizationUserType.Owner) .Select(o => o.OrganizationId).ToHashSet(); - foreach(var policy in twoFactorPolicies) + foreach (var policy in twoFactorPolicies) { - if(!ownerOrgs.Contains(policy.OrganizationId)) + if (!ownerOrgs.Contains(policy.OrganizationId)) { await organizationService.DeleteUserAsync(policy.OrganizationId, user.Id); var organization = await _organizationRepository.GetByIdAsync(policy.OrganizationId); diff --git a/src/Core/Services/NoopImplementations/NoopLicensingService.cs b/src/Core/Services/NoopImplementations/NoopLicensingService.cs index 61d7eb15ec..1c645c68d7 100644 --- a/src/Core/Services/NoopImplementations/NoopLicensingService.cs +++ b/src/Core/Services/NoopImplementations/NoopLicensingService.cs @@ -13,7 +13,7 @@ namespace Bit.Core.Services IWebHostEnvironment environment, GlobalSettings globalSettings) { - if(!environment.IsDevelopment() && globalSettings.SelfHosted) + if (!environment.IsDevelopment() && globalSettings.SelfHosted) { throw new Exception($"{nameof(NoopLicensingService)} cannot be used for self hosted instances."); } diff --git a/src/Core/Utilities/BillingHelpers.cs b/src/Core/Utilities/BillingHelpers.cs index c35ecd1a87..9c79ba5cab 100644 --- a/src/Core/Utilities/BillingHelpers.cs +++ b/src/Core/Utilities/BillingHelpers.cs @@ -11,39 +11,39 @@ namespace Bit.Core.Utilities internal static async Task AdjustStorageAsync(IPaymentService paymentService, IStorableSubscriber storableSubscriber, short storageAdjustmentGb, string storagePlanId) { - if(storableSubscriber == null) + if (storableSubscriber == null) { throw new ArgumentNullException(nameof(storableSubscriber)); } - if(string.IsNullOrWhiteSpace(storableSubscriber.GatewayCustomerId)) + if (string.IsNullOrWhiteSpace(storableSubscriber.GatewayCustomerId)) { throw new BadRequestException("No payment method found."); } - if(string.IsNullOrWhiteSpace(storableSubscriber.GatewaySubscriptionId)) + if (string.IsNullOrWhiteSpace(storableSubscriber.GatewaySubscriptionId)) { throw new BadRequestException("No subscription found."); } - if(!storableSubscriber.MaxStorageGb.HasValue) + if (!storableSubscriber.MaxStorageGb.HasValue) { throw new BadRequestException("No access to storage."); } var newStorageGb = (short)(storableSubscriber.MaxStorageGb.Value + storageAdjustmentGb); - if(newStorageGb < 1) + if (newStorageGb < 1) { newStorageGb = 1; } - if(newStorageGb > 100) + if (newStorageGb > 100) { throw new BadRequestException("Maximum storage is 100 GB."); } var remainingStorage = storableSubscriber.StorageBytesRemaining(newStorageGb); - if(remainingStorage < 0) + if (remainingStorage < 0) { throw new BadRequestException("You are currently using " + $"{CoreHelpers.ReadableBytesSize(storableSubscriber.Storage.GetValueOrDefault(0))} of storage. " + diff --git a/src/Core/Utilities/BitPayClient.cs b/src/Core/Utilities/BitPayClient.cs index 309eda1675..452df0a203 100644 --- a/src/Core/Utilities/BitPayClient.cs +++ b/src/Core/Utilities/BitPayClient.cs @@ -9,7 +9,7 @@ namespace Bit.Core.Utilities public BitPayClient(GlobalSettings globalSettings) { - if(CoreHelpers.SettingHasValue(globalSettings.BitPay.Token)) + if (CoreHelpers.SettingHasValue(globalSettings.BitPay.Token)) { _bpClient = new BitPayLight.BitPay(globalSettings.BitPay.Token, globalSettings.BitPay.Production ? BitPayLight.Env.Prod : BitPayLight.Env.Test); diff --git a/src/Core/Utilities/CoreHelpers.cs b/src/Core/Utilities/CoreHelpers.cs index af1f182da5..38761168e0 100644 --- a/src/Core/Utilities/CoreHelpers.cs +++ b/src/Core/Utilities/CoreHelpers.cs @@ -72,14 +72,14 @@ namespace Bit.Core.Utilities { T[] bucket = null; var count = 0; - foreach(var item in source) + foreach (var item in source) { - if(bucket == null) + if (bucket == null) { bucket = new T[size]; } bucket[count++] = item; - if(count != size) + if (count != size) { continue; } @@ -88,7 +88,7 @@ namespace Bit.Core.Utilities count = 0; } // Return the last bucket with all remaining elements - if(bucket != null && count > 0) + if (bucket != null && count > 0) { yield return bucket.Take(count); } @@ -105,9 +105,9 @@ namespace Bit.Core.Utilities table.SetTypeName($"[dbo].[{columnName}Array]"); table.Columns.Add(columnName, typeof(T)); - if(values != null) + if (values != null) { - foreach(var value in values) + foreach (var value in values) { table.Rows.Add(value); } @@ -126,9 +126,9 @@ namespace Bit.Core.Utilities var readOnlyColumn = new DataColumn("ReadOnly", typeof(bool)); table.Columns.Add(readOnlyColumn); - if(values != null) + if (values != null) { - foreach(var value in values) + foreach (var value in values) { var row = table.NewRow(); row[idColumn] = value.Id; @@ -155,7 +155,7 @@ namespace Bit.Core.Utilities var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadOnly); var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); - if(certCollection.Count > 0) + if (certCollection.Count > 0) { cert = certCollection[0]; } @@ -172,8 +172,8 @@ namespace Bit.Core.Utilities public async static Task GetEmbeddedCertificateAsync(string file, string password) { var assembly = typeof(CoreHelpers).GetTypeInfo().Assembly; - using(var s = assembly.GetManifestResourceStream($"Bit.Core.{file}")) - using(var ms = new MemoryStream()) + using (var s = assembly.GetManifestResourceStream($"Bit.Core.{file}")) + using (var ms = new MemoryStream()) { await s.CopyToAsync(ms); return new X509Certificate2(ms.ToArray(), password); @@ -185,10 +185,10 @@ namespace Bit.Core.Utilities { var blobClient = cloudStorageAccount.CreateCloudBlobClient(); var containerRef = blobClient.GetContainerReference(container); - if(await containerRef.ExistsAsync()) + if (await containerRef.ExistsAsync()) { var blobRef = containerRef.GetBlobReference(file); - if(await blobRef.ExistsAsync()) + if (await blobRef.ExistsAsync()) { var blobBytes = new byte[blobRef.Properties.Length]; await blobRef.DownloadToByteArrayAsync(blobBytes, 0); @@ -243,18 +243,18 @@ namespace Bit.Core.Utilities // ref https://stackoverflow.com/a/8996788/1090359 with modifications public static string SecureRandomString(int length, string characters) { - if(length < 0) + if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), "length cannot be less than zero."); } - if((characters?.Length ?? 0) == 0) + if ((characters?.Length ?? 0) == 0) { throw new ArgumentOutOfRangeException(nameof(characters), "characters invalid."); } const int byteSize = 0x100; - if(byteSize < characters.Length) + if (byteSize < characters.Length) { throw new ArgumentException( string.Format("{0} may contain no more than {1} characters.", nameof(characters), byteSize), @@ -262,19 +262,19 @@ namespace Bit.Core.Utilities } var outOfRangeStart = byteSize - (byteSize % characters.Length); - using(var rng = RandomNumberGenerator.Create()) + using (var rng = RandomNumberGenerator.Create()) { var sb = new StringBuilder(); var buffer = new byte[128]; - while(sb.Length < length) + while (sb.Length < length) { rng.GetBytes(buffer); - for(var i = 0; i < buffer.Length && sb.Length < length; ++i) + for (var i = 0; i < buffer.Length && sb.Length < length; ++i) { // Divide the byte into charSet-sized groups. If the random value falls into the last group and the // last group is too small to choose from the entire allowedCharSet, ignore the value in order to // avoid biasing the result. - if(outOfRangeStart <= buffer[i]) + if (outOfRangeStart <= buffer[i]) { continue; } @@ -290,25 +290,25 @@ namespace Bit.Core.Utilities private static string RandomStringCharacters(bool alpha, bool upper, bool lower, bool numeric, bool special) { var characters = string.Empty; - if(alpha) + if (alpha) { - if(upper) + if (upper) { characters += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } - if(lower) + if (lower) { characters += "abcdefghijklmnopqrstuvwxyz"; } } - if(numeric) + if (numeric) { characters += "0123456789"; } - if(special) + if (special) { characters += "!@#$%^*&"; } @@ -327,17 +327,17 @@ namespace Bit.Core.Utilities // Determine the suffix and readable value string suffix; double readable; - if(absoluteSize >= 0x40000000) // 1 Gigabyte + if (absoluteSize >= 0x40000000) // 1 Gigabyte { suffix = "GB"; readable = (size >> 20); } - else if(absoluteSize >= 0x100000) // 1 Megabyte + else if (absoluteSize >= 0x100000) // 1 Megabyte { suffix = "MB"; readable = (size >> 10); } - else if(absoluteSize >= 0x400) // 1 Kilobyte + else if (absoluteSize >= 0x400) // 1 Kilobyte { suffix = "KB"; readable = size; @@ -403,7 +403,7 @@ namespace Bit.Core.Utilities // 63rd char of encoding output = output.Replace('_', '/'); // Pad with trailing '='s - switch(output.Length % 4) + switch (output.Length % 4) { case 0: // No pad chars in this case @@ -424,17 +424,17 @@ namespace Bit.Core.Utilities public static string FormatLicenseSignatureValue(object val) { - if(val == null) + if (val == null) { return string.Empty; } - if(val.GetType() == typeof(DateTime)) + if (val.GetType() == typeof(DateTime)) { return ToEpocSeconds((DateTime)val).ToString(); } - if(val.GetType() == typeof(bool)) + if (val.GetType() == typeof(bool)) { return val.ToString().ToLowerInvariant(); } @@ -444,7 +444,7 @@ namespace Bit.Core.Utilities public static string GetVersion() { - if(string.IsNullOrWhiteSpace(_version)) + if (string.IsNullOrWhiteSpace(_version)) { _version = Assembly.GetEntryAssembly() .GetCustomAttribute() @@ -467,7 +467,7 @@ namespace Bit.Core.Utilities private static string Other2Qwerty(string value, string otherMap, string qwertyMap) { var sb = new StringBuilder(); - foreach(var c in value) + foreach (var c in value) { sb.Append(otherMap.IndexOf(c) > -1 ? qwertyMap[otherMap.IndexOf(c)] : c); } @@ -483,7 +483,7 @@ namespace Bit.Core.Utilities public static string DateTimeToTableStorageKey(DateTime? date = null) { - if(date.HasValue) + if (date.HasValue) { date = date.Value.ToUniversalTime(); } @@ -500,7 +500,7 @@ namespace Bit.Core.Utilities { var baseUri = uri.ToString(); var queryString = string.Empty; - if(baseUri.Contains("?")) + if (baseUri.Contains("?")) { var urlSplit = baseUri.Split('?'); baseUri = urlSplit[0]; @@ -508,13 +508,13 @@ namespace Bit.Core.Utilities } var queryCollection = HttpUtility.ParseQueryString(queryString); - foreach(var kvp in values ?? new Dictionary()) + foreach (var kvp in values ?? new Dictionary()) { queryCollection[kvp.Key] = kvp.Value; } var uriKind = uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative; - if(queryCollection.Count == 0) + if (queryCollection.Count == 0) { return new Uri(baseUri, uriKind); } @@ -534,7 +534,7 @@ namespace Bit.Core.Utilities { var unprotectedData = protector.Unprotect(token); var dataParts = unprotectedData.Split(' '); - if(dataParts.Length == 4 && dataParts[0] == "OrganizationUserInvite" && + if (dataParts.Length == 4 && dataParts[0] == "OrganizationUserInvite" && new Guid(dataParts[1]) == orgUserId && dataParts[2].Equals(userEmail, StringComparison.InvariantCultureIgnoreCase)) { @@ -554,17 +554,17 @@ namespace Bit.Core.Utilities public static string GetApplicationCacheServiceBusSubcriptionName(GlobalSettings globalSettings) { var subName = globalSettings.ServiceBus.ApplicationCacheSubscriptionName; - if(string.IsNullOrWhiteSpace(subName)) + if (string.IsNullOrWhiteSpace(subName)) { var websiteInstanceId = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"); - if(string.IsNullOrWhiteSpace(websiteInstanceId)) + if (string.IsNullOrWhiteSpace(websiteInstanceId)) { throw new Exception("No service bus subscription name available."); } else { subName = $"{globalSettings.ProjectName.ToLower()}_{websiteInstanceId}"; - if(subName.Length > 50) + if (subName.Length > 50) { subName = subName.Substring(0, 50); } @@ -576,16 +576,16 @@ namespace Bit.Core.Utilities public static string GetIpAddress(this Microsoft.AspNetCore.Http.HttpContext httpContext, GlobalSettings globalSettings) { - if(httpContext == null) + if (httpContext == null) { return null; } - if(!globalSettings.SelfHosted && httpContext.Request.Headers.ContainsKey(CloudFlareConnectingIp)) + if (!globalSettings.SelfHosted && httpContext.Request.Headers.ContainsKey(CloudFlareConnectingIp)) { return httpContext.Request.Headers[CloudFlareConnectingIp].ToString(); } - if(globalSettings.SelfHosted && httpContext.Request.Headers.ContainsKey(RealIp)) + if (globalSettings.SelfHosted && httpContext.Request.Headers.ContainsKey(RealIp)) { return httpContext.Request.Headers[RealIp].ToString(); } diff --git a/src/Core/Utilities/CustomIpRateLimitMiddleware.cs b/src/Core/Utilities/CustomIpRateLimitMiddleware.cs index 4b547bef31..125bdb2e1b 100644 --- a/src/Core/Utilities/CustomIpRateLimitMiddleware.cs +++ b/src/Core/Utilities/CustomIpRateLimitMiddleware.cs @@ -56,7 +56,7 @@ namespace Bit.Core.Utilities _memoryCache.TryGetValue(key, out int blockedCount); blockedCount++; - if(blockedCount > 10) + if (blockedCount > 10) { _blockIpService.BlockIpAsync(identity.ClientIp, false); _logger.LogInformation(Constants.BypassFiltersEventId, null, @@ -73,18 +73,18 @@ namespace Bit.Core.Utilities private string GetRequestInfo(HttpContext httpContext) { - if(httpContext == null || httpContext.Request == null) + if (httpContext == null || httpContext.Request == null) { return null; } var s = string.Empty; - foreach(var header in httpContext.Request.Headers) + foreach (var header in httpContext.Request.Headers) { s += $"Header \"{header.Key}\": {header.Value} \n"; } - foreach(var query in httpContext.Request.Query) + foreach (var query in httpContext.Request.Query) { s += $"Query \"{query.Key}\": {query.Value} \n"; } diff --git a/src/Core/Utilities/DuoApi.cs b/src/Core/Utilities/DuoApi.cs index aab41e7e7b..75584eb73c 100644 --- a/src/Core/Utilities/DuoApi.cs +++ b/src/Core/Utilities/DuoApi.cs @@ -40,7 +40,7 @@ namespace Bit.Core.Utilities.Duo public static string CanonicalizeParams(Dictionary parameters) { var ret = new List(); - foreach(var pair in parameters) + foreach (var pair in parameters) { var p = string.Format("{0}={1}", HttpUtility.UrlEncode(pair.Key), HttpUtility.UrlEncode(pair.Value)); // Signatures require upper-case hex digits. @@ -94,16 +94,16 @@ namespace Bit.Core.Utilities.Duo public string ApiCall(string method, string path, Dictionary parameters, int timeout, out HttpStatusCode statusCode) { - if(parameters == null) + if (parameters == null) { parameters = new Dictionary(); } var canonParams = CanonicalizeParams(parameters); var query = string.Empty; - if(!method.Equals("POST") && !method.Equals("PUT")) + if (!method.Equals("POST") && !method.Equals("PUT")) { - if(parameters.Count > 0) + if (parameters.Count > 0) { query = "?" + canonParams; } @@ -120,17 +120,17 @@ namespace Bit.Core.Utilities.Duo request.Headers.Add("X-Duo-Date", dateString); request.UserAgent = UserAgent; - if(method.Equals("POST") || method.Equals("PUT")) + if (method.Equals("POST") || method.Equals("PUT")) { var data = Encoding.UTF8.GetBytes(canonParams); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; - using(var requestStream = request.GetRequestStream()) + using (var requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } } - if(timeout > 0) + if (timeout > 0) { request.Timeout = timeout; } @@ -141,15 +141,15 @@ namespace Bit.Core.Utilities.Duo { response = (HttpWebResponse)request.GetResponse(); } - catch(WebException ex) + catch (WebException ex) { response = (HttpWebResponse)ex.Response; - if(response == null) + if (response == null) { throw; } } - using(var reader = new StreamReader(response.GetResponseStream())) + using (var reader = new StreamReader(response.GetResponseStream())) { statusCode = response.StatusCode; return reader.ReadToEnd(); @@ -176,7 +176,7 @@ namespace Bit.Core.Utilities.Duo try { var dict = JsonConvert.DeserializeObject>(res); - if(dict["stat"] as string == "OK") + if (dict["stat"] as string == "OK") { return dict["response"] as T; } @@ -185,18 +185,18 @@ namespace Bit.Core.Utilities.Duo var check = dict["code"] as int?; var code = check.GetValueOrDefault(0); var messageDetail = string.Empty; - if(dict.ContainsKey("message_detail")) + if (dict.ContainsKey("message_detail")) { messageDetail = dict["message_detail"] as string; } throw new ApiException(code, (int)statusCode, dict["message"] as string, messageDetail); } } - catch(ApiException) + catch (ApiException) { throw; } - catch(Exception e) + catch (Exception e) { throw new BadResponseException((int)statusCode, e); } @@ -207,7 +207,7 @@ namespace Bit.Core.Utilities.Duo var keyBytes = Encoding.ASCII.GetBytes(_skey); var dataBytes = Encoding.ASCII.GetBytes(data); - using(var hmac = new HMACSHA1(keyBytes)) + using (var hmac = new HMACSHA1(keyBytes)) { var hash = hmac.ComputeHash(dataBytes); var hex = BitConverter.ToString(hash); @@ -273,7 +273,7 @@ namespace Bit.Core.Utilities.Duo private static string FormatMessage(int httpStatus, Exception inner) { var innerMessage = "(null)"; - if(inner != null) + if (inner != null) { innerMessage = string.Format("'{0}'", inner.Message); } diff --git a/src/Core/Utilities/DuoWeb.cs b/src/Core/Utilities/DuoWeb.cs index e374e76490..b8f40d8892 100644 --- a/src/Core/Utilities/DuoWeb.cs +++ b/src/Core/Utilities/DuoWeb.cs @@ -80,23 +80,23 @@ namespace Bit.Core.Utilities.Duo var currentTimeValue = currentTime ?? DateTime.UtcNow; - if(username == string.Empty) + if (username == string.Empty) { return ErrorUser; } - if(username.Contains("|")) + if (username.Contains("|")) { return ErrorUser; } - if(ikey.Length != IKeyLength) + if (ikey.Length != IKeyLength) { return ErrorIKey; } - if(skey.Length != SKeyLength) + if (skey.Length != SKeyLength) { return ErrorSKey; } - if(akey.Length < AKeyLength) + if (akey.Length < AKeyLength) { return ErrorAKey; } @@ -145,7 +145,7 @@ namespace Bit.Core.Utilities.Duo return null; } - if(authUser != appUser) + if (authUser != appUser) { return null; } @@ -169,7 +169,7 @@ namespace Bit.Core.Utilities.Duo var ts = (long)(currentTime - _epoc).TotalSeconds; var parts = val.Split('|'); - if(parts.Length != 3) + if (parts.Length != 3) { return null; } @@ -179,19 +179,19 @@ namespace Bit.Core.Utilities.Duo var uSig = parts[2]; var sig = Sign(key, $"{uPrefix}|{uB64}"); - if(Sign(key, sig) != Sign(key, uSig)) + if (Sign(key, sig) != Sign(key, uSig)) { return null; } - if(uPrefix != prefix) + if (uPrefix != prefix) { return null; } var cookie = Decode64(uB64); var cookieParts = cookie.Split('|'); - if(cookieParts.Length != 3) + if (cookieParts.Length != 3) { return null; } @@ -200,13 +200,13 @@ namespace Bit.Core.Utilities.Duo var uIKey = cookieParts[1]; var expire = cookieParts[2]; - if(uIKey != ikey) + if (uIKey != ikey) { return null; } var expireTs = Convert.ToInt32(expire); - if(ts >= expireTs) + if (ts >= expireTs) { return null; } @@ -219,7 +219,7 @@ namespace Bit.Core.Utilities.Duo var keyBytes = Encoding.ASCII.GetBytes(skey); var dataBytes = Encoding.ASCII.GetBytes(data); - using(var hmac = new HMACSHA1(keyBytes)) + using (var hmac = new HMACSHA1(keyBytes)) { var hash = hmac.ComputeHash(dataBytes); var hex = BitConverter.ToString(hash); diff --git a/src/Core/Utilities/EncryptedValueAttribute.cs b/src/Core/Utilities/EncryptedValueAttribute.cs index c9de2e6579..94c671d02d 100644 --- a/src/Core/Utilities/EncryptedValueAttribute.cs +++ b/src/Core/Utilities/EncryptedValueAttribute.cs @@ -14,7 +14,7 @@ namespace Bit.Core.Utilities public override bool IsValid(object value) { - if(value == null) + if (value == null) { return true; } @@ -22,7 +22,7 @@ namespace Bit.Core.Utilities try { var encString = value?.ToString(); - if(string.IsNullOrWhiteSpace(encString)) + if (string.IsNullOrWhiteSpace(encString)) { return false; } @@ -31,10 +31,10 @@ namespace Bit.Core.Utilities string[] encStringPieces = null; var encType = Enums.EncryptionType.AesCbc256_B64; - if(headerPieces.Length == 1) + if (headerPieces.Length == 1) { encStringPieces = headerPieces[0].Split('|'); - if(encStringPieces.Length == 3) + if (encStringPieces.Length == 3) { encType = Enums.EncryptionType.AesCbc128_HmacSha256_B64; } @@ -43,35 +43,35 @@ namespace Bit.Core.Utilities encType = Enums.EncryptionType.AesCbc256_B64; } } - else if(headerPieces.Length == 2) + else if (headerPieces.Length == 2) { encStringPieces = headerPieces[1].Split('|'); - if(!Enum.TryParse(headerPieces[0], out encType)) + if (!Enum.TryParse(headerPieces[0], out encType)) { return false; } } - switch(encType) + switch (encType) { case Enums.EncryptionType.AesCbc256_B64: case Enums.EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64: case Enums.EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64: - if(encStringPieces.Length != 2) + if (encStringPieces.Length != 2) { return false; } break; case Enums.EncryptionType.AesCbc128_HmacSha256_B64: case Enums.EncryptionType.AesCbc256_HmacSha256_B64: - if(encStringPieces.Length != 3) + if (encStringPieces.Length != 3) { return false; } break; case Enums.EncryptionType.Rsa2048_OaepSha256_B64: case Enums.EncryptionType.Rsa2048_OaepSha1_B64: - if(encStringPieces.Length != 1) + if (encStringPieces.Length != 1) { return false; } @@ -80,23 +80,23 @@ namespace Bit.Core.Utilities return false; } - switch(encType) + switch (encType) { case Enums.EncryptionType.AesCbc256_B64: case Enums.EncryptionType.AesCbc128_HmacSha256_B64: case Enums.EncryptionType.AesCbc256_HmacSha256_B64: var iv = Convert.FromBase64String(encStringPieces[0]); var ct = Convert.FromBase64String(encStringPieces[1]); - if(iv.Length < 1 || ct.Length < 1) + if (iv.Length < 1 || ct.Length < 1) { return false; } - if(encType == Enums.EncryptionType.AesCbc128_HmacSha256_B64 || + if (encType == Enums.EncryptionType.AesCbc128_HmacSha256_B64 || encType == Enums.EncryptionType.AesCbc256_HmacSha256_B64) { var mac = Convert.FromBase64String(encStringPieces[2]); - if(mac.Length < 1) + if (mac.Length < 1) { return false; } @@ -108,16 +108,16 @@ namespace Bit.Core.Utilities case Enums.EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64: case Enums.EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64: var rsaCt = Convert.FromBase64String(encStringPieces[0]); - if(rsaCt.Length < 1) + if (rsaCt.Length < 1) { return false; } - if(encType == Enums.EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64 || + if (encType == Enums.EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64 || encType == Enums.EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64) { var mac = Convert.FromBase64String(encStringPieces[1]); - if(mac.Length < 1) + if (mac.Length < 1) { return false; } diff --git a/src/Core/Utilities/EnumKeyResolver.cs b/src/Core/Utilities/EnumKeyResolver.cs index 1f5671b2a8..c99b1240ac 100644 --- a/src/Core/Utilities/EnumKeyResolver.cs +++ b/src/Core/Utilities/EnumKeyResolver.cs @@ -10,7 +10,7 @@ namespace Bit.Core.Utilities var contract = base.CreateDictionaryContract(objectType); var keyType = contract.DictionaryKeyType; - if(keyType.BaseType == typeof(Enum)) + if (keyType.BaseType == typeof(Enum)) { contract.DictionaryKeyResolver = propName => ((T)Enum.Parse(keyType, propName)).ToString(); } diff --git a/src/Core/Utilities/LoggerFactoryExtensions.cs b/src/Core/Utilities/LoggerFactoryExtensions.cs index 61fa9583c6..9ec3229dfa 100644 --- a/src/Core/Utilities/LoggerFactoryExtensions.cs +++ b/src/Core/Utilities/LoggerFactoryExtensions.cs @@ -17,7 +17,7 @@ namespace Bit.Core.Utilities IHostApplicationLifetime applicationLifetime, GlobalSettings globalSettings) { - if(env.IsDevelopment()) + if (env.IsDevelopment()) { return; } @@ -30,19 +30,19 @@ namespace Bit.Core.Utilities WebHostBuilderContext context, Func filter = null) { - if(context.HostingEnvironment.IsDevelopment()) + if (context.HostingEnvironment.IsDevelopment()) { return builder; } bool inclusionPredicate(LogEvent e) { - if(filter == null) + if (filter == null) { return true; } var eventId = e.Properties.ContainsKey("EventId") ? e.Properties["EventId"].ToString() : null; - if(eventId?.Contains(Constants.BypassFiltersEventId.ToString()) ?? false) + if (eventId?.Contains(Constants.BypassFiltersEventId.ToString()) ?? false) { return true; } @@ -56,7 +56,7 @@ namespace Bit.Core.Utilities .Enrich.FromLogContext() .Filter.ByIncludingOnly(inclusionPredicate); - if(CoreHelpers.SettingHasValue(globalSettings?.DocumentDb.Uri) && + if (CoreHelpers.SettingHasValue(globalSettings?.DocumentDb.Uri) && CoreHelpers.SettingHasValue(globalSettings?.DocumentDb.Key)) { config.WriteTo.AzureDocumentDB(new Uri(globalSettings.DocumentDb.Uri), @@ -64,15 +64,15 @@ namespace Bit.Core.Utilities .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName); } - else if(CoreHelpers.SettingHasValue(globalSettings?.Sentry.Dsn)) + else if (CoreHelpers.SettingHasValue(globalSettings?.Sentry.Dsn)) { config.WriteTo.Sentry(globalSettings.Sentry.Dsn) .Enrich.FromLogContext() .Enrich.WithProperty("Project", globalSettings.ProjectName); } - else if(CoreHelpers.SettingHasValue(globalSettings.LogDirectory)) + else if (CoreHelpers.SettingHasValue(globalSettings.LogDirectory)) { - if(globalSettings.LogRollBySizeLimit.HasValue) + if (globalSettings.LogRollBySizeLimit.HasValue) { config.WriteTo.File($"{globalSettings.LogDirectory}/{globalSettings.ProjectName}/log.txt", rollOnFileSizeLimit: true, fileSizeLimitBytes: globalSettings.LogRollBySizeLimit); diff --git a/src/Core/Utilities/LoggingExceptionHandlerFilterAttribute.cs b/src/Core/Utilities/LoggingExceptionHandlerFilterAttribute.cs index 04e2fc2561..8df51b1e5f 100644 --- a/src/Core/Utilities/LoggingExceptionHandlerFilterAttribute.cs +++ b/src/Core/Utilities/LoggingExceptionHandlerFilterAttribute.cs @@ -9,7 +9,7 @@ namespace Bit.Core.Utilities public override void OnException(ExceptionContext context) { var exception = context.Exception; - if(exception == null) + if (exception == null) { // Should never happen. return; diff --git a/src/Core/Utilities/SelfHostedAttribute.cs b/src/Core/Utilities/SelfHostedAttribute.cs index 254ed71f0f..3c6ff74436 100644 --- a/src/Core/Utilities/SelfHostedAttribute.cs +++ b/src/Core/Utilities/SelfHostedAttribute.cs @@ -12,11 +12,11 @@ namespace Bit.Core.Utilities public override void OnActionExecuting(ActionExecutingContext context) { var globalSettings = context.HttpContext.RequestServices.GetRequiredService(); - if(SelfHostedOnly && !globalSettings.SelfHosted) + if (SelfHostedOnly && !globalSettings.SelfHosted) { throw new BadRequestException("Only allowed when self hosted."); } - else if(NotSelfHostedOnly && globalSettings.SelfHosted) + else if (NotSelfHostedOnly && globalSettings.SelfHosted) { throw new BadRequestException("Only allowed when not self hosted."); } diff --git a/src/Core/Utilities/ServiceCollectionExtensions.cs b/src/Core/Utilities/ServiceCollectionExtensions.cs index 014cf2338a..98a20daeeb 100644 --- a/src/Core/Utilities/ServiceCollectionExtensions.cs +++ b/src/Core/Utilities/ServiceCollectionExtensions.cs @@ -45,12 +45,12 @@ namespace Bit.Core.Utilities var usePostgreSql = CoreHelpers.SettingHasValue(globalSettings.PostgreSql?.ConnectionString); var useEf = usePostgreSql; - if(useEf) + if (useEf) { services.AddAutoMapper(typeof(EntityFrameworkRepos.UserRepository)); services.AddDbContext(options => { - if(usePostgreSql) + if (usePostgreSql) { options.UseNpgsql(globalSettings.PostgreSql.ConnectionString); } @@ -78,9 +78,9 @@ namespace Bit.Core.Utilities services.AddSingleton(); } - if(globalSettings.SelfHosted) + if (globalSettings.SelfHosted) { - if(useEf) + if (useEf) { // TODO } @@ -118,7 +118,7 @@ namespace Bit.Core.Utilities services.AddSingleton(); services.AddSingleton(); - if(CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && + if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName)) { services.AddSingleton(); @@ -128,11 +128,11 @@ namespace Bit.Core.Utilities services.AddSingleton(); } - if(CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret)) + if (CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret)) { services.AddSingleton(); } - else if(CoreHelpers.SettingHasValue(globalSettings.Mail?.Smtp?.Host)) + else if (CoreHelpers.SettingHasValue(globalSettings.Mail?.Smtp?.Host)) { services.AddSingleton(); } @@ -142,14 +142,14 @@ namespace Bit.Core.Utilities } services.AddSingleton(); - if(globalSettings.SelfHosted && + if (globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.PushRelayBaseUri) && globalSettings.Installation?.Id != null && CoreHelpers.SettingHasValue(globalSettings.Installation?.Key)) { services.AddSingleton(); } - else if(!globalSettings.SelfHosted) + else if (!globalSettings.SelfHosted) { services.AddSingleton(); } @@ -158,11 +158,11 @@ namespace Bit.Core.Utilities services.AddSingleton(); } - if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString)) + if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString)) { services.AddSingleton(); } - else if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret)) + else if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret)) { services.AddSingleton(); } @@ -171,11 +171,11 @@ namespace Bit.Core.Utilities services.AddSingleton(); } - if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString)) + if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString)) { services.AddSingleton(); } - else if(globalSettings.SelfHosted) + else if (globalSettings.SelfHosted) { services.AddSingleton(); } @@ -184,11 +184,11 @@ namespace Bit.Core.Utilities services.AddSingleton(); } - if(CoreHelpers.SettingHasValue(globalSettings.Attachment.ConnectionString)) + if (CoreHelpers.SettingHasValue(globalSettings.Attachment.ConnectionString)) { services.AddSingleton(); } - else if(CoreHelpers.SettingHasValue(globalSettings.Attachment.BaseDirectory)) + else if (CoreHelpers.SettingHasValue(globalSettings.Attachment.BaseDirectory)) { services.AddSingleton(); } @@ -315,7 +315,7 @@ namespace Bit.Core.Utilities options.SupportedTokens = SupportedTokens.Jwt; }); - if(addAuthorization != null) + if (addAuthorization != null) { services.AddAuthorization(config => { @@ -323,7 +323,7 @@ namespace Bit.Core.Utilities }); } - if(environment.IsDevelopment()) + if (environment.IsDevelopment()) { Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; } @@ -349,11 +349,11 @@ namespace Bit.Core.Utilities .AddInMemoryApiResources(ApiResources.GetApiResources()) .AddClientStoreCache(); - if(env.IsDevelopment()) + if (env.IsDevelopment()) { identityServerBuilder.AddDeveloperSigningCredential(false); } - else if(globalSettings.SelfHosted && + else if (globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.IdentityServer.CertificatePassword) && File.Exists("identity.pfx")) { @@ -361,13 +361,13 @@ namespace Bit.Core.Utilities globalSettings.IdentityServer.CertificatePassword); identityServerBuilder.AddSigningCredential(identityServerCert); } - else if(CoreHelpers.SettingHasValue(globalSettings.IdentityServer.CertificateThumbprint)) + else if (CoreHelpers.SettingHasValue(globalSettings.IdentityServer.CertificateThumbprint)) { var identityServerCert = CoreHelpers.GetCertificate( globalSettings.IdentityServer.CertificateThumbprint); identityServerBuilder.AddSigningCredential(identityServerCert); } - else if(!globalSettings.SelfHosted && + else if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString) && CoreHelpers.SettingHasValue(globalSettings.IdentityServer.CertificatePassword)) { @@ -393,27 +393,27 @@ namespace Bit.Core.Utilities public static void AddCustomDataProtectionServices( this IServiceCollection services, IWebHostEnvironment env, GlobalSettings globalSettings) { - if(env.IsDevelopment()) + if (env.IsDevelopment()) { return; } - if(globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.DataProtection.Directory)) + if (globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.DataProtection.Directory)) { services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(globalSettings.DataProtection.Directory)); } - if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString)) + if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString)) { var storageAccount = CloudStorageAccount.Parse(globalSettings.Storage.ConnectionString); X509Certificate2 dataProtectionCert = null; - if(CoreHelpers.SettingHasValue(globalSettings.DataProtection.CertificateThumbprint)) + if (CoreHelpers.SettingHasValue(globalSettings.DataProtection.CertificateThumbprint)) { dataProtectionCert = CoreHelpers.GetCertificate( globalSettings.DataProtection.CertificateThumbprint); } - else if(CoreHelpers.SettingHasValue(globalSettings.DataProtection.CertificatePassword)) + else if (CoreHelpers.SettingHasValue(globalSettings.DataProtection.CertificatePassword)) { dataProtectionCert = CoreHelpers.GetBlobCertificateAsync(storageAccount, "certificates", "dataprotection.pfx", globalSettings.DataProtection.CertificatePassword) @@ -439,7 +439,7 @@ namespace Bit.Core.Utilities { string GetHeaderValue(HttpContext httpContext, string header) { - if(httpContext.Request.Headers.ContainsKey(header)) + if (httpContext.Request.Headers.ContainsKey(header)) { return httpContext.Request.Headers[header]; } @@ -449,10 +449,10 @@ namespace Bit.Core.Utilities // Add version information to response headers app.Use(async (httpContext, next) => { - using(LogContext.PushProperty("IPAddress", httpContext.GetIpAddress(globalSettings))) - using(LogContext.PushProperty("UserAgent", GetHeaderValue(httpContext, "user-agent"))) - using(LogContext.PushProperty("DeviceType", GetHeaderValue(httpContext, "device-type"))) - using(LogContext.PushProperty("Origin", GetHeaderValue(httpContext, "origin"))) + using (LogContext.PushProperty("IPAddress", httpContext.GetIpAddress(globalSettings))) + using (LogContext.PushProperty("UserAgent", GetHeaderValue(httpContext, "user-agent"))) + using (LogContext.PushProperty("DeviceType", GetHeaderValue(httpContext, "device-type"))) + using (LogContext.PushProperty("Origin", GetHeaderValue(httpContext, "origin"))) { httpContext.Response.OnStarting((state) => { @@ -470,18 +470,18 @@ namespace Bit.Core.Utilities { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; - if(!string.IsNullOrWhiteSpace(globalSettings.KnownProxies)) + if (!string.IsNullOrWhiteSpace(globalSettings.KnownProxies)) { var proxies = globalSettings.KnownProxies.Split(','); - foreach(var proxy in proxies) + foreach (var proxy in proxies) { - if(System.Net.IPAddress.TryParse(proxy.Trim(), out var ip)) + if (System.Net.IPAddress.TryParse(proxy.Trim(), out var ip)) { options.KnownProxies.Add(ip); } } } - if(options.KnownProxies.Count > 1) + if (options.KnownProxies.Count > 1) { options.ForwardLimit = null; } diff --git a/src/Events/Controllers/CollectController.cs b/src/Events/Controllers/CollectController.cs index 889e3ae1ed..f97c85a90e 100644 --- a/src/Events/Controllers/CollectController.cs +++ b/src/Events/Controllers/CollectController.cs @@ -43,15 +43,15 @@ namespace Bit.Events.Controllers [HttpPost] public async Task Post([FromBody]IEnumerable model) { - if(model == null || !model.Any()) + if (model == null || !model.Any()) { return new BadRequestResult(); } var cipherEvents = new List>(); var ciphersCache = new Dictionary(); - foreach(var eventModel in model) + foreach (var eventModel in model) { - switch(eventModel.Type) + switch (eventModel.Type) { // User events case EventType.User_ClientExportedVault: @@ -66,12 +66,12 @@ namespace Bit.Events.Controllers case EventType.Cipher_ClientToggledHiddenFieldVisible: case EventType.Cipher_ClientToggledPasswordVisible: case EventType.Cipher_ClientViewed: - if(!eventModel.CipherId.HasValue) + if (!eventModel.CipherId.HasValue) { continue; } Cipher cipher = null; - if(ciphersCache.ContainsKey(eventModel.CipherId.Value)) + if (ciphersCache.ContainsKey(eventModel.CipherId.Value)) { cipher = ciphersCache[eventModel.CipherId.Value]; } @@ -80,11 +80,11 @@ namespace Bit.Events.Controllers cipher = await _cipherRepository.GetByIdAsync(eventModel.CipherId.Value, _currentContext.UserId.Value); } - if(cipher == null) + if (cipher == null) { continue; } - if(!ciphersCache.ContainsKey(eventModel.CipherId.Value)) + if (!ciphersCache.ContainsKey(eventModel.CipherId.Value)) { ciphersCache.Add(eventModel.CipherId.Value, cipher); } @@ -94,9 +94,9 @@ namespace Bit.Events.Controllers continue; } } - if(cipherEvents.Any()) + if (cipherEvents.Any()) { - foreach(var eventsBatch in cipherEvents.Batch(50)) + foreach (var eventsBatch in cipherEvents.Batch(50)) { await _eventService.LogCipherEventsAsync(eventsBatch); } diff --git a/src/Events/Program.cs b/src/Events/Program.cs index 91c52af225..cdacd16bf1 100644 --- a/src/Events/Program.cs +++ b/src/Events/Program.cs @@ -19,13 +19,13 @@ namespace Bit.Events logging.AddSerilog(hostingContext, e => { var context = e.Properties["SourceContext"].ToString(); - if(context.Contains("IdentityServer4.Validation.TokenValidator") || + if (context.Contains("IdentityServer4.Validation.TokenValidator") || context.Contains("IdentityServer4.Validation.TokenRequestValidator")) { return e.Level > LogEventLevel.Error; } - if(e.Properties.ContainsKey("RequestPath") && + if (e.Properties.ContainsKey("RequestPath") && !string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) && (context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer"))) { diff --git a/src/Events/Startup.cs b/src/Events/Startup.cs index c4ac34b094..44127a6224 100644 --- a/src/Events/Startup.cs +++ b/src/Events/Startup.cs @@ -51,7 +51,7 @@ namespace Bit.Events // Services var usingServiceBusAppCache = CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName); - if(usingServiceBusAppCache) + if (usingServiceBusAppCache) { services.AddSingleton(); } @@ -60,7 +60,7 @@ namespace Bit.Events services.AddSingleton(); } services.AddScoped(); - if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString)) + if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString)) { services.AddSingleton(); } @@ -75,7 +75,7 @@ namespace Bit.Events config.Filters.Add(new LoggingExceptionHandlerFilterAttribute()); }); - if(usingServiceBusAppCache) + if (usingServiceBusAppCache) { services.AddHostedService(); } @@ -89,7 +89,7 @@ namespace Bit.Events { app.UseSerilog(env, appLifetime, globalSettings); - if(env.IsDevelopment()) + if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } diff --git a/src/EventsProcessor/AzureQueueHostedService.cs b/src/EventsProcessor/AzureQueueHostedService.cs index f672bc39cd..9964e67a25 100644 --- a/src/EventsProcessor/AzureQueueHostedService.cs +++ b/src/EventsProcessor/AzureQueueHostedService.cs @@ -43,7 +43,7 @@ namespace Bit.EventsProcessor public async Task StopAsync(CancellationToken cancellationToken) { - if(_executingTask == null) + if (_executingTask == null) { return; } @@ -59,7 +59,7 @@ namespace Bit.EventsProcessor private async Task ExecuteAsync(CancellationToken cancellationToken) { var storageConnectionString = _configuration["azureStorageConnectionString"]; - if(string.IsNullOrWhiteSpace(storageConnectionString)) + if (string.IsNullOrWhiteSpace(storageConnectionString)) { return; } @@ -68,14 +68,14 @@ namespace Bit.EventsProcessor _eventWriteService = new RepositoryEventWriteService(repo); _queueClient = new QueueClient(storageConnectionString, "event"); - while(!cancellationToken.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { try { var messages = await _queueClient.ReceiveMessagesAsync(32); - if(messages.Value?.Any() ?? false) + if (messages.Value?.Any() ?? false) { - foreach(var message in messages.Value) + foreach (var message in messages.Value) { await ProcessQueueMessageAsync(message.MessageText, cancellationToken); await _queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt); @@ -86,7 +86,7 @@ namespace Bit.EventsProcessor await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); } } - catch(Exception e) + catch (Exception e) { _logger.LogError(e, "Exception occurred: " + e.Message); await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); @@ -98,7 +98,7 @@ namespace Bit.EventsProcessor public async Task ProcessQueueMessageAsync(string message, CancellationToken cancellationToken) { - if(_eventWriteService == null || message == null || message.Length == 0) + if (_eventWriteService == null || message == null || message.Length == 0) { return; } @@ -109,13 +109,13 @@ namespace Bit.EventsProcessor var events = new List(); var token = JToken.Parse(message); - if(token is JArray) + if (token is JArray) { var indexedEntities = token.ToObject>() .SelectMany(e => EventTableEntity.IndexEvent(e)); events.AddRange(indexedEntities); } - else if(token is JObject) + else if (token is JObject) { var eventMessage = token.ToObject(); events.AddRange(EventTableEntity.IndexEvent(eventMessage)); @@ -124,11 +124,11 @@ namespace Bit.EventsProcessor await _eventWriteService.CreateManyAsync(events); _logger.LogInformation("Processed message."); } - catch(JsonReaderException) + catch (JsonReaderException) { _logger.LogError("JsonReaderException: Unable to parse message."); } - catch(JsonSerializationException) + catch (JsonSerializationException) { _logger.LogError("JsonSerializationException: Unable to serialize token."); } diff --git a/src/Icons/Controllers/IconsController.cs b/src/Icons/Controllers/IconsController.cs index d653c08a38..55bfdd96b6 100644 --- a/src/Icons/Controllers/IconsController.cs +++ b/src/Icons/Controllers/IconsController.cs @@ -41,13 +41,13 @@ namespace Bit.Icons.Controllers [HttpGet("{hostname}/icon.png")] public async Task Get(string hostname) { - if(string.IsNullOrWhiteSpace(hostname) || !hostname.Contains(".")) + if (string.IsNullOrWhiteSpace(hostname) || !hostname.Contains(".")) { return new BadRequestResult(); } var url = $"http://{hostname}"; - if(!Uri.TryCreate(url, UriKind.Absolute, out var uri)) + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { return new BadRequestResult(); } @@ -60,10 +60,10 @@ namespace Bit.Icons.Controllers //} var mappedDomain = _domainMappingService.MapDomain(domain); - if(!_iconsSettings.CacheEnabled || !_memoryCache.TryGetValue(mappedDomain, out Icon icon)) + if (!_iconsSettings.CacheEnabled || !_memoryCache.TryGetValue(mappedDomain, out Icon icon)) { var result = await _iconFetchingService.GetIconAsync(domain); - if(result == null) + if (result == null) { _logger.LogWarning("Null result returned for {0}.", domain); icon = null; @@ -74,7 +74,7 @@ namespace Bit.Icons.Controllers } // Only cache not found and smaller images (<= 50kb) - if(_iconsSettings.CacheEnabled && (icon == null || icon.Image.Length <= 50012)) + if (_iconsSettings.CacheEnabled && (icon == null || icon.Image.Length <= 50012)) { _logger.LogInformation("Cache icon for {0}.", domain); _memoryCache.Set(mappedDomain, icon, new MemoryCacheEntryOptions @@ -86,7 +86,7 @@ namespace Bit.Icons.Controllers } } - if(icon == null) + if (icon == null) { return new NotFoundResult(); } diff --git a/src/Icons/Models/DomainName.cs b/src/Icons/Models/DomainName.cs index 0689e1dce2..62aec630f2 100644 --- a/src/Icons/Models/DomainName.cs +++ b/src/Icons/Models/DomainName.cs @@ -67,7 +67,7 @@ namespace Bit.Icons.Models public static bool TryParseBaseDomain(string domainString, out string result) { - if(Regex.IsMatch(domainString, IpRegex)) + if (Regex.IsMatch(domainString, IpRegex)) { result = domainString; return true; @@ -91,7 +91,7 @@ namespace Bit.Icons.Models MatchingRule = null; // If the fqdn is empty, we have a problem already - if(domainString.Trim() == string.Empty) + if (domainString.Trim() == string.Empty) { throw new ArgumentException("The domain cannot be blank"); } @@ -100,7 +100,7 @@ namespace Bit.Icons.Models MatchingRule = FindMatchingTLDRule(domainString); // At this point, no rules match, we have a problem - if(MatchingRule == null) + if (MatchingRule == null) { throw new FormatException("The domain does not have a recognized TLD"); } @@ -110,7 +110,7 @@ namespace Bit.Icons.Models var tldIndex = 0; // First, determine what type of rule we have, and set the TLD accordingly - switch(MatchingRule.Type) + switch (MatchingRule.Type) { case TLDRule.RuleType.Normal: tldIndex = domainString.LastIndexOf("." + MatchingRule.Name); @@ -140,13 +140,13 @@ namespace Bit.Icons.Models // If we have 0 parts left, there is just a tld and no domain or subdomain // If we have 1 part, it's the domain, and there is no subdomain // If we have 2+ parts, the last part is the domain, the other parts (combined) are the subdomain - if(lstRemainingParts.Count > 0) + if (lstRemainingParts.Count > 0) { // Set the domain: SLD = lstRemainingParts[lstRemainingParts.Count - 1]; // Set the subdomain, if there is one to set: - if(lstRemainingParts.Count > 1) + if (lstRemainingParts.Count > 1) { // We strip off the trailing period, too SubDomain = tempSudomainAndDomain.Substring(0, tempSudomainAndDomain.Length - SLD.Length - 1); @@ -169,23 +169,23 @@ namespace Bit.Icons.Models // Our 'matches' collection: var ruleMatches = new List(); - foreach(string domainPart in lstDomainParts) + foreach (string domainPart in lstDomainParts) { // Add on our next domain part: checkAgainst = string.Format("{0}.{1}", domainPart, checkAgainst); // If we end in a period, strip it off: - if(checkAgainst.EndsWith(".")) + if (checkAgainst.EndsWith(".")) { checkAgainst = checkAgainst.Substring(0, checkAgainst.Length - 1); } var rules = Enum.GetValues(typeof(TLDRule.RuleType)).Cast(); - foreach(var rule in rules) + foreach (var rule in rules) { // Try to match rule: TLDRule result; - if(TLDRulesCache.Instance.TLDRuleLists[rule].TryGetValue(checkAgainst, out result)) + if (TLDRulesCache.Instance.TLDRuleLists[rule].TryGetValue(checkAgainst, out result)) { ruleMatches.Add(result); } @@ -210,12 +210,12 @@ namespace Bit.Icons.Models public TLDRule(string RuleInfo) { // Parse the rule and set properties accordingly: - if(RuleInfo.StartsWith("*")) + if (RuleInfo.StartsWith("*")) { Type = RuleType.Wildcard; Name = RuleInfo.Substring(2); } - else if(RuleInfo.StartsWith("!")) + else if (RuleInfo.StartsWith("!")) { Type = RuleType.Exception; Name = RuleInfo.Substring(1); @@ -229,7 +229,7 @@ namespace Bit.Icons.Models public int CompareTo(TLDRule other) { - if(other == null) + if (other == null) { return -1; } @@ -261,11 +261,11 @@ namespace Bit.Icons.Models { get { - if(_uniqueInstance == null) + if (_uniqueInstance == null) { - lock(_syncObj) + lock (_syncObj) { - if(_uniqueInstance == null) + if (_uniqueInstance == null) { _uniqueInstance = new TLDRulesCache(); } @@ -279,7 +279,7 @@ namespace Bit.Icons.Models public static void Reset() { - lock(_syncObj) + lock (_syncObj) { _uniqueInstance = null; } @@ -289,7 +289,7 @@ namespace Bit.Icons.Models { var results = new Dictionary>(); var rules = Enum.GetValues(typeof(TLDRule.RuleType)).Cast(); - foreach(var rule in rules) + foreach (var rule in rules) { results[rule] = new Dictionary(StringComparer.CurrentCultureIgnoreCase); } @@ -301,7 +301,7 @@ namespace Bit.Icons.Models // b.) Blank var rulesStrings = ruleStrings .Where(ruleString => !ruleString.StartsWith("//") && ruleString.Trim().Length != 0); - foreach(var ruleString in rulesStrings) + foreach (var ruleString in rulesStrings) { var result = new TLDRule(ruleString); results[result.Type][result.Name] = result; @@ -318,9 +318,9 @@ namespace Bit.Icons.Models var assembly = typeof(TLDRulesCache).GetTypeInfo().Assembly; var stream = assembly.GetManifestResourceStream("Bit.Icons.Resources.public_suffix_list.dat"); string line; - using(var reader = new StreamReader(stream)) + using (var reader = new StreamReader(stream)) { - while((line = reader.ReadLine()) != null) + while ((line = reader.ReadLine()) != null) { yield return line; } diff --git a/src/Icons/Models/IconResult.cs b/src/Icons/Models/IconResult.cs index 48ed769c5c..9a22b1d67c 100644 --- a/src/Icons/Models/IconResult.cs +++ b/src/Icons/Models/IconResult.cs @@ -7,30 +7,30 @@ namespace Bit.Icons.Models public IconResult(string href, string sizes) { Path = href; - if(!string.IsNullOrWhiteSpace(sizes)) + if (!string.IsNullOrWhiteSpace(sizes)) { var sizeParts = sizes.Split('x'); - if(sizeParts.Length == 2 && int.TryParse(sizeParts[0].Trim(), out var width) && + if (sizeParts.Length == 2 && int.TryParse(sizeParts[0].Trim(), out var width) && int.TryParse(sizeParts[1].Trim(), out var height)) { DefinedWidth = width; DefinedHeight = height; - if(width == height) + if (width == height) { - if(width == 32) + if (width == 32) { Priority = 1; } - else if(width == 64) + else if (width == 64) { Priority = 2; } - else if(width >= 24 && width <= 128) + else if (width >= 24 && width <= 128) { Priority = 3; } - else if(width == 16) + else if (width == 16) { Priority = 4; } @@ -42,7 +42,7 @@ namespace Bit.Icons.Models } } - if(Priority == 0) + if (Priority == 0) { Priority = 200; } diff --git a/src/Icons/Services/DomainMappingService.cs b/src/Icons/Services/DomainMappingService.cs index 8147f91f15..abd969b0fe 100644 --- a/src/Icons/Services/DomainMappingService.cs +++ b/src/Icons/Services/DomainMappingService.cs @@ -15,7 +15,7 @@ namespace Bit.Icons.Services public string MapDomain(string hostname) { - if(_map.ContainsKey(hostname)) + if (_map.ContainsKey(hostname)) { return _map[hostname]; } diff --git a/src/Icons/Services/IconFetchingService.cs b/src/Icons/Services/IconFetchingService.cs index 3edda71e12..60f0edfca0 100644 --- a/src/Icons/Services/IconFetchingService.cs +++ b/src/Icons/Services/IconFetchingService.cs @@ -64,13 +64,13 @@ namespace Bit.Icons.Services public async Task GetIconAsync(string domain) { - if(_ipRegex.IsMatch(domain)) + if (_ipRegex.IsMatch(domain)) { _logger.LogWarning("IP address: {0}.", domain); return null; } - if(!Uri.TryCreate($"https://{domain}", UriKind.Absolute, out var parsedHttpsUri)) + if (!Uri.TryCreate($"https://{domain}", UriKind.Absolute, out var parsedHttpsUri)) { _logger.LogWarning("Bad domain: {0}.", domain); return null; @@ -78,24 +78,24 @@ namespace Bit.Icons.Services var uri = parsedHttpsUri; var response = await GetAndFollowAsync(uri, 2); - if((response == null || !response.IsSuccessStatusCode) && + if ((response == null || !response.IsSuccessStatusCode) && Uri.TryCreate($"http://{parsedHttpsUri.Host}", UriKind.Absolute, out var parsedHttpUri)) { Cleanup(response); uri = parsedHttpUri; response = await GetAndFollowAsync(uri, 2); - if(response == null || !response.IsSuccessStatusCode) + if (response == null || !response.IsSuccessStatusCode) { var dotCount = domain.Count(c => c == '.'); - if(dotCount > 1 && DomainName.TryParseBaseDomain(domain, out var baseDomain) && + if (dotCount > 1 && DomainName.TryParseBaseDomain(domain, out var baseDomain) && Uri.TryCreate($"https://{baseDomain}", UriKind.Absolute, out var parsedBaseUri)) { Cleanup(response); uri = parsedBaseUri; response = await GetAndFollowAsync(uri, 2); } - else if(dotCount < 2 && + else if (dotCount < 2 && Uri.TryCreate($"https://www.{parsedHttpsUri.Host}", UriKind.Absolute, out var parsedWwwUri)) { Cleanup(response); @@ -105,7 +105,7 @@ namespace Bit.Icons.Services } } - if(response?.Content == null || !response.IsSuccessStatusCode) + if (response?.Content == null || !response.IsSuccessStatusCode) { _logger.LogWarning("Couldn't load a website for {0}: {1}.", domain, response?.StatusCode.ToString() ?? "null"); @@ -114,12 +114,12 @@ namespace Bit.Icons.Services } var parser = new HtmlParser(); - using(response) - using(var htmlStream = await response.Content.ReadAsStreamAsync()) - using(var document = await parser.ParseDocumentAsync(htmlStream)) + using (response) + using (var htmlStream = await response.Content.ReadAsStreamAsync()) + using (var document = await parser.ParseDocumentAsync(htmlStream)) { uri = response.RequestMessage.RequestUri; - if(document.DocumentElement == null) + if (document.DocumentElement == null) { _logger.LogWarning("No DocumentElement for {0}.", domain); return null; @@ -127,10 +127,10 @@ namespace Bit.Icons.Services var baseUrl = "/"; var baseUrlNode = document.QuerySelector("head base[href]"); - if(baseUrlNode != null) + if (baseUrlNode != null) { var hrefAttr = baseUrlNode.Attributes["href"]; - if(!string.IsNullOrWhiteSpace(hrefAttr?.Value)) + if (!string.IsNullOrWhiteSpace(hrefAttr?.Value)) { baseUrl = hrefAttr.Value; } @@ -141,33 +141,33 @@ namespace Bit.Icons.Services var icons = new List(); var links = document.QuerySelectorAll("head link[href]"); - if(links != null) + if (links != null) { - foreach(var link in links.Take(200)) + foreach (var link in links.Take(200)) { var hrefAttr = link.Attributes["href"]; - if(string.IsNullOrWhiteSpace(hrefAttr?.Value)) + if (string.IsNullOrWhiteSpace(hrefAttr?.Value)) { continue; } var relAttr = link.Attributes["rel"]; var sizesAttr = link.Attributes["sizes"]; - if(relAttr != null && _iconRels.Contains(relAttr.Value.ToLower())) + if (relAttr != null && _iconRels.Contains(relAttr.Value.ToLower())) { icons.Add(new IconResult(hrefAttr.Value, sizesAttr?.Value)); } - else if(relAttr == null || !_blacklistedRels.Contains(relAttr.Value.ToLower())) + else if (relAttr == null || !_blacklistedRels.Contains(relAttr.Value.ToLower())) { try { var extension = Path.GetExtension(hrefAttr.Value); - if(_iconExtensions.Contains(extension.ToLower())) + if (_iconExtensions.Contains(extension.ToLower())) { icons.Add(new IconResult(hrefAttr.Value, sizesAttr?.Value)); } } - catch(ArgumentException) { } + catch (ArgumentException) { } } sizesAttr = null; @@ -179,29 +179,29 @@ namespace Bit.Icons.Services } var iconResultTasks = new List(); - foreach(var icon in icons.OrderBy(i => i.Priority).Take(10)) + foreach (var icon in icons.OrderBy(i => i.Priority).Take(10)) { Uri iconUri = null; - if(icon.Path.StartsWith("//") && Uri.TryCreate($"{GetScheme(uri)}://{icon.Path.Substring(2)}", + if (icon.Path.StartsWith("//") && Uri.TryCreate($"{GetScheme(uri)}://{icon.Path.Substring(2)}", UriKind.Absolute, out var slashUri)) { iconUri = slashUri; } - else if(Uri.TryCreate(icon.Path, UriKind.Relative, out var relUri)) + else if (Uri.TryCreate(icon.Path, UriKind.Relative, out var relUri)) { iconUri = ResolveUri($"{GetScheme(uri)}://{uri.Host}", baseUrl, relUri.OriginalString); } - else if(Uri.TryCreate(icon.Path, UriKind.Absolute, out var absUri)) + else if (Uri.TryCreate(icon.Path, UriKind.Absolute, out var absUri)) { iconUri = absUri; } - if(iconUri != null) + if (iconUri != null) { var task = GetIconAsync(iconUri).ContinueWith(async (r) => { var result = await r; - if(result != null) + if (result != null) { icon.Path = iconUri.ToString(); icon.Icon = result.Icon; @@ -212,11 +212,11 @@ namespace Bit.Icons.Services } await Task.WhenAll(iconResultTasks); - if(!icons.Any(i => i.Icon != null)) + if (!icons.Any(i => i.Icon != null)) { var faviconUri = ResolveUri($"{GetScheme(uri)}://{uri.Host}", "favicon.ico"); var result = await GetIconAsync(faviconUri); - if(result != null) + if (result != null) { icons.Add(result); } @@ -233,9 +233,9 @@ namespace Bit.Icons.Services private async Task GetIconAsync(Uri uri) { - using(var response = await GetAndFollowAsync(uri, 2)) + using (var response = await GetAndFollowAsync(uri, 2)) { - if(response?.Content?.Headers == null || !response.IsSuccessStatusCode) + if (response?.Content?.Headers == null || !response.IsSuccessStatusCode) { response?.Content?.Dispose(); return null; @@ -244,17 +244,17 @@ namespace Bit.Icons.Services var format = response.Content.Headers?.ContentType?.MediaType; var bytes = await response.Content.ReadAsByteArrayAsync(); response.Content.Dispose(); - if(format == null || !_allowedMediaTypes.Contains(format)) + if (format == null || !_allowedMediaTypes.Contains(format)) { - if(HeaderMatch(bytes, _icoHeader)) + if (HeaderMatch(bytes, _icoHeader)) { format = _icoMediaType; } - else if(HeaderMatch(bytes, _pngHeader) || HeaderMatch(bytes, _webpHeader)) + else if (HeaderMatch(bytes, _pngHeader) || HeaderMatch(bytes, _webpHeader)) { format = _pngMediaType; } - else if(HeaderMatch(bytes, _jpegHeader)) + else if (HeaderMatch(bytes, _jpegHeader)) { format = _jpegMediaType; } @@ -271,7 +271,7 @@ namespace Bit.Icons.Services private async Task GetAndFollowAsync(Uri uri, int maxRedirectCount) { var response = await GetAsync(uri); - if(response == null) + if (response == null) { return null; } @@ -280,7 +280,7 @@ namespace Bit.Icons.Services private async Task GetAsync(Uri uri) { - using(var message = new HttpRequestMessage()) + using (var message = new HttpRequestMessage()) { message.RequestUri = uri; message.Method = HttpMethod.Get; @@ -309,12 +309,12 @@ namespace Bit.Icons.Services private async Task FollowRedirectsAsync(HttpResponseMessage response, int maxFollowCount, int followCount = 0) { - if(response == null || response.IsSuccessStatusCode || followCount > maxFollowCount) + if (response == null || response.IsSuccessStatusCode || followCount > maxFollowCount) { return response; } - if(!(response.StatusCode == HttpStatusCode.Redirect || + if (!(response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.RedirectKeepVerb || response.StatusCode == HttpStatusCode.SeeOther) || @@ -325,11 +325,11 @@ namespace Bit.Icons.Services } Uri location = null; - if(response.Headers.Location.IsAbsoluteUri) + if (response.Headers.Location.IsAbsoluteUri) { - if(response.Headers.Location.Scheme != "http" && response.Headers.Location.Scheme != "https") + if (response.Headers.Location.Scheme != "http" && response.Headers.Location.Scheme != "https") { - if(Uri.TryCreate($"https://{response.Headers.Location.OriginalString}", + if (Uri.TryCreate($"https://{response.Headers.Location.OriginalString}", UriKind.Absolute, out var newUri)) { location = newUri; @@ -349,13 +349,13 @@ namespace Bit.Icons.Services Cleanup(response); var newResponse = await GetAsync(location); - if(newResponse != null) + if (newResponse != null) { followCount++; var redirectedResponse = await FollowRedirectsAsync(newResponse, maxFollowCount, followCount); - if(redirectedResponse != null) + if (redirectedResponse != null) { - if(redirectedResponse != newResponse) + if (redirectedResponse != newResponse) { Cleanup(newResponse); } @@ -374,9 +374,9 @@ namespace Bit.Icons.Services private Uri ResolveUri(string baseUrl, params string[] paths) { var url = baseUrl; - foreach(var path in paths) + foreach (var path in paths) { - if(Uri.TryCreate(new Uri(url), path, out var r)) + if (Uri.TryCreate(new Uri(url), path, out var r)) { url = r.ToString(); } diff --git a/src/Icons/Startup.cs b/src/Icons/Startup.cs index 8a50b7c44e..fed262e148 100644 --- a/src/Icons/Startup.cs +++ b/src/Icons/Startup.cs @@ -56,7 +56,7 @@ namespace Bit.Icons { app.UseSerilog(env, appLifetime, globalSettings); - if(env.IsDevelopment()) + if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } diff --git a/src/Identity/Program.cs b/src/Identity/Program.cs index 626fd87cc1..82e51e858b 100644 --- a/src/Identity/Program.cs +++ b/src/Identity/Program.cs @@ -19,13 +19,13 @@ namespace Bit.Identity logging.AddSerilog(hostingContext, e => { var context = e.Properties["SourceContext"].ToString(); - if(context.Contains(typeof(IpRateLimitMiddleware).FullName) && + if (context.Contains(typeof(IpRateLimitMiddleware).FullName) && e.Level == LogEventLevel.Information) { return true; } - if(context.Contains("IdentityServer4.Validation.TokenValidator") || + if (context.Contains("IdentityServer4.Validation.TokenValidator") || context.Contains("IdentityServer4.Validation.TokenRequestValidator")) { return e.Level > LogEventLevel.Error; diff --git a/src/Identity/Startup.cs b/src/Identity/Startup.cs index b2b4612db0..0603cd4bb4 100644 --- a/src/Identity/Startup.cs +++ b/src/Identity/Startup.cs @@ -31,7 +31,7 @@ namespace Bit.Identity // Settings var globalSettings = services.AddGlobalSettingsServices(Configuration); - if(!globalSettings.SelfHosted) + if (!globalSettings.SelfHosted) { services.Configure(Configuration.GetSection("IpRateLimitOptions")); services.Configure(Configuration.GetSection("IpRateLimitPolicies")); @@ -49,7 +49,7 @@ namespace Bit.Identity // Caching services.AddMemoryCache(); - if(!globalSettings.SelfHosted) + if (!globalSettings.SelfHosted) { // Rate limiting services.AddSingleton(); @@ -66,7 +66,7 @@ namespace Bit.Identity services.AddBaseServices(); services.AddDefaultServices(globalSettings); - if(CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && + if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) && CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName)) { services.AddHostedService(); @@ -85,7 +85,7 @@ namespace Bit.Identity // Default Middleware app.UseDefaultMiddleware(env, globalSettings); - if(!globalSettings.SelfHosted) + if (!globalSettings.SelfHosted) { // Rate limiting app.UseMiddleware(); diff --git a/src/Notifications/AzureQueueHostedService.cs b/src/Notifications/AzureQueueHostedService.cs index d757f20480..06f21905ba 100644 --- a/src/Notifications/AzureQueueHostedService.cs +++ b/src/Notifications/AzureQueueHostedService.cs @@ -39,7 +39,7 @@ namespace Bit.Notifications public async Task StopAsync(CancellationToken cancellationToken) { - if(_executingTask == null) + if (_executingTask == null) { return; } @@ -55,14 +55,14 @@ namespace Bit.Notifications private async Task ExecuteAsync(CancellationToken cancellationToken) { _queueClient = new QueueClient(_globalSettings.Notifications.ConnectionString, "notifications"); - while(!cancellationToken.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { try { var messages = await _queueClient.ReceiveMessagesAsync(32); - if(messages.Value?.Any() ?? false) + if (messages.Value?.Any() ?? false) { - foreach(var message in messages.Value) + foreach (var message in messages.Value) { try { @@ -70,11 +70,11 @@ namespace Bit.Notifications message.MessageText, _hubContext, cancellationToken); await _queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt); } - catch(Exception e) + catch (Exception e) { _logger.LogError("Error processing dequeued message: " + $"{message.MessageId} x{message.DequeueCount}. {e.Message}", e); - if(message.DequeueCount > 2) + if (message.DequeueCount > 2) { await _queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt); } @@ -86,7 +86,7 @@ namespace Bit.Notifications await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); } } - catch(Exception e) + catch (Exception e) { _logger.LogError("Error processing messages.", e); } diff --git a/src/Notifications/Controllers/SendController.cs b/src/Notifications/Controllers/SendController.cs index c49ef5fce6..f8e92ff770 100644 --- a/src/Notifications/Controllers/SendController.cs +++ b/src/Notifications/Controllers/SendController.cs @@ -31,10 +31,10 @@ namespace Bit.Notifications [SelfHosted(SelfHostedOnly = true)] public async Task PostSend() { - using(var reader = new StreamReader(Request.Body, Encoding.UTF8)) + using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) { var notificationJson = await reader.ReadToEndAsync(); - if(!string.IsNullOrWhiteSpace(notificationJson)) + if (!string.IsNullOrWhiteSpace(notificationJson)) { await HubHelpers.SendNotificationToHubAsync(notificationJson, _hubContext); } diff --git a/src/Notifications/HeartbeatHostedService.cs b/src/Notifications/HeartbeatHostedService.cs index c90394aa71..357fca5846 100644 --- a/src/Notifications/HeartbeatHostedService.cs +++ b/src/Notifications/HeartbeatHostedService.cs @@ -36,7 +36,7 @@ namespace Bit.Notifications public async Task StopAsync(CancellationToken cancellationToken) { - if(_executingTask == null) + if (_executingTask == null) { return; } @@ -51,7 +51,7 @@ namespace Bit.Notifications private async Task ExecuteAsync(CancellationToken cancellationToken) { - while(!cancellationToken.IsCancellationRequested) + while (!cancellationToken.IsCancellationRequested) { await _hubContext.Clients.All.SendAsync("Heartbeat"); await Task.Delay(120000); diff --git a/src/Notifications/HubHelpers.cs b/src/Notifications/HubHelpers.cs index f8900f28e1..7f907fde1e 100644 --- a/src/Notifications/HubHelpers.cs +++ b/src/Notifications/HubHelpers.cs @@ -13,7 +13,7 @@ namespace Bit.Notifications IHubContext hubContext, CancellationToken cancellationToken = default(CancellationToken)) { var notification = JsonConvert.DeserializeObject>(notificationJson); - switch(notification.Type) + switch (notification.Type) { case PushType.SyncCipherUpdate: case PushType.SyncCipherCreate: @@ -22,12 +22,12 @@ namespace Bit.Notifications var cipherNotification = JsonConvert.DeserializeObject>( notificationJson); - if(cipherNotification.Payload.UserId.HasValue) + if (cipherNotification.Payload.UserId.HasValue) { await hubContext.Clients.User(cipherNotification.Payload.UserId.ToString()) .SendAsync("ReceiveMessage", cipherNotification, cancellationToken); } - else if(cipherNotification.Payload.OrganizationId.HasValue) + else if (cipherNotification.Payload.OrganizationId.HasValue) { await hubContext.Clients.Group( $"Organization_{cipherNotification.Payload.OrganizationId}") diff --git a/src/Notifications/NotificationsHub.cs b/src/Notifications/NotificationsHub.cs index 0d14d08ffe..9822436c99 100644 --- a/src/Notifications/NotificationsHub.cs +++ b/src/Notifications/NotificationsHub.cs @@ -21,9 +21,9 @@ namespace Bit.Notifications { var currentContext = new CurrentContext(); currentContext.Build(Context.User, _globalSettings); - if(currentContext.Organizations != null) + if (currentContext.Organizations != null) { - foreach(var org in currentContext.Organizations) + foreach (var org in currentContext.Organizations) { await Groups.AddToGroupAsync(Context.ConnectionId, $"Organization_{org.Id}"); } @@ -36,9 +36,9 @@ namespace Bit.Notifications { var currentContext = new CurrentContext(); currentContext.Build(Context.User, _globalSettings); - if(currentContext.Organizations != null) + if (currentContext.Organizations != null) { - foreach(var org in currentContext.Organizations) + foreach (var org in currentContext.Organizations) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"Organization_{org.Id}"); } diff --git a/src/Notifications/Program.cs b/src/Notifications/Program.cs index a5780e101a..38b6ec1231 100644 --- a/src/Notifications/Program.cs +++ b/src/Notifications/Program.cs @@ -18,25 +18,25 @@ namespace Bit.Notifications logging.AddSerilog(hostingContext, e => { var context = e.Properties["SourceContext"].ToString(); - if(context.Contains("IdentityServer4.Validation.TokenValidator") || + if (context.Contains("IdentityServer4.Validation.TokenValidator") || context.Contains("IdentityServer4.Validation.TokenRequestValidator")) { return e.Level > LogEventLevel.Error; } - if(e.Level == LogEventLevel.Error && + if (e.Level == LogEventLevel.Error && e.MessageTemplate.Text == "Failed connection handshake.") { return false; } - if(e.Level == LogEventLevel.Error && + if (e.Level == LogEventLevel.Error && e.MessageTemplate.Text.StartsWith("Failed writing message.")) { return false; } - if(e.Level == LogEventLevel.Warning && + if (e.Level == LogEventLevel.Warning && e.MessageTemplate.Text.StartsWith("Heartbeat took longer")) { return false; diff --git a/src/Notifications/Startup.cs b/src/Notifications/Startup.cs index e38602500f..ada77819d4 100644 --- a/src/Notifications/Startup.cs +++ b/src/Notifications/Startup.cs @@ -57,7 +57,7 @@ namespace Bit.Notifications MessagePack.Resolvers.ContractlessStandardResolver.Instance }; }); - if(CoreHelpers.SettingHasValue(globalSettings.Notifications?.RedisConnectionString)) + if (CoreHelpers.SettingHasValue(globalSettings.Notifications?.RedisConnectionString)) { signalRServerBuilder.AddStackExchangeRedis(globalSettings.Notifications.RedisConnectionString, options => @@ -73,12 +73,12 @@ namespace Bit.Notifications services.AddMvc(); services.AddHostedService(); - if(!globalSettings.SelfHosted) + if (!globalSettings.SelfHosted) { // Hosted Services Jobs.JobsHostedService.AddJobsServices(services); services.AddHostedService(); - if(CoreHelpers.SettingHasValue(globalSettings.Notifications?.ConnectionString)) + if (CoreHelpers.SettingHasValue(globalSettings.Notifications?.ConnectionString)) { services.AddHostedService(); } @@ -94,7 +94,7 @@ namespace Bit.Notifications IdentityModelEventSource.ShowPII = true; app.UseSerilog(env, appLifetime, globalSettings); - if(env.IsDevelopment()) + if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } diff --git a/util/Migrator/DbMigrator.cs b/util/Migrator/DbMigrator.cs index 3067cd1d74..29dd1b813f 100644 --- a/util/Migrator/DbMigrator.cs +++ b/util/Migrator/DbMigrator.cs @@ -27,12 +27,12 @@ namespace Bit.Migrator public bool MigrateMsSqlDatabase(bool enableLogging = true, CancellationToken cancellationToken = default(CancellationToken)) { - if(enableLogging && _logger != null) + if (enableLogging && _logger != null) { _logger.LogInformation(Constants.BypassFiltersEventId, "Migrating database."); } - using(var connection = new SqlConnection(_masterConnectionString)) + using (var connection = new SqlConnection(_masterConnectionString)) { var command = new SqlCommand( "IF ((SELECT COUNT(1) FROM sys.databases WHERE [name] = 'vault') = 0) " + @@ -47,7 +47,7 @@ namespace Bit.Migrator } cancellationToken.ThrowIfCancellationRequested(); - using(var connection = new SqlConnection(_connectionString)) + using (var connection = new SqlConnection(_connectionString)) { // Rename old migration scripts to new namespace. var command = new SqlCommand( @@ -67,9 +67,9 @@ namespace Bit.Migrator .WithTransaction() .WithExecutionTimeout(new TimeSpan(0, 5, 0)); - if(enableLogging) + if (enableLogging) { - if(_logger != null) + if (_logger != null) { builder.LogTo(new DbUpLogger(_logger)); } @@ -82,9 +82,9 @@ namespace Bit.Migrator var upgrader = builder.Build(); var result = upgrader.PerformUpgrade(); - if(enableLogging && _logger != null) + if (enableLogging && _logger != null) { - if(result.Successful) + if (result.Successful) { _logger.LogInformation(Constants.BypassFiltersEventId, "Migration successful."); } diff --git a/util/Server/Program.cs b/util/Server/Program.cs index c9367db1a4..2dc558861d 100644 --- a/util/Server/Program.cs +++ b/util/Server/Program.cs @@ -23,13 +23,13 @@ namespace Bit.Server .ConfigureKestrel((context, options) => { }); var contentRoot = config.GetValue("contentRoot"); - if(string.IsNullOrWhiteSpace(contentRoot)) + if (string.IsNullOrWhiteSpace(contentRoot)) { builder.UseContentRoot(contentRoot); } var webRoot = config.GetValue("webRoot"); - if(string.IsNullOrWhiteSpace(webRoot)) + if (string.IsNullOrWhiteSpace(webRoot)) { builder.UseWebRoot(webRoot); } diff --git a/util/Server/Startup.cs b/util/Server/Startup.cs index 7ece2d18f4..467dfd620f 100644 --- a/util/Server/Startup.cs +++ b/util/Server/Startup.cs @@ -33,7 +33,7 @@ namespace Bit.Server IApplicationBuilder app, IConfiguration configuration) { - if(configuration.GetValue("serveUnknown") ?? false) + if (configuration.GetValue("serveUnknown") ?? false) { app.UseStaticFiles(new StaticFileOptions { @@ -47,7 +47,7 @@ namespace Bit.Server async context => await context.Response.WriteAsync(System.DateTime.UtcNow.ToString())); }); } - else if(configuration.GetValue("webVault") ?? false) + else if (configuration.GetValue("webVault") ?? false) { var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); @@ -57,18 +57,18 @@ namespace Bit.Server { OnPrepareResponse = ctx => { - if(!ctx.Context.Request.Path.HasValue || + if (!ctx.Context.Request.Path.HasValue || ctx.Context.Response.Headers.ContainsKey("Cache-Control")) { return; } var path = ctx.Context.Request.Path.Value; - if(_longCachedPaths.Any(ext => path.StartsWith(ext))) + if (_longCachedPaths.Any(ext => path.StartsWith(ext))) { // 14 days ctx.Context.Response.Headers.Append("Cache-Control", "max-age=1209600"); } - if(_mediumCachedPaths.Any(ext => path.StartsWith(ext))) + if (_mediumCachedPaths.Any(ext => path.StartsWith(ext))) { // 7 days ctx.Context.Response.Headers.Append("Cache-Control", "max-age=604800"); diff --git a/util/Setup/AppIdBuilder.cs b/util/Setup/AppIdBuilder.cs index 0b92666a12..b5392cb1a7 100644 --- a/util/Setup/AppIdBuilder.cs +++ b/util/Setup/AppIdBuilder.cs @@ -22,7 +22,7 @@ namespace Bit.Setup Helpers.WriteLine(_context, "Building FIDO U2F app id."); Directory.CreateDirectory("/bitwarden/web/"); var template = Helpers.ReadTemplate("AppId"); - using(var sw = File.CreateText("/bitwarden/web/app-id.json")) + using (var sw = File.CreateText("/bitwarden/web/app-id.json")) { sw.Write(template(model)); } diff --git a/util/Setup/CertBuilder.cs b/util/Setup/CertBuilder.cs index fbf4aa6562..b5f07e81c4 100644 --- a/util/Setup/CertBuilder.cs +++ b/util/Setup/CertBuilder.cs @@ -14,7 +14,7 @@ namespace Bit.Setup public void BuildForInstall() { - if(_context.Stub) + if (_context.Stub) { _context.Config.Ssl = true; _context.Install.Trusted = true; @@ -26,17 +26,17 @@ namespace Bit.Setup _context.Config.Ssl = _context.Config.SslManagedLetsEncrypt; - if(!_context.Config.Ssl) + if (!_context.Config.Ssl) { _context.Config.Ssl = Helpers.ReadQuestion("Do you have a SSL certificate to use?"); - if(_context.Config.Ssl) + if (_context.Config.Ssl) { Directory.CreateDirectory($"/bitwarden/ssl/{_context.Install.Domain}/"); var message = "Make sure 'certificate.crt' and 'private.key' are provided in the \n" + "appropriate directory before running 'start' (see docs for info)."; Helpers.ShowBanner(_context, "NOTE", message); } - else if(Helpers.ReadQuestion("Do you want to generate a self-signed SSL certificate?")) + else if (Helpers.ReadQuestion("Do you want to generate a self-signed SSL certificate?")) { Directory.CreateDirectory($"/bitwarden/ssl/self/{_context.Install.Domain}/"); Helpers.WriteLine(_context, "Generating self signed SSL certificate."); @@ -52,7 +52,7 @@ namespace Bit.Setup } } - if(_context.Config.SslManagedLetsEncrypt) + if (_context.Config.SslManagedLetsEncrypt) { _context.Install.Trusted = true; _context.Install.DiffieHellman = true; @@ -60,7 +60,7 @@ namespace Bit.Setup Helpers.Exec($"openssl dhparam -out " + $"/bitwarden/letsencrypt/live/{_context.Install.Domain}/dhparam.pem 2048"); } - else if(_context.Config.Ssl && !_context.Install.SelfSignedCert) + else if (_context.Config.Ssl && !_context.Install.SelfSignedCert) { _context.Install.Trusted = Helpers.ReadQuestion("Is this a trusted SSL certificate " + "(requires ca.crt, see docs)?"); @@ -76,14 +76,14 @@ namespace Bit.Setup Helpers.WriteLine(_context); - if(!_context.Config.Ssl) + if (!_context.Config.Ssl) { var message = "You are not using a SSL certificate. Bitwarden requires HTTPS to operate. \n" + "You must front your installation with a HTTPS proxy or the web vault (and \n" + "other Bitwarden apps) will not work properly."; Helpers.ShowBanner(_context, "WARNING", message, ConsoleColor.Yellow); } - else if(_context.Config.Ssl && !_context.Install.Trusted) + else if (_context.Config.Ssl && !_context.Install.Trusted) { var message = "You are using an untrusted SSL certificate. This certificate will not be \n" + "trusted by Bitwarden client applications. You must add this certificate to \n" + diff --git a/util/Setup/Configuration.cs b/util/Setup/Configuration.cs index 52b7d5feb4..d99bf25231 100644 --- a/util/Setup/Configuration.cs +++ b/util/Setup/Configuration.cs @@ -92,7 +92,7 @@ namespace Bit.Setup { get { - if(Uri.TryCreate(Url, UriKind.Absolute, out var uri)) + if (Uri.TryCreate(Url, UriKind.Absolute, out var uri)) { return uri.Host; } diff --git a/util/Setup/Context.cs b/util/Setup/Context.cs index 1b594c07dd..0f6c7b707e 100644 --- a/util/Setup/Context.cs +++ b/util/Setup/Context.cs @@ -28,13 +28,13 @@ namespace Bit.Setup public void LoadConfiguration() { - if(!File.Exists(ConfigPath)) + if (!File.Exists(ConfigPath)) { Helpers.WriteLine(this, "No existing `config.yml` detected. Let's generate one."); // Looks like updating from older version. Try to create config file. var url = Helpers.GetValueFromEnvFile("global", "globalSettings__baseServiceUri__vault"); - if(!Uri.TryCreate(url, UriKind.Absolute, out var uri)) + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { Helpers.WriteLine(this, "Unable to determine existing installation url."); return; @@ -45,36 +45,36 @@ namespace Bit.Setup Config.PushNotifications = push != "REPLACE"; var composeFile = "/bitwarden/docker/docker-compose.yml"; - if(File.Exists(composeFile)) + if (File.Exists(composeFile)) { var fileLines = File.ReadAllLines(composeFile); - foreach(var line in fileLines) + foreach (var line in fileLines) { - if(!line.StartsWith("# Parameter:")) + if (!line.StartsWith("# Parameter:")) { continue; } var paramParts = line.Split("="); - if(paramParts.Length < 2) + if (paramParts.Length < 2) { continue; } - if(paramParts[0] == "# Parameter:MssqlDataDockerVolume" && + if (paramParts[0] == "# Parameter:MssqlDataDockerVolume" && bool.TryParse(paramParts[1], out var mssqlDataDockerVolume)) { Config.DatabaseDockerVolume = mssqlDataDockerVolume; continue; } - if(paramParts[0] == "# Parameter:HttpPort" && int.TryParse(paramParts[1], out var httpPort)) + if (paramParts[0] == "# Parameter:HttpPort" && int.TryParse(paramParts[1], out var httpPort)) { Config.HttpPort = httpPort == 0 ? null : httpPort.ToString(); continue; } - if(paramParts[0] == "# Parameter:HttpsPort" && int.TryParse(paramParts[1], out var httpsPort)) + if (paramParts[0] == "# Parameter:HttpsPort" && int.TryParse(paramParts[1], out var httpsPort)) { Config.HttpsPort = httpsPort == 0 ? null : httpsPort.ToString(); continue; @@ -83,7 +83,7 @@ namespace Bit.Setup } var nginxFile = "/bitwarden/nginx/default.conf"; - if(File.Exists(nginxFile)) + if (File.Exists(nginxFile)) { var confContent = File.ReadAllText(nginxFile); var selfSigned = confContent.Contains("/etc/ssl/self/"); @@ -91,20 +91,20 @@ namespace Bit.Setup Config.SslManagedLetsEncrypt = !selfSigned && confContent.Contains("/etc/letsencrypt/live/"); var diffieHellman = confContent.Contains("/dhparam.pem;"); var trusted = confContent.Contains("ssl_trusted_certificate "); - if(Config.SslManagedLetsEncrypt) + if (Config.SslManagedLetsEncrypt) { Config.Ssl = true; } - else if(Config.Ssl) + else if (Config.Ssl) { var sslPath = selfSigned ? $"/etc/ssl/self/{Config.Domain}" : $"/etc/ssl/{Config.Domain}"; Config.SslCertificatePath = string.Concat(sslPath, "/", "certificate.crt"); Config.SslKeyPath = string.Concat(sslPath, "/", "private.key"); - if(trusted) + if (trusted) { Config.SslCaPath = string.Concat(sslPath, "/", "ca.crt"); } - if(diffieHellman) + if (diffieHellman) { Config.SslDiffieHellmanPath = string.Concat(sslPath, "/", "dhparam.pem"); } @@ -123,7 +123,7 @@ namespace Bit.Setup public void SaveConfiguration() { - if(Config == null) + if (Config == null) { throw new Exception("Config is null."); } @@ -134,7 +134,7 @@ namespace Bit.Setup .Build(); var yaml = serializer.Serialize(Config); Directory.CreateDirectory("/bitwarden/"); - using(var sw = File.CreateText(ConfigPath)) + using (var sw = File.CreateText(ConfigPath)) { sw.Write(yaml); } diff --git a/util/Setup/DockerComposeBuilder.cs b/util/Setup/DockerComposeBuilder.cs index bfb98bbee4..64afc8224f 100644 --- a/util/Setup/DockerComposeBuilder.cs +++ b/util/Setup/DockerComposeBuilder.cs @@ -27,7 +27,7 @@ namespace Bit.Setup { Directory.CreateDirectory("/bitwarden/docker/"); Helpers.WriteLine(_context, "Building docker-compose.yml."); - if(!_context.Config.GenerateComposeConfig) + if (!_context.Config.GenerateComposeConfig) { Helpers.WriteLine(_context, "...skipped"); return; @@ -35,7 +35,7 @@ namespace Bit.Setup var template = Helpers.ReadTemplate("DockerCompose"); var model = new TemplateModel(_context); - using(var sw = File.CreateText("/bitwarden/docker/docker-compose.yml")) + using (var sw = File.CreateText("/bitwarden/docker/docker-compose.yml")) { sw.Write(template(model)); } @@ -45,18 +45,18 @@ namespace Bit.Setup { public TemplateModel(Context context) { - if(!string.IsNullOrWhiteSpace(context.Config.ComposeVersion)) + if (!string.IsNullOrWhiteSpace(context.Config.ComposeVersion)) { ComposeVersion = context.Config.ComposeVersion; } MssqlDataDockerVolume = context.Config.DatabaseDockerVolume; HttpPort = context.Config.HttpPort; HttpsPort = context.Config.HttpsPort; - if(!string.IsNullOrWhiteSpace(context.CoreVersion)) + if (!string.IsNullOrWhiteSpace(context.CoreVersion)) { CoreVersion = context.CoreVersion; } - if(!string.IsNullOrWhiteSpace(context.WebVersion)) + if (!string.IsNullOrWhiteSpace(context.WebVersion)) { WebVersion = context.WebVersion; } diff --git a/util/Setup/EnvironmentFileBuilder.cs b/util/Setup/EnvironmentFileBuilder.cs index 8f97f1fbcb..12de57b5f0 100644 --- a/util/Setup/EnvironmentFileBuilder.cs +++ b/util/Setup/EnvironmentFileBuilder.cs @@ -56,7 +56,7 @@ namespace Bit.Setup LoadExistingValues(_globalOverrideValues, "/bitwarden/env/global.override.env"); LoadExistingValues(_mssqlOverrideValues, "/bitwarden/env/mssql.override.env"); - if(_context.Config.PushNotifications && + if (_context.Config.PushNotifications && _globalOverrideValues.ContainsKey("globalSettings__pushRelayBaseUri") && _globalOverrideValues["globalSettings__pushRelayBaseUri"] == "REPLACE") { @@ -115,7 +115,7 @@ namespace Bit.Setup ["adminSettings__admins"] = string.Empty, }; - if(!_context.Config.PushNotifications) + if (!_context.Config.PushNotifications) { _globalOverrideValues.Add("globalSettings__pushRelayBaseUri", "REPLACE"); } @@ -130,32 +130,32 @@ namespace Bit.Setup private void LoadExistingValues(IDictionary _values, string file) { - if(!File.Exists(file)) + if (!File.Exists(file)) { return; } var fileLines = File.ReadAllLines(file); - foreach(var line in fileLines) + foreach (var line in fileLines) { - if(!line.Contains("=")) + if (!line.Contains("=")) { continue; } var value = string.Empty; var lineParts = line.Split("=", 2); - if(lineParts.Length < 1) + if (lineParts.Length < 1) { continue; } - if(lineParts.Length > 1) + if (lineParts.Length > 1) { value = lineParts[1]; } - if(_values.ContainsKey(lineParts[0])) + if (_values.ContainsKey(lineParts[0])) { _values[lineParts[0]] = value; } @@ -172,13 +172,13 @@ namespace Bit.Setup Helpers.WriteLine(_context, "Building docker environment files."); Directory.CreateDirectory("/bitwarden/docker/"); - using(var sw = File.CreateText("/bitwarden/docker/global.env")) + using (var sw = File.CreateText("/bitwarden/docker/global.env")) { sw.Write(template(new TemplateModel(_globalValues))); } Helpers.Exec("chmod 600 /bitwarden/docker/global.env"); - using(var sw = File.CreateText("/bitwarden/docker/mssql.env")) + using (var sw = File.CreateText("/bitwarden/docker/mssql.env")) { sw.Write(template(new TemplateModel(_mssqlValues))); } @@ -186,22 +186,22 @@ namespace Bit.Setup Helpers.WriteLine(_context, "Building docker environment override files."); Directory.CreateDirectory("/bitwarden/env/"); - using(var sw = File.CreateText("/bitwarden/env/global.override.env")) + using (var sw = File.CreateText("/bitwarden/env/global.override.env")) { sw.Write(template(new TemplateModel(_globalOverrideValues))); } Helpers.Exec("chmod 600 /bitwarden/env/global.override.env"); - using(var sw = File.CreateText("/bitwarden/env/mssql.override.env")) + using (var sw = File.CreateText("/bitwarden/env/mssql.override.env")) { sw.Write(template(new TemplateModel(_mssqlOverrideValues))); } Helpers.Exec("chmod 600 /bitwarden/env/mssql.override.env"); // Empty uid env file. Only used on Linux hosts. - if(!File.Exists("/bitwarden/env/uid.env")) + if (!File.Exists("/bitwarden/env/uid.env")) { - using(var sw = File.CreateText("/bitwarden/env/uid.env")) { } + using (var sw = File.CreateText("/bitwarden/env/uid.env")) { } } } diff --git a/util/Setup/Helpers.cs b/util/Setup/Helpers.cs index a7e038cb80..66ec19271b 100644 --- a/util/Setup/Helpers.cs +++ b/util/Setup/Helpers.cs @@ -20,18 +20,18 @@ namespace Bit.Setup // ref https://stackoverflow.com/a/8996788/1090359 with modifications public static string SecureRandomString(int length, string characters) { - if(length < 0) + if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), "length cannot be less than zero."); } - if((characters?.Length ?? 0) == 0) + if ((characters?.Length ?? 0) == 0) { throw new ArgumentOutOfRangeException(nameof(characters), "characters invalid."); } const int byteSize = 0x100; - if(byteSize < characters.Length) + if (byteSize < characters.Length) { throw new ArgumentException( string.Format("{0} may contain no more than {1} characters.", nameof(characters), byteSize), @@ -39,19 +39,19 @@ namespace Bit.Setup } var outOfRangeStart = byteSize - (byteSize % characters.Length); - using(var rng = RandomNumberGenerator.Create()) + using (var rng = RandomNumberGenerator.Create()) { var sb = new StringBuilder(); var buffer = new byte[128]; - while(sb.Length < length) + while (sb.Length < length) { rng.GetBytes(buffer); - for(var i = 0; i < buffer.Length && sb.Length < length; ++i) + for (var i = 0; i < buffer.Length && sb.Length < length; ++i) { // Divide the byte into charSet-sized groups. If the random value falls into the last group and the // last group is too small to choose from the entire allowedCharSet, ignore the value in order to // avoid biasing the result. - if(outOfRangeStart <= buffer[i]) + if (outOfRangeStart <= buffer[i]) { continue; } @@ -67,25 +67,25 @@ namespace Bit.Setup private static string RandomStringCharacters(bool alpha, bool upper, bool lower, bool numeric, bool special) { var characters = string.Empty; - if(alpha) + if (alpha) { - if(upper) + if (upper) { characters += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } - if(lower) + if (lower) { characters += "abcdefghijklmnopqrstuvwxyz"; } } - if(numeric) + if (numeric) { characters += "0123456789"; } - if(special) + if (special) { characters += "!@#$%^*&"; } @@ -95,15 +95,15 @@ namespace Bit.Setup public static string GetValueFromEnvFile(string envFile, string key) { - if(!File.Exists($"/bitwarden/env/{envFile}.override.env")) + if (!File.Exists($"/bitwarden/env/{envFile}.override.env")) { return null; } var lines = File.ReadAllLines($"/bitwarden/env/{envFile}.override.env"); - foreach(var line in lines) + foreach (var line in lines) { - if(line.StartsWith($"{key}=")) + if (line.StartsWith($"{key}=")) { return line.Split(new char[] { '=' }, 2)[1].Trim('"'); } @@ -125,7 +125,7 @@ namespace Bit.Setup } }; - if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var escapedArgs = cmd.Replace("\"", "\\\""); process.StartInfo.FileName = "/bin/bash"; @@ -149,7 +149,7 @@ namespace Bit.Setup Console.Write("(!) "); Console.ResetColor(); Console.Write(prompt); - if(prompt.EndsWith("?")) + if (prompt.EndsWith("?")) { Console.Write(" (y/n)"); } @@ -167,11 +167,11 @@ namespace Bit.Setup public static void ShowBanner(Context context, string title, string message, ConsoleColor? color = null) { - if(!context.PrintToScreen()) + if (!context.PrintToScreen()) { return; } - if(color != null) + if (color != null) { Console.ForegroundColor = color.Value; } @@ -185,12 +185,12 @@ namespace Bit.Setup { var assembly = typeof(Helpers).GetTypeInfo().Assembly; var fullTemplateName = $"Bit.Setup.Templates.{templateName}.hbs"; - if(!assembly.GetManifestResourceNames().Any(f => f == fullTemplateName)) + if (!assembly.GetManifestResourceNames().Any(f => f == fullTemplateName)) { return null; } - using(var s = assembly.GetManifestResourceStream(fullTemplateName)) - using(var sr = new StreamReader(s)) + using (var s = assembly.GetManifestResourceStream(fullTemplateName)) + using (var sr = new StreamReader(s)) { var templateText = sr.ReadToEnd(); return HandlebarsDotNet.Handlebars.Compile(templateText); @@ -200,23 +200,23 @@ namespace Bit.Setup public static void WriteLine(Context context, string format = null, object arg0 = null, object arg1 = null, object arg2 = null) { - if(!context.PrintToScreen()) + if (!context.PrintToScreen()) { return; } - if(format != null && arg0 != null && arg1 != null && arg2 != null) + if (format != null && arg0 != null && arg1 != null && arg2 != null) { Console.WriteLine(format, arg0, arg1, arg2); } - else if(format != null && arg0 != null && arg1 != null) + else if (format != null && arg0 != null && arg1 != null) { Console.WriteLine(format, arg0, arg1); } - else if(format != null && arg0 != null) + else if (format != null && arg0 != null) { Console.WriteLine(format, arg0); } - else if(format != null) + else if (format != null) { Console.WriteLine(format); } diff --git a/util/Setup/NginxConfigBuilder.cs b/util/Setup/NginxConfigBuilder.cs index 6f82e2eeea..cf602a6a1a 100644 --- a/util/Setup/NginxConfigBuilder.cs +++ b/util/Setup/NginxConfigBuilder.cs @@ -24,7 +24,7 @@ namespace Bit.Setup public void BuildForInstaller() { var model = new TemplateModel(_context); - if(model.Ssl && !_context.Config.SslManagedLetsEncrypt) + if (model.Ssl && !_context.Config.SslManagedLetsEncrypt) { var sslPath = _context.Install.SelfSignedCert ? $"/etc/ssl/self/{model.Domain}" : $"/etc/ssl/{model.Domain}"; @@ -32,12 +32,12 @@ namespace Bit.Setup string.Concat(sslPath, "/", "certificate.crt"); _context.Config.SslKeyPath = model.KeyPath = string.Concat(sslPath, "/", "private.key"); - if(_context.Install.Trusted) + if (_context.Install.Trusted) { _context.Config.SslCaPath = model.CaPath = string.Concat(sslPath, "/", "ca.crt"); } - if(_context.Install.DiffieHellman) + if (_context.Install.DiffieHellman) { _context.Config.SslDiffieHellmanPath = model.DiffieHellmanPath = string.Concat(sslPath, "/", "dhparam.pem"); @@ -56,14 +56,14 @@ namespace Bit.Setup { Directory.CreateDirectory("/bitwarden/nginx/"); Helpers.WriteLine(_context, "Building nginx config."); - if(!_context.Config.GenerateNginxConfig) + if (!_context.Config.GenerateNginxConfig) { Helpers.WriteLine(_context, "...skipped"); return; } var template = Helpers.ReadTemplate("NginxConfig"); - using(var sw = File.CreateText(ConfFile)) + using (var sw = File.CreateText(ConfFile)) { sw.WriteLine(template(model)); } @@ -80,9 +80,9 @@ namespace Bit.Setup Url = context.Config.Url; RealIps = context.Config.RealIps; - if(Ssl) + if (Ssl) { - if(context.Config.SslManagedLetsEncrypt) + if (context.Config.SslManagedLetsEncrypt) { var sslPath = $"/etc/letsencrypt/live/{Domain}"; CertificatePath = CaPath = string.Concat(sslPath, "/", "fullchain.pem"); @@ -98,7 +98,7 @@ namespace Bit.Setup } } - if(!string.IsNullOrWhiteSpace(context.Config.SslCiphersuites)) + if (!string.IsNullOrWhiteSpace(context.Config.SslCiphersuites)) { SslCiphers = context.Config.SslCiphersuites; } @@ -110,7 +110,7 @@ namespace Bit.Setup "ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"; } - if(!string.IsNullOrWhiteSpace(context.Config.SslVersions)) + if (!string.IsNullOrWhiteSpace(context.Config.SslVersions)) { SslProtocols = context.Config.SslVersions; } diff --git a/util/Setup/Program.cs b/util/Setup/Program.cs index bc2b340a0f..0cfccf4972 100644 --- a/util/Setup/Program.cs +++ b/util/Setup/Program.cs @@ -22,23 +22,23 @@ namespace Bit.Setup }; ParseParameters(); - if(_context.Parameters.ContainsKey("q")) + if (_context.Parameters.ContainsKey("q")) { _context.Quiet = _context.Parameters["q"] == "true" || _context.Parameters["q"] == "1"; } - if(_context.Parameters.ContainsKey("os")) + if (_context.Parameters.ContainsKey("os")) { _context.HostOS = _context.Parameters["os"]; } - if(_context.Parameters.ContainsKey("corev")) + if (_context.Parameters.ContainsKey("corev")) { _context.CoreVersion = _context.Parameters["corev"]; } - if(_context.Parameters.ContainsKey("webv")) + if (_context.Parameters.ContainsKey("webv")) { _context.WebVersion = _context.Parameters["webv"]; } - if(_context.Parameters.ContainsKey("stub")) + if (_context.Parameters.ContainsKey("stub")) { _context.Stub = _context.Parameters["stub"] == "true" || _context.Parameters["stub"] == "1"; @@ -46,15 +46,15 @@ namespace Bit.Setup Helpers.WriteLine(_context); - if(_context.Parameters.ContainsKey("install")) + if (_context.Parameters.ContainsKey("install")) { Install(); } - else if(_context.Parameters.ContainsKey("update")) + else if (_context.Parameters.ContainsKey("update")) { Update(); } - else if(_context.Parameters.ContainsKey("printenv")) + else if (_context.Parameters.ContainsKey("printenv")) { PrintEnvironment(); } @@ -66,22 +66,22 @@ namespace Bit.Setup private static void Install() { - if(_context.Parameters.ContainsKey("letsencrypt")) + if (_context.Parameters.ContainsKey("letsencrypt")) { _context.Config.SslManagedLetsEncrypt = _context.Parameters["letsencrypt"].ToLowerInvariant() == "y"; } - if(_context.Parameters.ContainsKey("domain")) + if (_context.Parameters.ContainsKey("domain")) { _context.Install.Domain = _context.Parameters["domain"].ToLowerInvariant(); } - if(_context.Stub) + if (_context.Stub) { _context.Install.InstallationId = Guid.Empty; _context.Install.InstallationKey = "SECRET_INSTALLATION_KEY"; } - else if(!ValidateInstallation()) + else if (!ValidateInstallation()) { return; } @@ -116,7 +116,7 @@ namespace Bit.Setup "`./bitwarden.sh rebuild` or `./bitwarden.sh update`"); Console.WriteLine("\nNext steps, run:"); - if(_context.HostOS == "win") + if (_context.HostOS == "win") { Console.WriteLine("`.\\bitwarden.ps1 -start`"); } @@ -129,7 +129,7 @@ namespace Bit.Setup private static void Update() { - if(_context.Parameters.ContainsKey("db")) + if (_context.Parameters.ContainsKey("db")) { MigrateDatabase(); } @@ -142,7 +142,7 @@ namespace Bit.Setup private static void PrintEnvironment() { _context.LoadConfiguration(); - if(!_context.PrintToScreen()) + if (!_context.PrintToScreen()) { return; } @@ -150,7 +150,7 @@ namespace Bit.Setup Console.WriteLine("==================================================="); Console.WriteLine("\nvisit {0}", _context.Config.Url); Console.Write("to update, run "); - if(_context.HostOS == "win") + if (_context.HostOS == "win") { Console.Write("`.\\bitwarden.ps1 -updateself` and then `.\\bitwarden.ps1 -update`"); } @@ -170,7 +170,7 @@ namespace Bit.Setup "globalSettings__sqlServer__connectionString"); var migrator = new DbMigrator(vaultConnectionString, null); var success = migrator.MigrateMsSqlDatabase(false); - if(success) + if (success) { Helpers.WriteLine(_context, "Migration successful."); } @@ -179,9 +179,9 @@ namespace Bit.Setup Helpers.WriteLine(_context, "Migration failed."); } } - catch(SqlException e) + catch (SqlException e) { - if(e.Message.Contains("Server is in script upgrade mode") && attempt < 10) + if (e.Message.Contains("Server is in script upgrade mode") && attempt < 10) { var nextAttempt = attempt + 1; Helpers.WriteLine(_context, "Database is in script upgrade mode. " + @@ -197,7 +197,7 @@ namespace Bit.Setup private static bool ValidateInstallation() { var installationId = Helpers.ReadInput("Enter your installation id (get at https://bitwarden.com/host)"); - if(!Guid.TryParse(installationId.Trim(), out var installationidGuid)) + if (!Guid.TryParse(installationId.Trim(), out var installationidGuid)) { Console.WriteLine("Invalid installation id."); return false; @@ -211,9 +211,9 @@ namespace Bit.Setup var response = new HttpClient().GetAsync("https://api.bitwarden.com/installations/" + _context.Install.InstallationId).GetAwaiter().GetResult(); - if(!response.IsSuccessStatusCode) + if (!response.IsSuccessStatusCode) { - if(response.StatusCode == System.Net.HttpStatusCode.NotFound) + if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { Console.WriteLine("Invalid installation id."); } @@ -227,7 +227,7 @@ namespace Bit.Setup var resultString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); var result = JsonConvert.DeserializeObject(resultString); - if(!(bool)result.Enabled) + if (!(bool)result.Enabled) { Console.WriteLine("Installation id has been disabled."); return false; @@ -265,9 +265,9 @@ namespace Bit.Setup private static void ParseParameters() { _context.Parameters = new Dictionary(); - for(var i = 0; i < _context.Args.Length; i = i + 2) + for (var i = 0; i < _context.Args.Length; i = i + 2) { - if(!_context.Args[i].StartsWith("-")) + if (!_context.Args[i].StartsWith("-")) { continue; } diff --git a/util/Setup/YamlComments.cs b/util/Setup/YamlComments.cs index 22075b89e4..a4630f4c4f 100644 --- a/util/Setup/YamlComments.cs +++ b/util/Setup/YamlComments.cs @@ -97,10 +97,10 @@ namespace Bit.Setup public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { - if(value is CommentsObjectDescriptor commentsDescriptor && commentsDescriptor.Comment != null) + if (value is CommentsObjectDescriptor commentsDescriptor && commentsDescriptor.Comment != null) { context.Emit(new Comment(string.Empty, false)); - foreach(var comment in commentsDescriptor.Comment.Split(Environment.NewLine)) + foreach (var comment in commentsDescriptor.Comment.Split(Environment.NewLine)) { context.Emit(new Comment(comment, false)); }