1
0
mirror of https://github.com/bitwarden/server.git synced 2025-07-04 01:22:50 -05:00

Changed all C# control flow block statements to include space between keyword and open paren

This commit is contained in:
Chad Scharf
2020-03-27 14:36:37 -04:00
parent 943aea9a12
commit 9800b752c0
243 changed files with 2258 additions and 2258 deletions

View File

@ -11,39 +11,39 @@ namespace Bit.Core.Utilities
internal static async Task<string> 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. " +

View File

@ -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);

View File

@ -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<X509Certificate2> 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<AssemblyInformationalVersionAttribute>()
@ -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<string, string>())
foreach (var kvp in values ?? new Dictionary<string, string>())
{
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();
}

View File

@ -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";
}

View File

@ -40,7 +40,7 @@ namespace Bit.Core.Utilities.Duo
public static string CanonicalizeParams(Dictionary<string, string> parameters)
{
var ret = new List<string>();
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<string, string> parameters, int timeout,
out HttpStatusCode statusCode)
{
if(parameters == null)
if (parameters == null)
{
parameters = new Dictionary<string, string>();
}
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<Dictionary<string, object>>(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);
}

View File

@ -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);

View File

@ -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;
}

View File

@ -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();
}

View File

@ -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<LogEvent, bool> 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);

View File

@ -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;

View File

@ -12,11 +12,11 @@ namespace Bit.Core.Utilities
public override void OnActionExecuting(ActionExecutingContext context)
{
var globalSettings = context.HttpContext.RequestServices.GetRequiredService<GlobalSettings>();
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.");
}

View File

@ -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<EntityFrameworkRepos.DatabaseContext>(options =>
{
if(usePostgreSql)
if (usePostgreSql)
{
options.UseNpgsql(globalSettings.PostgreSql.ConnectionString);
}
@ -78,9 +78,9 @@ namespace Bit.Core.Utilities
services.AddSingleton<IPolicyRepository, SqlServerRepos.PolicyRepository>();
}
if(globalSettings.SelfHosted)
if (globalSettings.SelfHosted)
{
if(useEf)
if (useEf)
{
// TODO
}
@ -118,7 +118,7 @@ namespace Bit.Core.Utilities
services.AddSingleton<IMailService, HandlebarsMailService>();
services.AddSingleton<ILicensingService, LicensingService>();
if(CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) &&
if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) &&
CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName))
{
services.AddSingleton<IApplicationCacheService, InMemoryServiceBusApplicationCacheService>();
@ -128,11 +128,11 @@ namespace Bit.Core.Utilities
services.AddSingleton<IApplicationCacheService, InMemoryApplicationCacheService>();
}
if(CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret))
if (CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret))
{
services.AddSingleton<IMailDeliveryService, AmazonSesMailDeliveryService>();
}
else if(CoreHelpers.SettingHasValue(globalSettings.Mail?.Smtp?.Host))
else if (CoreHelpers.SettingHasValue(globalSettings.Mail?.Smtp?.Host))
{
services.AddSingleton<IMailDeliveryService, MailKitSmtpMailDeliveryService>();
}
@ -142,14 +142,14 @@ namespace Bit.Core.Utilities
}
services.AddSingleton<IPushNotificationService, MultiServicePushNotificationService>();
if(globalSettings.SelfHosted &&
if (globalSettings.SelfHosted &&
CoreHelpers.SettingHasValue(globalSettings.PushRelayBaseUri) &&
globalSettings.Installation?.Id != null &&
CoreHelpers.SettingHasValue(globalSettings.Installation?.Key))
{
services.AddSingleton<IPushRegistrationService, RelayPushRegistrationService>();
}
else if(!globalSettings.SelfHosted)
else if (!globalSettings.SelfHosted)
{
services.AddSingleton<IPushRegistrationService, NotificationHubPushRegistrationService>();
}
@ -158,11 +158,11 @@ namespace Bit.Core.Utilities
services.AddSingleton<IPushRegistrationService, NoopPushRegistrationService>();
}
if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString))
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString))
{
services.AddSingleton<IBlockIpService, AzureQueueBlockIpService>();
}
else if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret))
else if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret))
{
services.AddSingleton<IBlockIpService, AmazonSqsBlockIpService>();
}
@ -171,11 +171,11 @@ namespace Bit.Core.Utilities
services.AddSingleton<IBlockIpService, NoopBlockIpService>();
}
if(!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString))
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString))
{
services.AddSingleton<IEventWriteService, AzureQueueEventWriteService>();
}
else if(globalSettings.SelfHosted)
else if (globalSettings.SelfHosted)
{
services.AddSingleton<IEventWriteService, RepositoryEventWriteService>();
}
@ -184,11 +184,11 @@ namespace Bit.Core.Utilities
services.AddSingleton<IEventWriteService, NoopEventWriteService>();
}
if(CoreHelpers.SettingHasValue(globalSettings.Attachment.ConnectionString))
if (CoreHelpers.SettingHasValue(globalSettings.Attachment.ConnectionString))
{
services.AddSingleton<IAttachmentStorageService, AzureAttachmentStorageService>();
}
else if(CoreHelpers.SettingHasValue(globalSettings.Attachment.BaseDirectory))
else if (CoreHelpers.SettingHasValue(globalSettings.Attachment.BaseDirectory))
{
services.AddSingleton<IAttachmentStorageService, LocalAttachmentStorageService>();
}
@ -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<ClientStore>();
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;
}