1
0
mirror of https://github.com/bitwarden/server synced 2025-12-21 02:33:30 +00:00
Files
server/src/Core/Services/IUserService.cs
Rui Tomé f7c615cc01 [PM-21411] Refactor interface for determining premium status and features (#6688)
* Removed 2FA user interface from premium method signatures

* Added some more comments for clarity and small touchups.

* Add PremiumAccessCacheCheck feature flag to Constants.cs

* Add IPremiumAccessQuery interface and PremiumAccessQuery implementation for checking user premium access status

* Add unit tests for PremiumAccessQuery to validate user premium access logic

* Add XML documentation to Premium in OrganizationUserUserDetails and User classes

* Add PremiumAccessQueries to UserServiceCollectionExtensions

* Refactor TwoFactorIsEnabledQuery to incorporate PremiumAccessQuery and feature flag for premium access checks. Enhanced user premium status retrieval logic and improved handling of user details based on feature flag state.

* Mark methods in IUserRepository and IUserService as obsolete, directing users to new methods in IPremiumAccessQuery for premium access checks.

* Rename CanAccessPremiumBulkAsync to CanAccessPremiumAsync in IPremiumAccessQuery

* Update TwoFactorIsEnabledQuery to use CanAccessPremiumAsync for premium status checks

* Refactor TwoFactorIsEnabledQuery to introduce VNextAsync methods for improved premium access checks and user detail handling. Removed obsolete feature service dependency and enhanced test coverage for new functionality.

* Refactor IPremiumAccessQuery and PremiumAccessQuery to remove the overloaded CanAccessPremiumAsync method. Update related methods to streamline premium access checks using the User object directly. Enhance test coverage by removing obsolete tests and ensuring proper functionality with the new method signatures.

* Add new sync static method to determine if TwoFactor is enabled

* Enhance XML documentation for Premium property in OrganizationUserUserDetails and User classes to clarify its usage and limitations regarding personal and organizational premium access.

* Refactor IPremiumAccessQuery and PremiumAccessQuery to replace User parameter with Guid for user ID in CanAccessPremiumAsync methods. Update related methods and tests to streamline premium access checks and improve clarity in method signatures.

* Update feature flag references in IUserRepository and IUserService to use 'PremiumAccessQuery' instead of 'PremiumAccessCacheCheck'. Adjust related XML documentation for clarity on premium access methods.

* Rename IPremiumAccessQuery to IHasPremiumAccessQuery and move to Billing owned folder

* Remove unnecessary whitespace from IHasPremiumAccessQuery interface.

* Refactor HasPremiumAccessQuery to throw NotFoundException for null users

* Add NotFoundException handling in HasPremiumAccessQuery for mismatched user counts

* Refactor TwoFactorIsEnabledQuery to optimize premium access checks and improve two-factor provider handling. Introduced bulk fetching of premium status for users with only premium providers and streamlined the logic for determining if two-factor authentication is enabled.

* Refactor TwoFactorIsEnabledQueryTests to enhance clarity and optimize test scenarios. Consolidated test cases for two-factor authentication, improved naming conventions, and ensured premium access checks are only performed when necessary.

* Add UserPremiumAccess model to represent user premium access status from personal subscriptions and memberships

* Add User_ReadPremiumAccessByIds stored procedure and UserPremiumAccessView view to enhance premium access retrieval. Updated Organization table index to include UsersGetPremium for optimized queries.

* Add SQL migration script

* Add premium access retrieval methods to IUserRepository and implementations in UserRepository classes. Introduced GetPremiumAccessByIdsAsync and GetPremiumAccessAsync methods to fetch premium status for multiple users and a single user, respectively. Updated using directives to include necessary models.

* Refactor HasPremiumAccessQuery and IHasPremiumAccessQuery to streamline premium access checks. Updated method names for clarity and improved documentation. Adjusted test cases to reflect changes in user premium access retrieval logic.

* Update IUserRepository to reflect new method names for premium access retrieval. Changed obsolete method messages to point to GetPremiumAccessByIdsAsync and GetPremiumAccessAsync. Added internal use notes for IHasPremiumAccessQuery. Improved documentation for clarity.

* Refactor TwoFactorIsEnabledQuery to utilize IFeatureService for premium access checks.

* Enhance EF UserRepository to improve premium access retrieval by including related organization data.

* Add unit tests for premium access retrieval in UserRepositoryTests.

* Optimize HasPremiumAccessQuery to eliminate duplicate user IDs before checking premium access. Updated logic to ensure accurate comparison of premium users against distinct user IDs.

* Refactor TwoFactorIsEnabledQuery to improve handling of users without two-factor providers. Added early exit for users lacking providers and streamlined premium status checks for enabled two-factor authentication.

* Update HasPremiumAccessQueryTests to use simplified exception handling and improve test clarity

* Replaced fully qualified exception references with simplified ones.
* Refactored test setup to use individual user variables for better readability.
* Ensured assertions reflect the updated user variable structure.

* Enhance TwoFactorIsEnabledQuery to throw NotFoundException for non-existent users

* Updated TwoFactorIsEnabledQuery to throw NotFoundException when a user is not found instead of returning false.
* Added a new unit test to verify that the NotFoundException is thrown when a user is not found while premium access query is enabled.

* Move premium access query to Billing owned ServiceCollectionExtensions

* Refactor IUserService to enhance premium access checks

* Updated CanAccessPremium and HasPremiumFromOrganization methods to clarify usage with the new premium access query.
* Integrated IHasPremiumAccessQuery into UserService for improved premium access handling based on feature flag.
* Adjusted method documentation to reflect changes in premium access logic.

* Update IUserRepository to clarify usage of premium access methods

* Modified Obsolete attribute messages for GetManyWithCalculatedPremiumAsync and GetCalculatedPremiumAsync to indicate that callers should use the new methods when the 'PremiumAccessQuery' feature flag is enabled.
* Enhanced documentation to improve clarity regarding premium access handling.

* Update IUserRepository and IUserService to clarify deprecation of premium access methods

* Modified Obsolete attribute messages for GetManyWithCalculatedPremiumAsync and GetCalculatedPremiumAsync in IUserRepository to indicate these methods will be removed in a future version.
* Updated Obsolete attribute message for HasPremiumFromOrganization in IUserService to reflect the same deprecation notice.

* Refactor TwoFactorIsEnabledQuery to streamline user ID retrieval

* Consolidated user ID retrieval logic to avoid redundancy.
* Ensured consistent handling of user ID checks for premium access queries.
* Improved code readability by reducing duplicate code blocks.

* Rename migration script to fix the date

* Update migration script to create the index with DROP_EXISTING = ON

* Refactor UserPremiumAccessView to use LEFT JOINs and GROUP BY for improved performance and clarity

* Update HasPremiumAccessQueryTests to return null for GetPremiumAccessAsync instead of throwing NotFoundException

* Add unit tests for premium access scenarios in UserRepositoryTests

- Implement tests for GetPremiumAccessAsync to cover various user and organization premium access combinations.
- Validate behavior when users belong to multiple organizations, including cases with and without premium access.
- Update email generation for user creation to ensure uniqueness without specific prefixes.
- Enhance assertions to verify expected premium access results across different test cases.

* Bump date on migration script

* Update OrganizationEntityTypeConfiguration to include UsersGetPremium in index properties

* Add migration scripts for OrganizationUsersGetPremiumIndex across MySQL, PostgreSQL, and SQLite

- Introduced new migration files to create the OrganizationUsersGetPremiumIndex.
- Updated the DatabaseContextModelSnapshot to include UsersGetPremium in index properties for all database types.
- Ensured consistency in index creation across different database implementations.

---------

Co-authored-by: Todd Martin <tmartin@bitwarden.com>
Co-authored-by: Patrick Pimentel <ppimentel@bitwarden.com>
2025-12-16 10:31:56 +00:00

146 lines
7.7 KiB
C#

// FIXME: Update this file to be null safe and then delete the line below
#nullable disable
using System.Security.Claims;
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Auth.Enums;
using Bit.Core.Billing.Models.Business;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Models.Business;
using Fido2NetLib;
using Microsoft.AspNetCore.Identity;
namespace Bit.Core.Services;
public interface IUserService
{
Guid? GetProperUserId(ClaimsPrincipal principal);
Task<User> GetUserByIdAsync(string userId);
Task<User> GetUserByIdAsync(Guid userId);
Task<User> GetUserByPrincipalAsync(ClaimsPrincipal principal);
Task<DateTime> GetAccountRevisionDateByIdAsync(Guid userId);
Task SaveUserAsync(User user, bool push = false);
Task<IdentityResult> CreateUserAsync(User user);
Task<IdentityResult> CreateUserAsync(User user, string masterPasswordHash);
Task SendMasterPasswordHintAsync(string email);
Task<CredentialCreateOptions> StartWebAuthnRegistrationAsync(User user);
Task<bool> DeleteWebAuthnKeyAsync(User user, int id);
Task<bool> CompleteWebAuthRegistrationAsync(User user, int value, string name, AuthenticatorAttestationRawResponse attestationResponse);
Task SendEmailVerificationAsync(User user);
Task<IdentityResult> ConfirmEmailAsync(User user, string token);
Task InitiateEmailChangeAsync(User user, string newEmail);
Task<IdentityResult> ChangeEmailAsync(User user, string masterPassword, string newEmail, string newMasterPassword,
string token, string key);
Task<IdentityResult> ChangePasswordAsync(User user, string masterPassword, string newMasterPassword, string passwordHint, string key);
Task<IdentityResult> SetKeyConnectorKeyAsync(User user, string key, string orgIdentifier);
Task<IdentityResult> ConvertToKeyConnectorAsync(User user);
Task<IdentityResult> AdminResetPasswordAsync(OrganizationUserType type, Guid orgId, Guid id, string newMasterPassword, string key);
Task<IdentityResult> UpdateTempPasswordAsync(User user, string newMasterPassword, string key, string hint);
Task<IdentityResult> RefreshSecurityStampAsync(User user, string masterPasswordHash);
Task UpdateTwoFactorProviderAsync(User user, TwoFactorProviderType type, bool setEnabled = true, bool logEvent = true);
Task DisableTwoFactorProviderAsync(User user, TwoFactorProviderType type);
Task<IdentityResult> DeleteAsync(User user);
Task<IdentityResult> DeleteAsync(User user, string token);
Task SendDeleteConfirmationAsync(string email);
Task<Tuple<bool, string>> SignUpPremiumAsync(User user, string paymentToken,
PaymentMethodType paymentMethodType, short additionalStorageGb, UserLicense license,
TaxInfo taxInfo);
Task UpdateLicenseAsync(User user, UserLicense license);
Task<string> AdjustStorageAsync(User user, short storageAdjustmentGb);
Task ReplacePaymentMethodAsync(User user, string paymentToken, PaymentMethodType paymentMethodType, TaxInfo taxInfo);
Task CancelPremiumAsync(User user, bool? endOfPeriod = null);
Task ReinstatePremiumAsync(User user);
Task EnablePremiumAsync(Guid userId, DateTime? expirationDate);
Task DisablePremiumAsync(Guid userId, DateTime? expirationDate);
Task UpdatePremiumExpirationAsync(Guid userId, DateTime? expirationDate);
Task<UserLicense> GenerateLicenseAsync(User user, SubscriptionInfo subscriptionInfo = null,
int? version = null);
Task<bool> CheckPasswordAsync(User user, string password);
/// <summary>
/// Checks if the user has access to premium features, either through a personal subscription or through an organization.
///
/// This is the preferred way to definitively know if a user has access to premium features when you already have the User object.
/// </summary>
/// <param name="user">user being acted on</param>
/// <returns>true if they can access premium; false otherwise.</returns>
Task<bool> CanAccessPremium(User user);
/// <summary>
/// Checks if the user has inherited access to premium features through an organization.
///
/// This primarily serves as a means to communicate to the client when a user has inherited their premium status
/// through an organization. Feature gating logic probably should not be behind this check.
/// </summary>
/// <param name="user">user being acted on</param>
/// <returns>true if they can access premium because of organization membership; false otherwise.</returns>
[Obsolete("Use IHasPremiumAccessQuery.HasPremiumFromOrganizationAsync instead. This method will be removed in a future version.")]
Task<bool> HasPremiumFromOrganization(User user);
Task<string> GenerateSignInTokenAsync(User user, string purpose);
Task<IdentityResult> UpdatePasswordHash(User user, string newPassword,
bool validatePassword = true, bool refreshStamp = true);
Task RotateApiKeyAsync(User user);
string GetUserName(ClaimsPrincipal principal);
Task SendOTPAsync(User user);
Task<bool> VerifyOTPAsync(User user, string token);
Task<bool> VerifySecretAsync(User user, string secret, bool isSettingMFA = false);
/// <summary>
/// We use this method to check if the user has an active new device verification bypass
/// </summary>
/// <param name="userId">self</param>
/// <returns>returns true if the value is found in the cache</returns>
Task<bool> ActiveNewDeviceVerificationException(Guid userId);
/// <summary>
/// We use this method to toggle the new device verification bypass
/// </summary>
/// <param name="userId">Id of user bypassing new device verification</param>
Task ToggleNewDeviceVerificationException(Guid userId);
void SetTwoFactorProvider(User user, TwoFactorProviderType type, bool setEnabled = true);
/// <summary>
/// This method is used by the TwoFactorAuthenticationValidator to recover two
/// factor for a user. This allows users to be logged in after a successful recovery
/// attempt.
///
/// This method logs the event, sends an email to the user, and removes two factor
/// providers on the user account. This means that a user will have to accomplish
/// new device verification on their account on new logins, if it is enabled for their user.
/// </summary>
/// <param name="recoveryCode">recovery code associated with the user logging in</param>
/// <param name="user">The user to refresh the 2FA and Recovery Code on.</param>
/// <returns>true if the recovery code is valid; false otherwise</returns>
Task<bool> RecoverTwoFactorAsync(User user, string recoveryCode);
/// <summary>
/// Returns true if the user is a legacy user. Legacy users use their master key as their
/// encryption key. We force these users to the web to migrate their encryption scheme.
/// </summary>
Task<bool> IsLegacyUser(string userId);
/// <summary>
/// Indicates if the user is managed by any organization.
/// </summary>
/// <remarks>
/// A user is considered managed by an organization if their email domain matches one of the
/// verified domains of that organization, and the user is a member of it.
/// The organization must be enabled and able to have verified domains.
/// </remarks>
Task<bool> IsClaimedByAnyOrganizationAsync(Guid userId);
/// <summary>
/// Verify whether the new email domain meets the requirements for managed users.
/// </summary>
/// <returns>
/// IdentityResult
/// </returns>
Task<IdentityResult> ValidateClaimedUserDomainAsync(User user, string newEmail);
/// <summary>
/// Gets the organizations that manage the user.
/// </summary>
/// <inheritdoc cref="IsClaimedByAnyOrganizationAsync"/>
Task<IEnumerable<Organization>> GetOrganizationsClaimingUserAsync(Guid userId);
}