Class AuthService
- Namespace
- Builvero.Application.Services
- Assembly
- Builvero.Application.dll
Service for handling user authentication, including signup, login, email verification, and OAuth flows. Manages JWT token generation and user session creation.
public class AuthService : IAuthService
- Inheritance
-
AuthService
- Implements
- Inherited Members
Remarks
This service implements the complete authentication workflow:
- User signup with invitation code validation
- Email/password login with credential verification
- Email verification code generation and validation
- OAuth authentication (Google, LinkedIn) with account linking
- JWT token generation with role claims
Constructors
AuthService(IUserRepository, IInvitationRepository, IEmailVerificationCodeRepository, IOAuthAccountRepository, IPasswordHasher, IEmailService, ITokenGenerator, IOptions<JwtOptions>, IConfiguration, IS3Service, IHostEnvironment)
Initializes a new instance of the AuthService class.
public AuthService(IUserRepository userRepository, IInvitationRepository invitationRepository, IEmailVerificationCodeRepository verificationCodeRepository, IOAuthAccountRepository oauthAccountRepository, IPasswordHasher passwordHasher, IEmailService emailService, ITokenGenerator tokenGenerator, IOptions<JwtOptions> jwtOptions, IConfiguration configuration, IS3Service s3Service, IHostEnvironment environment)
Parameters
userRepositoryIUserRepositoryRepository for user data access
invitationRepositoryIInvitationRepositoryRepository for invitation code validation
verificationCodeRepositoryIEmailVerificationCodeRepositoryRepository for email verification codes
oauthAccountRepositoryIOAuthAccountRepositoryRepository for OAuth account linking
passwordHasherIPasswordHasherService for password hashing and verification
emailServiceIEmailServiceService for sending verification emails
tokenGeneratorITokenGeneratorService for generating JWT tokens
jwtOptionsIOptions<JwtOptions>JWT configuration options
configurationIConfigurationApplication configuration for building verification links
s3ServiceIS3ServiceService for S3 operations (profile photo management)
environmentIHostEnvironmentHosting environment for environment-aware behavior
Methods
GenerateJwtTokenAsync(Guid, string, string, string, CancellationToken)
Generates a JWT (JSON Web Token) for user authentication.
public Task<string> GenerateJwtTokenAsync(Guid userId, string email, string role, string status, CancellationToken cancellationToken = default)
Parameters
userIdGuidThe unique identifier of the user.
emailstringThe email address of the user.
rolestringThe role of the user (e.g., "User", "Admin", "Moderator").
statusstringThe status of the user account (e.g., "Active").
cancellationTokenCancellationTokenCancellation token to cancel the operation.
Returns
Remarks
The generated token includes the following claims:
- NameIdentifier: User's unique identifier (GUID)
- Email: User's email address
- Role: User's role
The token is signed using HMAC-SHA256 with a symmetric key from JWT configuration. Token expiration is set to 24 hours from generation time. The token issuer and audience are configured via JwtOptions.
HandleOAuthCallbackAsync(OAuthProvider, string, string, string?, string?, string?, CancellationToken)
Handles OAuth authentication callback from external providers (Google, LinkedIn, etc.).
public Task<AuthResponse> HandleOAuthCallbackAsync(OAuthProvider provider, string providerUserId, string email, string? name, string? photoUrl, string? invitationCode, CancellationToken cancellationToken = default)
Parameters
providerOAuthProviderThe OAuth provider (e.g., Google, LinkedIn).
providerUserIdstringThe unique user identifier from the OAuth provider.
emailstringThe email address from the OAuth provider.
namestringThe user's full name from the OAuth provider, if available.
photoUrlstringThe user's profile photo URL from the OAuth provider, if available.
invitationCodestringOptional invitation code for new user registration.
cancellationTokenCancellationTokenCancellation token to cancel the operation.
Returns
- Task<AuthResponse>
An AuthResponse containing the JWT token and user information.
Remarks
This method handles two scenarios:
- Existing OAuth Account: If an OAuth account already exists for this provider and provider user ID, the user is logged in immediately.
- New OAuth Account: If no OAuth account exists, the method checks if a user with the email exists:
- If user exists: Links the OAuth account to the existing user (supports mixed auth methods)
- If user doesn't exist: Creates a new user account (requires valid invitation code)
For new users, an invitation code is required. The user account is created with OAuth authentication method. If a profile photo URL is provided by the OAuth provider, it is stored as an external URL (legacy format). Profile photo URLs are automatically converted to presigned URLs when returned in responses.
Exceptions
- Exception
Thrown when:
- Account is disabled or blocked
- Invitation code is required for new users but is missing or invalid
- Email is already registered with a different authentication method
LoginAsync(LoginRequest, CancellationToken)
Authenticates a user with email and password credentials.
public Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken cancellationToken = default)
Parameters
requestLoginRequestThe login request containing email and password.
cancellationTokenCancellationTokenCancellation token to cancel the operation.
Returns
- Task<AuthResponse>
An AuthResponse containing the JWT token and user information.
Remarks
This method performs the following steps:
- Retrieves the user by email address
- Verifies the password hash using secure verification
- Checks account status (blocked/disabled accounts cannot log in)
- Updates the last login timestamp
- Generates a JWT token with user claims
- Maps profile photo URL to presigned URL if applicable
The response includes a flag indicating whether profile completion is required. Profile photo URLs are automatically converted to presigned URLs (15-minute TTL) for secure access.
Exceptions
- Exception
Thrown when:
- Email or password is invalid
- User account is blocked or disabled
SignupAsync(SignupRequest, CancellationToken)
Registers a new user account with email and password.
public Task<AuthResponse> SignupAsync(SignupRequest request, CancellationToken cancellationToken = default)
Parameters
requestSignupRequestThe signup request containing email, password, and invitation code
cancellationTokenCancellationTokenCancellation token to cancel the operation
Returns
- Task<AuthResponse>
An AuthResponse containing the JWT token and user information
Remarks
This method performs the following steps:
- Validates the invitation code and checks usage limits
- Checks if the email is already registered
- Hashes the password using secure hashing
- Creates a new user account with User role
- Increments the invitation usage count
- Generates and sends an email verification code
- Generates a JWT token for immediate authentication
The user account is created with status Active, but email verification is required. The response includes a flag indicating whether profile completion is required.
Exceptions
- Exception
Thrown when:
- Invitation code is missing or invalid
- Invitation code has been used up
- Email is already registered
- Password does not meet requirements
VerifyEmailAsync(VerifyEmailRequest, CancellationToken)
Verifies a user's email using a verification code and activates the account.
public Task<AuthResponse> VerifyEmailAsync(VerifyEmailRequest request, CancellationToken cancellationToken = default)
Parameters
requestVerifyEmailRequest- Service for handling user authentication, including signup, login, email verification, and OAuth flows. Manages JWT token generation and user session creation.
cancellationTokenCancellationToken- Service for handling user authentication, including signup, login, email verification, and OAuth flows. Manages JWT token generation and user session creation.
Returns
- Task<AuthResponse>
- Service for handling user authentication, including signup, login, email verification, and OAuth flows. Manages JWT token generation and user session creation.