auth.service.ts155 lines, 4.7 KB
| 1 | import { User } from "../entities/user.entity"; |
| 2 | import { AppDataSource } from "../config/database"; |
| 3 | import { AppError } from "../utils/errors"; |
| 4 | import { StatusCodes } from "http-status-codes"; |
| 5 | import crypto from "crypto"; |
| 6 | import jwt, { Secret, SignOptions } from "jsonwebtoken"; |
| 7 | import { EmailService } from "./email.service"; |
| 8 | |
| 9 | export class AuthService { |
| 10 | private static readonly userRepository = AppDataSource.getRepository(User); |
| 11 | private static readonly JWT_SECRET: Secret = |
| 12 | process.env.JWT_SECRET || "secret"; |
| 13 | private static readonly JWT_EXPIRES_IN = (process.env.JWT_EXPIRES_IN || |
| 14 | "24h") as SignOptions["expiresIn"]; |
| 15 | |
| 16 | static async register(email: string, password: string, name?: string) { |
| 17 | const existingUser = await this.userRepository.findOne({ |
| 18 | where: { email }, |
| 19 | }); |
| 20 | if (existingUser) { |
| 21 | throw new AppError(StatusCodes.BAD_REQUEST, "Invalid credentials"); |
| 22 | } |
| 23 | |
| 24 | // Create a verification token |
| 25 | const verificationToken = crypto.randomBytes(32).toString("hex"); |
| 26 | const tokenExpires = new Date(); |
| 27 | tokenExpires.setHours(tokenExpires.getHours() + 24); // 24 hours |
| 28 | |
| 29 | const user = new User(); |
| 30 | user.email = email; |
| 31 | user.password = password; |
| 32 | user.name = name || ""; |
| 33 | user.emailVerificationToken = verificationToken; |
| 34 | user.emailVerificationTokenExpires = tokenExpires; |
| 35 | |
| 36 | await this.userRepository.save(user); |
| 37 | |
| 38 | await EmailService.sendVerificationEmail(email, verificationToken); |
| 39 | |
| 40 | const token = this.generateToken(user); |
| 41 | return { user, token }; |
| 42 | } |
| 43 | |
| 44 | static async login(email: string, password: string) { |
| 45 | const user = await this.userRepository.findOne({ where: { email } }); |
| 46 | if (!user) { |
| 47 | throw new AppError(StatusCodes.BAD_REQUEST, "Invalid credentials"); |
| 48 | } |
| 49 | |
| 50 | const isPasswordValid = await user.comparePassword(password); |
| 51 | if (!isPasswordValid) { |
| 52 | throw new AppError(StatusCodes.BAD_REQUEST, "Invalid credentials"); |
| 53 | } |
| 54 | |
| 55 | user.lastLogin = new Date(); |
| 56 | await this.userRepository.save(user); |
| 57 | |
| 58 | const token = this.generateToken(user); |
| 59 | return { user, token }; |
| 60 | } |
| 61 | |
| 62 | static async verifyEmail(token: string) { |
| 63 | const user = await this.userRepository.findOne({ |
| 64 | where: { emailVerificationToken: token }, |
| 65 | }); |
| 66 | |
| 67 | if (!user) { |
| 68 | throw new AppError(StatusCodes.BAD_REQUEST, "Invalid verification token"); |
| 69 | } |
| 70 | |
| 71 | if ( |
| 72 | !user.emailVerificationTokenExpires || |
| 73 | user.emailVerificationTokenExpires < new Date() |
| 74 | ) { |
| 75 | throw new AppError(StatusCodes.BAD_REQUEST, "Verification token expired"); |
| 76 | } |
| 77 | |
| 78 | user.isEmailVerified = true; |
| 79 | user.emailVerificationToken = null; |
| 80 | user.emailVerificationTokenExpires = null; |
| 81 | await this.userRepository.save(user); |
| 82 | |
| 83 | await EmailService.sendWelcomeEmail(user.email, user.name); |
| 84 | |
| 85 | return { message: "Email verified successfully" }; |
| 86 | } |
| 87 | |
| 88 | static async resendVerificationEmail(email: string) { |
| 89 | const user = await this.userRepository.findOne({ where: { email } }); |
| 90 | |
| 91 | if (!user) { |
| 92 | throw new AppError(StatusCodes.BAD_REQUEST, "User not found"); |
| 93 | } |
| 94 | |
| 95 | if (user.isEmailVerified) { |
| 96 | throw new AppError(StatusCodes.BAD_REQUEST, "Email already verified"); |
| 97 | } |
| 98 | |
| 99 | // Create a new verification token |
| 100 | const verificationToken = crypto.randomBytes(32).toString("hex"); |
| 101 | const tokenExpires = new Date(); |
| 102 | tokenExpires.setHours(tokenExpires.getHours() + 24); // 24 hours |
| 103 | |
| 104 | user.emailVerificationToken = verificationToken; |
| 105 | user.emailVerificationTokenExpires = tokenExpires; |
| 106 | await this.userRepository.save(user); |
| 107 | |
| 108 | await EmailService.sendVerificationEmail(email, verificationToken); |
| 109 | |
| 110 | return { message: "Verification email sent" }; |
| 111 | } |
| 112 | |
| 113 | static generateToken(user: User): string { |
| 114 | return jwt.sign({ userId: user.id, email: user.email }, this.JWT_SECRET, { |
| 115 | expiresIn: this.JWT_EXPIRES_IN, |
| 116 | }); |
| 117 | } |
| 118 | |
| 119 | static verifyToken(token: string): { userId: string; email: string } { |
| 120 | try { |
| 121 | return jwt.verify(token, this.JWT_SECRET) as { |
| 122 | userId: string; |
| 123 | email: string; |
| 124 | }; |
| 125 | } catch (error) { |
| 126 | throw new AppError(StatusCodes.UNAUTHORIZED, "Invalid token"); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | static async getProfile(userId: string) { |
| 131 | const user = await this.userRepository.findOne({ |
| 132 | where: { id: userId }, |
| 133 | relations: ["videos"], |
| 134 | }); |
| 135 | if (!user) { |
| 136 | throw new AppError(StatusCodes.NOT_FOUND, "User not found"); |
| 137 | } |
| 138 | |
| 139 | // Generate a fresh token to extend the session |
| 140 | const token = this.generateToken(user); |
| 141 | |
| 142 | return { user, token }; |
| 143 | } |
| 144 | |
| 145 | static async getUserById(userId: string): Promise<User> { |
| 146 | const user = await this.userRepository.findOne({ |
| 147 | where: { id: userId }, |
| 148 | relations: ["videos"], |
| 149 | }); |
| 150 | if (!user) { |
| 151 | throw new AppError(StatusCodes.NOT_FOUND, "User not found"); |
| 152 | } |
| 153 | return user; |
| 154 | } |
| 155 | } |