Skip to content

Commit 9c63cdb

Browse files
committed
🐞 FIX: refresh token if expired
1 parent 60d52f9 commit 9c63cdb

File tree

1 file changed

+33
-10
lines changed

1 file changed

+33
-10
lines changed

src/app/auth/auth.service.ts

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import jwt from 'jsonwebtoken';
22
import bcrypt from 'bcryptjs';
3-
import { BadRequestError, UnauthorizedError } from '../../utils/exceptions';
3+
import {
4+
BadRequestError,
5+
InternalServerError,
6+
UnauthorizedError,
7+
} from '../../utils/exceptions';
48
import { userTable } from '../user/user.model';
59
import { connectdb } from '../../configs/db';
610
import { eq } from 'drizzle-orm';
@@ -19,7 +23,7 @@ export class AuthService {
1923
constructor() {
2024
this.accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
2125
this.refreshTokenSecret = process.env.REFRESH_TOKEN_SECRET;
22-
this.accessTokenExpiry = '12h';
26+
this.accessTokenExpiry = '15m';
2327
this.refreshTokenExpiry = '7d';
2428
}
2529

@@ -87,39 +91,58 @@ export class AuthService {
8791
}
8892

8993
async login({ email, password }: { email: string; password: string }) {
90-
// Check if email and password are provided
9194
if (!email || !password) {
9295
throw new BadRequestError('Email and password are required');
9396
}
9497

95-
// Fetch the user by email
96-
// const user = await UserModel.findOne({ email });
98+
// Fetch user by email
9799
const { db, connection } = await connectdb();
98100
const [user] = await db
99101
.select()
100102
.from(userTable)
101103
.where(eq(userTable.email, email))
102104
.execute();
103-
await connection.end();
104105

105106
if (!user) {
106107
throw new UnauthorizedError('Invalid credentials');
107108
}
108109

109-
// Compare the plain password with the hashed password in the database
110110
const isPasswordValid = await this.comparePassword(password, user.hash);
111111
if (!isPasswordValid) {
112112
throw new UnauthorizedError('Invalid credentials');
113113
}
114114

115-
console.log({ user });
116115
// Generate access token
117116
const accessToken = this.generateAccessToken({
118117
email: user.email,
119118
id: user.id,
120119
});
121120

122-
// Return the generated tokens
121+
// Handle refresh token verification or renewal
122+
let refreshToken = user.refresh_token;
123+
try {
124+
this.verifyRefreshToken(refreshToken);
125+
} catch (err) {
126+
console.log('Refresh token is invalid, generating a new one...');
127+
refreshToken = this.generateRefreshToken({
128+
id: user.id,
129+
email: user.email,
130+
});
131+
132+
try {
133+
await db
134+
.update(userTable)
135+
.set({ refresh_token: refreshToken })
136+
.where(eq(userTable.id, user.id))
137+
.execute();
138+
console.log('Refresh token updated successfully');
139+
await connection.end();
140+
} catch (updateErr) {
141+
console.error('Database update error:', updateErr);
142+
throw new InternalServerError("Couldn't refresh token");
143+
}
144+
}
145+
123146
return {
124147
message: 'Login successful',
125148
user: {
@@ -128,7 +151,7 @@ export class AuthService {
128151
},
129152
data: {
130153
accessToken,
131-
refreshToken: user.refresh_token,
154+
refreshToken,
132155
},
133156
};
134157
}

0 commit comments

Comments
 (0)