Skip to content
This repository has been archived by the owner on Oct 26, 2024. It is now read-only.

Commit

Permalink
refactor: 🔄 update session logic, introduce cookie-session module
Browse files Browse the repository at this point in the history
Adjusted the session logic by replacing the Session entity with UserSession. The change has been applied uniformly across all relevant files. A new `express-session` module was included to handle session data. This takes care of storing each user's ID within their respective session, improving the user identification process. A new cookie session functionality was also integrated with the use of the `nestjs-cookie-session` module.
  • Loading branch information
keinsell committed Dec 20, 2023
1 parent ac87821 commit 923ee80
Show file tree
Hide file tree
Showing 24 changed files with 495 additions and 96 deletions.
5 changes: 5 additions & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,16 @@
"argon2": "^0.31.2",
"bcrypt": "^5.1.1",
"bytes": "^3.1.2",
"cookie-session": "^2.0.0",
"copyfiles": "^2.4.1",
"craftpack": "^0.0.16",
"create-nestjs-middleware-module": "^0.3.1",
"delay": "^6.0.0",
"detect-port": "^1.5.1",
"dotenv": "^16.3.1",
"envalid": "^8.0.0",
"express": "^4.18.2",
"express-session": "^1.17.3",
"figlet": "^1.7.0",
"get-port": "^7.0.0",
"immutable": "5.0.0-beta.4",
Expand Down Expand Up @@ -114,7 +117,9 @@
"@nestjs/schematics": "^10.0.3",
"@nestjs/testing": "^10.2.8",
"@types/bcrypt": "^5.0.2",
"@types/cookie-session": "^2.0.48",
"@types/express": "^4.17.21",
"@types/express-session": "^1.17.10",
"@types/jest": "^29.5.8",
"@types/jsonwebtoken": "^9.0.5",
"@types/lodash": "^4.14.202",
Expand Down
2 changes: 1 addition & 1 deletion apps/server/public/api/openapi3.json

Large diffs are not rendered by default.

121 changes: 121 additions & 0 deletions apps/server/src/common/middleware/cookie-session/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Cookie Session
This module implements a session with storing data directly in `Cookie`.

If you want to store data in one of [external stores](https://github.com/expressjs/session#compatible-session-stores) and passing ID of session to client via `Cookie`/`Set-Cookie` headers, you can look at [nestjs-session](https://github.com/iamolegga/nestjs-session).

## Example

Register module:

```ts
// app.module.ts
import { Module } from '@nestjs/common';
import {
NestCookieSessionOptions,
CookieSessionModule,
} from 'nestjs-cookie-session';
import { ViewsController } from './views.controller';

@Module({
imports: [
// sync params:

CookieSessionModule.forRoot({
session: { secret: 'keyboard cat' },
}),

// or async:

CookieSessionModule.forRootAsync({
imports: [ConfigModule],
inject: [Config],
// TIP: to get autocomplete in return object
// add `NestCookieSessionOptions` here ↓↓↓
useFactory: async (config: Config): Promise<NestCookieSessionOptions> => {
return {
session: { secret: config.secret },
};
},
}),
],
controllers: [ViewsController],
})
export class AppModule {}
```

Use in controllers with NestJS built-in `Session` decorator:

```ts
// views.controller.ts
import { Controller, Get, Session } from '@nestjs/common';

@Controller('views')
export class ViewsController {
@Get()
getViews(@Session() session: { views?: number }) {
session.views = (session.views || 0) + 1;
return session.views;
}
}
```

To run examples:

```sh
git clone https://github.com/iamolegga/nestjs-cookie-session.git
cd nestjs-cookie-session
npm i
npm run build
cd example
npm i
npm start
```

## Install

```sh
npm i nestjs-cookie-session cookie-session @types/cookie-session
```

## API

### CookieSessionModule

`CookieSessionModule` class has two static methods, that returns `DynamicModule`, that you need to import:

- `CookieSessionModule.forRoot` for sync configuration without dependencies
- `CookieSessionModule.forRootAsync` for sync/async configuration with dependencies

### CookieSessionModule.forRoot

Accept `NestCookieSessionOptions`. Returns NestJS `DynamicModule` for import.

### CookieSessionModule.forRootAsync

Accept `NestCookieSessionAsyncOptions`. Returns NestJS `DynamicModule` for import.

### NestCookieSessionOptions

`NestCookieSessionOptions` is the interface of all options, has next properties:

- `session` - **required** - [cookie-session options](https://github.com/expressjs/cookie-session#options).
- `forRoutes` - **optional** - same as NestJS built-in `MiddlewareConfigProxy['forRoutes']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes.
- `exclude` - **optional** - same as NestJS built-in `MiddlewareConfigProxy['exclude']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should not have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes.

### NestCookieSessionAsyncOptions

`NestCookieSessionOptions` is the interface of options to create cookie session module, that depends on other modules, has next properties:

- `imports` - **optional** - modules, that cookie session module depends on. See [official docs](https://docs.nestjs.com/modules).
- `inject` - **optional** - providers from `imports`-property modules, that will be passed as arguments to `useFactory` method.
- `useFactory` - **required** - method, that returns `NestCookieSessionOptions`.

## Migration

### v2

`cookie-session` and `@types/cookie-session` are moved to peer dependencies, so you can update them independently.

<h2 align="center">Do you use this library?<br/>Don't be shy to give it a star! ★</h2>

<h3 align="center">Also if you are into NestJS you might be interested in one of my <a href="https://github.com/iamolegga#nestjs">other NestJS libs</a>.</h3>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import cookieSession = require('cookie-session')
import {AsyncOptions, createModule, SyncOptions} from 'create-nestjs-middleware-module';



interface Options {
/**
* cookie-session options. @see https://www.npmjs.com/package/cookie-session#options
*/
session: Parameters<typeof cookieSession>[0];
}

export type NestCookieSessionOptions = SyncOptions<Options>;

export type NestCookieSessionAsyncOptions = AsyncOptions<Options>;

export const CookieSessionModule = createModule<Options>(({ session }) =>
cookieSession(session),
);
40 changes: 40 additions & 0 deletions apps/server/src/common/middleware/session/retries-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {InternalServerErrorException} from '@nestjs/common';
import * as express from 'express';



type WaitingStrategy = (attempt: number) => number;

export function createRetriesMiddleware(
sessionMiddleware: express.RequestHandler,
retries: number,
retiesStrategy: WaitingStrategy = () => 0,
): express.RequestHandler {
return async (req, res, next) => {
let attempt = 0;

async function lookupSession(error?: unknown) {
if (error) {
return next(error);
}

if (req.session !== undefined) {
return next();
}

if (attempt > retries) {
return next(new InternalServerErrorException('Cannot create session'));
}

if (attempt !== 0) {
await new Promise((r) => setTimeout(r, retiesStrategy(attempt)));
}

attempt++;

sessionMiddleware(req, res, lookupSession);
}

await lookupSession();
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {AsyncOptions, createModule, SyncOptions} from 'create-nestjs-middleware-module';
import expressSession from 'express-session';

import {createRetriesMiddleware} from './retries-middleware.js';



interface Options {
/**
* express-session options. @see https://github.com/expressjs/session#options
*/
session: expressSession.SessionOptions;
/**
* by default if your session store lost connection to database it will return
* session as `undefined`, and no errors will be thrown, and then you need to
* check session in controller. But you can set this property how many times
* it should retry to get session, and on fail `InternalServerErrorException`
* will be thrown. If you don't want retries, but just want to
* `InternalServerErrorException` to be throw, then set to `0`. Set this
* option, if you dont't want manualy check session inside controllers.
*/
retries?: number;
/**
* function that returns number of ms to wait between next attempt. Not calls
* on first attempt.
*/
retriesStrategy?: Parameters<typeof createRetriesMiddleware>[2];
}

export type NestSessionOptions = SyncOptions<Options>;

export type NestSessionAsyncOptions = AsyncOptions<Options>;

export const SessionMiddlewareModule = createModule<Options>((options) => {
const { retries, session, retriesStrategy } = options;
let middleware = expressSession(session);

if (retries !== undefined) {
middleware = createRetriesMiddleware(middleware, retries, retriesStrategy);
}

return middleware;
});
67 changes: 52 additions & 15 deletions apps/server/src/common/shared-module.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,61 @@
import {Module} from "@nestjs/common"
import {DocumentaitonModule} from "./modules/documentation/documentaiton-module.js"
import {DeveloperToolsModule} from "./modules/environment/dev-tools/developer-tools.module.js"
import {AsyncLocalStorageModule} from "./modules/environment/local-storage/async-local-storage-module.js"
import {ContinuationLocalStorageModule} from "./modules/environment/local-storage/continuation-local-storage-module.js"
import {HealthModule} from "./modules/observability/healthcheck/health-module.js"
import {TelemetryModule} from "./modules/observability/telemetry/telemetry-module.js"
import {DatabaseModule} from "./modules/storage/database/database.module.js"

import {Module} from "@nestjs/common"
import {
SessionMiddlewareModule
} from "./middleware/session/session-middleware-module.js"
import {
DocumentaitonModule
} from "./modules/documentation/documentaiton-module.js"
import {
DeveloperToolsModule
} from "./modules/environment/dev-tools/developer-tools.module.js"
import {
AsyncLocalStorageModule
} from "./modules/environment/local-storage/async-local-storage-module.js"
import {
ContinuationLocalStorageModule
} from "./modules/environment/local-storage/continuation-local-storage-module.js"
import {
HealthModule
} from "./modules/observability/healthcheck/health-module.js"
import {
TelemetryModule
} from "./modules/observability/telemetry/telemetry-module.js"
import {DatabaseModule} from "./modules/storage/database/database.module.js"


@Module({
imports: [
TelemetryModule, DatabaseModule, ContinuationLocalStorageModule,
AsyncLocalStorageModule, DocumentaitonModule, HealthModule,
TelemetryModule,
DatabaseModule,
ContinuationLocalStorageModule,
AsyncLocalStorageModule,
DocumentaitonModule,
HealthModule,
DeveloperToolsModule,
SessionMiddlewareModule.forRoot({
session: {
secret: "secretomitted",
rolling: false,
resave: false,
saveUninitialized: false,
},
}),
// https://stackoverflow.com/questions/56046527/express-session-req-session-touch-not-a-function
//CookieSessionModule.forRoot({
// session: {
// name: 'session', secret: 'secretomitted', maxAge: 0
// }
//})
],
exports: [
TelemetryModule, DatabaseModule, ContinuationLocalStorageModule,
AsyncLocalStorageModule
, DocumentaitonModule, HealthModule, DeveloperToolsModule,
TelemetryModule,
DatabaseModule,
ContinuationLocalStorageModule,
AsyncLocalStorageModule,
DocumentaitonModule,
HealthModule,
DeveloperToolsModule,
],
})
export class SharedModule {}
export class SharedModule {
}
7 changes: 7 additions & 0 deletions apps/server/src/common/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import session from 'express-session';

declare module 'express-session' {
export interface SessionData extends session.SessionData {
userId?: number;
}
}
5 changes: 4 additions & 1 deletion apps/server/src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {BillingModule} from "@boundary/billing/billing.module.js"
import {IdentityAndAccessModule} from "@boundary/identity-and-access/identity-and-access.module.js"
import {Module} from '@nestjs/common';
import {EventEmitterModule} from "@nestjs/event-emitter"
import {SessionMiddlewareModule} from "./common/middleware/session/session-middleware-module.js"
import {SharedModule} from "./common/shared-module.js"
import {CartModule} from "./modules/cart/cart-module.js"
import {ProductModule} from "./modules/product/product-module.js"
Expand All @@ -11,7 +12,9 @@ import {ProductModule} from "./modules/product/product-module.js"
@Module({
imports: [
IdentityAndAccessModule, SharedModule, ProductModule, CartModule, BillingModule,
EventEmitterModule.forRoot(),
EventEmitterModule.forRoot(), SessionMiddlewareModule.forRoot({
session: {secret: "qwerty"}
})
],
controllers: [],
providers: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {JwtTokenManagement, TokenManagement} from "./services/token-management.j
@Module({
imports: [
CredentialValidatorModule, AccountModule, PassportModule.register({
session: false,
session: true,
}), DatabaseModule, JwtModule.register({
secretOrPrivateKey: authorizationConfiguration.jwtSecret,
}),
Expand Down
Loading

0 comments on commit 923ee80

Please sign in to comment.