mirror of
https://github.com/immich-app/immich.git
synced 2025-12-24 09:14:58 +03:00
refactor(server): cookies (#8920)
This commit is contained in:
@@ -10,13 +10,8 @@ import { SchemaObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.inte
|
||||
import _ from 'lodash';
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
CLIP_MODEL_INFO,
|
||||
IMMICH_ACCESS_COOKIE,
|
||||
IMMICH_API_KEY_HEADER,
|
||||
IMMICH_API_KEY_NAME,
|
||||
serverVersion,
|
||||
} from 'src/constants';
|
||||
import { CLIP_MODEL_INFO, serverVersion } from 'src/constants';
|
||||
import { ImmichCookie, ImmichHeader } from 'src/dtos/auth.dto';
|
||||
import { ILoggerRepository } from 'src/interfaces/logger.interface';
|
||||
import { Metadata } from 'src/middleware/auth.guard';
|
||||
|
||||
@@ -143,14 +138,14 @@ export const useSwagger = (app: INestApplication, isDevelopment: boolean) => {
|
||||
scheme: 'Bearer',
|
||||
in: 'header',
|
||||
})
|
||||
.addCookieAuth(IMMICH_ACCESS_COOKIE)
|
||||
.addCookieAuth(ImmichCookie.ACCESS_TOKEN)
|
||||
.addApiKey(
|
||||
{
|
||||
type: 'apiKey',
|
||||
in: 'header',
|
||||
name: IMMICH_API_KEY_HEADER,
|
||||
name: ImmichHeader.API_KEY,
|
||||
},
|
||||
IMMICH_API_KEY_NAME,
|
||||
Metadata.API_KEY_SECURITY,
|
||||
)
|
||||
.addServer('/api')
|
||||
.build();
|
||||
|
||||
36
server/src/utils/response.ts
Normal file
36
server/src/utils/response.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { CookieOptions, Response } from 'express';
|
||||
import { Duration } from 'luxon';
|
||||
import { CookieResponse, ImmichCookie } from 'src/dtos/auth.dto';
|
||||
|
||||
export const respondWithCookie = <T>(res: Response, body: T, { isSecure, values }: CookieResponse) => {
|
||||
const defaults: CookieOptions = {
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
httpOnly: true,
|
||||
secure: isSecure,
|
||||
maxAge: Duration.fromObject({ days: 400 }).toMillis(),
|
||||
};
|
||||
|
||||
const cookieOptions: Record<ImmichCookie, CookieOptions> = {
|
||||
[ImmichCookie.AUTH_TYPE]: defaults,
|
||||
[ImmichCookie.ACCESS_TOKEN]: defaults,
|
||||
// no httpOnly so that the client can know the auth state
|
||||
[ImmichCookie.IS_AUTHENTICATED]: { ...defaults, httpOnly: false },
|
||||
[ImmichCookie.SHARED_LINK_TOKEN]: { ...defaults, maxAge: Duration.fromObject({ days: 1 }).toMillis() },
|
||||
};
|
||||
|
||||
for (const { key, value } of values) {
|
||||
const options = cookieOptions[key];
|
||||
res.cookie(key, value, options);
|
||||
}
|
||||
|
||||
return body;
|
||||
};
|
||||
|
||||
export const respondWithoutCookie = <T>(res: Response, body: T, cookies: ImmichCookie[]) => {
|
||||
for (const cookie of cookies) {
|
||||
res.clearCookie(cookie);
|
||||
}
|
||||
|
||||
return body;
|
||||
};
|
||||
Reference in New Issue
Block a user