refactor(auth): cleanup auth module and streamline the registration flow

This commit is contained in:
2025-06-18 16:50:11 -04:00
parent 25b94d3e02
commit cdcfe8d7e2
24 changed files with 2140 additions and 1387 deletions

View File

@@ -35,21 +35,22 @@ public static class DependencyInjection
// Scoped services // Scoped services
builder.Services.AddScoped<IdentityService>(); builder.Services.AddScoped<IdentityService>();
builder.Services.AddTransient<IUserLookup, UserLookup>(); builder.Services.AddScoped<EmailVerificationService>();
builder.Services.AddScoped<IUserLookup, UserLookup>();
return builder; return builder;
} }
public static async Task<IApplicationBuilder> UseIdentityModuleAsync( public static async Task<IApplicationBuilder> UseIdentityModuleAsync(
this IApplicationBuilder app, this IApplicationBuilder app,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>(); IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope(); using IServiceScope scope = scopeFactory.CreateScope();
await using var context = scope.ServiceProvider.GetRequiredService<IdentityDbContext>(); await using IdentityDbContext context = scope.ServiceProvider.GetRequiredService<IdentityDbContext>();
await context.Database.MigrateAsync(cancellationToken: cancellationToken); await context.Database.MigrateAsync(cancellationToken);
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<Role>>(); RoleManager<Role> roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<Role>>();
await TrySeedAsync(roleManager); await TrySeedAsync(roleManager);
return app; return app;
@@ -57,13 +58,13 @@ public static class DependencyInjection
private static async Task TrySeedAsync(RoleManager<Role> roleManager) private static async Task TrySeedAsync(RoleManager<Role> roleManager)
{ {
var administratorRole = new Role(KnownRoles.Administrator); Role administratorRole = new(KnownRoles.Administrator);
if (roleManager.Roles.All(r => r.Name != administratorRole.Name)) if (roleManager.Roles.All(r => r.Name != administratorRole.Name))
{ {
await roleManager.CreateAsync(administratorRole); await roleManager.CreateAsync(administratorRole);
} }
var roleCreator = new Role(KnownRoles.Creator); Role roleCreator = new(KnownRoles.Creator);
if (roleManager.Roles.All(r => r.Name != roleCreator.Name)) if (roleManager.Roles.All(r => r.Name != roleCreator.Name))
{ {
await roleManager.CreateAsync(roleCreator); await roleManager.CreateAsync(roleCreator);

View File

@@ -1,4 +1,3 @@
using System.Text;
using System.Web; using System.Web;
using Hutopy.Infrastructure.Configuration; using Hutopy.Infrastructure.Configuration;
using Hutopy.Infrastructure.Emailer.Contracts; using Hutopy.Infrastructure.Emailer.Contracts;
@@ -30,7 +29,7 @@ public class ForgotPasswordHandler(
CancellationToken ct) CancellationToken ct)
{ {
// Find user by email // Find user by email
var user = await userManager.FindByEmailAsync(request.Email); User? user = await userManager.FindByEmailAsync(request.Email);
// Always return OK even if user not found to prevent email enumeration // Always return OK even if user not found to prevent email enumeration
if (user is null) if (user is null)
@@ -40,22 +39,50 @@ public class ForgotPasswordHandler(
} }
// Generate password reset token // Generate password reset token
var token = await userManager.GeneratePasswordResetTokenAsync(user); string token = await userManager.GeneratePasswordResetTokenAsync(user);
// URL encode the token as it may contain characters that are not URL safe // URL encode the token as it may contain characters that are not URL safe
var encodedToken = HttpUtility.UrlEncode(token); string encodedToken = HttpUtility.UrlEncode(token);
// Build reset link // Build reset link
var resetLink = $"{options.Value.FrontendBaseUrl}/reset-password?email={HttpUtility.UrlEncode(request.Email)}&token={encodedToken}"; string resetLink =
$"{options.Value.FrontendBaseUrl}/reset-password?email={HttpUtility.UrlEncode(request.Email)}&token={encodedToken}";
// TODO: Write a better email template // Create a styled email message
var subject = "Reset Your Password"; string subject = "Reset your Hutopy password";
var message = new StringBuilder() string message = $"""
.AppendLine("<h1>Reset Your Password</h1>") <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333;">
.AppendLine("<p>Please click the link below to reset your password:</p>") <h1 style="color: #2c3e50; margin-bottom: 20px;">Reset Your Hutopy Password</h1>
.AppendLine($"<p><a href=\"{resetLink}\">Reset Password</a></p>")
.AppendLine("<p>If you did not request a password reset, please ignore this email.</p>") <p style="font-size: 16px; line-height: 1.5; margin-bottom: 25px;">
.ToString(); Please click the button below to reset your password:
</p>
<div style="text-align: center; margin: 30px 0;">
<a href='{resetLink}'
style="background-color: #3498db;
color: white;
text-decoration: none;
padding: 12px 24px;
border-radius: 4px;
font-weight: bold;
display: inline-block;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
Reset Password
</a>
</div>
<p style="font-size: 14px; color: #7f8c8d; margin-top: 30px;">
If you did not request a password reset, please ignore this email.
</p>
<p style="font-size: 14px; color: #7f8c8d; margin-top: 20px;">
If the button doesn't work, you can copy and paste this link into your browser:
<br>
<a href='{resetLink}' style="color: #3498db; word-break: break-all;">{resetLink}</a>
</p>
</div>
""";
// Send email // Send email
await emailSender.SendEmailAsync(request.Email, subject, message); await emailSender.SendEmailAsync(request.Email, subject, message);

View File

@@ -32,8 +32,8 @@ public class LoginHandler(
LoginRequest request, LoginRequest request,
CancellationToken ct) CancellationToken ct)
{ {
// Find user by email // Find the user by email
var user = await userManager.FindByEmailAsync(request.Email); User? user = await userManager.FindByEmailAsync(request.Email);
if (user is null) if (user is null)
{ {
await SendStringAsync( await SendStringAsync(
@@ -44,7 +44,7 @@ public class LoginHandler(
} }
// Verify password // Verify password
var isPasswordValid = await userManager.CheckPasswordAsync(user, request.Password); bool isPasswordValid = await userManager.CheckPasswordAsync(user, request.Password);
if (!isPasswordValid) if (!isPasswordValid)
{ {
await SendStringAsync( await SendStringAsync(
@@ -54,26 +54,36 @@ public class LoginHandler(
return; return;
} }
// Generate new refresh token // Check if the email is confirmed
if (!user.EmailConfirmed)
{
await SendStringAsync(
"Email not verified. Please check your email for verification instructions.",
401,
cancellation: ct);
return;
}
// Generate a new refresh token
user.RefreshToken = RefreshTokenGenerator.Next(); user.RefreshToken = RefreshTokenGenerator.Next();
user.RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime); user.RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime);
await userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
// Generate JWT token // Generate JWT token
var accessToken = JwtTokenHelper.GenerateJwtToken( string accessToken = JwtTokenHelper.GenerateJwtToken(
expiresIn: jwtOptions.Value.Lifetime, jwtOptions.Value.Lifetime,
issuer: jwtOptions.Value.Issuer, jwtOptions.Value.Issuer,
audience: jwtOptions.Value.Audience, jwtOptions.Value.Audience,
key: jwtOptions.Value.Key, jwtOptions.Value.Key,
userId: user.Id.ToString(), user.Id.ToString(),
email: user.Email ?? string.Empty, user.Email ?? string.Empty,
alias: user.Alias, user.Alias,
firstname: user.Firstname ?? string.Empty, user.Firstname ?? string.Empty,
lastname: user.Lastname ?? string.Empty, user.Lastname ?? string.Empty,
portraitUrl: user.PortraitUrl); user.PortraitUrl);
await SendOkAsync( await SendOkAsync(
new LoginResponse(accessToken, user.RefreshToken), new LoginResponse(accessToken, user.RefreshToken),
cancellation: ct); ct);
} }
} }

View File

@@ -3,6 +3,7 @@ using System.Text.Json.Serialization;
using Hutopy.Infrastructure.Security; using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Configuration; using Hutopy.Modules.Identity.Configuration;
using Hutopy.Modules.Identity.Data; using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Hutopy.Modules.Identity.Handlers; namespace Hutopy.Modules.Identity.Handlers;
@@ -56,8 +57,8 @@ public class LoginWithFacebookHandler(
CancellationToken ct) CancellationToken ct)
{ {
// Verify the token with Facebook // Verify the token with Facebook
using var httpClient = httpClientFactory.CreateClient(); using HttpClient httpClient = httpClientFactory.CreateClient();
using var response = await httpClient.GetAsync( using HttpResponseMessage response = await httpClient.GetAsync(
$"https://graph.facebook.com/me?access_token={request.Token}&fields=id,name,email,picture.width(200).height(200)", $"https://graph.facebook.com/me?access_token={request.Token}&fields=id,name,email,picture.width(200).height(200)",
ct); ct);
if (!response.IsSuccessStatusCode) if (!response.IsSuccessStatusCode)
@@ -70,8 +71,8 @@ public class LoginWithFacebookHandler(
} }
// Extract the user info (email, name, profile picture) // Extract the user info (email, name, profile picture)
var content = await response.Content.ReadAsStringAsync(ct); string content = await response.Content.ReadAsStringAsync(ct);
var userInfo = JsonSerializer.Deserialize<FacebookUserInfo>(content); FacebookUserInfo? userInfo = JsonSerializer.Deserialize<FacebookUserInfo>(content);
if (userInfo is null || string.IsNullOrEmpty(userInfo.Id)) if (userInfo is null || string.IsNullOrEmpty(userInfo.Id))
{ {
await SendStringAsync( await SendStringAsync(
@@ -82,23 +83,24 @@ public class LoginWithFacebookHandler(
} }
// Check if user exists or create a new one // Check if user exists or create a new one
var user = await userManager.FindByEmailAsync(userInfo.Email!); User? user = await userManager.FindByEmailAsync(userInfo.Email!);
if (user is null) if (user is null)
{ {
var generatedPassword = PasswordGenerator.Next(); string generatedPassword = PasswordGenerator.Next();
var generatedUser = new User User generatedUser = new()
{ {
UserName = userInfo.Email ?? $"fb_{userInfo.Id}", UserName = userInfo.Email ?? $"fb_{userInfo.Id}",
Email = userInfo.Email, Email = userInfo.Email,
EmailConfirmed = true,
Firstname = userInfo.Name.Split(' ').FirstOrDefault() ?? "", Firstname = userInfo.Name.Split(' ').FirstOrDefault() ?? "",
Lastname = userInfo.Name.Split(' ').Skip(1).FirstOrDefault() ?? "", Lastname = userInfo.Name.Split(' ').Skip(1).FirstOrDefault() ?? "",
Alias = userInfo.Name, Alias = userInfo.Name,
PortraitUrl = userInfo.Picture.Picture.Url, PortraitUrl = userInfo.Picture.Picture.Url,
FacebookId = userInfo.Id, // Storing Facebook ID FacebookId = userInfo.Id // Storing Facebook ID
}; };
var result = await userManager.CreateAsync( IdentityResult result = await userManager.CreateAsync(
generatedUser, generatedUser,
generatedPassword); generatedPassword);
@@ -115,27 +117,27 @@ public class LoginWithFacebookHandler(
} }
// Generate refresh token // Generate refresh token
var refreshToken = RefreshTokenGenerator.Next(); string refreshToken = RefreshTokenGenerator.Next();
// Store refresh token in user's properties // Store refresh token in user's properties
user.RefreshToken = refreshToken; user.RefreshToken = refreshToken;
user.RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime); user.RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime);
await userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
var accessToken = JwtTokenHelper.GenerateJwtToken( string accessToken = JwtTokenHelper.GenerateJwtToken(
expiresIn: jwtOptions.Value.Lifetime, jwtOptions.Value.Lifetime,
issuer: jwtOptions.Value.Issuer, jwtOptions.Value.Issuer,
audience: jwtOptions.Value.Audience, jwtOptions.Value.Audience,
key: jwtOptions.Value.Key, jwtOptions.Value.Key,
userId: user.Id.ToString(), user.Id.ToString(),
email: user.Email ?? string.Empty, user.Email ?? string.Empty,
alias: user.Alias, user.Alias,
firstname: user.Firstname ?? string.Empty, user.Firstname ?? string.Empty,
lastname: user.Lastname ?? string.Empty, user.Lastname ?? string.Empty,
portraitUrl: user.PortraitUrl); user.PortraitUrl);
await SendOkAsync( await SendOkAsync(
new LoginWithFacebookResponse(accessToken, refreshToken), new LoginWithFacebookResponse(accessToken, refreshToken),
cancellation: ct); ct);
} }
} }

View File

@@ -3,11 +3,12 @@ using System.Text.Json.Serialization;
using Hutopy.Infrastructure.Security; using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Configuration; using Hutopy.Modules.Identity.Configuration;
using Hutopy.Modules.Identity.Data; using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Hutopy.Modules.Identity.Handlers; namespace Hutopy.Modules.Identity.Handlers;
class GoogleToken internal class GoogleToken
{ {
[JsonPropertyName("access_token")] public required string AccessToken { get; init; } [JsonPropertyName("access_token")] public required string AccessToken { get; init; }
[JsonPropertyName("token_type")] public required string TokenType { get; init; } [JsonPropertyName("token_type")] public required string TokenType { get; init; }
@@ -55,11 +56,11 @@ public class LoginWithGoogleHandler(
LoginWithGoogleRequest request, LoginWithGoogleRequest request,
CancellationToken ct) CancellationToken ct)
{ {
var googleToken = JsonSerializer.Deserialize<GoogleToken>(request.Token)!; GoogleToken googleToken = JsonSerializer.Deserialize<GoogleToken>(request.Token)!;
// Verify the token with Google // Verify the token with Google
using var httpClient = httpClientFactory.CreateClient(); using HttpClient httpClient = httpClientFactory.CreateClient();
using var response = await httpClient.GetAsync( using HttpResponseMessage response = await httpClient.GetAsync(
$"https://www.googleapis.com/oauth2/v1/userinfo?access_token={googleToken.AccessToken}", $"https://www.googleapis.com/oauth2/v1/userinfo?access_token={googleToken.AccessToken}",
ct); ct);
if (!response.IsSuccessStatusCode) if (!response.IsSuccessStatusCode)
@@ -72,8 +73,8 @@ public class LoginWithGoogleHandler(
} }
// Extract the user info (email, name, etc.). // Extract the user info (email, name, etc.).
var content = await response.Content.ReadAsStringAsync(ct); string content = await response.Content.ReadAsStringAsync(ct);
var userInfo = JsonSerializer.Deserialize<GoogleUserInfo>(content); GoogleUserInfo? userInfo = JsonSerializer.Deserialize<GoogleUserInfo>(content);
if (userInfo is null if (userInfo is null
|| !userInfo.VerifiedEmail || !userInfo.VerifiedEmail
|| string.IsNullOrEmpty(userInfo.Email)) || string.IsNullOrEmpty(userInfo.Email))
@@ -85,17 +86,18 @@ public class LoginWithGoogleHandler(
return; return;
} }
// Check if user exists or create a new one // Check if the user exists or create a new one
var user = await userManager.FindByEmailAsync(userInfo.Email); User? user = await userManager.FindByEmailAsync(userInfo.Email);
if (user is null) if (user is null)
{ {
var generatedPassword = PasswordGenerator.Next(); string generatedPassword = PasswordGenerator.Next();
var refreshToken = RefreshTokenGenerator.Next(); string refreshToken = RefreshTokenGenerator.Next();
var generatedUser = new User User generatedUser = new()
{ {
UserName = userInfo.Email, UserName = userInfo.Email,
Email = userInfo.Email, Email = userInfo.Email,
EmailConfirmed = true,
Firstname = userInfo.GivenName, Firstname = userInfo.GivenName,
Lastname = userInfo.FamilyName, Lastname = userInfo.FamilyName,
Alias = userInfo.Name, Alias = userInfo.Name,
@@ -105,7 +107,7 @@ public class LoginWithGoogleHandler(
RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime) RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime)
}; };
var result = await userManager.CreateAsync( IdentityResult result = await userManager.CreateAsync(
generatedUser, generatedUser,
generatedPassword); generatedPassword);
@@ -121,25 +123,25 @@ public class LoginWithGoogleHandler(
user = generatedUser; user = generatedUser;
} }
// Generate new refresh token // Generate the new refresh token
user.RefreshToken = RefreshTokenGenerator.Next(); user.RefreshToken = RefreshTokenGenerator.Next();
user.RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime); user.RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime);
await userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
var accessToken = JwtTokenHelper.GenerateJwtToken( string accessToken = JwtTokenHelper.GenerateJwtToken(
expiresIn: jwtOptions.Value.Lifetime, jwtOptions.Value.Lifetime,
issuer: jwtOptions.Value.Issuer, jwtOptions.Value.Issuer,
audience: jwtOptions.Value.Audience, jwtOptions.Value.Audience,
key: jwtOptions.Value.Key, jwtOptions.Value.Key,
userId: user.Id.ToString(), user.Id.ToString(),
email: user.Email ?? string.Empty, user.Email ?? string.Empty,
alias: user.Alias, user.Alias,
firstname: user.Firstname ?? string.Empty, user.Firstname ?? string.Empty,
lastname: user.Lastname ?? string.Empty, user.Lastname ?? string.Empty,
portraitUrl: user.PortraitUrl); user.PortraitUrl);
await SendOkAsync( await SendOkAsync(
new LoginWithGoogleResponse(accessToken, user.RefreshToken), new LoginWithGoogleResponse(accessToken, user.RefreshToken),
cancellation: ct); ct);
} }
} }

View File

@@ -1,7 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Configuration;
using Hutopy.Modules.Identity.Data; using Hutopy.Modules.Identity.Data;
using Microsoft.Extensions.Options; using Hutopy.Modules.Identity.Services;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers; namespace Hutopy.Modules.Identity.Handlers;
@@ -13,13 +12,12 @@ public record RegisterRequest(
[PublicAPI] [PublicAPI]
public record RegisterResponse( public record RegisterResponse(
string AccessToken, string Message);
string RefreshToken);
[PublicAPI] [PublicAPI]
public class RegisterHandler( public class RegisterHandler(
UserManager userManager, UserManager userManager,
IOptionsSnapshot<JwtOptions> jwtOptions) EmailVerificationService emailVerificationService)
: Endpoint<RegisterRequest, RegisterResponse> : Endpoint<RegisterRequest, RegisterResponse>
{ {
public override void Configure() public override void Configure()
@@ -34,7 +32,7 @@ public class RegisterHandler(
CancellationToken ct) CancellationToken ct)
{ {
// Check if the user already exists // Check if the user already exists
var existingUser = await userManager.FindByEmailAsync(request.Email); User? existingUser = await userManager.FindByEmailAsync(request.Email);
if (existingUser is not null) if (existingUser is not null)
{ {
await SendStringAsync( await SendStringAsync(
@@ -44,27 +42,22 @@ public class RegisterHandler(
return; return;
} }
// Create a refresh token
var refreshToken = RefreshTokenGenerator.Next();
// Split the name into firstname and lastname (if provided) // Split the name into firstname and lastname (if provided)
var nameParts = request.Name.Split(' ', 2); string[] nameParts = request.Name.Split(' ', 2);
var firstname = nameParts[0]; string firstname = nameParts[0];
var lastname = nameParts.Length > 1 ? nameParts[1] : string.Empty; string lastname = nameParts.Length > 1 ? nameParts[1] : string.Empty;
// Create a new user // Create a new user
var user = new User User user = new()
{ {
UserName = request.Email, UserName = request.Email,
Email = request.Email, Email = request.Email,
Firstname = firstname, Firstname = firstname,
Lastname = lastname, Lastname = lastname,
Alias = request.Name, Alias = request.Name
RefreshToken = refreshToken,
RefreshTokenExpiryTime = DateTime.UtcNow.Add(jwtOptions.Value.RefreshTokenLifetime)
}; };
var result = await userManager.CreateAsync( IdentityResult result = await userManager.CreateAsync(
user, user,
request.Password); request.Password);
@@ -77,21 +70,10 @@ public class RegisterHandler(
return; return;
} }
// Generate JWT token await emailVerificationService.SendVerificationEmailAsync(user);
var accessToken = JwtTokenHelper.GenerateJwtToken(
expiresIn: jwtOptions.Value.Lifetime,
issuer: jwtOptions.Value.Issuer,
audience: jwtOptions.Value.Audience,
key: jwtOptions.Value.Key,
userId: user.Id.ToString(),
email: user.Email ?? string.Empty,
alias: user.Alias,
firstname: user.Firstname ?? string.Empty,
lastname: user.Lastname ?? string.Empty,
portraitUrl: user.PortraitUrl);
await SendOkAsync( await SendOkAsync(
new RegisterResponse(accessToken, user.RefreshToken), new RegisterResponse("Registration successful! Please check your email to verify your account."),
cancellation: ct); ct);
} }
} }

View File

@@ -0,0 +1,58 @@
using Hutopy.Modules.Identity.Data;
using Hutopy.Modules.Identity.Services;
namespace Hutopy.Modules.Identity.Handlers;
[PublicAPI]
public record ResendVerificationRequest(
string Email);
[PublicAPI]
public record ResendVerificationResponse(
string Message);
[PublicAPI]
public class ResendVerificationHandler(
EmailVerificationService emailWriter,
UserManager userManager)
: Endpoint<ResendVerificationRequest, ResendVerificationResponse>
{
public override void Configure()
{
AllowAnonymous();
Post("/api/users/resend-verification");
Options(o => o.WithTags("Users"));
}
public override async Task HandleAsync(
ResendVerificationRequest request,
CancellationToken ct)
{
// Find a user by email
User? user = await userManager.FindByEmailAsync(request.Email);
if (user is null)
{
// Don't reveal that the user doesn't exist
await SendOkAsync(
new ResendVerificationResponse(
"If your email exists in our system, a verification link has been sent."),
ct);
return;
}
// Check if the email is already confirmed
if (user.EmailConfirmed)
{
await SendOkAsync(
new ResendVerificationResponse("Your email is already verified. You can log in."),
ct);
return;
}
await emailWriter.SendVerificationEmailAsync(user);
await SendOkAsync(
new ResendVerificationResponse("If your email exists in our system, a verification link has been sent."),
ct);
}
}

View File

@@ -0,0 +1,60 @@
using System.Web;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
[PublicAPI]
public record VerifyEmailRequest(
string UserId,
string Token);
[PublicAPI]
public record VerifyEmailResponse(
string Message);
[PublicAPI]
public class VerifyEmailHandler(
UserManager userManager)
: Endpoint<VerifyEmailRequest, VerifyEmailResponse>
{
public override void Configure()
{
AllowAnonymous();
Get("/api/users/verify-email");
Options(o => o.WithTags("Users"));
}
public override async Task HandleAsync(
VerifyEmailRequest request,
CancellationToken ct)
{
// Find user by ID
User? user = await userManager.FindByIdAsync(request.UserId);
if (user is null)
{
await SendStringAsync(
"Invalid verification link",
400,
cancellation: ct);
return;
}
// Verify the token and confirm email
string decoded = HttpUtility.UrlDecode(request.Token);
string decodedWithPlus = request.Token.Replace(" ", "+");
IdentityResult result = await userManager.ConfirmEmailAsync(user, decodedWithPlus);
if (!result.Succeeded)
{
await SendStringAsync(
"Invalid verification link or the link has expired",
400,
cancellation: ct);
return;
}
await SendOkAsync(
new VerifyEmailResponse("Email verification successful! You can now log in."),
ct);
}
}

View File

@@ -0,0 +1,61 @@
using System.Web;
using Hutopy.Infrastructure.Configuration;
using Hutopy.Infrastructure.Emailer.Contracts;
using Hutopy.Modules.Identity.Data;
using Microsoft.Extensions.Options;
namespace Hutopy.Modules.Identity.Services;
[PublicAPI]
public sealed class EmailVerificationService(
IOptionsSnapshot<WebsiteOptions> options,
UserManager userManager,
IEmailSender emailSender)
{
public async Task SendVerificationEmailAsync(
User user)
{
// Generate email confirmation token
string token = await userManager.GenerateEmailConfirmationTokenAsync(user);
string encodedToken = HttpUtility.UrlEncode(token);
string verificationLink = $"{options.Value.FrontendBaseUrl}/verify-email?userId={user.Id}&token={encodedToken}";
// Send verification email
await emailSender.SendEmailAsync(
user.Email!,
"Verify your email address",
$"""
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333;">
<h1 style="color: #2c3e50; margin-bottom: 20px;">Welcome to Hutopy!</h1>
<p style="font-size: 16px; line-height: 1.5; margin-bottom: 25px;">
Please verify your email address by clicking the button below:
</p>
<div style="text-align: center; margin: 30px 0;">
<a href='{verificationLink}'
style="background-color: #3498db;
color: white;
text-decoration: none;
padding: 12px 24px;
border-radius: 4px;
font-weight: bold;
display: inline-block;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
Verify Email Address
</a>
</div>
<p style="font-size: 14px; color: #7f8c8d; margin-top: 30px;">
If you did not request this, please ignore this email.
</p>
<p style="font-size: 14px; color: #7f8c8d; margin-top: 20px;">
If the button doesn't work, you can copy and paste this link into your browser:
<br>
<a href='{verificationLink}' style="color: #3498db; word-break: break-all;">{verificationLink}</a>
</p>
</div>
""");
}
}

View File

@@ -3,6 +3,7 @@ using Hutopy.Infrastructure.Payments.Stripe.Configuration;
using Hutopy.Modules.Memberships.Contracts; using Hutopy.Modules.Memberships.Contracts;
using Hutopy.Modules.Tipping.Contracts; using Hutopy.Modules.Tipping.Contracts;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Stripe; using Stripe;
using Stripe.Checkout; using Stripe.Checkout;
@@ -18,19 +19,19 @@ public class StripeWebhookEndpoint(
{ {
Post("/api/stripe"); Post("/api/stripe");
AllowAnonymous(); AllowAnonymous();
Options(o => o.WithTags( "Webhooks")); Options(o => o.WithTags("Webhooks"));
} }
public override async Task HandleAsync(CancellationToken ct) public override async Task HandleAsync(CancellationToken ct)
{ {
using var streamReader = new StreamReader(HttpContext.Request.Body); using StreamReader streamReader = new(HttpContext.Request.Body);
var json = await streamReader.ReadToEndAsync(ct); string json = await streamReader.ReadToEndAsync(ct);
var signatureHeader = HttpContext.Request.Headers["Stripe-Signature"]; StringValues signatureHeader = HttpContext.Request.Headers["Stripe-Signature"];
var stripeEvent = EventUtility.ConstructEvent(json, signatureHeader, options.Value.WebhookSecret); Event? stripeEvent = EventUtility.ConstructEvent(json, signatureHeader, options.Value.WebhookSecret);
var stripeSession = stripeEvent.Data.Object as Session; Session? stripeSession = stripeEvent.Data.Object as Session;
var stripeSubscription = stripeEvent.Data.Object as Subscription; Subscription? stripeSubscription = stripeEvent.Data.Object as Subscription;
switch (stripeEvent.Type) switch (stripeEvent.Type)
{ {
@@ -41,11 +42,23 @@ public class StripeWebhookEndpoint(
// Check if this is a one-time tip // Check if this is a one-time tip
case "payment" when stripeSession.PaymentIntentId != null case "payment" when stripeSession.PaymentIntentId != null
&& stripeSession.PaymentIntent.Status == "paid": && stripeSession.PaymentIntent.Status == "paid":
// Get the customer email from the appropriate place
string customerEmail = stripeSession.CustomerDetails?.Email ??
stripeSession.Customer?.Email ??
"";
// Get the receipt URL, preferring the one directly on the charge if available
string receiptUrl = stripeSession.PaymentIntent?.Charges?.Data.FirstOrDefault()?.ReceiptUrl ??
stripeSession.Invoice?.HostedInvoiceUrl ??
"";
await tipPaymentNotifier.NotifyPaymentSucceedAsync( await tipPaymentNotifier.NotifyPaymentSucceedAsync(
stripeSession.Id, stripeSession.Id,
stripeSession.Invoice.HostedInvoiceUrl, receiptUrl,
customerEmail,
ct); ct);
break; break;
// Check if this is a subscription // Check if this is a subscription
case "subscription" when stripeSession.SubscriptionId != null: case "subscription" when stripeSession.SubscriptionId != null:
await membershipNotifier.NotifyPaymentSucceedAsync( await membershipNotifier.NotifyPaymentSucceedAsync(
@@ -53,13 +66,13 @@ public class StripeWebhookEndpoint(
stripeSession.Invoice.HostedInvoiceUrl, stripeSession.Invoice.HostedInvoiceUrl,
stripeSession.Invoice.Total, stripeSession.Invoice.Total,
stripeSession.Invoice.Currency, stripeSession.Invoice.Currency,
cancellationToken: ct); ct);
break; break;
} }
break; break;
case "invoice.payment_succeeded": case "invoice.payment_succeeded":
var invoice = (stripeEvent.Data.Object as Invoice); Invoice? invoice = stripeEvent.Data.Object as Invoice;
Debug.Assert(invoice != null); Debug.Assert(invoice != null);
Debug.Assert(invoice.Subscription != null); Debug.Assert(invoice.Subscription != null);
await membershipNotifier.NotifyPaymentSucceedAsync( await membershipNotifier.NotifyPaymentSucceedAsync(
@@ -67,7 +80,7 @@ public class StripeWebhookEndpoint(
invoice.HostedInvoiceUrl, invoice.HostedInvoiceUrl,
invoice.Total, invoice.Total,
invoice.Currency, invoice.Currency,
cancellationToken: ct); ct);
break; break;
case "customer.subscription.updated": case "customer.subscription.updated":

View File

@@ -2,5 +2,9 @@ namespace Hutopy.Modules.Tipping.Contracts;
public interface ITipPaymentNotifier public interface ITipPaymentNotifier
{ {
Task NotifyPaymentSucceedAsync(string stripeId, string invoiceUrl, CancellationToken ct); Task NotifyPaymentSucceedAsync(
string stripeId,
string invoiceUrl,
string customerEmail,
CancellationToken ct);
} }

View File

@@ -1,3 +1,5 @@
using Hutopy.Infrastructure.Emailer.Contracts;
using Hutopy.Modules.Creators.Contracts;
using Hutopy.Modules.Tipping.Contracts; using Hutopy.Modules.Tipping.Contracts;
using Hutopy.Modules.Tipping.Data; using Hutopy.Modules.Tipping.Data;
@@ -5,27 +7,104 @@ namespace Hutopy.Modules.Tipping.Services;
public class TipPaymentNotifier( public class TipPaymentNotifier(
TippingDbContext dbContext, TippingDbContext dbContext,
IEmailSender emailSender,
ICreatorLookup creatorLookup,
ILogger<TipPaymentNotifier> logger) ILogger<TipPaymentNotifier> logger)
: ITipPaymentNotifier : ITipPaymentNotifier
{ {
public async Task NotifyPaymentSucceedAsync( public async Task NotifyPaymentSucceedAsync(
string sessionId, string sessionId,
string invoiceUrl, string receiptUrl,
string customerEmail,
CancellationToken ct) CancellationToken ct)
{ {
var tip = await dbContext.Tips.SingleOrDefaultAsync( Tip? tip = await dbContext.Tips.SingleOrDefaultAsync(
t => t.StripeSessionId == sessionId, t => t.StripeSessionId == sessionId,
cancellationToken: ct); ct);
if (tip is not null) if (tip is not null)
{ {
tip.Status = TipStatus.Paid; tip.Status = TipStatus.Paid;
tip.StripeInvoiceUrl = invoiceUrl; tip.StripeInvoiceUrl = receiptUrl; // Store the receipt URL
await dbContext.SaveChangesAsync(ct); await dbContext.SaveChangesAsync(ct);
// Look up creator information
CreatorReference? creator = await creatorLookup.GetCreatorAsync(tip.CreatorId, ct);
if (!string.IsNullOrEmpty(customerEmail))
{
await SendTipConfirmationEmailAsync(
customerEmail,
creator?.Name ?? "le créateur",
tip.Amount,
tip.Currency,
receiptUrl); // Pass the receipt URL
}
} }
else else
{ {
logger.LogError("Tip with session ID {SessionId} not found", sessionId); logger.LogError("Tip with session ID {SessionId} not found", sessionId);
} }
} }
private async Task SendTipConfirmationEmailAsync(
string email,
string creatorUsername,
decimal amount,
string currency,
string receiptUrl) // Add receipt URL parameter
{
string subject = $"Merci pour votre soutien à {creatorUsername}";
string message = $"""
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333;">
<h1 style="color: #2c3e50; margin-bottom: 20px;">{creatorUsername} vous remercie !</h1>
<p style="font-size: 16px; line-height: 1.5; margin-bottom: 15px;">
Votre paiement de <strong>{amount} {currency}</strong> a é traité avec succès.
</p>
<div style="background-color: #f8f9fa; border-radius: 4px; padding: 20px; margin: 30px 0; border-left: 4px solid #3498db;">
<p style="font-size: 16px; margin: 0; line-height: 1.5;">
Ce reçu confirme votre soutien à <strong>{creatorUsername}</strong>. Merci de contribuer à son travail !
</p>
</div>
{(string.IsNullOrEmpty(receiptUrl) ? "" : $"""
<div style="text-align: center; margin: 30px 0;">
<a href='{receiptUrl}'
style="background-color: #3498db;
color: white;
text-decoration: none;
padding: 12px 24px;
border-radius: 4px;
font-weight: bold;
display: inline-block;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
Voir le reçu
</a>
</div>
""")}
<p style="font-size: 14px; color: #7f8c8d; margin-top: 30px;">
Cet email sert de reçu pour votre transaction. Nous vous conseillons de le conserver pour vos archives.
</p>
<p style="font-size: 14px; color: #7f8c8d; margin-top: 20px; text-align: center; border-top: 1px solid #eee; padding-top: 20px;">
Merci d'utiliser Hutopy pour soutenir vos créateurs préférés !
</p>
</div>
""";
try
{
await emailSender.SendEmailAsync(email, subject, message);
logger.LogInformation("Tip confirmation email sent to {Email} for tip to {Creator}", email,
creatorUsername);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to send tip confirmation email to {Email}", email);
// Don't throw the exception as this should not fail the payment processing
}
}
} }

View File

@@ -3,7 +3,8 @@ import { createRouter, createWebHistory } from 'vue-router';
import CreatorHome from '@/views/creators/CreatorHome.vue'; import CreatorHome from '@/views/creators/CreatorHome.vue';
import CreatorLayout from '@/views/creators/CreatorLayout.vue'; import CreatorLayout from '@/views/creators/CreatorLayout.vue';
const LoginView = () => import('@/views/LoginView.vue');
const LoginView = () => import('@/views/auth/LoginView.vue');
const About = () => import('@/views/documentation/About.vue'); const About = () => import('@/views/documentation/About.vue');
const ContentPolicy = () => import('@/views/documentation/ContentPolicy.vue'); const ContentPolicy = () => import('@/views/documentation/ContentPolicy.vue');
@@ -14,151 +15,158 @@ const HelpAndContact = () => import('@/views/documentation/HelpAndContact.vue');
const Pricing = () => import('@/views/documentation/Pricing.vue'); const Pricing = () => import('@/views/documentation/Pricing.vue');
const TermsAndConditions = () => import('@/views/documentation/TermsAndConditions.vue'); const TermsAndConditions = () => import('@/views/documentation/TermsAndConditions.vue');
const ProfilePage = () => import('@/views/profile/ProfilePage.vue'); const ProfilePage = () => import('@/views/profile/ProfilePage.vue');
const PaymentCompleted = () => import('@/views/PaymentCompleted.vue'); const PaymentCompleted = () => import('@/views/creators/PaymentCompleted.vue');
const PaymentFailed = () => import('@/views/PaymentFailed.vue'); const PaymentFailed = () => import('@/views/creators/PaymentFailed.vue');
const Landing = () => import('@/views/main/Landing.vue'); const Landing = () => import('@/views/main/Landing.vue');
const CreateCreator = () => import('@/views/creators/CreateCreator.vue'); const CreateCreator = () => import('@/views/creators/CreateCreator.vue');
const RegisterView = () => import('@/views/RegisterView.vue'); const RegisterView = () => import('@/views/auth/RegisterView.vue');
const ForgotPasswordView = () => import('@/views/ForgotPasswordView.vue'); const ForgotPasswordView = () => import('@/views/auth/ForgotPasswordView.vue');
const ResetPasswordView = () => import('@/views/ResetPasswordView.vue'); const ResetPasswordView = () => import('@/views/auth/ResetPasswordView.vue');
const VerifyEmailView = () => import('@/views/auth/VerifyEmailView.vue');
const routes = [ const routes = [
{ {
path: '/landing', path: '/landing',
name: 'landing', name: 'landing',
component: Landing, component: Landing,
}, },
{ {
path: '/', path: '/',
redirect: { name: 'landing' }, redirect: { name: 'landing' },
}, },
{ {
path: '/@:creator', path: '/@:creator',
component: CreatorLayout, component: CreatorLayout,
children: [ children: [
{ {
path: '', path: '',
name: 'creator', name: 'creator',
component: CreatorHome, component: CreatorHome,
}, },
{ {
path: 'tip-completed', path: 'tip-completed',
name: 'PaymentCompleted', name: 'PaymentCompleted',
component: PaymentCompleted, component: PaymentCompleted,
}, },
{ {
path: 'tip-cancelled', path: 'tip-cancelled',
name: 'PaymentFailed', name: 'PaymentFailed',
component: PaymentFailed, component: PaymentFailed,
} },
], ],
}, },
{ {
path: '/documents', path: '/documents',
component: DocumentationLayout, component: DocumentationLayout,
children: [ children: [
{ {
path: 'helpandcontact', path: 'helpandcontact',
name: 'helpandcontact', name: 'helpandcontact',
component: HelpAndContact, component: HelpAndContact,
}, },
{ {
path: 'termsandconditions', path: 'termsandconditions',
name: 'termsandconditions', name: 'termsandconditions',
component: TermsAndConditions, component: TermsAndConditions,
}, },
{ {
path: 'contentpolicy', path: 'contentpolicy',
name: 'contentpolicy', name: 'contentpolicy',
component: ContentPolicy, component: ContentPolicy,
}, },
{ {
path: 'faq', path: 'faq',
name: 'FAQ', name: 'FAQ',
component: FAQ, component: FAQ,
}, },
{ {
path: 'guideforcreators', path: 'guideforcreators',
name: 'guideforcreators', name: 'guideforcreators',
component: CreatorGuide, component: CreatorGuide,
}, },
{ {
path: 'about', path: 'about',
name: 'about', name: 'about',
component: About, component: About,
}, },
{ {
path: 'pricing', path: 'pricing',
name: 'pricing', name: 'pricing',
component: Pricing, component: Pricing,
}, },
], ],
}, },
{ {
path: '/login', path: '/login',
name: 'login', name: 'login',
component: LoginView, component: LoginView,
meta: { notAuthenticated: true }, meta: { notAuthenticated: true },
props: (route) => ({ returnUrl: route.query.returnUrl || '/landing' }) props: route => ({ returnUrl: route.query.returnUrl || '/landing' }),
}, },
{ {
path: '/profile', path: '/profile',
name: 'profile', name: 'profile',
component: ProfilePage, component: ProfilePage,
meta: { requiresAuth: true }, meta: { requiresAuth: true },
}, },
{ {
path: '/create-creator', path: '/create-creator',
name: 'create-creator', name: 'create-creator',
component: CreateCreator, component: CreateCreator,
meta: { requiresAuth: true }, meta: { requiresAuth: true },
}, },
{ {
path: '/register', path: '/register',
name: 'register', name: 'register',
component: RegisterView, component: RegisterView,
meta: { requiresAuth: false } meta: { requiresAuth: false },
}, },
{ {
path: '/forgot-password', path: '/forgot-password',
name: 'forgot-password', name: 'forgot-password',
component: ForgotPasswordView, component: ForgotPasswordView,
meta: { notAuthenticated: true } meta: { notAuthenticated: true },
}, },
{ {
path: '/reset-password', path: '/reset-password',
name: 'reset-password', name: 'reset-password',
component: ResetPasswordView, component: ResetPasswordView,
meta: { notAuthenticated: true }, meta: { notAuthenticated: true },
props: (route) => ({ email: route.query.email, token: route.query.token }) props: route => ({ email: route.query.email, token: route.query.token }),
} },
{
path: '/verify-email',
name: 'verify-email',
component: VerifyEmailView,
meta: { notAuthenticated: true },
},
]; ];
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
routes, routes,
}); });
// Navigation guards // Navigation guards
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
const authStore = useAuthStore(); const authStore = useAuthStore();
if (to.matched.some((record) => record.meta.requiresAuth)) { if (to.matched.some(record => record.meta.requiresAuth)) {
if (!authStore.isAuthenticated) { if (!authStore.isAuthenticated) {
next({ next({
name: 'login', name: 'login',
query: { returnUrl: to.fullPath } query: { returnUrl: to.fullPath },
}); });
} else {
next();
}
} else if (to.matched.some(record => record.meta.notAuthenticated)) {
if (authStore.isAuthenticated) next({ name: 'landing' });
else next();
} else { } else {
next(); next();
} }
} else if (to.matched.some((record) => record.meta.notAuthenticated)) {
if (authStore.isAuthenticated) next({ name: 'landing' });
else next();
} else {
next();
}
}); });
export default router; export default router;

View File

@@ -4,280 +4,273 @@ import { useRouter } from 'vue-router';
import { useClient } from '@/plugins/api.js'; import { useClient } from '@/plugins/api.js';
import { useSessionStorage } from '@vueuse/core'; import { useSessionStorage } from '@vueuse/core';
import { jwtDecode } from 'jwt-decode'; import { jwtDecode } from 'jwt-decode';
import { formatDuration } from "@/internal_time_ago.js"; import { formatDuration } from '@/internal_time_ago.js';
export const useAuthStore = defineStore('auth', () => { export const useAuthStore = defineStore('auth', () => {
const clientApi = useClient(); const clientApi = useClient();
const router = useRouter(); const router = useRouter();
const isRefreshing = ref(false); const isRefreshing = ref(false);
let refreshPromise = null; let refreshPromise = null;
const accessToken = useSessionStorage('auth-accessToken', undefined); const accessToken = useSessionStorage('auth-accessToken', undefined);
const refreshToken = useSessionStorage('auth-refreshToken', undefined); const refreshToken = useSessionStorage('auth-refreshToken', undefined);
const tokenClaims = useSessionStorage('auth-tokenClaims', null, { const tokenClaims = useSessionStorage('auth-tokenClaims', null, {
serializer: { serializer: {
read: (v) => (v ? JSON.parse(v) : null), read: v => (v ? JSON.parse(v) : null),
write: (v) => (v ? JSON.stringify(v) : null) write: v => (v ? JSON.stringify(v) : null),
} },
}); });
const isAuthenticated = computed(() => !!accessToken.value); const isAuthenticated = computed(() => !!accessToken.value);
const userId = computed(() => tokenClaims.value?.sub); const userId = computed(() => tokenClaims.value?.sub);
function updateTokens(data) { function updateTokens(data) {
if (!data?.accessToken || !data?.refreshToken) { if (!data?.accessToken || !data?.refreshToken) {
throw new Error('Invalid token data'); throw new Error('Invalid token data');
}
accessToken.value = data.accessToken;
refreshToken.value = data.refreshToken;
const claims = getClaimsFromToken(data.accessToken);
tokenClaims.value = claims;
console.log('Tokens updated, user ID:', claims?.sub);
}
function cleanTokens() {
console.log('cleanTokens called - clearing stored tokens');
accessToken.value = undefined;
refreshToken.value = undefined;
tokenClaims.value = null;
}
async function logout(redirectTo = '/landing') {
console.log('logout called, redirecting to:', redirectTo);
try {
// Optionally call logout endpoint if you have one
// await clientApi.post('api/users/logout');
} catch (error) {
console.error('Logout failed:', error);
} finally {
cleanTokens();
await router.push(redirectTo);
}
}
async function login(email, password) {
console.log('login called with email:', email);
if (!email || !password) {
throw new Error('Email and password are required');
}
try {
const response = await clientApi.post('api/users/login', {
email: email.trim(),
password: password
});
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid login response');
}
updateTokens(response.data);
console.log('login successful');
return true;
} catch (error) {
console.error('Login failed:', error);
cleanTokens();
throw error;
}
}
async function loginWithGoogle(accessTokenParam) {
console.log('loginWithGoogle called');
if (!accessTokenParam) {
throw new Error('Google access token is required');
}
try {
const response = await clientApi.post('api/users/login-with-google', {
token: accessTokenParam
});
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid Google login response');
}
updateTokens(response.data);
console.log('Google login successful');
return true;
} catch (error) {
console.error('Google login failed:', error);
cleanTokens();
throw error;
}
}
async function loginWithFacebook(authResponse) {
console.log('loginWithFacebook called');
if (!authResponse?.accessToken) {
throw new Error('Facebook access token is required');
}
try {
const response = await clientApi.post('api/users/login-with-facebook', {
token: authResponse.accessToken
});
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid Facebook login response');
}
updateTokens(response.data);
console.log('Facebook login successful');
return true;
} catch (error) {
console.error('Facebook login failed:', error);
cleanTokens();
throw error;
}
}
async function refresh() {
console.log('refresh called');
if (!refreshToken.value) {
cleanTokens(); // Clear tokens first
throw new Error('No refresh token available');
}
if (isRefreshing.value && refreshPromise) {
console.log('Already refreshing, returning existing refreshPromise');
return refreshPromise;
}
try {
isRefreshing.value = true;
refreshPromise = (async () => {
try {
console.log('Sending refresh request...');
const response = await clientApi.post('api/users/refresh', {
refreshToken: refreshToken.value
});
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid refresh response');
}
updateTokens({
accessToken: response.data.accessToken,
refreshToken: response.data.refreshToken
});
console.log('Token refresh successful');
return true;
} catch (error) {
console.error('Token refresh failed:', error);
cleanTokens();
const currentRoute = router.currentRoute.value;
const returnUrl = currentRoute.fullPath;
// Handle navigation
router.push({
name: 'login',
query: { returnUrl }
}).catch(navError => {
console.error('Navigation error after token refresh failure:', navError);
});
throw error; // Re-throw to notify callers
} }
})(); accessToken.value = data.accessToken;
refreshToken.value = data.refreshToken;
return await refreshPromise; const claims = getClaimsFromToken(data.accessToken);
} catch (error) { tokenClaims.value = claims;
throw error; console.log('Tokens updated, user ID:', claims?.sub);
} finally {
// Ensure these are always reset, even if an error is thrown
isRefreshing.value = false;
refreshPromise = null;
}
}
function getClaimsFromToken(token) {
if (!token) return null;
try {
return jwtDecode(token);
} catch (error) {
console.error('Failed to decode token:', error);
return null;
}
}
function isTokenExpiringSoon(token) {
if (!token) {
console.log('No token provided, considered expiring soon');
return true;
} }
const claims = getClaimsFromToken(token); function cleanTokens() {
if (!claims || !claims.exp) { console.log('cleanTokens called - clearing stored tokens');
console.log('No valid claims found, considered expiring soon'); accessToken.value = undefined;
return true; refreshToken.value = undefined;
tokenClaims.value = null;
} }
const expirationTime = claims.exp * 1000; // Convert to milliseconds async function logout() {
const currentTime = Date.now(); cleanTokens();
const fiveMinutesInMs = 2 * 60 * 1000; // 2 minutes for demonstration await router.push('/');
// Calculate time remaining (can be negative if already expired)
const timeRemainingMs = expirationTime - currentTime;
// Token is expiring soon if less than 2 minutes remaining or already expired
const isExpiring = timeRemainingMs < fiveMinutesInMs;
// Determine the sign for display purposes
const formattedTimeRemaining = timeRemainingMs < 0
? `-${formatDuration(Math.abs(timeRemainingMs))}`
: formatDuration(timeRemainingMs);
if (isExpiring) {
console.log(`Token expiration check; is token expired: ${isExpiring}`, {
expirationTime: new Date(expirationTime).toLocaleString(),
currentTime: new Date(currentTime).toLocaleString(),
timeRemaining: formattedTimeRemaining
});
} }
return isExpiring; async function login(email, password) {
} console.log('login called with email:', email);
if (!email || !password) {
throw new Error('Email and password are required');
}
async function changePassword(newPassword) { try {
console.log('changePassword called'); const response = await clientApi.post('api/users/login', {
if (!isAuthenticated.value) { email: email.trim(),
throw new Error('User must be authenticated to change password'); password: password,
});
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid login response');
}
updateTokens(response.data);
console.log('login successful');
return true;
} catch (error) {
console.error('Login failed:', error);
cleanTokens();
throw error;
}
} }
if (!newPassword) { async function loginWithGoogle(accessTokenParam) {
throw new Error('New password is required'); console.log('loginWithGoogle called');
if (!accessTokenParam) {
throw new Error('Google access token is required');
}
try {
const response = await clientApi.post('api/users/login-with-google', {
token: accessTokenParam,
});
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid Google login response');
}
updateTokens(response.data);
console.log('Google login successful');
return true;
} catch (error) {
console.error('Google login failed:', error);
cleanTokens();
throw error;
}
} }
try { async function loginWithFacebook(authResponse) {
const response = await clientApi.post('api/users/set-password', { console.log('loginWithFacebook called');
newPassword if (!authResponse?.accessToken) {
}); throw new Error('Facebook access token is required');
}
console.log('Password changed successfully'); try {
return true; const response = await clientApi.post('api/users/login-with-facebook', {
} catch (error) { token: authResponse.accessToken,
console.error('Password change failed:', error); });
throw error;
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid Facebook login response');
}
updateTokens(response.data);
console.log('Facebook login successful');
return true;
} catch (error) {
console.error('Facebook login failed:', error);
cleanTokens();
throw error;
}
} }
}
return { async function refresh() {
accessToken, console.log('refresh called');
refreshToken,
isAuthenticated, if (!refreshToken.value) {
userId, cleanTokens(); // Clear tokens first
isRefreshing, throw new Error('No refresh token available');
login, }
loginWithGoogle,
loginWithFacebook, if (isRefreshing.value && refreshPromise) {
logout, console.log('Already refreshing, returning existing refreshPromise');
refresh, return refreshPromise;
isTokenExpiringSoon, }
changePassword
}; try {
isRefreshing.value = true;
refreshPromise = (async () => {
try {
console.log('Sending refresh request...');
const response = await clientApi.post('api/users/refresh', {
refreshToken: refreshToken.value,
});
if (!response.data?.accessToken || !response.data?.refreshToken) {
throw new Error('Invalid refresh response');
}
updateTokens({
accessToken: response.data.accessToken,
refreshToken: response.data.refreshToken,
});
console.log('Token refresh successful');
return true;
} catch (error) {
console.error('Token refresh failed:', error);
cleanTokens();
const currentRoute = router.currentRoute.value;
const returnUrl = currentRoute.fullPath;
// Handle navigation
router
.push({
name: 'login',
query: { returnUrl },
})
.catch(navError => {
console.error('Navigation error after token refresh failure:', navError);
});
throw error; // Re-throw to notify callers
}
})();
return await refreshPromise;
} catch (error) {
throw error;
} finally {
// Ensure these are always reset, even if an error is thrown
isRefreshing.value = false;
refreshPromise = null;
}
}
function getClaimsFromToken(token) {
if (!token) return null;
try {
return jwtDecode(token);
} catch (error) {
console.error('Failed to decode token:', error);
return null;
}
}
function isTokenExpiringSoon(token) {
if (!token) {
console.log('No token provided, considered expiring soon');
return true;
}
const claims = getClaimsFromToken(token);
if (!claims || !claims.exp) {
console.log('No valid claims found, considered expiring soon');
return true;
}
const expirationTime = claims.exp * 1000; // Convert to milliseconds
const currentTime = Date.now();
const fiveMinutesInMs = 2 * 60 * 1000; // 2 minutes for demonstration
// Calculate time remaining (can be negative if already expired)
const timeRemainingMs = expirationTime - currentTime;
// Token is expiring soon if less than 2 minutes remaining or already expired
const isExpiring = timeRemainingMs < fiveMinutesInMs;
// Determine the sign for display purposes
const formattedTimeRemaining =
timeRemainingMs < 0 ? `-${formatDuration(Math.abs(timeRemainingMs))}` : formatDuration(timeRemainingMs);
if (isExpiring) {
console.log(`Token expiration check; is token expired: ${isExpiring}`, {
expirationTime: new Date(expirationTime).toLocaleString(),
currentTime: new Date(currentTime).toLocaleString(),
timeRemaining: formattedTimeRemaining,
});
}
return isExpiring;
}
async function changePassword(newPassword) {
console.log('changePassword called');
if (!isAuthenticated.value) {
throw new Error('User must be authenticated to change password');
}
if (!newPassword) {
throw new Error('New password is required');
}
try {
const response = await clientApi.post('api/users/set-password', {
newPassword,
});
console.log('Password changed successfully');
return true;
} catch (error) {
console.error('Password change failed:', error);
throw error;
}
}
return {
accessToken,
refreshToken,
isAuthenticated,
userId,
isRefreshing,
login,
loginWithGoogle,
loginWithFacebook,
logout,
refresh,
isTokenExpiringSoon,
changePassword,
};
}); });

View File

@@ -1,167 +0,0 @@
<template>
<div class="flex min-h-full w-full items-center justify-center p-20">
<div class="card justify-items-center">
<img :alt="t('alt')" src="/images/hutopymedia/loginpage/hutopylogin.svg" />
<div class="flex flex-col gap-10">
<h1 class="login-text text-center text-2xl font-bold ">
{{ t('title') }}
</h1>
<v-form @submit.prevent="handleRegister">
<div class="flex flex-col gap-4">
<v-text-field v-model="name" :label="t('name')" required></v-text-field>
<v-text-field v-model="email" :label="t('email')" type="email" required></v-text-field>
<v-text-field v-model="password" :label="t('password')" :type="showPassword ? 'text' : 'password'" required
:hint="t('passwordRequirements')">
<template v-slot:append-inner>
<v-icon @click="showPassword = !showPassword" class="visibility-toggle" size="small"
:icon="showPassword ? mdiEyeOff : mdiEye" />
</template>
</v-text-field>
<v-text-field v-model="confirmPassword" :label="t('confirmPassword')"
:type="showConfirmPassword ? 'text' : 'password'" required>
<template v-slot:append-inner>
<v-icon @click="showConfirmPassword = !showConfirmPassword" class="visibility-toggle" size="small"
:icon="showConfirmPassword ? mdiEyeOff : mdiEye" />
</template>
</v-text-field>
<v-btn type="submit" color="primary" block :loading="isLoading">
{{ t('register') }}
</v-btn>
<div class="mt-4 text-center">
{{ t('alreadyHaveAccount') }}
<router-link to="/login" class="text-blue-500">
{{ t('signIn') }}
</router-link>
</div>
</div>
</v-form>
</div>
</div>
<v-snackbar v-model="errorSnackBar" color="error">
{{ errorMessage }}
</v-snackbar>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useClient } from '@/plugins/api.js';
import { useAuthStore } from '@/stores/authStore.js';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { mdiEye, mdiEyeOff } from '@mdi/js';
const { t } = useI18n();
const router = useRouter();
const authStore = useAuthStore();
const clientApi = useClient();
const name = ref('');
const email = ref('');
const password = ref('');
const confirmPassword = ref('');
const isLoading = ref(false);
const errorSnackBar = ref(false);
const errorMessage = ref('');
const showPassword = ref(false);
const showConfirmPassword = ref(false);
async function handleRegister() {
if (password.value !== confirmPassword.value) {
errorMessage.value = t('passwordsDoNotMatch');
errorSnackBar.value = true;
return;
}
isLoading.value = true;
try {
// Register the user
const response = await clientApi.post('api/users/register', {
name: name.value,
email: email.value.trim(),
password: password.value
});
// If registration is successful, log them in
await authStore.login(email.value, password.value);
// Redirect to home or welcome page
await router.push('/landing');
} catch (error) {
console.error('Registration failed:', error);
errorMessage.value = error.response?.data?.message || t('registrationFailed');
errorSnackBar.value = true;
} finally {
isLoading.value = false;
}
}
</script>
<style scoped>
.visibility-toggle {
@apply cursor-pointer;
@apply transition-opacity duration-300;
@apply opacity-60 hover:opacity-100;
@apply z-10;
}
/* Override Vuetify's default padding to accommodate our icon */
:deep(.v-field__append-inner) {
padding-inline-start: 0;
}
</style>
<i18n>
{
"en": {
"title": "Create your account",
"alt": "Hutopy Registration",
"name": "Full Name",
"email": "Email",
"password": "Password",
"confirmPassword": "Confirm Password",
"passwordRequirements": "Password must be at least 8 characters",
"register": "Register",
"alreadyHaveAccount": "Already have an account?",
"signIn": "Sign in",
"passwordsDoNotMatch": "Passwords do not match",
"registrationFailed": "Registration failed. Please try again."
},
"fr": {
"title": "Créer votre compte",
"alt": "Inscription Hutopy",
"name": "Nom complet",
"email": "Email",
"password": "Mot de passe",
"confirmPassword": "Confirmer le mot de passe",
"passwordRequirements": "Le mot de passe doit comporter au moins 8 caractères",
"register": "S'inscrire",
"alreadyHaveAccount": "Vous avez déjà un compte?",
"signIn": "Se connecter",
"passwordsDoNotMatch": "Les mots de passe ne correspondent pas",
"registrationFailed": "L'inscription a échoué. Veuillez réessayer."
},
"es": {
"title": "Crea tu cuenta",
"alt": "Registro de Hutopy",
"name": "Nombre completo",
"email": "Correo electrónico",
"password": "Contraseña",
"confirmPassword": "Confirmar contraseña",
"passwordRequirements": "La contraseña debe tener al menos 8 caracteres",
"register": "Registrarse",
"alreadyHaveAccount": "¿Ya tienes una cuenta?",
"signIn": "Iniciar sesión",
"passwordsDoNotMatch": "Las contraseñas no coinciden",
"registrationFailed": "El registro falló. Por favor, inténtelo de nuevo."
}
}
</i18n>

View File

@@ -44,6 +44,12 @@
</a> </a>
</div> </div>
<div class="mt-2 text-center">
<a @click="resendVerification" class="cursor-pointer text-sm text-blue-500">
{{ t('resendVerification') }}
</a>
</div>
<div class="mt-4 text-center"> <div class="mt-4 text-center">
{{ t('noAccount') }} {{ t('noAccount') }}
<router-link to="/register" class="text-blue-500"> <router-link to="/register" class="text-blue-500">
@@ -113,6 +119,10 @@ async function googleCallback(token) {
function forgotPassword() { function forgotPassword() {
router.push('/forgot-password'); router.push('/forgot-password');
} }
function resendVerification() {
router.push('/verify-email');
}
</script> </script>
<style scoped> <style scoped>
@@ -146,6 +156,7 @@ function forgotPassword() {
"password": "Password", "password": "Password",
"signIn": "Connect", "signIn": "Connect",
"forgotPassword": "Forgot password?", "forgotPassword": "Forgot password?",
"resendVerification": "Resend verification email",
"orContinueWith": "Or", "orContinueWith": "Or",
"noAccount": "Don't have an account?", "noAccount": "Don't have an account?",
"register": "Register", "register": "Register",
@@ -159,6 +170,7 @@ function forgotPassword() {
"password": "Mot de passe", "password": "Mot de passe",
"signIn": "Connexion", "signIn": "Connexion",
"forgotPassword": "Mot de passe oublié?", "forgotPassword": "Mot de passe oublié?",
"resendVerification": "Renvoyer l'email de vérification",
"orContinueWith": "Ou", "orContinueWith": "Ou",
"noAccount": "Vous n'avez pas de compte?", "noAccount": "Vous n'avez pas de compte?",
"register": "S'inscrire", "register": "S'inscrire",
@@ -172,6 +184,7 @@ function forgotPassword() {
"password": "Contraseña", "password": "Contraseña",
"signIn": "Conéctate", "signIn": "Conéctate",
"forgotPassword": "¿Olvidó su contraseña?", "forgotPassword": "¿Olvidó su contraseña?",
"resendVerification": "Reenviar correo de verificación",
"orContinueWith": "o", "orContinueWith": "o",
"noAccount": "¿No tiene una cuenta?", "noAccount": "¿No tiene una cuenta?",
"register": "Registrarse", "register": "Registrarse",

View File

@@ -0,0 +1,257 @@
<template>
<div class="flex min-h-full w-full items-center justify-center p-20">
<!-- Show verification message on success -->
<div
v-if="registrationSuccess"
class="card justify-items-center"
>
<img
:alt="t('alt')"
src="/images/hutopymedia/loginpage/hutopylogin.svg"
/>
<div class="flex flex-col gap-10 text-center">
<h1 class="login-text text-2xl font-bold text-green-600">
{{ t('success.title') }}
</h1>
<div class="text-hOnSurface">
<p>{{ t('success.message') }}</p>
<p class="mt-2 font-medium">{{ userEmail }}</p>
</div>
<div class="mt-4 flex flex-col gap-2">
<router-link
class="text-blue-500 hover:underline"
to="/login"
>
{{ t('success.backToLogin') }}
</router-link>
<router-link
class="text-blue-500 hover:underline"
:to="{ path: '/verify-email', query: { email: userEmail } }"
>
{{ t('success.resendVerification') }}
</router-link>
</div>
</div>
</div>
<!-- Show registration form -->
<div
v-else
class="card justify-items-center"
>
<img
:alt="t('alt')"
src="/images/hutopymedia/loginpage/hutopylogin.svg"
/>
<div class="flex flex-col gap-10">
<h1 class="login-text text-center text-2xl font-bold">
{{ t('title') }}
</h1>
<v-form @submit.prevent="handleRegister">
<div class="flex flex-col gap-4">
<v-text-field
v-model="name"
:label="t('name')"
required
></v-text-field>
<v-text-field
v-model="email"
:label="t('email')"
required
type="email"
></v-text-field>
<v-text-field
v-model="password"
:hint="t('passwordRequirements')"
:label="t('password')"
:type="showPassword ? 'text' : 'password'"
required
>
<template v-slot:append-inner>
<v-icon
:icon="showPassword ? mdiEyeOff : mdiEye"
class="visibility-toggle"
size="small"
@click="showPassword = !showPassword"
/>
</template>
</v-text-field>
<v-text-field
v-model="confirmPassword"
:label="t('confirmPassword')"
:type="showConfirmPassword ? 'text' : 'password'"
required
>
<template v-slot:append-inner>
<v-icon
:icon="showConfirmPassword ? mdiEyeOff : mdiEye"
class="visibility-toggle"
size="small"
@click="showConfirmPassword = !showConfirmPassword"
/>
</template>
</v-text-field>
<v-btn
:loading="isLoading"
block
color="primary"
type="submit"
>
{{ t('register') }}
</v-btn>
<!-- Error message displayed as block text below submit button -->
<div
v-if="errorMessage"
class="mt-2 p-3 bg-red-50 border border-red-200 rounded text-red-700 text-sm"
>
{{ errorMessage }}
</div>
<div class="mt-4 text-center">
{{ t('alreadyHaveAccount') }}
<router-link
class="text-blue-500"
to="/login"
>
{{ t('signIn') }}
</router-link>
</div>
</div>
</v-form>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useClient } from '@/plugins/api.js';
import { useI18n } from 'vue-i18n';
import { mdiEye, mdiEyeOff } from '@mdi/js';
const { t } = useI18n();
const clientApi = useClient();
const name = ref('');
const email = ref('');
const password = ref('');
const confirmPassword = ref('');
const isLoading = ref(false);
const errorMessage = ref('');
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const registrationSuccess = ref(false);
const userEmail = ref('');
async function handleRegister() {
if (password.value !== confirmPassword.value) {
errorMessage.value = t('passwordsDoNotMatch');
return;
}
isLoading.value = true;
errorMessage.value = '';
try {
await clientApi.post('api/users/register', {
name: name.value,
email: email.value.trim(),
password: password.value,
});
// On success, show verification message
userEmail.value = email.value.trim();
registrationSuccess.value = true;
} catch (error) {
console.error('Registration failed:', error);
errorMessage.value = error.response?.data?.message || t('registrationFailed');
} finally {
isLoading.value = false;
}
}
</script>
<style scoped>
.visibility-toggle {
@apply cursor-pointer;
@apply transition-opacity duration-300;
@apply opacity-60 hover:opacity-100;
@apply z-10;
}
/* Override Vuetify's default padding to accommodate our icon */
:deep(.v-field__append-inner) {
padding-inline-start: 0;
}
</style>
<i18n>
{
"en": {
"title": "Create your account",
"alt": "Hutopy Registration",
"name": "Full Name",
"email": "Email",
"password": "Password",
"confirmPassword": "Confirm Password",
"passwordRequirements": "Password must be at least 8 characters",
"register": "Register",
"alreadyHaveAccount": "Already have an account?",
"signIn": "Sign in",
"passwordsDoNotMatch": "Passwords do not match",
"registrationFailed": "Registration failed. Please try again.",
"success": {
"title": "Registration Successful!",
"message": "Please check your email to verify your account. We've sent a verification link to:",
"backToLogin": "Back to Login",
"resendVerification": "Didn't receive the email? Resend verification"
}
},
"fr": {
"title": "Créer votre compte",
"alt": "Inscription Hutopy",
"name": "Nom complet",
"email": "Email",
"password": "Mot de passe",
"confirmPassword": "Confirmer le mot de passe",
"passwordRequirements": "Le mot de passe doit comporter au moins 8 caractères",
"register": "S'inscrire",
"alreadyHaveAccount": "Vous avez déjà un compte?",
"signIn": "Se connecter",
"passwordsDoNotMatch": "Les mots de passe ne correspondent pas",
"registrationFailed": "L'inscription a échoué. Veuillez réessayer.",
"success": {
"title": "Inscription réussie!",
"message": "Veuillez vérifier votre email pour activer votre compte. Nous avons envoyé un lien de vérification à:",
"backToLogin": "Retour à la connexion",
"resendVerification": "Vous n'avez pas reçu l'email? Renvoyer la vérification"
}
},
"es": {
"title": "Crea tu cuenta",
"alt": "Registro de Hutopy",
"name": "Nombre completo",
"email": "Correo electrónico",
"password": "Contraseña",
"confirmPassword": "Confirmar contraseña",
"passwordRequirements": "La contraseña debe tener al menos 8 caracteres",
"register": "Registrarse",
"alreadyHaveAccount": "¿Ya tienes una cuenta?",
"signIn": "Iniciar sesión",
"passwordsDoNotMatch": "Las contraseñas no coinciden",
"registrationFailed": "El registro falló. Por favor, inténtelo de nuevo.",
"success": {
"title": "¡Registro exitoso!",
"message": "Por favor revisa tu correo electrónico para verificar tu cuenta. Hemos enviado un enlace de verificación a:",
"backToLogin": "Volver al inicio de sesión",
"resendVerification": "¿No recibiste el correo? Reenviar verificación"
}
}
}
</i18n>

View File

@@ -0,0 +1,219 @@
<template>
<div class="flex min-h-full w-full items-center justify-center p-4">
<div class="flex w-full max-w-[512px] flex-col gap-10 text-center">
<!-- Loading state while verification is in progress -->
<div v-if="isLoading" class="flex flex-col items-center gap-4">
<v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
<h2 class="text-xl font-medium">{{ t('verifying') }}</h2>
</div>
<!-- Success state -->
<div v-else-if="verificationSuccess" class="flex flex-col items-center gap-6">
<v-icon icon="mdi-check-circle" color="green" size="64"></v-icon>
<h1 class="text-2xl font-bold text-green-600">{{ t('success.title') }}</h1>
<p>{{ t('success.message') }}</p>
<v-btn color="primary" @click="goToLogin">{{ t('success.goToLogin') }}</v-btn>
</div>
<!-- Error state -->
<div v-else class="flex flex-col items-center gap-6">
<v-icon icon="mdi-alert-circle" color="error" size="64"></v-icon>
<h1 class="text-2xl font-bold text-red-600">{{ t('error.title') }}</h1>
<p>{{ errorMessage || t('error.defaultMessage') }}</p>
<div class="mt-4 flex flex-col gap-4 w-full">
<v-btn color="primary" @click="goToLogin">{{ t('error.goToLogin') }}</v-btn>
<v-divider class="my-4"></v-divider>
<!-- Resend verification email section -->
<h2 class="text-xl font-medium">{{ t('resend.title') }}</h2>
<v-form @submit.prevent="handleResendVerification" class="w-full">
<div class="flex flex-col gap-4">
<v-text-field
v-model="resendEmail"
:label="t('resend.emailLabel')"
type="email"
required
:error-messages="resendEmailError"
></v-text-field>
<v-btn
type="submit"
color="secondary"
block
:loading="resendLoading"
>
{{ t('resend.button') }}
</v-btn>
<!-- Resend success message -->
<div v-if="resendSuccess" class="mt-2 p-3 bg-green-50 border border-green-200 rounded text-green-700 text-sm">
{{ t('resend.success') }}
</div>
<!-- Resend error message -->
<div v-if="resendError" class="mt-2 p-3 bg-red-50 border border-red-200 rounded text-red-700 text-sm">
{{ resendError }}
</div>
</div>
</v-form>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useClient } from '@/plugins/api.js';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const clientApi = useClient();
// Verification state
const isLoading = ref(true);
const verificationSuccess = ref(false);
const errorMessage = ref('');
// Resend verification state
const resendEmail = ref('');
const resendEmailError = ref('');
const resendLoading = ref(false);
const resendSuccess = ref(false);
const resendError = ref('');
onMounted(async () => {
const userId = route.query.userId;
const token = route.query.token;
// Populate resend email field if it was in the URL
if (route.query.email) {
resendEmail.value = route.query.email;
}
// Check if we have the required parameters
if (!userId || !token) {
isLoading.value = false;
errorMessage.value = t('error.missingParams');
return;
}
try {
// Call the verification endpoint
await clientApi.get(`/api/users/verify-email?userId=${userId}&token=${token}`);
verificationSuccess.value = true;
} catch (error) {
console.error('Email verification failed:', error);
errorMessage.value = error.response?.data?.message || t('error.defaultMessage');
} finally {
isLoading.value = false;
}
});
async function handleResendVerification() {
// Reset states
resendEmailError.value = '';
resendSuccess.value = false;
resendError.value = '';
// Simple email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(resendEmail.value)) {
resendEmailError.value = t('resend.invalidEmail');
return;
}
resendLoading.value = true;
try {
await clientApi.post('/api/users/resend-verification', {
email: resendEmail.value.trim()
});
resendSuccess.value = true;
} catch (error) {
console.error('Resend verification failed:', error);
resendError.value = error.response?.data?.message || t('resend.error');
} finally {
resendLoading.value = false;
}
}
function goToLogin() {
router.push('/login');
}
</script>
<i18n>
{
"en": {
"verifying": "Verifying your email...",
"success": {
"title": "Email Verified Successfully!",
"message": "Your email has been verified. You can now log in to your account.",
"goToLogin": "Go to Login"
},
"error": {
"title": "Verification Failed",
"defaultMessage": "We couldn't verify your email. The link may be invalid or expired.",
"missingParams": "Missing required verification parameters.",
"goToLogin": "Go to Login"
},
"resend": {
"title": "Resend Verification Email",
"emailLabel": "Email",
"button": "Resend Verification Email",
"success": "Verification email sent successfully. Please check your inbox.",
"error": "Failed to send verification email. Please try again.",
"invalidEmail": "Please enter a valid email address."
}
},
"fr": {
"verifying": "Vérification de votre email...",
"success": {
"title": "Email vérifié avec succès !",
"message": "Votre email a été vérifié. Vous pouvez maintenant vous connecter à votre compte.",
"goToLogin": "Aller à la connexion"
},
"error": {
"title": "Échec de la vérification",
"defaultMessage": "Nous n'avons pas pu vérifier votre email. Le lien peut être invalide ou expiré.",
"missingParams": "Paramètres de vérification requis manquants.",
"goToLogin": "Aller à la connexion"
},
"resend": {
"title": "Renvoyer l'email de vérification",
"emailLabel": "Email",
"button": "Renvoyer l'email de vérification",
"success": "Email de vérification envoyé avec succès. Veuillez vérifier votre boîte de réception.",
"error": "Échec de l'envoi de l'email de vérification. Veuillez réessayer.",
"invalidEmail": "Veuillez entrer une adresse email valide."
}
},
"es": {
"verifying": "Verificando tu correo electrónico...",
"success": {
"title": "¡Correo electrónico verificado con éxito!",
"message": "Tu correo electrónico ha sido verificado. Ahora puedes iniciar sesión en tu cuenta.",
"goToLogin": "Ir al inicio de sesión"
},
"error": {
"title": "Falló la verificación",
"defaultMessage": "No pudimos verificar tu correo electrónico. El enlace puede ser inválido o estar caducado.",
"missingParams": "Faltan parámetros de verificación requeridos.",
"goToLogin": "Ir al inicio de sesión"
},
"resend": {
"title": "Reenviar correo de verificación",
"emailLabel": "Correo electrónico",
"button": "Reenviar correo de verificación",
"success": "Correo de verificación enviado con éxito. Por favor revisa tu bandeja de entrada.",
"error": "Error al enviar el correo de verificación. Por favor, inténtelo de nuevo.",
"invalidEmail": "Por favor, introduce una dirección de correo electrónico válida."
}
}
}
</i18n>

File diff suppressed because it is too large Load Diff

View File

@@ -1,191 +1,206 @@
<script setup> <script setup>
import { useI18n } from "vue-i18n"; import { useI18n } from 'vue-i18n';
import { useAuthStore } from "@/stores/authStore.js"; import { useAuthStore } from '@/stores/authStore.js';
import { useCreatorProfileStore } from "@/stores/creatorProfileStore.js"; import { useCreatorProfileStore } from '@/stores/creatorProfileStore.js';
import { useUserProfileStore } from "@/stores/userProfileStore.js"; import { useUserProfileStore } from '@/stores/userProfileStore.js';
import { useLanguageStore } from "@/stores/languageStore.js"; import { useLanguageStore } from '@/stores/languageStore.js';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import { mdiFileAccountOutline, mdiAccount, mdiLogin, mdiTranslateVariant, mdiLogout } from '@mdi/js'; import { mdiAccount, mdiFileAccountOutline, mdiLogin, mdiLogout, mdiTranslateVariant } from '@mdi/js';
const { locale, t } = useI18n(); const { locale, t } = useI18n();
const languageStore = useLanguageStore(); const languageStore = useLanguageStore();
const route = useRoute(); const route = useRoute();
const userProfileStore = useUserProfileStore(); const userProfileStore = useUserProfileStore();
const creatorProfileStore = useCreatorProfileStore(); const creatorProfileStore = useCreatorProfileStore();
const authStore = useAuthStore(); const authStore = useAuthStore();
function toggleLanguage() { function toggleLanguage() {
const languages = ['fr', 'en', 'es']; const languages = ['fr', 'en', 'es'];
const currentIndex = languages.indexOf(locale.value); const currentIndex = languages.indexOf(locale.value);
const nextIndex = (currentIndex + 1) % languages.length; const nextIndex = (currentIndex + 1) % languages.length;
languageStore.setLocale(languages[nextIndex]); languageStore.setLocale(languages[nextIndex]);
} }
function handleLogout() { function handleLogout() {
// Check if current route requires authentication authStore.logout();
const requiresAuth = route.matched.some(record => record.meta.requiresAuth); }
// If on a protected page, redirect to landing, otherwise stay on current page
const redirectTo = requiresAuth ? '/landing' : route.fullPath;
authStore.logout(redirectTo);
}
</script> </script>
<template> <template>
<nav class="side-container"> <nav class="side-container">
<div class="side-logo">
<div class="side-logo"> <router-link to="/@hutopy">
<router-link to="/@hutopy"> <img
<img src="/images/hutopy-logo.png" alt="hutopy logo" height="50"> alt="hutopy logo"
</router-link> height="50"
</div> src="/images/hutopy-logo.png"
/>
<div class="side-menu"> </router-link>
<div v-if="authStore.isAuthenticated" class="side-menu-portrait">
<img :src="userProfileStore.portraitUrl" alt="Profile Image" referrerpolicy="no-referrer" class="rounded-full">
<span class="profile-label">{{ userProfileStore.alias }}</span>
</div>
<div class="side-menu-items">
<template v-if="authStore.isAuthenticated">
<router-link v-if="creatorProfileStore.hasCreator" :to="`/@${creatorProfileStore.creator.slug}`">
<button class="menu-item-action">
<v-icon :icon="mdiFileAccountOutline" />
<span class="label">{{ t('sidebar.myPage') }}</span>
</button>
</router-link>
<router-link v-else to="/create-creator">
<button class="menu-item-action">
<v-icon :icon="mdiFileAccountOutline" />
<span class="label">{{ t('sidebar.myPage') }}</span>
</button>
</router-link>
</template>
<template v-if="authStore.isAuthenticated">
<router-link to="/profile">
<button class="menu-item-action">
<v-icon :icon="mdiAccount" />
<span class="label">{{ t('sidebar.myProfile') }}</span>
</button>
</router-link>
</template>
<button class="menu-item-action" @click="toggleLanguage">
<v-icon :icon="mdiTranslateVariant" />
<span class="label">{{ locale }}</span>
</button>
<template v-if="!authStore.isAuthenticated">
<router-link to="/login">
<button class="menu-item-action">
<v-icon :icon="mdiLogin" />
<span class="label">{{ t('sidebar.signIn') }}</span>
</button>
</router-link>
</template>
<div v-else>
<button class="menu-item-action" @click="handleLogout">
<v-icon :icon="mdiLogout" />
<span class="label">{{ t('sidebar.signOut') }}</span>
</button>
</div> </div>
</div> <div class="side-menu">
</div> <div
</nav> v-if="authStore.isAuthenticated"
class="side-menu-portrait"
>
<img
:src="userProfileStore.portraitUrl"
alt="Profile Image"
class="rounded-full"
referrerpolicy="no-referrer"
/>
<span class="profile-label">{{ userProfileStore.alias }}</span>
</div>
<div class="side-menu-items">
<template v-if="authStore.isAuthenticated">
<router-link
v-if="creatorProfileStore.hasCreator"
:to="`/@${creatorProfileStore.creator.slug}`"
>
<button class="menu-item-action">
<v-icon :icon="mdiFileAccountOutline" />
<span class="label">{{ t('sidebar.myPage') }}</span>
</button>
</router-link>
<router-link
v-else
to="/create-creator"
>
<button class="menu-item-action">
<v-icon :icon="mdiFileAccountOutline" />
<span class="label">{{ t('sidebar.myPage') }}</span>
</button>
</router-link>
</template>
<template v-if="authStore.isAuthenticated">
<router-link to="/profile">
<button class="menu-item-action">
<v-icon :icon="mdiAccount" />
<span class="label">{{ t('sidebar.myProfile') }}</span>
</button>
</router-link>
</template>
<button
class="menu-item-action"
@click="toggleLanguage"
>
<v-icon :icon="mdiTranslateVariant" />
<span class="label">{{ locale }}</span>
</button>
<template v-if="!authStore.isAuthenticated">
<router-link to="/login">
<button class="menu-item-action">
<v-icon :icon="mdiLogin" />
<span class="label">{{ t('sidebar.signIn') }}</span>
</button>
</router-link>
</template>
<div v-else>
<button
class="menu-item-action"
@click="handleLogout"
>
<v-icon :icon="mdiLogout" />
<span class="label">{{ t('sidebar.signOut') }}</span>
</button>
</div>
</div>
</div>
</nav>
</template> </template>
<style scoped> <style scoped>
.side-container { .side-container {
@apply bg-hSurface text-hOnSurface; @apply bg-hSurface text-hOnSurface;
@apply lg:fixed lg:max-h-screen; @apply lg:fixed lg:max-h-screen;
@apply flex; @apply flex;
@apply lg:flex-col lg:w-64 lg:max-w-64; @apply lg:flex-col lg:w-64 lg:max-w-64;
@apply h-16 lg:h-screen; @apply h-16 lg:h-screen;
@apply lg:border-r-2 lg:border-[#2d282d]; @apply lg:border-r-2 lg:border-[#2d282d];
} }
.side-logo { .side-logo {
@apply flex flex-grow; @apply flex flex-grow;
@apply items-center justify-start p-4; @apply items-center justify-start p-4;
@apply lg:items-start lg:justify-center lg:pt-4; @apply lg:items-start lg:justify-center lg:pt-4;
} }
.side-menu { .side-menu {
@apply flex gap-4 p-6; @apply flex gap-4 p-6;
@apply items-center lg:items-stretch; @apply items-center lg:items-stretch;
@apply flex-row-reverse lg:flex-col; @apply flex-row-reverse lg:flex-col;
} }
.side-menu-portrait { .side-menu-portrait {
@apply w-10 h-10; @apply w-10 h-10;
@apply -ml-1; @apply -ml-1;
@apply flex items-center justify-start; @apply flex items-center justify-start;
} }
.side-menu-items { .side-menu-items {
@apply flex gap-2; @apply flex gap-2;
@apply flex-row; @apply flex-row;
@apply lg:w-full lg:flex-col; @apply lg:w-full lg:flex-col;
} }
.profile-label { .profile-label {
@apply ml-5; @apply ml-5;
@apply text-lg font-sans capitalize; @apply text-lg font-sans capitalize;
@apply font-semibold; @apply font-semibold;
@apply hidden lg:inline; @apply hidden lg:inline;
@apply min-w-40 truncate; @apply min-w-40 truncate;
} }
.label { .label {
@apply text-nowrap; @apply text-nowrap;
@apply ml-4; @apply ml-4;
@apply hidden lg:inline; @apply hidden lg:inline;
} }
.menu-item-action { .menu-item-action {
@apply bg-hSurface text-hOnSurface hover:mix-blend-screen; @apply bg-hSurface text-hOnSurface hover:mix-blend-screen;
@apply capitalize; @apply capitalize;
@apply flex items-center gap-3 p-2 rounded-full md:rounded-full; @apply flex items-center gap-3 p-2 rounded-full md:rounded-full;
@apply mx-0; @apply mx-0;
@apply lg:pl-2; @apply lg:pl-2;
@apply w-10 h-10 justify-center lg:w-full lg:h-auto lg:justify-normal; @apply w-10 h-10 justify-center lg:w-full lg:h-auto lg:justify-normal;
i { i {
@apply text-xl; @apply text-xl;
} }
} }
</style> </style>
<i18n> <i18n>
{ {
"en": { "en": {
"sidebar": { "sidebar": {
"myPage": "My Page", "myPage": "My Page",
"myProfile": "My Profile", "myProfile": "My Profile",
"signIn": "Sign In", "signIn": "Sign In",
"signOut": "Sign Out" "signOut": "Sign Out"
}
},
"fr": {
"sidebar": {
"myPage": "Ma Page",
"myProfile": "Mon Profil",
"signIn": "Se Connecter",
"signOut": "Se Déconnecter"
}
},
"es": {
"sidebar": {
"myPage": "Mi Página",
"myProfile": "Mi Perfil",
"signIn": "Iniciar Sesión",
"signOut": "Cerrar Sesión"
}
} }
},
"fr": {
"sidebar": {
"myPage": "Ma Page",
"myProfile": "Mon Profil",
"signIn": "Se Connecter",
"signOut": "Se Déconnecter"
}
},
"es": {
"sidebar": {
"myPage": "Mi Página",
"myProfile": "Mi Perfil",
"signIn": "Iniciar Sesión",
"signOut": "Cerrar Sesión"
}
}
} }
</i18n> </i18n>