1
0
mirror of https://github.com/bitwarden/server.git synced 2025-06-17 00:03:17 -05:00

[PM-14476] Avoid multiple lookups in dictionaries (#4973)

* Avoid multiple lookups in dictionaries

* Consistency in fallback to empty CollectionIds

* Readability at the cost of lines changed

* Readability

* Changes after running dotnet format
This commit is contained in:
Henrik 2025-06-02 18:18:28 +02:00 committed by GitHub
parent 2c4393cc16
commit 8bac7f0145
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
44 changed files with 179 additions and 212 deletions

View File

@ -287,11 +287,10 @@ public class ProviderService : IProviderService
foreach (var user in users)
{
if (!keyedFilteredUsers.ContainsKey(user.Id))
if (!keyedFilteredUsers.TryGetValue(user.Id, out var providerUser))
{
continue;
}
var providerUser = keyedFilteredUsers[user.Id];
try
{
if (providerUser.Status != ProviderUserStatusType.Accepted || providerUser.ProviderId != providerId)

View File

@ -16,8 +16,8 @@ public class Program
{
var context = e.Properties["SourceContext"].ToString();
if (e.Properties.ContainsKey("RequestPath") &&
!string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) &&
if (e.Properties.TryGetValue("RequestPath", out var requestPath) &&
!string.IsNullOrWhiteSpace(requestPath?.ToString()) &&
(context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer")))
{
return false;

View File

@ -370,8 +370,8 @@ public class AccountController : Controller
// for the user identifier.
static bool nameIdIsNotTransient(Claim c) => c.Type == ClaimTypes.NameIdentifier
&& (c.Properties == null
|| !c.Properties.ContainsKey(SamlPropertyKeys.ClaimFormat)
|| c.Properties[SamlPropertyKeys.ClaimFormat] != SamlNameIdFormats.Transient);
|| !c.Properties.TryGetValue(SamlPropertyKeys.ClaimFormat, out var claimFormat)
|| claimFormat != SamlNameIdFormats.Transient);
// Try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier

View File

@ -17,8 +17,8 @@ public class Program
logging.AddSerilog(hostingContext, (e, globalSettings) =>
{
var context = e.Properties["SourceContext"].ToString();
if (e.Properties.ContainsKey("RequestPath") &&
!string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) &&
if (e.Properties.TryGetValue("RequestPath", out var requestPath) &&
!string.IsNullOrWhiteSpace(requestPath?.ToString()) &&
(context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer")))
{
return false;

View File

@ -46,9 +46,9 @@ public static class OpenIdConnectOptionsExtensions
// Handle State if we've gotten that back
var decodedState = options.StateDataFormat.Unprotect(state);
if (decodedState != null && decodedState.Items.ContainsKey("scheme"))
if (decodedState != null && decodedState.Items.TryGetValue("scheme", out var stateScheme))
{
return decodedState.Items["scheme"] == scheme;
return stateScheme == scheme;
}
}
catch

View File

@ -39,7 +39,7 @@ public class ReadOnlyEnvIdentityUserStore : ReadOnlyIdentityUserStore
}
}
var userStamp = usersDict.ContainsKey(normalizedEmail) ? usersDict[normalizedEmail] : null;
var userStamp = usersDict.GetValueOrDefault(normalizedEmail);
if (userStamp == null)
{
return Task.FromResult<IdentityUser>(null);

View File

@ -20,8 +20,8 @@ public class Program
logging.AddSerilog(hostingContext, (e, globalSettings) =>
{
var context = e.Properties["SourceContext"].ToString();
if (e.Properties.ContainsKey("RequestPath") &&
!string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) &&
if (e.Properties.TryGetValue("RequestPath", out var requestPath) &&
!string.IsNullOrWhiteSpace(requestPath?.ToString()) &&
(context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer")))
{
return false;

View File

@ -29,12 +29,12 @@ public class AccessControlService : IAccessControlService
}
var userRole = GetUserRoleFromClaim();
if (string.IsNullOrEmpty(userRole) || !RolePermissionMapping.RolePermissions.ContainsKey(userRole))
if (string.IsNullOrEmpty(userRole) || !RolePermissionMapping.RolePermissions.TryGetValue(userRole, out var rolePermissions))
{
return false;
}
return RolePermissionMapping.RolePermissions[userRole].Contains(permission);
return rolePermissions.Contains(permission);
}
public string GetUserRole(string userEmail)

View File

@ -25,7 +25,7 @@ public class UpdateTwoFactorAuthenticatorRequestModel : SecretVerificationReques
{
providers = new Dictionary<TwoFactorProviderType, TwoFactorProvider>();
}
else if (providers.ContainsKey(TwoFactorProviderType.Authenticator))
else
{
providers.Remove(TwoFactorProviderType.Authenticator);
}
@ -62,7 +62,7 @@ public class UpdateTwoFactorDuoRequestModel : SecretVerificationRequestModel, IV
{
providers = [];
}
else if (providers.ContainsKey(TwoFactorProviderType.Duo))
else
{
providers.Remove(TwoFactorProviderType.Duo);
}
@ -88,7 +88,7 @@ public class UpdateTwoFactorDuoRequestModel : SecretVerificationRequestModel, IV
{
providers = [];
}
else if (providers.ContainsKey(TwoFactorProviderType.OrganizationDuo))
else
{
providers.Remove(TwoFactorProviderType.OrganizationDuo);
}
@ -145,7 +145,7 @@ public class UpdateTwoFactorYubicoOtpRequestModel : SecretVerificationRequestMod
{
providers = new Dictionary<TwoFactorProviderType, TwoFactorProvider>();
}
else if (providers.ContainsKey(TwoFactorProviderType.YubiKey))
else
{
providers.Remove(TwoFactorProviderType.YubiKey);
}
@ -228,7 +228,7 @@ public class TwoFactorEmailRequestModel : SecretVerificationRequestModel
{
providers = new Dictionary<TwoFactorProviderType, TwoFactorProvider>();
}
else if (providers.ContainsKey(TwoFactorProviderType.Email))
else
{
providers.Remove(TwoFactorProviderType.Email);
}

View File

@ -13,9 +13,9 @@ public class TwoFactorAuthenticatorResponseModel : ResponseModel
ArgumentNullException.ThrowIfNull(user);
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Authenticator);
if (provider?.MetaData?.ContainsKey("Key") ?? false)
if (provider?.MetaData?.TryGetValue("Key", out var keyValue) ?? false)
{
Key = (string)provider.MetaData["Key"];
Key = (string)keyValue;
Enabled = provider.Enabled;
}
else

View File

@ -15,9 +15,9 @@ public class TwoFactorEmailResponseModel : ResponseModel
}
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Email);
if (provider?.MetaData?.ContainsKey("Email") ?? false)
if (provider?.MetaData?.TryGetValue("Email", out var email) ?? false)
{
Email = (string)provider.MetaData["Email"];
Email = (string)email;
Enabled = provider.Enabled;
}
else

View File

@ -19,29 +19,29 @@ public class TwoFactorYubiKeyResponseModel : ResponseModel
{
Enabled = provider.Enabled;
if (provider.MetaData.ContainsKey("Key1"))
if (provider.MetaData.TryGetValue("Key1", out var key1))
{
Key1 = (string)provider.MetaData["Key1"];
Key1 = (string)key1;
}
if (provider.MetaData.ContainsKey("Key2"))
if (provider.MetaData.TryGetValue("Key2", out var key2))
{
Key2 = (string)provider.MetaData["Key2"];
Key2 = (string)key2;
}
if (provider.MetaData.ContainsKey("Key3"))
if (provider.MetaData.TryGetValue("Key3", out var key3))
{
Key3 = (string)provider.MetaData["Key3"];
Key3 = (string)key3;
}
if (provider.MetaData.ContainsKey("Key4"))
if (provider.MetaData.TryGetValue("Key4", out var key4))
{
Key4 = (string)provider.MetaData["Key4"];
Key4 = (string)key4;
}
if (provider.MetaData.ContainsKey("Key5"))
if (provider.MetaData.TryGetValue("Key5", out var key5))
{
Key5 = (string)provider.MetaData["Key5"];
Key5 = (string)key5;
}
if (provider.MetaData.ContainsKey("Nfc"))
if (provider.MetaData.TryGetValue("Nfc", out var nfc))
{
Nfc = (bool)provider.MetaData["Nfc"];
Nfc = (bool)nfc;
}
}
else

View File

@ -62,9 +62,9 @@ public static class ApiHelpers
}
}
if (eventTypeHandlers.ContainsKey(eventGridEvent.EventType))
if (eventTypeHandlers.TryGetValue(eventGridEvent.EventType, out var eventTypeHandler))
{
await eventTypeHandlers[eventGridEvent.EventType](eventGridEvent);
await eventTypeHandler(eventGridEvent);
}
}

View File

@ -1188,14 +1188,14 @@ public class CiphersController : Controller
var cipher = await GetByIdAsync(id, userId);
var attachments = cipher?.GetAttachments();
if (attachments == null || !attachments.ContainsKey(attachmentId) || attachments[attachmentId].Validated)
if (attachments == null || !attachments.TryGetValue(attachmentId, out var attachment) || attachment.Validated)
{
throw new NotFoundException();
}
return new AttachmentUploadDataResponseModel
{
Url = await _attachmentStorageService.GetAttachmentUploadUrlAsync(cipher, attachments[attachmentId]),
Url = await _attachmentStorageService.GetAttachmentUploadUrlAsync(cipher, attachment),
FileUploadType = _attachmentStorageService.FileUploadType,
};
}
@ -1214,11 +1214,10 @@ public class CiphersController : Controller
var userId = _userService.GetProperUserId(User).Value;
var cipher = await GetByIdAsync(id, userId);
var attachments = cipher?.GetAttachments();
if (attachments == null || !attachments.ContainsKey(attachmentId))
if (attachments == null || !attachments.TryGetValue(attachmentId, out var attachmentData))
{
throw new NotFoundException();
}
var attachmentData = attachments[attachmentId];
await Request.GetFileAsync(async (stream) =>
{
@ -1368,7 +1367,7 @@ public class CiphersController : Controller
var cipher = await _cipherRepository.GetByIdAsync(new Guid(cipherId));
var attachments = cipher?.GetAttachments() ?? new Dictionary<string, CipherAttachment.MetaData>();
if (cipher == null || !attachments.ContainsKey(attachmentId) || attachments[attachmentId].Validated)
if (cipher == null || !attachments.TryGetValue(attachmentId, out var attachment) || attachment.Validated)
{
if (_attachmentStorageService is AzureSendFileStorageService azureFileStorageService)
{
@ -1378,7 +1377,7 @@ public class CiphersController : Controller
return;
}
await _cipherService.ValidateCipherAttachmentFile(cipher, attachments[attachmentId]);
await _cipherService.ValidateCipherAttachmentFile(cipher, attachment);
}
catch (Exception e)
{

View File

@ -113,18 +113,25 @@ public class CipherRequestModel
if (hasAttachments2)
{
foreach (var attachment in attachments.Where(a => Attachments2.ContainsKey(a.Key)))
foreach (var attachment in attachments)
{
var attachment2 = Attachments2[attachment.Key];
if (!Attachments2.TryGetValue(attachment.Key, out var attachment2))
{
continue;
}
attachment.Value.FileName = attachment2.FileName;
attachment.Value.Key = attachment2.Key;
}
}
else if (hasAttachments)
{
foreach (var attachment in attachments.Where(a => Attachments.ContainsKey(a.Key)))
foreach (var attachment in attachments)
{
attachment.Value.FileName = Attachments[attachment.Key];
if (!Attachments.TryGetValue(attachment.Key, out var attachmentForKey))
{
continue;
}
attachment.Value.FileName = attachmentForKey;
attachment.Value.Key = null;
}
}

View File

@ -129,13 +129,13 @@ public class CipherDetailsResponseModel : CipherResponseModel
IDictionary<Guid, IGrouping<Guid, CollectionCipher>> collectionCiphers, string obj = "cipherDetails")
: base(cipher, user, organizationAbilities, globalSettings, obj)
{
if (collectionCiphers?.ContainsKey(cipher.Id) ?? false)
if (collectionCiphers?.TryGetValue(cipher.Id, out var collectionCipher) ?? false)
{
CollectionIds = collectionCiphers[cipher.Id].Select(c => c.CollectionId);
CollectionIds = collectionCipher.Select(c => c.CollectionId);
}
else
{
CollectionIds = new Guid[] { };
CollectionIds = [];
}
}
@ -147,7 +147,7 @@ public class CipherDetailsResponseModel : CipherResponseModel
IEnumerable<CollectionCipher> collectionCiphers, string obj = "cipherDetails")
: base(cipher, user, organizationAbilities, globalSettings, obj)
{
CollectionIds = collectionCiphers?.Select(c => c.CollectionId) ?? new List<Guid>();
CollectionIds = collectionCiphers?.Select(c => c.CollectionId) ?? [];
}
public CipherDetailsResponseModel(
@ -158,7 +158,7 @@ public class CipherDetailsResponseModel : CipherResponseModel
string obj = "cipherDetails")
: base(cipher, user, organizationAbilities, globalSettings, obj)
{
CollectionIds = cipher.CollectionIds ?? new List<Guid>();
CollectionIds = cipher.CollectionIds ?? [];
}
public IEnumerable<Guid> CollectionIds { get; set; }
@ -170,13 +170,13 @@ public class CipherMiniDetailsResponseModel : CipherMiniResponseModel
IDictionary<Guid, IGrouping<Guid, CollectionCipher>> collectionCiphers, bool orgUseTotp, string obj = "cipherMiniDetails")
: base(cipher, globalSettings, orgUseTotp, obj)
{
if (collectionCiphers?.ContainsKey(cipher.Id) ?? false)
if (collectionCiphers?.TryGetValue(cipher.Id, out var collectionCipher) ?? false)
{
CollectionIds = collectionCiphers[cipher.Id].Select(c => c.CollectionId);
CollectionIds = collectionCipher.Select(c => c.CollectionId);
}
else
{
CollectionIds = new Guid[] { };
CollectionIds = [];
}
}
@ -184,7 +184,7 @@ public class CipherMiniDetailsResponseModel : CipherMiniResponseModel
GlobalSettings globalSettings, bool orgUseTotp, string obj = "cipherMiniDetails")
: base(cipher, globalSettings, orgUseTotp, obj)
{
CollectionIds = cipher.CollectionIds ?? new List<Guid>();
CollectionIds = cipher.CollectionIds ?? [];
}
public CipherMiniDetailsResponseModel(CipherOrganizationDetailsWithCollections cipher,

View File

@ -28,8 +28,8 @@ public class AppleController : Controller
return new BadRequestResult();
}
var key = HttpContext.Request.Query.ContainsKey("key") ?
HttpContext.Request.Query["key"].ToString() : null;
var key = HttpContext.Request.Query.TryGetValue("key", out var keyValue) ?
keyValue.ToString() : null;
if (!CoreHelpers.FixedTimeEquals(key, _billingSettings.AppleWebhookKey))
{
return new BadRequestResult();

View File

@ -51,8 +51,8 @@ public class PayPalController : Controller
[HttpPost("ipn")]
public async Task<IActionResult> PostIpn()
{
var key = HttpContext.Request.Query.ContainsKey("key")
? HttpContext.Request.Query["key"].ToString()
var key = HttpContext.Request.Query.TryGetValue("key", out var keyValue)
? keyValue.ToString()
: null;
if (string.IsNullOrEmpty(key))

View File

@ -20,8 +20,8 @@ public class Program
return e.Level >= globalSettings.MinLogLevel.BillingSettings.Jobs;
}
if (e.Properties.ContainsKey("RequestPath") &&
!string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) &&
if (e.Properties.TryGetValue("RequestPath", out var requestPath) &&
!string.IsNullOrWhiteSpace(requestPath?.ToString()) &&
(context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer")))
{
return false;

View File

@ -257,12 +257,12 @@ public class Organization : ITableObject<Guid>, IStorableSubscriber, IRevisable
public bool TwoFactorProviderIsEnabled(TwoFactorProviderType provider)
{
var providers = GetTwoFactorProviders();
if (providers == null || !providers.ContainsKey(provider))
if (providers == null || !providers.TryGetValue(provider, out var twoFactorProvider))
{
return false;
}
return providers[provider].Enabled && Use2fa;
return twoFactorProvider.Enabled && Use2fa;
}
public bool TwoFactorIsEnabled()
@ -279,12 +279,7 @@ public class Organization : ITableObject<Guid>, IStorableSubscriber, IRevisable
public TwoFactorProvider? GetTwoFactorProvider(TwoFactorProviderType provider)
{
var providers = GetTwoFactorProviders();
if (providers == null || !providers.ContainsKey(provider))
{
return null;
}
return providers[provider];
return providers?.GetValueOrDefault(provider);
}
public void UpdateFromLicense(OrganizationLicense license, IFeatureService featureService)

View File

@ -104,8 +104,8 @@ public class SavePolicyCommand : ISavePolicyCommand
var dependentPolicyTypes = _policyValidators.Values
.Where(otherValidator => otherValidator.RequiredPolicies.Contains(policyUpdate.Type))
.Select(otherValidator => otherValidator.Type)
.Where(otherPolicyType => savedPoliciesDict.ContainsKey(otherPolicyType) &&
savedPoliciesDict[otherPolicyType].Enabled)
.Where(otherPolicyType => savedPoliciesDict.TryGetValue(otherPolicyType, out var savedPolicy) &&
savedPolicy.Enabled)
.ToList();
switch (dependentPolicyTypes)

View File

@ -462,13 +462,13 @@ public class EventService : IEventService
private bool CanUseEvents(IDictionary<Guid, OrganizationAbility> orgAbilities, Guid orgId)
{
return orgAbilities != null && orgAbilities.ContainsKey(orgId) &&
orgAbilities[orgId].Enabled && orgAbilities[orgId].UseEvents;
return orgAbilities != null && orgAbilities.TryGetValue(orgId, out var orgAbility) &&
orgAbility.Enabled && orgAbility.UseEvents;
}
private bool CanUseProviderEvents(IDictionary<Guid, ProviderAbility> providerAbilities, Guid providerId)
{
return providerAbilities != null && providerAbilities.ContainsKey(providerId) &&
providerAbilities[providerId].Enabled && providerAbilities[providerId].UseEvents;
return providerAbilities != null && providerAbilities.TryGetValue(providerId, out var providerAbility) &&
providerAbility.Enabled && providerAbility.UseEvents;
}
}

View File

@ -612,12 +612,12 @@ public class OrganizationService : IOrganizationService
}
var providers = organization.GetTwoFactorProviders();
if (!providers?.ContainsKey(type) ?? true)
if (providers is null || !providers.TryGetValue(type, out var provider))
{
return;
}
providers[type].Enabled = true;
provider.Enabled = true;
organization.SetTwoFactorProviders(providers);
await UpdateAsync(organization);
}
@ -1115,7 +1115,7 @@ public class OrganizationService : IOrganizationService
var existingUsersDict = existingExternalUsers.ToDictionary(u => u.ExternalId);
var removeUsersSet = new HashSet<string>(removeUserExternalIds)
.Except(newUsersSet)
.Where(u => existingUsersDict.ContainsKey(u) && existingUsersDict[u].Type != OrganizationUserType.Owner)
.Where(u => existingUsersDict.TryGetValue(u, out var existingUser) && existingUser.Type != OrganizationUserType.Owner)
.Select(u => existingUsersDict[u]);
await _organizationUserRepository.DeleteManyAsync(removeUsersSet.Select(u => u.Id));

View File

@ -68,7 +68,7 @@ public class PolicyService : IPolicyService
var excludedUserTypes = GetUserTypesExcludedFromPolicy(policyType);
var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync();
return organizationUserPolicyDetails.Where(o =>
(!orgAbilities.ContainsKey(o.OrganizationId) || orgAbilities[o.OrganizationId].UsePolicies) &&
(!orgAbilities.TryGetValue(o.OrganizationId, out var orgAbility) || orgAbility.UsePolicies) &&
o.PolicyEnabled &&
!excludedUserTypes.Contains(o.OrganizationUserType) &&
o.OrganizationUserStatus >= minStatus &&

View File

@ -43,7 +43,7 @@ public class EmailTwoFactorTokenProvider : EmailTokenProvider
private static bool HasProperMetaData(TwoFactorProvider provider)
{
return provider?.MetaData != null && provider.MetaData.ContainsKey("Email") &&
!string.IsNullOrWhiteSpace((string)provider.MetaData["Email"]);
return provider?.MetaData != null && provider.MetaData.TryGetValue("Email", out var emailValue) &&
!string.IsNullOrWhiteSpace((string)emailValue);
}
}

View File

@ -80,7 +80,7 @@ public class WebAuthnTokenProvider : IUserTwoFactorTokenProvider<User>
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.WebAuthn);
var keys = LoadKeys(provider);
if (!provider.MetaData.TryGetValue("login", out var value))
if (!provider.MetaData.TryGetValue("login", out var login))
{
return false;
}
@ -88,7 +88,7 @@ public class WebAuthnTokenProvider : IUserTwoFactorTokenProvider<User>
var clientResponse = JsonSerializer.Deserialize<AuthenticatorAssertionRawResponse>(token,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
var jsonOptions = value.ToString();
var jsonOptions = login.ToString();
var options = AssertionOptions.FromJson(jsonOptions);
var webAuthCred = keys.Find(k => k.Item2.Descriptor.Id.SequenceEqual(clientResponse.Id));
@ -148,9 +148,9 @@ public class WebAuthnTokenProvider : IUserTwoFactorTokenProvider<User>
for (var i = 1; i <= 5; i++)
{
var keyName = $"Key{i}";
if (provider.MetaData.ContainsKey(keyName))
if (provider.MetaData.TryGetValue(keyName, out var value))
{
var key = new TwoFactorProvider.WebAuthnData((dynamic)provider.MetaData[keyName]);
var key = new TwoFactorProvider.WebAuthnData((dynamic)value);
keys.Add(new Tuple<string, TwoFactorProvider.WebAuthnData>(keyName, key));
}

View File

@ -64,39 +64,39 @@ public class CurrentContext : ICurrentContext
HttpContext = httpContext;
await BuildAsync(httpContext.User, globalSettings);
if (DeviceIdentifier == null && httpContext.Request.Headers.ContainsKey("Device-Identifier"))
if (DeviceIdentifier == null && httpContext.Request.Headers.TryGetValue("Device-Identifier", out var deviceIdentifier))
{
DeviceIdentifier = httpContext.Request.Headers["Device-Identifier"];
DeviceIdentifier = deviceIdentifier;
}
if (httpContext.Request.Headers.ContainsKey("Device-Type") &&
Enum.TryParse(httpContext.Request.Headers["Device-Type"].ToString(), out DeviceType dType))
if (httpContext.Request.Headers.TryGetValue("Device-Type", out var deviceType) &&
Enum.TryParse(deviceType.ToString(), out DeviceType dType))
{
DeviceType = dType;
}
if (!BotScore.HasValue && httpContext.Request.Headers.ContainsKey("X-Cf-Bot-Score") &&
int.TryParse(httpContext.Request.Headers["X-Cf-Bot-Score"], out var parsedBotScore))
if (!BotScore.HasValue && httpContext.Request.Headers.TryGetValue("X-Cf-Bot-Score", out var cfBotScore) &&
int.TryParse(cfBotScore, out var parsedBotScore))
{
BotScore = parsedBotScore;
}
if (httpContext.Request.Headers.ContainsKey("X-Cf-Worked-Proxied"))
if (httpContext.Request.Headers.TryGetValue("X-Cf-Worked-Proxied", out var cfWorkedProxied))
{
CloudflareWorkerProxied = httpContext.Request.Headers["X-Cf-Worked-Proxied"] == "1";
CloudflareWorkerProxied = cfWorkedProxied == "1";
}
if (httpContext.Request.Headers.ContainsKey("X-Cf-Is-Bot"))
if (httpContext.Request.Headers.TryGetValue("X-Cf-Is-Bot", out var cfIsBot))
{
IsBot = httpContext.Request.Headers["X-Cf-Is-Bot"] == "1";
IsBot = cfIsBot == "1";
}
if (httpContext.Request.Headers.ContainsKey("X-Cf-Maybe-Bot"))
if (httpContext.Request.Headers.TryGetValue("X-Cf-Maybe-Bot", out var cfMaybeBot))
{
MaybeBot = httpContext.Request.Headers["X-Cf-Maybe-Bot"] == "1";
MaybeBot = cfMaybeBot == "1";
}
if (httpContext.Request.Headers.ContainsKey("Bitwarden-Client-Version") && Version.TryParse(httpContext.Request.Headers["Bitwarden-Client-Version"], out var cVersion))
if (httpContext.Request.Headers.TryGetValue("Bitwarden-Client-Version", out var bitWardenClientVersion) && Version.TryParse(bitWardenClientVersion, out var cVersion))
{
ClientVersion = cVersion;
}
@ -190,14 +190,14 @@ public class CurrentContext : ICurrentContext
private List<CurrentContextOrganization> GetOrganizations(Dictionary<string, IEnumerable<Claim>> claimsDict, bool orgApi)
{
var accessSecretsManager = claimsDict.ContainsKey(Claims.SecretsManagerAccess)
? claimsDict[Claims.SecretsManagerAccess].ToDictionary(s => s.Value, _ => true)
var accessSecretsManager = claimsDict.TryGetValue(Claims.SecretsManagerAccess, out var secretsManagerAccessClaim)
? secretsManagerAccessClaim.ToDictionary(s => s.Value, _ => true)
: new Dictionary<string, bool>();
var organizations = new List<CurrentContextOrganization>();
if (claimsDict.ContainsKey(Claims.OrganizationOwner))
if (claimsDict.TryGetValue(Claims.OrganizationOwner, out var organizationOwnerClaim))
{
organizations.AddRange(claimsDict[Claims.OrganizationOwner].Select(c =>
organizations.AddRange(organizationOwnerClaim.Select(c =>
new CurrentContextOrganization
{
Id = new Guid(c.Value),
@ -214,9 +214,9 @@ public class CurrentContext : ICurrentContext
});
}
if (claimsDict.ContainsKey(Claims.OrganizationAdmin))
if (claimsDict.TryGetValue(Claims.OrganizationAdmin, out var organizationAdminClaim))
{
organizations.AddRange(claimsDict[Claims.OrganizationAdmin].Select(c =>
organizations.AddRange(organizationAdminClaim.Select(c =>
new CurrentContextOrganization
{
Id = new Guid(c.Value),
@ -225,9 +225,9 @@ public class CurrentContext : ICurrentContext
}));
}
if (claimsDict.ContainsKey(Claims.OrganizationUser))
if (claimsDict.TryGetValue(Claims.OrganizationUser, out var organizationUserClaim))
{
organizations.AddRange(claimsDict[Claims.OrganizationUser].Select(c =>
organizations.AddRange(organizationUserClaim.Select(c =>
new CurrentContextOrganization
{
Id = new Guid(c.Value),
@ -236,9 +236,9 @@ public class CurrentContext : ICurrentContext
}));
}
if (claimsDict.ContainsKey(Claims.OrganizationCustom))
if (claimsDict.TryGetValue(Claims.OrganizationCustom, out var organizationCustomClaim))
{
organizations.AddRange(claimsDict[Claims.OrganizationCustom].Select(c =>
organizations.AddRange(organizationCustomClaim.Select(c =>
new CurrentContextOrganization
{
Id = new Guid(c.Value),
@ -254,9 +254,9 @@ public class CurrentContext : ICurrentContext
private List<CurrentContextProvider> GetProviders(Dictionary<string, IEnumerable<Claim>> claimsDict)
{
var providers = new List<CurrentContextProvider>();
if (claimsDict.ContainsKey(Claims.ProviderAdmin))
if (claimsDict.TryGetValue(Claims.ProviderAdmin, out var providerAdminClaim))
{
providers.AddRange(claimsDict[Claims.ProviderAdmin].Select(c =>
providers.AddRange(providerAdminClaim.Select(c =>
new CurrentContextProvider
{
Id = new Guid(c.Value),
@ -264,9 +264,9 @@ public class CurrentContext : ICurrentContext
}));
}
if (claimsDict.ContainsKey(Claims.ProviderServiceUser))
if (claimsDict.TryGetValue(Claims.ProviderServiceUser, out var providerServiceUserClaim))
{
providers.AddRange(claimsDict[Claims.ProviderServiceUser].Select(c =>
providers.AddRange(providerServiceUserClaim.Select(c =>
new CurrentContextProvider
{
Id = new Guid(c.Value),
@ -504,20 +504,20 @@ public class CurrentContext : ICurrentContext
private string GetClaimValue(Dictionary<string, IEnumerable<Claim>> claims, string type)
{
if (!claims.ContainsKey(type))
if (!claims.TryGetValue(type, out var claim))
{
return null;
}
return claims[type].FirstOrDefault()?.Value;
return claim.FirstOrDefault()?.Value;
}
private Permissions SetOrganizationPermissionsFromClaims(string organizationId, Dictionary<string, IEnumerable<Claim>> claimsDict)
{
bool hasClaim(string claimKey)
{
return claimsDict.ContainsKey(claimKey) ?
claimsDict[claimKey].Any(x => x.Value == organizationId) : false;
return claimsDict.TryGetValue(claimKey, out var claim) ?
claim.Any(x => x.Value == organizationId) : false;
}
return new Permissions

View File

@ -195,12 +195,7 @@ public class User : ITableObject<Guid>, IStorableSubscriber, IRevisable, ITwoFac
public TwoFactorProvider? GetTwoFactorProvider(TwoFactorProviderType provider)
{
var providers = GetTwoFactorProviders();
if (providers == null || !providers.TryGetValue(provider, out var value))
{
return null;
}
return value;
return providers?.GetValueOrDefault(provider);
}
public long StorageBytesRemaining()

View File

@ -63,6 +63,6 @@ public class DistributedCacheCookieManager : ICookieManager
private string GetKey(string key, string id) => $"{CacheKeyPrefix}-{key}-{id}";
private string GetId(HttpContext context, string key) =>
context.Request.Cookies.ContainsKey(key) ?
context.Request.Cookies[key] : null;
context.Request.Cookies.TryGetValue(key, out var cookie) ?
cookie : null;
}

View File

@ -50,14 +50,7 @@ public class InMemoryApplicationCacheService : IApplicationCacheService
await InitProviderAbilitiesAsync();
var newAbility = new ProviderAbility(provider);
if (_providerAbilities.ContainsKey(provider.Id))
{
_providerAbilities[provider.Id] = newAbility;
}
else
{
_providerAbilities.Add(provider.Id, newAbility);
}
_providerAbilities[provider.Id] = newAbility;
}
public virtual async Task UpsertOrganizationAbilityAsync(Organization organization)
@ -65,32 +58,19 @@ public class InMemoryApplicationCacheService : IApplicationCacheService
await InitOrganizationAbilitiesAsync();
var newAbility = new OrganizationAbility(organization);
if (_orgAbilities.ContainsKey(organization.Id))
{
_orgAbilities[organization.Id] = newAbility;
}
else
{
_orgAbilities.Add(organization.Id, newAbility);
}
_orgAbilities[organization.Id] = newAbility;
}
public virtual Task DeleteOrganizationAbilityAsync(Guid organizationId)
{
if (_orgAbilities != null && _orgAbilities.ContainsKey(organizationId))
{
_orgAbilities.Remove(organizationId);
}
_orgAbilities?.Remove(organizationId);
return Task.FromResult(0);
}
public virtual Task DeleteProviderAbilityAsync(Guid providerId)
{
if (_providerAbilities != null && _providerAbilities.ContainsKey(providerId))
{
_providerAbilities.Remove(providerId);
}
_providerAbilities?.Remove(providerId);
return Task.FromResult(0);
}

View File

@ -182,9 +182,8 @@ public class LicensingService : ILicensingService
// Only check once per day
var now = DateTime.UtcNow;
if (_userCheckCache.ContainsKey(user.Id))
if (_userCheckCache.TryGetValue(user.Id, out var lastCheck))
{
var lastCheck = _userCheckCache[user.Id];
if (lastCheck < now && now - lastCheck < TimeSpan.FromDays(1))
{
return user.Premium;

View File

@ -72,8 +72,8 @@ public class SendGridMailDeliveryService : IMailDeliveryService, IDisposable
msg.SetOpenTracking(false);
if (message.MetaData != null &&
message.MetaData.ContainsKey("SendGridBypassListManagement") &&
Convert.ToBoolean(message.MetaData["SendGridBypassListManagement"]))
message.MetaData.TryGetValue("SendGridBypassListManagement", out var sendGridBypassListManagement) &&
Convert.ToBoolean(sendGridBypassListManagement))
{
msg.SetBypassListManagement(true);
}

View File

@ -357,12 +357,12 @@ public class UserService : UserManager<User>, IUserService, IDisposable
public async Task SendTwoFactorEmailAsync(User user, bool authentication = true)
{
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.Email);
if (provider == null || provider.MetaData == null || !provider.MetaData.ContainsKey("Email"))
if (provider == null || provider.MetaData == null || !provider.MetaData.TryGetValue("Email", out var emailValue))
{
throw new ArgumentNullException("No email.");
}
var email = ((string)provider.MetaData["Email"]).ToLowerInvariant();
var email = ((string)emailValue).ToLowerInvariant();
var token = await base.GenerateTwoFactorTokenAsync(user,
CoreHelpers.CustomProviderName(TwoFactorProviderType.Email));
@ -390,12 +390,12 @@ public class UserService : UserManager<User>, IUserService, IDisposable
public async Task<bool> 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.TryGetValue("Email", out var emailValue))
{
throw new ArgumentNullException("No email.");
}
var email = ((string)provider.MetaData["Email"]).ToLowerInvariant();
var email = ((string)emailValue).ToLowerInvariant();
return await base.VerifyTwoFactorTokenAsync(user,
CoreHelpers.CustomProviderName(TwoFactorProviderType.Email), token);
}
@ -453,12 +453,12 @@ public class UserService : UserManager<User>, IUserService, IDisposable
var keyId = $"Key{id}";
var provider = user.GetTwoFactorProvider(TwoFactorProviderType.WebAuthn);
if (!provider?.MetaData?.ContainsKey("pending") ?? true)
if (provider?.MetaData is null || !provider.MetaData.TryGetValue("pending", out var pendingValue))
{
return false;
}
var options = CredentialCreateOptions.FromJson((string)provider.MetaData["pending"]);
var options = CredentialCreateOptions.FromJson((string)pendingValue);
// Callback to ensure credential ID is unique. Always return true since we don't care if another
// account uses the same 2FA key.
@ -1353,14 +1353,14 @@ public class UserService : UserManager<User>, IUserService, IDisposable
public void SetTwoFactorProvider(User user, TwoFactorProviderType type, bool setEnabled = true)
{
var providers = user.GetTwoFactorProviders();
if (!providers?.ContainsKey(type) ?? true)
if (providers is null || !providers.TryGetValue(type, out var provider))
{
return;
}
if (setEnabled)
{
providers[type].Enabled = true;
provider.Enabled = true;
}
user.SetTwoFactorProviders(providers);

View File

@ -637,9 +637,9 @@ public static class CoreHelpers
return null;
}
if (!globalSettings.SelfHosted && httpContext.Request.Headers.ContainsKey(RealConnectingIp))
if (!globalSettings.SelfHosted && httpContext.Request.Headers.TryGetValue(RealConnectingIp, out var realConnectingIp))
{
return httpContext.Request.Headers[RealConnectingIp].ToString();
return realConnectingIp.ToString();
}
return httpContext.Connection?.RemoteIpAddress?.ToString();

View File

@ -46,7 +46,7 @@ public static class LoggerFactoryExtensions
{
return true;
}
var eventId = e.Properties.ContainsKey("EventId") ? e.Properties["EventId"].ToString() : null;
var eventId = e.Properties.TryGetValue("EventId", out var eventIdValue) ? eventIdValue.ToString() : null;
if (eventId?.Contains(Constants.BypassFiltersEventId.ToString()) ?? false)
{
return true;

View File

@ -251,16 +251,17 @@ public class AzureAttachmentStorageService : IAttachmentStorageService
private async Task InitAsync(string containerName)
{
if (!_attachmentContainers.ContainsKey(containerName) || _attachmentContainers[containerName] == null)
if (!_attachmentContainers.TryGetValue(containerName, out var attachmentContainer) || attachmentContainer == null)
{
_attachmentContainers[containerName] = _blobServiceClient.GetBlobContainerClient(containerName);
attachmentContainer = _blobServiceClient.GetBlobContainerClient(containerName);
_attachmentContainers[containerName] = attachmentContainer;
if (containerName == "attachments")
{
await _attachmentContainers[containerName].CreateIfNotExistsAsync(PublicAccessType.Blob, null, null);
await attachmentContainer.CreateIfNotExistsAsync(PublicAccessType.Blob, null, null);
}
else
{
await _attachmentContainers[containerName].CreateIfNotExistsAsync(PublicAccessType.None, null, null);
await attachmentContainer.CreateIfNotExistsAsync(PublicAccessType.None, null, null);
}
}
}

View File

@ -312,13 +312,11 @@ public class CipherService : ICipherService
}
var attachments = cipher.GetAttachments();
if (!attachments.ContainsKey(attachmentId))
if (!attachments.TryGetValue(attachmentId, out var originalAttachmentMetadata))
{
throw new BadRequestException($"Cipher does not own specified attachment");
}
var originalAttachmentMetadata = attachments[attachmentId];
if (originalAttachmentMetadata.TempMetadata != null)
{
throw new BadRequestException("Another process is trying to migrate this attachment");
@ -395,12 +393,11 @@ public class CipherService : ICipherService
{
var attachments = cipher?.GetAttachments() ?? new Dictionary<string, CipherAttachment.MetaData>();
if (!attachments.ContainsKey(attachmentId))
if (!attachments.TryGetValue(attachmentId, out var data))
{
throw new NotFoundException();
}
var data = attachments[attachmentId];
var response = new AttachmentResponseData
{
Cipher = cipher,

View File

@ -69,9 +69,9 @@ public class CollectController : Controller
continue;
}
Cipher cipher = null;
if (ciphersCache.ContainsKey(eventModel.CipherId.Value))
if (ciphersCache.TryGetValue(eventModel.CipherId.Value, out var cachedCipher))
{
cipher = ciphersCache[eventModel.CipherId.Value];
cipher = cachedCipher;
}
else
{
@ -96,10 +96,7 @@ public class CollectController : Controller
continue;
}
}
if (!ciphersCache.ContainsKey(eventModel.CipherId.Value))
{
ciphersCache.Add(eventModel.CipherId.Value, cipher);
}
ciphersCache.TryAdd(eventModel.CipherId.Value, cipher);
cipherEvents.Add(new Tuple<Cipher, EventType, DateTime?>(cipher, eventModel.Type, eventModel.Date));
break;
case EventType.Organization_ClientExportedVault:

View File

@ -22,8 +22,8 @@ public class Program
return e.Level >= globalSettings.MinLogLevel.EventsSettings.IdentityToken;
}
if (e.Properties.ContainsKey("RequestPath") &&
!string.IsNullOrWhiteSpace(e.Properties["RequestPath"]?.ToString()) &&
if (e.Properties.TryGetValue("RequestPath", out var requestPath) &&
!string.IsNullOrWhiteSpace(requestPath?.ToString()) &&
(context.Contains(".Server.Kestrel") || context.Contains(".Core.IISHttpServer")))
{
return false;

View File

@ -13,9 +13,9 @@ public class DomainMappingService : IDomainMappingService
public string MapDomain(string hostname)
{
if (_map.ContainsKey(hostname))
if (_map.TryGetValue(hostname, out var mappedDomain))
{
return _map[hostname];
return mappedDomain;
}
return hostname;

View File

@ -240,7 +240,7 @@ public class TwoFactorAuthenticationValidator(
private bool OrgUsing2fa(IDictionary<Guid, OrganizationAbility> orgAbilities, Guid orgId)
{
return orgAbilities != null && orgAbilities.ContainsKey(orgId) &&
orgAbilities[orgId].Enabled && orgAbilities[orgId].Using2fa;
return orgAbilities != null && orgAbilities.TryGetValue(orgId, out var orgAbility) &&
orgAbility.Enabled && orgAbility.Using2fa;
}
}

View File

@ -120,9 +120,9 @@ public class Startup
// Pass domain_hint onto the sso idp
context.ProtocolMessage.DomainHint = context.Properties.Items["domain_hint"];
context.ProtocolMessage.Parameters.Add("organizationId", context.Properties.Items["organizationId"]);
if (context.Properties.Items.ContainsKey("user_identifier"))
if (context.Properties.Items.TryGetValue("user_identifier", out var userIdentifier))
{
context.ProtocolMessage.SessionState = context.Properties.Items["user_identifier"];
context.ProtocolMessage.SessionState = userIdentifier;
}
if (context.Properties.Parameters.Count > 0 &&

View File

@ -27,9 +27,9 @@ public class SutProvider<TSut> : ISutProvider
=> SetDependency(typeof(T), dependency, parameterName);
public SutProvider<TSut> SetDependency(Type dependencyType, object dependency, string parameterName = "")
{
if (_dependencies.ContainsKey(dependencyType))
if (_dependencies.TryGetValue(dependencyType, out var dependencyForType))
{
_dependencies[dependencyType][parameterName] = dependency;
dependencyForType[parameterName] = dependency;
}
else
{
@ -46,12 +46,11 @@ public class SutProvider<TSut> : ISutProvider
{
return _dependencies[dependencyType][parameterName];
}
else if (_dependencies.ContainsKey(dependencyType))
else if (_dependencies.TryGetValue(dependencyType, out var knownDependencies))
{
var knownDependencies = _dependencies[dependencyType];
if (knownDependencies.Values.Count == 1)
{
return _dependencies[dependencyType].Values.Single();
return knownDependencies.Values.Single();
}
else
{

View File

@ -20,30 +20,29 @@ public class Program
ParseParameters();
if (_context.Parameters.ContainsKey("q"))
if (_context.Parameters.TryGetValue("q", out var q))
{
_context.Quiet = _context.Parameters["q"] == "true" || _context.Parameters["q"] == "1";
_context.Quiet = q == "true" || q == "1";
}
if (_context.Parameters.ContainsKey("os"))
if (_context.Parameters.TryGetValue("os", out var os))
{
_context.HostOS = _context.Parameters["os"];
_context.HostOS = os;
}
if (_context.Parameters.ContainsKey("corev"))
if (_context.Parameters.TryGetValue("corev", out var coreVersion))
{
_context.CoreVersion = _context.Parameters["corev"];
_context.CoreVersion = coreVersion;
}
if (_context.Parameters.ContainsKey("webv"))
if (_context.Parameters.TryGetValue("webv", out var webVersion))
{
_context.WebVersion = _context.Parameters["webv"];
_context.WebVersion = webVersion;
}
if (_context.Parameters.ContainsKey("keyconnectorv"))
if (_context.Parameters.TryGetValue("keyconnectorv", out var keyConnectorVersion))
{
_context.KeyConnectorVersion = _context.Parameters["keyconnectorv"];
_context.KeyConnectorVersion = keyConnectorVersion;
}
if (_context.Parameters.ContainsKey("stub"))
if (_context.Parameters.TryGetValue("stub", out var stub))
{
_context.Stub = _context.Parameters["stub"] == "true" ||
_context.Parameters["stub"] == "1";
_context.Stub = stub == "true" || stub == "1";
}
Helpers.WriteLine(_context);
@ -68,18 +67,18 @@ public class Program
private static void Install()
{
if (_context.Parameters.ContainsKey("letsencrypt"))
if (_context.Parameters.TryGetValue("letsencrypt", out var sslManagedLetsEncrypt))
{
_context.Config.SslManagedLetsEncrypt =
_context.Parameters["letsencrypt"].ToLowerInvariant() == "y";
sslManagedLetsEncrypt.ToLowerInvariant() == "y";
}
if (_context.Parameters.ContainsKey("domain"))
if (_context.Parameters.TryGetValue("domain", out var domain))
{
_context.Install.Domain = _context.Parameters["domain"].ToLowerInvariant();
_context.Install.Domain = domain.ToLowerInvariant();
}
if (_context.Parameters.ContainsKey("dbname"))
if (_context.Parameters.TryGetValue("dbname", out var database))
{
_context.Install.Database = _context.Parameters["dbname"];
_context.Install.Database = database;
}
if (_context.Stub)