Skip to content

feat: add mongo session store #1884

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 7, 2025
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ Valid environment variables for the .env file. See [.env.example](/.env.example)
| `ACCESS_GROUPS_OIDCPAYLOAD_ENABLED` | string | Yes | Flag to enable/disable fetching access groups directly from OIDC response. Requires specifying a field via `OIDC_ACCESS_GROUPS_PROPERTY` to extract access groups. | false |
| `DOI_PREFIX` | string | | The facility DOI prefix, with trailing slash. | |
| `EXPRESS_SESSION_SECRET` | string | No | Secret used to set up express session. Required if using OIDC authentication | |
| `EXPRESS_SESSION_STORE` | string | Yes | Where to store the express session. When "mongo" on mongo else in memory | |
| `HTTP_MAX_REDIRECTS` | number | Yes | Max redirects for HTTP requests. | 5 |
| `HTTP_TIMEOUT` | number | Yes | Timeout for HTTP requests in ms. | 5000 |
| `JWT_SECRET` | string | | The secret for your JWT token, used for authorization. | |
Expand Down
56 changes: 55 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"bcrypt": "^5.1.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"connect-mongo": "^5.1.0",
"dotenv": "^16.0.3",
"express-session": "^1.17.3",
"handlebars": "^4.7.7",
Expand Down Expand Up @@ -93,7 +94,7 @@
"@types/bcrypt": "^5.0.0",
"@types/chai": "^5.0.0",
"@types/express": "^5.0.0",
"@types/express-session": "^1.17.4",
"@types/express-session": "^1.18.1",
"@types/jest": "^27.0.2",
"@types/js-yaml": "^4.0.9",
"@types/jsonpath-plus": "^5.0.5",
Expand Down
18 changes: 16 additions & 2 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Module } from "@nestjs/common";
import { MiddlewareConsumer, Module, RequestMethod } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { UsersModule } from "../users/users.module";
import { PassportModule } from "@nestjs/passport";
Expand All @@ -14,6 +14,7 @@ import { BuildOpenIdClient, OidcStrategy } from "./strategies/oidc.strategy";
import { accessGroupServiceFactory } from "./access-group-provider/access-group-service-factory";
import { AccessGroupService } from "./access-group-provider/access-group.service";
import { CaslModule } from "src/casl/casl.module";
import { SessionMiddleware } from "./middlewares/session.middleware";

const OidcStrategyFactory = {
provide: "OidcStrategy",
Expand Down Expand Up @@ -68,4 +69,17 @@ const OidcStrategyFactory = {
controllers: [AuthController],
exports: [AuthService, JwtModule, PassportModule],
})
export class AuthModule {}
export class AuthModule {
constructor(private configService: ConfigService) {}

configure(consumer: MiddlewareConsumer) {
if (!this.configService.get<string>("expressSession.secret")) return;
consumer
.apply(SessionMiddleware)
.forRoutes(
{ path: "auth/oidc", method: RequestMethod.GET, version: "3" },
{ path: "auth/oidc/callback", method: RequestMethod.GET, version: "3" },
{ path: "auth/logout", method: RequestMethod.POST, version: "3" },
);
}
}
2 changes: 1 addition & 1 deletion src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export class AuthService {
async logout(req: Request) {
const logoutURL = this.configService.get<string>("logoutURL") || "";
const expressSessionSecret = this.configService.get<string>(
"expressSessionSecret",
"expressSession.secret",
);

const logoutResult = await this.additionalLogoutTasks(req, logoutURL);
Expand Down
117 changes: 117 additions & 0 deletions src/auth/middlewares/session.middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { Test } from "@nestjs/testing";
import { SessionMiddleware } from "./session.middleware";
import { ConfigService } from "@nestjs/config";
import MongoStore from "connect-mongo";
import session from "express-session";
import { Request, Response } from "express";
import { getConnectionToken } from "@nestjs/mongoose";

jest.mock("express-session", () => {
const actual = jest.requireActual("express-session");
return {
__esModule: true,
...actual,
default: jest.fn(() => jest.fn()),
};
});

[
["mongo", 1],
["other", 0],
].forEach(([store, callCount]) => {
describe(`SessionMiddleware ${store}`, () => {
let middleware: SessionMiddleware;
let mongoStoreMock: jest.SpyInstance;
let sessionMock: jest.Mock;
let sessionHandlerMock: jest.Mock;

beforeEach(async () => {
mongoStoreMock = jest.spyOn(MongoStore, "create").mockReturnValue({
client: "mockClient",
ttl: 3600,
} as unknown as MongoStore);

sessionMock = session as unknown as jest.Mock;
sessionHandlerMock = jest.fn();
sessionMock.mockReturnValue(sessionHandlerMock);

const configServiceMock = {
get: jest.fn((key: string) => {
switch (key) {
case "expressSession.secret":
return "secret";
case "expressSession.store":
return store;
case "jwt.expiresIn":
return 3600;
default:
return null;
}
}),
};

const mongoConnectionMock = {
getClient: () => "mockClient",
};

const moduleRef = await Test.createTestingModule({
providers: [
SessionMiddleware,
{
provide: ConfigService,
useValue: configServiceMock,
},
{
provide: getConnectionToken(),
useValue: mongoConnectionMock,
},
],
}).compile();

middleware = moduleRef.get<SessionMiddleware>(SessionMiddleware);
});

afterEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});

it("should be defined", () => {
expect(middleware).toBeDefined();
});

it("should call MongoStore.create if store is mongo", () => {
expect(mongoStoreMock).toHaveBeenCalledTimes(callCount as number);
let store = {};
const commonSessionOptions = {
secret: "secret",
resave: false,
saveUninitialized: true,
};
if (callCount)
store = {
store: {
client: "mockClient",
ttl: 3600,
},
};
expect(sessionMock).toHaveBeenCalledWith(
Object.assign({}, commonSessionOptions, store),
);
if (!callCount) return;
expect(mongoStoreMock).toHaveBeenCalledWith({
client: "mockClient",
ttl: 3600,
});
});

it("should invoke session() with proper arguments", () => {
const req = {} as Request;
const res = {} as Response;
const next = jest.fn();

middleware.use(req, res, next);
expect(sessionHandlerMock).toHaveBeenCalledWith(req, res, next);
});
});
});
35 changes: 35 additions & 0 deletions src/auth/middlewares/session.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Injectable, NestMiddleware } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { InjectConnection } from "@nestjs/mongoose";
import MongoStore from "connect-mongo";
import { Request, Response, NextFunction, RequestHandler } from "express";
import session, { Store } from "express-session";
import { Connection } from "mongoose";

@Injectable()
export class SessionMiddleware implements NestMiddleware {
private readonly requestHandler: RequestHandler;
constructor(
private readonly configService: ConfigService,
@InjectConnection() private readonly mongoConnection: Connection,
) {
let store: { store: Store } | object = {};
if (this.configService.get<string>("expressSession.store") === "mongo")
store = {
store: MongoStore.create({
client: this.mongoConnection.getClient(),
ttl: this.configService.get<number>("jwt.expiresIn"),
}),
};
this.requestHandler = session({
secret: this.configService.get<string>("expressSession.secret") as string,
resave: false,
saveUninitialized: true,
...store,
});
}

use(req: Request, res: Response, next: NextFunction) {
return this.requestHandler(req, res, next);
}
}
5 changes: 4 additions & 1 deletion src/config/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,10 @@ const configuration = () => {
accessGroupProperty: process.env?.OIDC_ACCESS_GROUPS_PROPERTY, // Example: groups
},
doiPrefix: process.env.DOI_PREFIX,
expressSessionSecret: process.env.EXPRESS_SESSION_SECRET,
expressSession: {
secret: process.env.EXPRESS_SESSION_SECRET,
store: process.env.EXPRESS_SESSION_STORE,
},
functionalAccounts: [],
httpMaxRedirects: process.env.HTTP_MAX_REDIRECTS ?? 5,
httpTimeOut: process.env.HTTP_TIMEOUT ?? 5000,
Expand Down
14 changes: 0 additions & 14 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import session from "express-session";
import { NestFactory } from "@nestjs/core";
import {
DocumentBuilder,
Expand Down Expand Up @@ -92,19 +91,6 @@ async function bootstrap() {
extended: true,
});

const expressSessionSecret = configService.get<string>(
"expressSessionSecret",
);
if (expressSessionSecret) {
app.use(
session({
secret: expressSessionSecret,
resave: false,
saveUninitialized: true,
}),
);
}

const port = configService.get<number>("port") ?? 3000;
Logger.log("Scicat Backend listening on port: " + port, "Main");

Expand Down
Loading
Loading