Skip to content

Commit

Permalink
Fix(auth-bloc): make auth-block queries indepence from postgres to sq…
Browse files Browse the repository at this point in the history
…lite (#147)

* update 14 files

* update 9 files

* update app.controller.spec.ts and schema.gql

* update access.strategy.ts and schema.gql

* update app.module.ts and schema.gql

* Apply automatic changes

* 

* Merge branch 'fix' of https://github.com/524H0003/Project_W into fix
  • Loading branch information
Nguyễn Việt Anh authored Feb 20, 2025
1 parent 65be43c commit 85c3836
Show file tree
Hide file tree
Showing 21 changed files with 1,105 additions and 282 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
secrets/*.pem
**/*.env*
securedSessionKey
**/*.sqlite

# Execlude files
!page/src/shims-vue.d.ts
Expand Down
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"types": true,
"graphql": true,
"securedSessionKey": true,
"src/schema.gql": true
"src/schema.gql": true,
"**/*.sqlite": true
},
"jest.outputConfig": { "clearOnRun": "terminal" },
"jest.runMode": {
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
"react-dom": "^19.0.0",
"rxjs": "^7.8.1",
"smtp-tester": "^2.1.0",
"sqlite3": "^5.1.7",
"start-server-and-test": "^2.0.10",
"typeorm": "^0.3.20",
"typeorm-extension": "^3.6.3",
Expand Down Expand Up @@ -159,7 +160,10 @@
"@fastify/session": "11.1.0",
"@fastify/formbody": "8.0.2",
"@fastify/multipart": "9.0.3"
}
},
"onlyBuiltDependencies": [
"sqlite3"
]
},
"engines": {
"node": "23.x"
Expand Down
1,184 changes: 995 additions & 189 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

24 changes: 18 additions & 6 deletions src/app/app.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,13 @@ describe('signUp', () => {
],
});
await execute(
() =>
async () =>
svc.bloc.find({
owner: { baseUser: { email: usr.baseUser.email.lower } },
ownerId: (
await svc.user.findOne({
baseUser: { email: usr.baseUser.email.lower },
})
).id,
}),
{ exps: [{ type: 'toHaveLength', params: [1] }] },
);
Expand Down Expand Up @@ -116,9 +120,13 @@ describe('login', () => {
);

await execute(
() =>
async () =>
svc.bloc.find({
owner: { baseUser: { email: usr.baseUser.email.lower } },
ownerId: (
await svc.user.findOne({
baseUser: { email: usr.baseUser.email.lower },
})
).id,
}),
{ exps: [{ type: 'toHaveLength', params: [2] }] },
);
Expand Down Expand Up @@ -180,9 +188,13 @@ describe('logout', () => {
],
onFinish: async () => {
await execute(
() =>
async () =>
svc.bloc.find({
owner: { baseUser: { email: usr.baseUser.email.lower } },
ownerId: (
await svc.user.findOne({
baseUser: { email: usr.baseUser.email.lower },
})
).id,
}),
{ exps: [{ type: 'toHaveLength', params: [0] }] },
);
Expand Down
5 changes: 1 addition & 4 deletions src/app/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,7 @@ export class AppController extends BaseController {
): Promise<UserRecieve> {
const { metaData, rootId, blocHash, blocId } = refresh;

if (
JSON.stringify(sortObjectKeys(metaData)) !==
JSON.stringify(sortObjectKeys(mtdt))
) {
if (metaData !== JSON.stringify(sortObjectKeys(mtdt))) {
await this.svc.bloc.removeTree(rootId);
return new UserRecieve({
response: { message: err('Invalid', 'Signature', '') },
Expand Down
2 changes: 1 addition & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ const modules = [
@Module({
imports: [
TerminusModule.forRoot({
errorLogStyle: 'json',
gracefulShutdownTimeoutMs: (30).s2ms,
logger: false,
}),
TypeOrmModule.forFeature([BaseUser]),
...modules.map((i) => forwardRef(() => i)),
Expand Down
40 changes: 33 additions & 7 deletions src/app/module/sql.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { readFileSync } from 'fs';
import { join } from 'path';
import { TlsOptions } from 'tls';
import { DataSourceOptions } from 'typeorm';
import { createPostgresDatabase } from 'typeorm-extension';
Expand All @@ -18,10 +19,15 @@ function readSslCa(): TlsOptions | boolean {
}

/**
* Server sql configuration
* Sql type
*/
export const sqlOptions = (
type: 'deploy' | 'test',
type SqlType = 'deploy' | 'test';

/**
* Server postgresql configuration
*/
export const postgresConfig = (
type: SqlType,
cfgSvc: ConfigService,
): DataSourceOptions => ({
type: 'postgres',
Expand All @@ -36,23 +42,43 @@ export const sqlOptions = (
});

/**
* @ignore
* Server postgresql module
*/
export const SqlModule = (type: 'deploy' | 'test') =>
export const PostgresModule = (type: SqlType) =>
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (cfgSvc: ConfigService) => {
try {
await createPostgresDatabase({
options: sqlOptions(type, cfgSvc),
options: postgresConfig(type, cfgSvc),
ifNotExist: true,
});
} catch {}
return {
...sqlOptions(type, cfgSvc),
...postgresConfig(type, cfgSvc),
autoLoadEntities: true,
synchronize: true,
};
},
});

/**
* Server sqlite module
*/
export const SqliteModule = (type: SqlType) =>
TypeOrmModule.forRootAsync({
name: 'sqlite_db',
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: 'sqlite',
database: join(
__dirname,
(type === 'deploy' ? config.get<string>('POSTGRES_DB') : type) +
'.sqlite',
),
synchronize: true,
autoLoadEntities: true,
}),
});
5 changes: 3 additions & 2 deletions src/app/module/test.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { ApolloDriver } from '@nestjs/apollo';
import { Global, Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { SqlModule } from 'app/module/sql.module';
import { PostgresModule, SqliteModule } from 'app/module/sql.module';
import { loadEnv } from './config.module';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { CacheModule } from '@nestjs/cache-manager';
Expand Down Expand Up @@ -37,7 +37,8 @@ export const rootPublic = process.env.SERVER_PUBLIC || 'public/';
CacheModule.register({ isGlobal: true, ttl: 0 }),
JwtModule.register({ global: true }),
loadEnv,
SqlModule('test'),
PostgresModule('test'),
SqliteModule('test'),
],
providers: [
{ provide: MailerService, useValue: { sendMail: jest.fn() } },
Expand Down
4 changes: 2 additions & 2 deletions src/app/typeorm/typeorm.config.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { sqlOptions } from 'app/module/sql.module';
import { postgresConfig } from 'app/module/sql.module';
import { NestFactory } from '@nestjs/core';
import { TypeOrmModule } from './typeorm.module';

async function bootstrap() {
const app = await NestFactory.create(TypeOrmModule),
config = app.get(ConfigService);

return new DataSource(sqlOptions('deploy', config));
return new DataSource(postgresConfig('deploy', config));
}

export default bootstrap();
42 changes: 11 additions & 31 deletions src/auth/bloc/bloc.entity.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import { SensitiveInfomations } from 'app/utils/typeorm.utils';
import { BeforeInsert, Column, Entity, ManyToOne } from 'typeorm';
import { User } from 'user/user.entity';
import { IBlocEntity, IBlocInfo, IBlocRelationships } from './bloc.model';
import { MetaData } from 'auth/guards';
import { BeforeInsert, Column, Entity } from 'typeorm';
import { IBlocEntity, IBlocInfo } from './bloc.model';
import { dataHashing } from 'app/utils/auth.utils';

/**
* Bloc Content
*/
interface IBlocContent {
metaData: MetaData;
}

/**
* Bloc entity
*/
Expand All @@ -21,23 +12,18 @@ export class Bloc extends SensitiveInfomations implements IBlocEntity {
* Create device with infomations
* @param {IBlocInfo} payload - the device's infomations
*/
constructor(payload: IBlocInfo & Partial<IBlocRelationships>) {
constructor(payload: IBlocInfo) {
super();

if (payload) Object.assign(this, payload);
}

// Relationships
// Infomations
/**
* Bloc owner
* Bloc owner id
*/
@ManyToOne(() => User, (_) => _.authBloc, {
onDelete: 'CASCADE',
nullable: true,
})
owner: User | null;
@Column({ nullable: true, update: false }) ownerId: string | null;

// Infomations
/**
* Previous bloc hash
*/
Expand All @@ -61,27 +47,21 @@ export class Bloc extends SensitiveInfomations implements IBlocEntity {
/**
* Current bloc content
*/
@Column({ type: 'jsonb', default: {} }) content?: IBlocContent;
@Column({ nullable: true }) metaData?: string;

// Methods
/**
* Hashing bloc
*/
@BeforeInsert() hashBloc() {
const { prev, content, signature, owner, lastIssue } = this;
@BeforeInsert() private hashBloc() {
const { prev, metaData, signature, ownerId, lastIssue } = this;

return (this.hash = dataHashing(
JSON.stringify({
...content,
lastIssue,
prev,
signature,
ownerId: owner?.id || '',
}),
JSON.stringify({ metaData, lastIssue, prev, signature, ownerId }),
));
}

static test(from: string) {
return new Bloc({ content: { from } });
return new Bloc({ metaData: from });
}
}
17 changes: 7 additions & 10 deletions src/auth/bloc/bloc.model.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { IEntityId } from 'app/app.model';
import { IUserEntity } from 'user/user.model';

// Interfaces
/**
Expand All @@ -17,24 +16,22 @@ export interface IBlocInfo extends IEntityId {
hash?: string;

/**
* Current bloc content
* Current bloc meta data
*/
content?: object;
metaData?: string;

/**
* Bloc last issue time
*/
lastIssue?: number;
}

/**
* Bloc relationships
*/
export interface IBlocRelationships {
owner: IUserEntity;
/**
* Bloc owner id
*/
ownerId?: string;
}

/**
* Bloc entity
*/
export interface IBlocEntity extends IBlocInfo, IBlocRelationships {}
export interface IBlocEntity extends IBlocInfo {}
5 changes: 4 additions & 1 deletion src/auth/bloc/bloc.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { Bloc } from './bloc.entity';
import { BlocService } from './bloc.service';

@Module({
imports: [TypeOrmModule.forFeature([Bloc]), forwardRef(() => AppModule)],
imports: [
TypeOrmModule.forFeature([Bloc], 'sqlite_db'),
forwardRef(() => AppModule),
],
providers: [BlocService],
exports: [BlocService],
})
Expand Down
2 changes: 1 addition & 1 deletion src/auth/bloc/bloc.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ beforeEach(async () => {
const rawUser = User.test(fileName);

(svc = appSvc),
(repo = module.get(getRepositoryToken(Bloc))),
(repo = module.get(getRepositoryToken(Bloc, 'sqlite_db'))),
(bloc = module.get(BlocService)),
(mtdt = new UAParser(fileName + '_' + (20).string).getResult()),
(user = await svc.auth.signUp({ ...rawUser, ...rawUser.baseUser }, null));
Expand Down
Loading

0 comments on commit 85c3836

Please sign in to comment.