authService.ts207 lines, 5.3 KB
| 1 | import { AuthTokens, JWTPayload, ServiceError } from "../../../shared/types"; |
| 2 | import prisma from "./database"; |
| 3 | import { createServiceError } from "../../../shared/utils"; |
| 4 | import bcrypt from "bcryptjs"; |
| 5 | import jwt, { SignOptions } from "jsonwebtoken"; |
| 6 | import { StringValue } from "ms"; |
| 7 | |
| 8 | export class AuthService { |
| 9 | private readonly jwtSecret: string; |
| 10 | private readonly jwtRefreshSecret: string; |
| 11 | private readonly jwtExpiresIn: string; |
| 12 | private readonly jwtRefreshExpiresIn: string; |
| 13 | private readonly bcryptRounds: number; |
| 14 | |
| 15 | constructor() { |
| 16 | this.jwtSecret = process.env.JWT_SECRET!; |
| 17 | this.jwtRefreshSecret = process.env.JWT_REFRESH_SECRET!; |
| 18 | this.jwtExpiresIn = process.env.JWT_EXPIRES_IN || "15m"; |
| 19 | this.jwtRefreshExpiresIn = process.env.JWT_REFRESH_EXPIRES_IN || "7d"; |
| 20 | this.bcryptRounds = parseInt(process.env.BCRYPT_ROUNDS || "10", 10); |
| 21 | |
| 22 | if (!this.jwtSecret || !this.jwtRefreshSecret) { |
| 23 | throw new Error("JWT secrets are not defined in environment variables"); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | async register(email: string, password: string): Promise<AuthTokens> { |
| 28 | // check if user already exists |
| 29 | const existingUser = await prisma.user.findUnique({ |
| 30 | where: { email }, |
| 31 | }); |
| 32 | |
| 33 | if (existingUser) { |
| 34 | throw createServiceError("User already exists", 409); |
| 35 | } |
| 36 | |
| 37 | // hash the password |
| 38 | const hashedPassword = await bcrypt.hash(password, this.bcryptRounds); |
| 39 | |
| 40 | // create the user |
| 41 | const user = await prisma.user.create({ |
| 42 | data: { |
| 43 | email, |
| 44 | password: hashedPassword, |
| 45 | }, |
| 46 | }); |
| 47 | |
| 48 | // generate tokens |
| 49 | return this.generateTokens(user.id, user.email); |
| 50 | } |
| 51 | |
| 52 | async login(email: string, password: string): Promise<AuthTokens> { |
| 53 | // find the user |
| 54 | const user = await prisma.user.findUnique({ |
| 55 | where: { email }, |
| 56 | }); |
| 57 | |
| 58 | if (!user) { |
| 59 | throw createServiceError("Invalid email or password", 401); |
| 60 | } |
| 61 | |
| 62 | // verify the password |
| 63 | const isPasswordValid = await bcrypt.compare(password, user.password); |
| 64 | if (!isPasswordValid) { |
| 65 | throw createServiceError("Invalid email or password", 401); |
| 66 | } |
| 67 | |
| 68 | // generate tokens |
| 69 | return this.generateTokens(user.id, user.email); |
| 70 | } |
| 71 | |
| 72 | async refreshToken(refreshToken: string): Promise<AuthTokens> { |
| 73 | try { |
| 74 | // verify the refresh token |
| 75 | const decoded = jwt.verify( |
| 76 | refreshToken, |
| 77 | this.jwtRefreshSecret |
| 78 | ) as JWTPayload; |
| 79 | |
| 80 | // check if the refresh token exists in the database |
| 81 | const storedToken = await prisma.refreshToken.findUnique({ |
| 82 | where: { token: refreshToken }, |
| 83 | include: { user: true }, |
| 84 | }); |
| 85 | |
| 86 | if (!storedToken || storedToken.expiresAt < new Date()) { |
| 87 | throw createServiceError("Invalid or expired refresh token", 401); |
| 88 | } |
| 89 | |
| 90 | // generate new tokens |
| 91 | const tokens = await this.generateTokens( |
| 92 | storedToken.user.id, |
| 93 | storedToken.user.email |
| 94 | ); |
| 95 | |
| 96 | // delete the old refresh token |
| 97 | await prisma.refreshToken.delete({ |
| 98 | where: { id: storedToken.id }, |
| 99 | }); |
| 100 | |
| 101 | return tokens; |
| 102 | } catch (error) { |
| 103 | if (error instanceof ServiceError) { |
| 104 | throw error; |
| 105 | } |
| 106 | throw createServiceError("Invalid refresh token", 401, error); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | async logout(refreshToken: string): Promise<void> { |
| 111 | // delete the refresh token from the database |
| 112 | await prisma.refreshToken.deleteMany({ |
| 113 | where: { token: refreshToken }, |
| 114 | }); |
| 115 | } |
| 116 | |
| 117 | async validateToken(token: string): Promise<JWTPayload> { |
| 118 | try { |
| 119 | const decoded = jwt.verify(token, this.jwtSecret) as JWTPayload; |
| 120 | |
| 121 | // Check if the user exists |
| 122 | const user = await prisma.user.findUnique({ |
| 123 | where: { id: decoded.userId }, |
| 124 | }); |
| 125 | |
| 126 | if (!user) { |
| 127 | throw createServiceError("User not found", 404); |
| 128 | } |
| 129 | |
| 130 | return decoded; |
| 131 | } catch (error) { |
| 132 | if (error instanceof jwt.JsonWebTokenError) { |
| 133 | throw createServiceError("Invalid token", 401); |
| 134 | } |
| 135 | throw createServiceError("Token validation failed", 500, error); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | private async generateTokens( |
| 140 | userId: string, |
| 141 | email: string |
| 142 | ): Promise<AuthTokens> { |
| 143 | const payload = { userId, email }; |
| 144 | |
| 145 | // Generate access token |
| 146 | const accessTokenOptions: SignOptions = { |
| 147 | expiresIn: this.jwtExpiresIn as StringValue, |
| 148 | }; |
| 149 | |
| 150 | const accessToken = jwt.sign( |
| 151 | payload, |
| 152 | this.jwtSecret, |
| 153 | accessTokenOptions |
| 154 | ) as string; |
| 155 | |
| 156 | // Generate refresh token |
| 157 | const refreshTokenOptions: SignOptions = { |
| 158 | expiresIn: this.jwtRefreshExpiresIn as StringValue, |
| 159 | }; |
| 160 | const refreshToken = jwt.sign( |
| 161 | payload, |
| 162 | this.jwtRefreshSecret, |
| 163 | refreshTokenOptions |
| 164 | ) as string; |
| 165 | |
| 166 | // Store refresh token in the database |
| 167 | const expiresAt = new Date(); |
| 168 | expiresAt.setDate(expiresAt.getDate() + 7); // 7 days from now |
| 169 | |
| 170 | await prisma.refreshToken.create({ |
| 171 | data: { |
| 172 | userId, |
| 173 | token: refreshToken, |
| 174 | expiresAt, |
| 175 | }, |
| 176 | }); |
| 177 | |
| 178 | return { |
| 179 | accessToken, |
| 180 | refreshToken, |
| 181 | }; |
| 182 | } |
| 183 | |
| 184 | async getUserById(userId: string) { |
| 185 | const user = await prisma.user.findUnique({ |
| 186 | where: { id: userId }, |
| 187 | select: { |
| 188 | id: true, |
| 189 | email: true, |
| 190 | createdAt: true, |
| 191 | updatedAt: true, |
| 192 | }, |
| 193 | }); |
| 194 | |
| 195 | if (!user) { |
| 196 | throw createServiceError("User not found", 404); |
| 197 | } |
| 198 | |
| 199 | return user; |
| 200 | } |
| 201 | |
| 202 | async deleteUser(userId: string): Promise<void> { |
| 203 | await prisma.user.delete({ |
| 204 | where: { id: userId }, |
| 205 | }); |
| 206 | } |
| 207 | } |