Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ SMTP_USER=
SMTP_PASSWORD=
EMAIL_FROM=noreply@stellaiverse.com
EMAIL_VERIFICATION_URL=http://localhost:3000/auth/verify-email
PASSWORD_RESET_URL=http://localhost:3000/auth/password-reset
# Oracle Service Configuration
# Contract address for on-chain oracle (set to actual deployed contract)
ORACLE_CONTRACT_ADDRESS=0x0000000000000000000000000000000000000000
Expand Down
3 changes: 2 additions & 1 deletion src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { EnhancedAuthService } from "./enhanced-auth.service";
import { User } from "src/user/entities/user.entity";
import { EmailVerification } from "./entities/email-verification.entity";
import { Wallet } from "./entities/wallet.entity";
import { RefreshToken, TwoFactorAuth } from "./entities/auth.entity";
import { RefreshToken, TwoFactorAuth, PasswordResetToken } from "./entities/auth.entity";

@Module({
imports: [
Expand All @@ -47,6 +47,7 @@ import { RefreshToken, TwoFactorAuth } from "./entities/auth.entity";
Wallet,
RefreshToken,
TwoFactorAuth,
PasswordResetToken,
]),
],
controllers: [AuthController, EnhancedAuthController],
Expand Down
17 changes: 17 additions & 0 deletions src/auth/dto/auth.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,20 @@ export class AuthStatusDto {
role: string;
};
}

export class PasswordResetRequestDto {
@IsEmail()
@IsNotEmpty()
email: string;
}

export class PasswordResetConfirmDto {
@IsString()
@IsNotEmpty()
token: string;

@IsString()
@IsNotEmpty()
@MinLength(8)
newPassword: string;
}
74 changes: 74 additions & 0 deletions src/auth/email.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,80 @@ export class EmailService {
};
}

async sendPasswordResetEmail(
email: string,
token: string,
): Promise<{ messageId: string; previewUrl?: string }> {
const resetUrl = `${this.configService.get<string>("PASSWORD_RESET_URL")}?token=${token}`;

const info = await this.transporter.sendMail({
from: this.configService.get<string>("EMAIL_FROM"),
to: email,
subject: "Reset your password - StellAIverse",
html: `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
.content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
.button { display: inline-block; padding: 12px 30px; background: #667eea; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
.footer { text-align: center; margin-top: 20px; color: #666; font-size: 12px; }
.code { background: #fff; padding: 15px; border-left: 4px solid #667eea; margin: 20px 0; font-family: monospace; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🔑 Reset Your Password</h1>
</div>
<div class="content">
<p>Hello!</p>
<p>You've requested to reset your password for your StellAIverse account.</p>
<p>Click the button below to reset your password:</p>
<p style="text-align: center;">
<a href="${resetUrl}" class="button">Reset Password</a>
</p>
<p>Or copy and paste this link into your browser:</p>
<div class="code">${resetUrl}</div>
<p><strong>This link will expire in 15 minutes.</strong></p>
<p>If you didn't request this password reset, you can safely ignore this email.</p>
</div>
<div class="footer">
<p>© ${new Date().getFullYear()} StellAIverse. All rights reserved.</p>
</div>
</div>
</body>
</html>
`,
text: `
Reset Your Password - StellAIverse

You've requested to reset your password for your StellAIverse account.

Click the link below to reset your password:
${resetUrl}

This link will expire in 15 minutes.

If you didn't request this password reset, you can safely ignore this email.
`,
});

const previewUrl = nodemailer.getTestMessageUrl(info);

if (previewUrl) {
this.logger.log(`Password reset email preview URL: ${previewUrl}`);
}

return {
messageId: info.messageId,
previewUrl: previewUrl || undefined,
};
}

/**
* Generic send mail method for custom emails
*/
Expand Down
58 changes: 57 additions & 1 deletion src/auth/enhanced-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ import {
} from "@nestjs/swagger";
import { JwtAuthGuard } from "./jwt.guard";
import { EnhancedAuthService } from "./enhanced-auth.service";
import { RegisterDto, LoginDto } from "./dto/auth.dto";
import {
RegisterDto,
LoginDto,
PasswordResetRequestDto,
PasswordResetConfirmDto,
} from "./dto/auth.dto";
import {
TwoFactorSetupDto,
TwoFactorVerifyDto,
Expand Down Expand Up @@ -219,4 +224,55 @@ export class EnhancedAuthController {
body.password,
);
}

@Public()
@Post("password-reset")
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Request password reset",
description: "Send password reset link to user's email",
})
@ApiResponse({
status: 200,
description: "Password reset request processed",
})
async requestPasswordReset(@Body() passwordResetRequestDto: PasswordResetRequestDto) {
return this.enhancedAuthService.requestPasswordReset(passwordResetRequestDto);
}

@Public()
@Post("password-reset/confirm")
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Confirm password reset",
description: "Reset user's password using the reset token",
})
@ApiResponse({
status: 200,
description: "Password reset successfully",
})
@ApiResponse({
status: 400,
description: "Invalid or expired token",
})
async confirmPasswordReset(@Body() passwordResetConfirmDto: PasswordResetConfirmDto) {
return this.enhancedAuthService.confirmPasswordReset(passwordResetConfirmDto);
}

@Post("logout")
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Logout",
description: "Revoke the refresh token",
})
@ApiResponse({
status: 200,
description: "Logged out successfully",
})
async logout(@Body() refreshTokenDto: RefreshTokenDto) {
await this.enhancedAuthService.revokeRefreshToken(refreshTokenDto.refreshToken);
return { message: "Logged out successfully" };
}
}
77 changes: 77 additions & 0 deletions src/auth/enhanced-auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,18 @@ import {
TwoFactorAuth,
TwoFactorType,
TwoFactorStatus,
PasswordResetToken,
} from "./entities/auth.entity";
import {
LoginDto,
RegisterDto,
RefreshTokenDto,
TwoFactorVerifyDto,
PasswordResetRequestDto,
PasswordResetConfirmDto,
} from "./dto/auth.dto";
import { TwoFactorSetupDto } from "./dto/kyc.dto";
import { v4 as uuidv4 } from "uuid";

@Injectable()
export class EnhancedAuthService {
Expand All @@ -38,6 +42,8 @@ export class EnhancedAuthService {
private readonly refreshTokenRepository: Repository<RefreshToken>,
@InjectRepository(TwoFactorAuth)
private readonly twoFactorRepository: Repository<TwoFactorAuth>,
@InjectRepository(PasswordResetToken)
private readonly passwordResetTokenRepository: Repository<PasswordResetToken>,
private readonly jwtService: JwtService,
@Inject(forwardRef(() => EmailService))
private readonly emailService: EmailService,
Expand Down Expand Up @@ -430,7 +436,78 @@ export class EnhancedAuthService {
);
}

async revokeRefreshToken(refreshToken: string): Promise<void> {
const tokenEntity = await this.refreshTokenRepository.findOne({
where: { token: refreshToken },
});
if (tokenEntity) {
await this.refreshTokenRepository.update(tokenEntity.id, {
revoked: true,
revokedAt: new Date(),
});
}
}

async validateUser(userId: string): Promise<User | null> {
return this.userRepository.findOne({ where: { id: userId } });
}

async requestPasswordReset(
passwordResetRequestDto: PasswordResetRequestDto,
): Promise<{ message: string }> {
const { email } = passwordResetRequestDto;
const user = await this.userRepository.findOne({ where: { email } });

if (!user) {
return { message: "If the email exists, a reset link has been sent." };
}

const resetToken = this.generateRefreshToken();
const expiresAt = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes

const passwordResetToken = this.passwordResetTokenRepository.create({
userId: user.id,
token: resetToken,
expiresAt,
});

await this.passwordResetTokenRepository.save(passwordResetToken);

await this.emailService.sendPasswordResetEmail(email, resetToken);

return { message: "If the email exists, a reset link has been sent." };
}

async confirmPasswordReset(
passwordResetConfirmDto: PasswordResetConfirmDto,
): Promise<{ message: string }> {
const { token, newPassword } = passwordResetConfirmDto;

const resetToken = await this.passwordResetTokenRepository.findOne({
where: { token },
relations: ["user"],
});

if (
!resetToken ||
resetToken.expiresAt < new Date() ||
resetToken.used
) {
throw new BadRequestException("Invalid or expired reset token");
}

const saltRounds = 12;
const hashedPassword = await bcrypt.hash(newPassword, saltRounds);
await this.userRepository.update(resetToken.user.id, {
password: hashedPassword,
});

await this.passwordResetTokenRepository.update(resetToken.id, {
used: true,
});

await this.revokeAllRefreshTokens(resetToken.user.id);

return { message: "Password reset successfully" };
}
}
26 changes: 26 additions & 0 deletions src/auth/entities/auth.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,29 @@ export class TwoFactorAuth {
@UpdateDateColumn()
updatedAt: Date;
}

@Entity("password_reset_tokens")
export class PasswordResetToken {
@PrimaryGeneratedColumn("uuid")
id: string;

@Column({ type: "uuid" })
@Index()
userId: string;

@ManyToOne(() => User)
@JoinColumn({ name: "userId" })
user: User;

@Column({ unique: true })
token: string;

@Column({ type: "timestamp" })
expiresAt: Date;

@Column({ default: false })
used: boolean;

@CreateDateColumn()
createdAt: Date;
}
Loading