dl-commons 0.0.1-testing.1 → 0.0.1-testing.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/dl-commons.module.d.ts +8 -0
  2. package/dist/dl-commons.module.js +19 -3
  3. package/dist/dl-commons.module.js.map +1 -1
  4. package/dist/guards/permission.guard.d.ts +2 -2
  5. package/dist/guards/permission.guard.js +24 -5
  6. package/dist/guards/permission.guard.js.map +1 -1
  7. package/dist/index.d.ts +6 -1
  8. package/dist/index.js +8 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/models/consts/env-vars.const.d.ts +1 -0
  11. package/dist/models/consts/env-vars.const.js +2 -1
  12. package/dist/models/consts/env-vars.const.js.map +1 -1
  13. package/dist/models/interfaces/session-user.interface.d.ts +11 -0
  14. package/dist/models/interfaces/session-user.interface.js +3 -0
  15. package/dist/models/interfaces/session-user.interface.js.map +1 -0
  16. package/dist/models/interfaces/session.interface.d.ts +8 -0
  17. package/dist/models/interfaces/session.interface.js +3 -0
  18. package/dist/models/interfaces/session.interface.js.map +1 -0
  19. package/dist/models/interfaces/user.interface.d.ts +14 -0
  20. package/dist/models/interfaces/user.interface.js +3 -0
  21. package/dist/models/interfaces/user.interface.js.map +1 -0
  22. package/dist/models/schemas/embedded/session-user.schema.d.ts +23 -0
  23. package/dist/models/schemas/embedded/session-user.schema.js +48 -0
  24. package/dist/models/schemas/embedded/session-user.schema.js.map +1 -0
  25. package/dist/models/schemas/session.schema.d.ts +20 -0
  26. package/dist/models/schemas/session.schema.js +39 -0
  27. package/dist/models/schemas/session.schema.js.map +1 -0
  28. package/dist/services/dictionaries.service.d.ts +11 -0
  29. package/dist/services/dictionaries.service.js +64 -0
  30. package/dist/services/dictionaries.service.js.map +1 -0
  31. package/dist/services/sessions.service.d.ts +12 -1
  32. package/dist/services/sessions.service.js +48 -2
  33. package/dist/services/sessions.service.js.map +1 -1
  34. package/dist/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +34 -32
  36. package/src/dl-commons.module.ts +29 -4
  37. package/src/guards/permission.guard.ts +27 -30
  38. package/src/index.ts +14 -0
  39. package/src/models/consts/env-vars.const.ts +2 -0
  40. package/src/models/interfaces/session-user.interface.ts +12 -0
  41. package/src/models/interfaces/session.interface.ts +9 -0
  42. package/src/models/interfaces/user.interface.ts +15 -0
  43. package/src/models/schemas/embedded/session-user.schema.ts +32 -0
  44. package/src/models/schemas/session.schema.ts +24 -0
  45. package/src/services/dictionaries.service.ts +57 -0
  46. package/src/services/sessions.service.ts +57 -2
package/package.json CHANGED
@@ -1,33 +1,35 @@
1
1
  {
2
- "name": "dl-commons",
3
- "type": "commonjs",
4
- "version": "0.0.1-testing.1",
5
- "description": "distance learning commons",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
- "scripts": {
9
- "prepublish": "tsc",
10
- "build": "tsc",
11
- "pack": "npm run build && npm pack --pack-destination ./packs"
12
- },
13
- "author": "",
14
- "license": "ISC",
15
- "dependencies": {
16
- "@nestjs/common": "^10.3.7",
17
- "@nestjs/config": "^3.1.1",
18
- "@nestjs/core": "^10.3.1",
19
- "@nestjs/mongoose": "^10.0.2",
20
- "class-transformer": "^0.5.1",
21
- "class-validator": "^0.14.0",
22
- "express": "^4.18.2",
23
- "mongoose": "^8.0.4"
24
- },
25
- "devDependencies": {
26
- "@types/express": "^4.17.17",
27
- "@types/node": "^18.15.11",
28
- "@typescript-eslint/eslint-plugin": "^6.18.1",
29
- "@typescript-eslint/parser": "^6.18.1",
30
- "eslint": "^8.56.0",
31
- "typescript": "^5.0.4"
32
- }
33
- }
2
+ "name": "dl-commons",
3
+ "type": "commonjs",
4
+ "version": "0.0.1-testing.3",
5
+ "description": "distance learning commons",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "prepublish": "tsc",
10
+ "build": "tsc",
11
+ "pack": "npm run build && npm pack --pack-destination ./packs"
12
+ },
13
+ "author": "",
14
+ "license": "ISC",
15
+ "dependencies": {
16
+ "@nestjs/axios": "^3.1.0",
17
+ "@nestjs/common": "^10.3.7",
18
+ "@nestjs/config": "^3.1.1",
19
+ "@nestjs/core": "^10.3.1",
20
+ "@nestjs/mongoose": "^10.0.2",
21
+ "class-transformer": "^0.5.1",
22
+ "class-validator": "^0.14.0",
23
+ "express": "^4.18.2",
24
+ "mongoose": "^8.0.4",
25
+ "reflect-metadata": "^0.2.2"
26
+ },
27
+ "devDependencies": {
28
+ "@types/express": "^4.17.17",
29
+ "@types/node": "^18.15.11",
30
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
31
+ "@typescript-eslint/parser": "^6.18.1",
32
+ "eslint": "^8.56.0",
33
+ "typescript": "^5.0.4"
34
+ }
35
+ }
@@ -1,11 +1,36 @@
1
1
  import { Module } from '@nestjs/common';
2
- import { ConfigModule } from '@nestjs/config';
2
+ import { ConfigModule, ConfigService } from '@nestjs/config';
3
3
  import { SessionsService } from './services/sessions.service';
4
+ import { MongooseModule } from '@nestjs/mongoose';
5
+ import { DL_SESSIONS__MONGO__CS } from './models/consts/env-vars.const';
6
+ import { Session, SessionSchema } from './models/schemas/session.schema';
7
+ import { HttpModule } from '@nestjs/axios';
8
+ import { ISession } from './models/interfaces/session.interface';
9
+ import { DictionariesService } from './services/dictionaries.service';
10
+
11
+ declare global {
12
+ namespace Express {
13
+ interface Request {
14
+ session: ISession;
15
+ }
16
+ }
17
+ }
4
18
 
5
19
  @Module({
6
- imports: [ConfigModule],
20
+ imports: [
21
+ ConfigModule,
22
+ HttpModule,
23
+ MongooseModule.forRootAsync({
24
+ connectionName: 'sessions-store',
25
+ useFactory: async (configService: ConfigService) => ({
26
+ uri: configService.get(DL_SESSIONS__MONGO__CS),
27
+ }),
28
+ inject: [ConfigService],
29
+ }),
30
+ MongooseModule.forFeature([{ name: Session.name, schema: SessionSchema }], 'sessions-store'),
31
+ ],
7
32
  controllers: [],
8
- providers: [SessionsService],
9
- exports: [SessionsService],
33
+ providers: [SessionsService, DictionariesService],
34
+ exports: [SessionsService, DictionariesService],
10
35
  })
11
36
  export class DLCommonsModule {}
@@ -1,6 +1,5 @@
1
- import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
1
+ import { Injectable, CanActivate, ExecutionContext, UnauthorizedException, ForbiddenException } from '@nestjs/common';
2
2
  import { Reflector } from '@nestjs/core';
3
- import { Observable, of } from 'rxjs';
4
3
  import { SessionsService } from '../services/sessions.service';
5
4
 
6
5
  export class PermissionGuardArgs {
@@ -14,8 +13,9 @@ export const AllowPermissions = Reflector.createDecorator<PermissionGuardArgs>()
14
13
  export class PermissionGuard implements CanActivate {
15
14
  constructor(private readonly _sessionsService: SessionsService, private readonly _reflector: Reflector) {}
16
15
 
17
- canActivate(context: ExecutionContext): Observable<boolean> {
18
- const args = this._reflector.get(PermissionGuardArgs, context.getHandler());
16
+ async canActivate(context: ExecutionContext) {
17
+ const args = this._reflector.get<PermissionGuardArgs>(AllowPermissions, context.getHandler());
18
+
19
19
  const request = context.switchToHttp().getRequest();
20
20
  const token: string = this._getToken(request);
21
21
 
@@ -23,9 +23,28 @@ export class PermissionGuard implements CanActivate {
23
23
  throw new UnauthorizedException();
24
24
  }
25
25
 
26
- console.log(args);
26
+ const session = await this._sessionsService.read(token);
27
+ if (!session) {
28
+ throw new UnauthorizedException();
29
+ }
30
+
31
+ let isPermissionsOk = true;
32
+ if (args && args.keywords) {
33
+ isPermissionsOk = false;
34
+ for (let keyword of args.keywords) {
35
+ isPermissionsOk = this._checkPermission(session.user.permissions, keyword);
36
+ if (isPermissionsOk) {
37
+ break;
38
+ }
39
+ }
40
+ }
41
+
42
+ if (!isPermissionsOk) {
43
+ throw new ForbiddenException();
44
+ }
27
45
 
28
- return of(true);
46
+ request.session = session;
47
+ return true;
29
48
  }
30
49
 
31
50
  private _getToken(request: any) {
@@ -41,29 +60,7 @@ export class PermissionGuard implements CanActivate {
41
60
  return token;
42
61
  }
43
62
 
44
- /*
45
- private _checkPermission(userPermissions: IPermission[], allowedPermission: string): boolean {
46
- if (allowedPermission) {
47
- return userPermissions.some((item) => item.keyword === allowedPermission);
48
- } else {
49
- return true;
50
- }
51
- }
52
-
53
- private setUserData(userData: ISessionUserData, client: IClient, permissions: IPermission[], request: Request) {
54
- const userInfo = {
55
- ...userData,
56
- client,
57
- permissions,
58
- };
59
- request['user'] = userInfo;
60
- }
61
-
62
- private validateUserData(userData: ISessionUserData) {
63
- if (!userData) {
64
- throw new RESTError('unauthorized', HttpStatus.UNAUTHORIZED);
65
- }
66
- return userData;
63
+ private _checkPermission(userPermissions: string[], allowedPermission: string): boolean {
64
+ return userPermissions.some((keyword) => keyword === allowedPermission);
67
65
  }
68
- */
69
66
  }
package/src/index.ts CHANGED
@@ -32,6 +32,8 @@ import { IPerson } from './models/interfaces/person.interface';
32
32
  import { IRecord } from './models/interfaces/record.interface';
33
33
  import { IResidence } from './models/interfaces/residence.interface';
34
34
  import { IRole } from './models/interfaces/role.interface';
35
+ import { ISession } from './models/interfaces/session.interface';
36
+ import { ISessionUser } from './models/interfaces/session-user.interface';
35
37
  import { Base, BaseDocument, BaseSchema } from './models/schemas/base.schema';
36
38
  import { Contact, ContactDocument, ContactSchema } from './models/schemas/embedded/contact.schema';
37
39
  import { DictionaryEmbedded, DictionaryEmbeddedDocument, DictionaryEmbeddedSchema } from './models/schemas/embedded/dictionary-embedded.schema';
@@ -44,6 +46,9 @@ import { MongoIdPipe } from './pipes/mongo-id.pipe';
44
46
  import { MongoIdsPipe } from './pipes/mongo-ids.pipe';
45
47
  import { SessionsService } from './services/sessions.service';
46
48
  import { transformers } from './transformers/common.transformer';
49
+ import { IUser } from './models/interfaces/user.interface';
50
+ import { SessionUser, SessionUserDocument, SessionUserSchema } from './models/schemas/embedded/session-user.schema';
51
+ import { Session, SessionDocument, SessionSchema } from './models/schemas/session.schema';
47
52
 
48
53
  export {
49
54
  /**
@@ -107,6 +112,9 @@ export {
107
112
  IContact,
108
113
  IPerson,
109
114
  IResidence,
115
+ ISessionUser,
116
+ ISession,
117
+ IUser,
110
118
 
111
119
  /**
112
120
  * Schemas & Documents
@@ -135,6 +143,12 @@ export {
135
143
  DictionaryEmbedded,
136
144
  DictionaryEmbeddedSchema,
137
145
  DictionaryEmbeddedDocument,
146
+ SessionUser,
147
+ SessionUserSchema,
148
+ SessionUserDocument,
149
+ Session,
150
+ SessionSchema,
151
+ SessionDocument,
138
152
 
139
153
  /**
140
154
  * Filters
@@ -5,3 +5,5 @@ export const APP__ACCESS_TOKEN = 'APP__ACCESS_TOKEN';
5
5
  export const MONGO__CS = 'MONGO__CS';
6
6
  export const REDIS__CS = 'REDIS__CS';
7
7
  export const KAFKA__BROKERS = 'KAFKA__BROKERS';
8
+
9
+ export const DL_SESSIONS__MONGO__CS = 'DL_SESSIONS__MONGO__CS';
@@ -0,0 +1,12 @@
1
+ import { UserVerificationLevel } from '../enums/user-verifiation-level.enum';
2
+ import { IContact } from './contact.interface';
3
+ import { IPerson } from './person.interface';
4
+
5
+ export interface ISessionUser {
6
+ _id: string;
7
+ username: string;
8
+ person: IPerson;
9
+ contacts: IContact[];
10
+ permissions: string[];
11
+ verificationLevel: UserVerificationLevel;
12
+ }
@@ -0,0 +1,9 @@
1
+ import { IIdentifable } from './identifable.interface';
2
+ import { ISessionUser } from './session-user.interface';
3
+
4
+ export interface ISession extends IIdentifable {
5
+ token: string;
6
+ user: ISessionUser;
7
+ expiresAt: Date;
8
+ userAgent: string;
9
+ }
@@ -0,0 +1,15 @@
1
+ import { UserVerificationLevel } from '../enums/user-verifiation-level.enum';
2
+ import { IBase } from './base.interface';
3
+ import { IContact } from './contact.interface';
4
+ import { IPerson } from './person.interface';
5
+ import { IRole } from './role.interface';
6
+
7
+ export interface IUser extends IBase {
8
+ username: string;
9
+ password: string;
10
+ salt: string;
11
+ person: IPerson;
12
+ contacts: IContact[];
13
+ roles: IRole[];
14
+ verificationLevel: UserVerificationLevel;
15
+ }
@@ -0,0 +1,32 @@
1
+ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
2
+ import { HydratedDocument } from 'mongoose';
3
+ import { UserVerificationLevel } from '../../enums/user-verifiation-level.enum';
4
+ import { IContact } from '../../interfaces/contact.interface';
5
+ import { IPerson } from '../../interfaces/person.interface';
6
+ import { ISessionUser } from '../../interfaces/session-user.interface';
7
+ import { ContactSchema } from './contact.schema';
8
+ import { PersonSchema } from './person.schema';
9
+
10
+ @Schema({ id: false })
11
+ export class SessionUser implements ISessionUser {
12
+ @Prop({ required: true, type: String })
13
+ _id: string;
14
+
15
+ @Prop({ required: true, type: String })
16
+ username: string;
17
+
18
+ @Prop({ type: PersonSchema, required: true })
19
+ person: IPerson;
20
+
21
+ @Prop({ type: [ContactSchema], required: true, default: [] })
22
+ contacts: IContact[];
23
+
24
+ @Prop({ type: [String], required: true, default: [] })
25
+ permissions: string[];
26
+
27
+ @Prop({ type: String, enum: UserVerificationLevel, required: true, default: UserVerificationLevel.None })
28
+ verificationLevel: UserVerificationLevel;
29
+ }
30
+
31
+ export const SessionUserSchema = SchemaFactory.createForClass(SessionUser);
32
+ export type SessionUserDocument = HydratedDocument<SessionUser>;
@@ -0,0 +1,24 @@
1
+ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
2
+ import { HydratedDocument } from 'mongoose';
3
+ import { ISessionUser } from '../interfaces/session-user.interface';
4
+ import { ISession } from '../interfaces/session.interface';
5
+ import { SessionUserSchema } from './embedded/session-user.schema';
6
+ import { Identifable } from './identifable.schema';
7
+
8
+ @Schema()
9
+ export class Session extends Identifable implements ISession {
10
+ @Prop({ type: String, unique: true, required: true })
11
+ token: string;
12
+
13
+ @Prop({ type: SessionUserSchema, required: true })
14
+ user: ISessionUser;
15
+
16
+ @Prop({ required: true })
17
+ expiresAt: Date;
18
+
19
+ @Prop({ required: true })
20
+ userAgent: string;
21
+ }
22
+
23
+ export const SessionSchema = SchemaFactory.createForClass(Session);
24
+ export type SessionDocument = HydratedDocument<Session>;
@@ -0,0 +1,57 @@
1
+ import { HttpService } from '@nestjs/axios';
2
+ import { Injectable } from '@nestjs/common';
3
+ import { ConfigService } from '@nestjs/config';
4
+ import { RESTResponseBody, RESTError } from '../models/dtos/wrappers/rest-wrapper.class';
5
+ import { firstValueFrom } from 'rxjs';
6
+ import { IDictionary } from '../models/interfaces/dictionary.interface';
7
+
8
+ @Injectable()
9
+ export class DictionariesService {
10
+ //#region Private Members
11
+ private _baseUrl: string;
12
+ //#endregion
13
+
14
+ //#region Constructor
15
+ constructor(private readonly _httpService: HttpService, private readonly _configService: ConfigService) {
16
+ this._baseUrl = this._configService.getOrThrow('DL_DICTIONARIES__REST__BASE_URL');
17
+ }
18
+ //#endregion
19
+
20
+ //#region Public API
21
+ public async fetchById(id: string) {
22
+ try {
23
+ const endpoint = `${this._baseUrl}/v1/dictionaries/by-id/${id}`;
24
+ const response$ = this._httpService.get<RESTResponseBody<IDictionary>>(endpoint);
25
+ const response = await firstValueFrom(response$);
26
+
27
+ if (response.data.errors) {
28
+ throw new RESTError('dictionaries_api_error', response.data.errors);
29
+ }
30
+ if (!response.data || !response.data.result) {
31
+ throw new RESTError('dictionaries_api_error', 'empty response');
32
+ }
33
+ return response.data.result.data;
34
+ } catch (e) {
35
+ throw RESTError.createFromCatch(e, { keyword: 'unknown', debug: e });
36
+ }
37
+ }
38
+
39
+ public async fetchByKeyword(keyword: string) {
40
+ try {
41
+ const endpoint = `${this._baseUrl}/v1/dictionaries/by-keyword/${keyword}`;
42
+ const response$ = this._httpService.get<RESTResponseBody<IDictionary>>(endpoint);
43
+ const response = await firstValueFrom(response$);
44
+
45
+ if (response.data.errors) {
46
+ throw new RESTError('dictionaries_api_error', response.data.errors);
47
+ }
48
+ if (!response.data || !response.data.result) {
49
+ throw new RESTError('dictionaries_api_error', 'empty response');
50
+ }
51
+ return response.data.result.data;
52
+ } catch (e) {
53
+ throw RESTError.createFromCatch(e, { keyword: 'unknown', debug: e });
54
+ }
55
+ }
56
+ //#endregion
57
+ }
@@ -1,6 +1,61 @@
1
- import { Injectable } from '@nestjs/common';
1
+ import { HttpService } from '@nestjs/axios';
2
+ import { Injectable, UnauthorizedException } from '@nestjs/common';
3
+ import { ConfigService } from '@nestjs/config';
4
+ import { RESTResponseBody, RESTError } from '../models/dtos/wrappers/rest-wrapper.class';
5
+ import { ISession } from '../models/interfaces/session.interface';
6
+ import { firstValueFrom } from 'rxjs';
7
+ import { Model } from 'mongoose';
8
+ import { Session, SessionDocument } from '../models/schemas/session.schema';
9
+ import { InjectModel } from '@nestjs/mongoose';
2
10
 
3
11
  @Injectable()
4
12
  export class SessionsService {
5
- constructor() {}
13
+ //#region Private Members
14
+ private _baseUrl: string;
15
+ //#endregion
16
+
17
+ //#region Constructor
18
+ constructor(
19
+ @InjectModel(Session.name, 'sessions-store')
20
+ private readonly _sessionModel: Model<SessionDocument>,
21
+ private readonly _httpService: HttpService,
22
+ private readonly _configService: ConfigService,
23
+ ) {
24
+ this._baseUrl = this._configService.getOrThrow('DL_SESSIONS__REST__BASE_URL');
25
+ }
26
+ //#endregion
27
+
28
+ //#region Public API
29
+ public async create(userId: string, userAgent: string, ip: string) {
30
+ try {
31
+ const endpoint = `${this._baseUrl}/v1/sessions/${userId}`;
32
+ const headers = { 'user-agent': userAgent, 'x-ip': ip };
33
+ const response$ = this._httpService.post<RESTResponseBody<ISession>>(endpoint, null, { headers });
34
+ const response = await firstValueFrom(response$);
35
+
36
+ if (response.data.errors) {
37
+ throw new RESTError('sessions_api_error', response.data.errors);
38
+ }
39
+ if (!response.data || !response.data.result) {
40
+ throw new RESTError('sessions_api_error', 'empty response');
41
+ }
42
+ return response.data.result.data;
43
+ } catch (e) {
44
+ throw RESTError.createFromCatch(e, { keyword: 'unknown', debug: e });
45
+ }
46
+ }
47
+
48
+ public async read(token: string): Promise<ISession> {
49
+ if (!token) {
50
+ throw new UnauthorizedException();
51
+ }
52
+
53
+ const session = await this._sessionModel.findOne({ token });
54
+ if (!session) {
55
+ throw new UnauthorizedException();
56
+ }
57
+
58
+ return session;
59
+ }
60
+ //#endregion
6
61
  }