Skip to content

Commit

Permalink
feat: connect to a mocked mongo sandbox
Browse files Browse the repository at this point in the history
  • Loading branch information
douglasduteil committed Dec 27, 2023
1 parent 463cbcc commit 59c6de2
Show file tree
Hide file tree
Showing 17 changed files with 966 additions and 128 deletions.
1 change: 1 addition & 0 deletions back/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"prestart:dev": "rm -rf dist",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
Expand Down
30 changes: 7 additions & 23 deletions back/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,22 @@
//

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ServeStaticModule } from '@nestjs/serve-static';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { join } from 'path';
import { AppController } from './app.controller';
import { config } from './config';
import { KeysGenerator } from './keys/keys-generator';
import { KeysModule } from './keys/keys.module';
import { OidcClientModule } from './oidc-client/oidc-client.module';
import { ServiceProvider } from './oidc-client/service-provider-adapter-mongo.schema';

const dataSource: TypeOrmModuleOptions = {
type: 'postgres',
host: config.DATABASE_HOST,
port: config.DATABASE_PORT,
username: config.DATABASE_USERNAME,
password: config.DATABASE_PASSWORD,
database: config.DATABASE_NAME,
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: config.DATA_SYNCHRONIZE,
};

const dataSource_2: TypeOrmModuleOptions = {
type: 'mongodb',
url: config.MONGODB_CONNECTION_STRING,
database: config.MONGODB_DATABASE,
entities: [ServiceProvider],
autoLoadEntities: true,
};
//

@Module({
imports: [
TypeOrmModule.forRoot(dataSource),
MongooseModule.forRoot(config.MONGODB_SANDBOX_CONNECTION_STRING, {
connectionName: 'sandbox',
}),
OidcClientModule,
KeysModule,
ServeStaticModule.forRoot({
rootPath: join(__dirname, '../..', 'front/dist'),
}),
Expand Down
5 changes: 3 additions & 2 deletions back/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ if (process.env.DATABASE_URL) {

const config = {
PORT: Number(process.env.PORT) || 3000,
MONGODB_CONNECTION_STRING: process.env.MONGODB_CONNECTION_STRING || '',
MONGODB_DATABASE: process.env.MONGODB_DATABASE || '',
MONGODB_SANDBOX_CONNECTION_STRING:
process.env.MONGODB_SANDBOX_CONNECTION_STRING || '',
MONGODB_SANDBOX_DATABASE: process.env.MONGODB_SANDBOX_DATABASE || '',
DATABASE_NAME: process.env.DATABASE_NAME || '',
DATABASE_USERNAME: process.env.DATABASE_USER || '',
DATABASE_PASSWORD: process.env.DATABASE_PASSWORD || '',
Expand Down
9 changes: 6 additions & 3 deletions back/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
//

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import * as dotenv from 'dotenv';
import { AppModule } from './app.module';
import { config } from './config';

dotenv.config();
import { config } from './config';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.useGlobalPipes(new ValidationPipe());
app.setGlobalPrefix('api');
app.enableCors();

await app.listen(config.PORT, () => {
Expand Down
97 changes: 36 additions & 61 deletions back/src/oidc-client/oidc-client.controller.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,47 @@
import {
Body,
Controller,
Get,
HttpException,
HttpStatus,
Param,
Post,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MongoRepository } from 'typeorm';
import { CreateOidcClientDto } from './oidc-client.dto';
import { OidcClientSaver } from './oidc-client.saver';
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ServiceProvider } from './service-provider-adapter-mongo.schema';

@Controller('oidc-clients')
export class OidcClientController {
constructor(
private readonly oidcClientSaver: OidcClientSaver,
@InjectRepository(ServiceProvider)
private readonly serviceProvider: MongoRepository<ServiceProvider>,
) {
this.oidcClientSaver = oidcClientSaver;
}

@InjectModel(ServiceProvider.name, 'sandbox')
private readonly serviceProvider: Model<ServiceProvider>,
) {}
@Get()
async findAll() {
console.log(this.serviceProvider.find());
return [
{
clientDescription: 'Description',
clientId: 'clientId',
clientSecret: 'ClientSecret',
clientName: 'Rebecca Project 123',
redirectUris: ['http://example.com/callback'],
postLogoutRedirectUris: ['http://example.com/logout'],
scope: ['firstname', 'lastname'],
},
] satisfies CreateOidcClientDto[];
return await this.serviceProvider.find().exec();
}

@Get('/:id')
async find_by_id(@Param('id') id: string) {
@Get('/:key')
async find_by_id(@Param('key') key: string) {
const service = await this.serviceProvider.findOne({ key }).exec();
if (!service) throw new NotFoundException();
return {
clientDescription: 'Description',
clientId: 'clientId',
clientSecret: 'ClientSecret',
clientName: 'Rebecca Project 123',
redirectUris: ['http://example.com/callback'],
postLogoutRedirectUris: ['http://example.com/logout'],
scope: ['firstname', 'lastname'],
} satisfies CreateOidcClientDto;
}

@Post()
async create(@Body() createOidcClientDto: CreateOidcClientDto) {
try {
return await this.oidcClientSaver.save(createOidcClientDto);
} catch (error) {
throw new HttpException(
{
status: HttpStatus.BAD_REQUEST,
error: `Error occurs : ${error.message}`,
},
HttpStatus.BAD_REQUEST,
{
cause: error,
},
);
}
clientName: service.name,
clientDescription: service.email,
clientId: service.entityId,
clientSecret: service.client_secret,
scope: service.scopes,
postLogoutRedirectUris: service.post_logout_redirect_uris,
redirectUris: service.redirect_uris,
};
}
// @Post()
// async create(@Body() createOidcClientDto: CreateOidcClientDto) {
// try {
// return await this.oidcClientSaver.save(createOidcClientDto);
// } catch (error) {
// throw new HttpException(
// {
// status: HttpStatus.BAD_REQUEST,
// error: `Error occurs : ${error.message}`,
// },
// HttpStatus.BAD_REQUEST,
// {
// cause: error,
// },
// );
// }
// }
}
20 changes: 13 additions & 7 deletions back/src/oidc-client/oidc-client.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
//

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MongooseModule } from '@nestjs/mongoose';
import { OidcClientController } from './oidc-client.controller';
import { OidcClient } from './oidc-client.entity';
import { OidcClientSaver } from './oidc-client.saver';
import { ServiceProvider } from './service-provider-adapter-mongo.schema';
import {
ServiceProvider,
ServiceProviderSchema,
} from './service-provider-adapter-mongo.schema';

@Module({
imports: [TypeOrmModule.forFeature([OidcClient, ServiceProvider])],
imports: [
MongooseModule.forFeature(
[{ name: ServiceProvider.name, schema: ServiceProviderSchema }],
'sandbox',
),
],
controllers: [OidcClientController],
providers: [OidcClientSaver],
exports: [OidcClientSaver],
})
export class OidcClientModule {}
18 changes: 18 additions & 0 deletions back/src/oidc-client/service-provider-adapter-mongo.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,29 @@ export class ServiceProvider extends Document {
@Prop({ type: String })
name: string;

@Prop({ type: Boolean })
active: boolean;

@Prop({ type: String, unique: true, index: true })
key: string;

@Prop({ type: String, index: true })
entityId: string;

@Prop({ type: String, index: true })
email: string;

@Prop({ type: String })
client_secret: string;

@Prop({ type: [String] })
scopes: string[];

@Prop({ type: [String] })
redirect_uris: string[];

@Prop({ type: [String] })
post_logout_redirect_uris: string[];
}

export const ServiceProviderSchema =
Expand Down
25 changes: 3 additions & 22 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,26 +1,7 @@
version: '3.7'

services:
database:
image: postgres:14-alpine
environment:
POSTGRES_DB: partenaire
POSTGRES_USER: partenaire
POSTGRES_PASSWORD: pwd
POSTGRES_PORT: 5432
ports:
- '5432:5432'

database-admin:
image: adminer
ports:
- 8080:8080
expose:
- '8080'
depends_on:
- database

mongo:
mongo-sandbox:
image: mongo:4.4
ports:
- '27017:27017'
Expand All @@ -38,6 +19,6 @@ services:
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: rootAdmin
ME_CONFIG_MONGODB_ADMINPASSWORD: pass
ME_CONFIG_MONGODB_URL: mongodb://rootAdmin:pass@mongo:27017/
ME_CONFIG_MONGODB_URL: mongodb://rootAdmin:pass@mongo-sandbox:27017/
depends_on:
- mongo
- mongo-sandbox
2 changes: 1 addition & 1 deletion front/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite build --watch",
"dev": "vite build --minify false --watch",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
Expand Down
19 changes: 13 additions & 6 deletions front/src/clients/back-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
//

import axios from 'axios';
import { OidcClient } from '../types';
const VITE_BASE_URL = import.meta.env.VITE_BASE_URL ?? '';

//

const API_URL = `${import.meta.env.VITE_BASE_URL ?? ''}/api`;

//

export const backendClient = {
getKeys,
Expand All @@ -11,25 +18,25 @@ export const backendClient = {
};

async function getKeys() {
const response = await axios.get(VITE_BASE_URL + '/keys');
const response = await axios.get(API_URL + '/keys');
return response.data;
}

async function getList() {
const response = await axios.get(VITE_BASE_URL + '/list');
const response = await axios.get(API_URL + '/list');
return response.data;
}

async function getDashboard() {
const response = await axios.get(VITE_BASE_URL + '/oidc-clients/');
const response = await axios.get(API_URL + '/oidc-clients/');
return response.data;
}

async function getDashboardItem(id: string) {
const response = await axios.get(VITE_BASE_URL + '/oidc-clients/' + id);
const response = await axios.get(`${API_URL}/oidc-clients/${id}`);
return response.data;
}

async function postOidcClient(data: OidcClient) {
return await axios.post(VITE_BASE_URL + '/oidc-clients', data);
return await axios.post(API_URL + '/oidc-clients', data);
}
3 changes: 3 additions & 0 deletions front/src/headers/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ function Header() {
// NOTE(douglasduteil): use mocked data for now
// Will be replaced by
// to: '/connexion',
// or
// to: `${import.meta.env.VITE_BASE_URL}/api/auth/login`,
// target: '_self',
to: '/dashboard',
},
text: 'Se connecter',
Expand Down
2 changes: 1 addition & 1 deletion front/src/providers/details/ProviderScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { OidcClientFormContext } from './oidc-client-form.context';

export const ProviderScope = () => {
const { setOidcClientForm, oidcClientForm } = useContext(
OidcClientFormContext
OidcClientFormContext,
);
const [scope, setScope] = useState<string[]>(oidcClientForm.scope);

Expand Down
3 changes: 2 additions & 1 deletion front/src/providers/details/oidc-client-form.context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export function OidcClientFormProvider({
children,
}: PropsWithChildren<{ id?: string }>) {
const item = useLoaderData() as OidcClient;

const [oidcClientForm, setOidcClientForm] = useState<OidcClient>(
item ?? {
clientName: 'Test ' + new Date().toLocaleDateString(),
Expand All @@ -23,7 +24,7 @@ export function OidcClientFormProvider({
redirectUris: [],
postLogoutRedirectUris: [],
scope: [],
}
},
);

return (
Expand Down
4 changes: 4 additions & 0 deletions front/src/routes/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ const router = createBrowserRouter([
<a href="/dashboard/new">NEW</a>
<br />
<a href="/dashboard/123">Rebecca Project 123</a>
<br />
<a href="/dashboard/6925fb8143c76eded44d32b40c0cb1006065f7f003de52712b78985704f39950">
FSA - FSA1-LOW
</a>
</>
</PageLayout>
),
Expand Down
Loading

0 comments on commit 59c6de2

Please sign in to comment.