Skip to content

Commit

Permalink
ADD: refresh-fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniil-Oberlev committed Sep 6, 2024
1 parent 2426df4 commit d6c2a65
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 16 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
AUTH_API_URL=http://localhost:4444
JWT_SECRET=secret123
ACCESS_TOKEN_SECRET=secret123
NODE_ENV=production
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
AUTH_API_URL=
JWT_SECRET=
ACCESS_TOKEN_SECRET=
NODE_ENV=
23 changes: 15 additions & 8 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { jwtVerify } from 'jose'
import { NextRequest, NextResponse } from 'next/server'

const SECRET_KEY = new TextEncoder().encode(process.env.JWT_SECRET)
const ACCESS_TOKEN_SECRET = new TextEncoder().encode(
process.env.ACCESS_TOKEN_SECRET,
)
const REFRESH_TOKEN_SECRET = new TextEncoder().encode(
process.env.REFRESH_TOKEN_SECRET,
)

const parseCookies = (cookieHeader: string): Record<string, string> => {
return cookieHeader.split('; ').reduce(
Expand All @@ -15,21 +20,18 @@ const parseCookies = (cookieHeader: string): Record<string, string> => {
}

export async function middleware(request: NextRequest) {
console.log('Middleware triggered for:', request.nextUrl.pathname)

const cookiesHeader = request.headers.get('cookie') || ''
const cookies = parseCookies(cookiesHeader)
const accessToken = cookies['accessToken']?.trim()
const refreshToken = cookies['refreshToken']?.trim()

if (!accessToken || !refreshToken) {
console.log('Tokens are missing')
return NextResponse.redirect(new URL('/login', request.url))
}

try {
const { payload } = await jwtVerify(accessToken, SECRET_KEY)
console.log('Decoded token:', payload)
// Validate access token
await jwtVerify(accessToken, ACCESS_TOKEN_SECRET)
return NextResponse.next()
} catch (err) {
console.error('Access token invalid or expired:', err)
Expand All @@ -41,7 +43,7 @@ export async function middleware(request: NextRequest) {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: refreshToken }), // Correctly send the refresh token
body: JSON.stringify({ token: refreshToken }),
})

if (response.ok) {
Expand All @@ -51,7 +53,12 @@ export async function middleware(request: NextRequest) {

const responseNext = NextResponse.next()
responseNext.cookies.set('accessToken', newAccessToken)
responseNext.cookies.set('refreshToken', newRefreshToken)

// Обновление refreshToken в cookies, если сервер его предоставляет
if (newRefreshToken) {
responseNext.cookies.set('refreshToken', newRefreshToken)
}

return responseNext
} else {
throw new Error('Failed to refresh token')
Expand Down
2 changes: 0 additions & 2 deletions src/services/api/profileApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@ import { apiClient, handleApiError } from './apiClient'

export const fetchProfileData = async (accessToken: string) => {
try {
console.log('Making request to /auth/me with accessToken')
const response = await apiClient.get('/auth/me', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
console.log('Received response from /auth/me:', response.data)
return response.data
} catch (error) {
console.error('Error fetching profile data:', error)
Expand Down
4 changes: 0 additions & 4 deletions src/services/profileService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ const handleTokenRefresh = async (
fetchData: (token: string) => Promise<ProfileData>,
): Promise<string> => {
try {
console.log('Access token expired, attempting to refresh...')
const newAccessToken = await refreshToken()
const data = await fetchData(newAccessToken)
console.log('Profile data received after refreshing token:', data)
return data.fullName || ''
} catch (refreshError) {
if (axios.isAxiosError(refreshError)) {
Expand All @@ -32,9 +30,7 @@ const handleTokenRefresh = async (

export const getProfile = async (accessToken: string): Promise<string> => {
try {
console.log('Fetching profile data with accessToken:', accessToken)
const data: ProfileData = await fetchProfileData(accessToken)
console.log('Profile data received:', data)
return data.fullName || ''
} catch (error) {
if (axios.isAxiosError(error)) {
Expand Down

0 comments on commit d6c2a65

Please sign in to comment.