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
33 changes: 26 additions & 7 deletions apps/api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

@Injectable()
export class AuthService {
private readonly JWT_ACCESS_TOKEN_TTL
private readonly JWT_REFRESH_TOKEN_TTL
private readonly JWT_ACCESS_TOKEN_TTL: string
private readonly JWT_REFRESH_TOKEN_TTL: string
private readonly COOKIE_DOMAIN: string
private readonly COOKIE_TTL: string

Expand Down Expand Up @@ -60,7 +60,7 @@
},
})

return await this.auth(res, user.id)

Check warning on line 63 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`
}

async login(res: Response, dto: LoginRequestDto) {
Expand All @@ -80,13 +80,13 @@
throw new NotFoundException('Пользователь не найден')
}

const isPasswordValid = await verify(user.password, password)

Check warning on line 83 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`

if (!isPasswordValid) {
throw new NotFoundException('Пользователь не найден')
}

return await this.auth(res, user.id)

Check warning on line 89 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`
}

async refresh(req: Request, res: Response) {
Expand Down Expand Up @@ -118,7 +118,7 @@
throw new NotFoundException('Пользователь не найден')
}

return await this.auth(res, user.id)

Check warning on line 121 in apps/api/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / ci

Unsafe argument of type error typed assigned to a parameter of type `string`
}
}

Expand All @@ -132,7 +132,8 @@
}
}

this.setCookie(res, 'refreshToken', new Date(0))
this.setCookie(res, 'refreshToken', '', new Date(0), '/auth/refresh')
this.setCookie(res, 'accessToken', '', new Date(0), '/')

return { message: 'Пользователь успешно вышел', success: true }
}
Expand All @@ -158,34 +159,52 @@

this.setCookie(
res,
'refreshToken',
refreshToken,
new Date(Date.now() + parseTTLToMs(this.COOKIE_TTL)),
'/auth/refresh',
)

this.setCookie(
res,
'accessToken',
accessToken,
new Date(Date.now() + parseTTLToMs(this.JWT_ACCESS_TOKEN_TTL)),
'/',
)

// TODO: удалить когда фронтенд перейдёт на cookie-only
return { accessToken }
}

private generateTokens(userId: string) {
const payload: JwtPayload = { id: userId }

const accessToken = this.jwtService.sign(payload, {
expiresIn: this.JWT_ACCESS_TOKEN_TTL,
expiresIn: parseTTLToMs(this.JWT_ACCESS_TOKEN_TTL) / 1000,
})

const refreshToken = this.jwtService.sign(payload, {
expiresIn: this.JWT_REFRESH_TOKEN_TTL,
expiresIn: parseTTLToMs(this.JWT_REFRESH_TOKEN_TTL) / 1000,
})

return { accessToken, refreshToken }
}

private setCookie(res: Response, value: string, expires: Date) {
res.cookie('refreshToken', value, {
private setCookie(
res: Response,
name: string,
value: string,
expires: Date,
path = '/',
) {
res.cookie(name, value, {
httpOnly: true,
secure: !isDev(this.configService),
sameSite: isDev(this.configService) ? 'lax' : 'strict',
domain: this.COOKIE_DOMAIN,
expires,
path,
})
}
}
6 changes: 5 additions & 1 deletion apps/api/src/strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from 'passport-jwt'
import type { Request } from 'express'
import { AuthService } from 'src/auth/auth.service'
import { JwtPayload } from 'src/auth/interfaces/jwt.interface'

Expand All @@ -12,7 +13,10 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
private readonly configService: ConfigService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
(req: Request) => req?.cookies?.['accessToken'] ?? null,
]),
ignoreExpiration: false,
secretOrKey: configService.getOrThrow<string>('JWT_SECRET'),
algorithms: ['HS256'],
Expand Down
6 changes: 3 additions & 3 deletions apps/web/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ import { NextResponse, type NextRequest, type ProxyConfig } from 'next/server'

export function proxy(request: NextRequest) {
const { pathname, search } = request.nextUrl
const refreshToken = !!request.cookies.get('refreshToken')?.value
const accessToken = !!request.cookies.get('accessToken')?.value

if (!refreshToken && isProtectedRoute(pathname)) {
if (!accessToken && isProtectedRoute(pathname)) {
const url = new URL(ROUTES.login, request.url)
url.searchParams.set(ROUTE_QUERY_PARAMS.from, `${pathname}${search}`)
return NextResponse.redirect(url)
}

if (refreshToken && isAuthRoute(pathname)) {
if (accessToken && isAuthRoute(pathname)) {
return NextResponse.redirect(new URL(ROUTES.teams, request.url))
}

Expand Down
Loading