@drax/identity-back 1.0.0 → 1.1.0

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.
@@ -1,6 +1,6 @@
1
1
  import { beforeAll, afterAll, describe, it, expect } from "vitest"
2
2
  import UserService from "../../src/services/UserService";
3
- import MongoInMemory from "../db/MongoInMemory";
3
+ import MongoInMemory from "../setup/MongoInMemory";
4
4
  import RoleMongoInitializer from "../initializers/RoleMongoInitializer";
5
5
  import {IRole} from "../../../identity-share/src/interfaces/IRole";
6
6
  import UserMongoRepository from "../../src/repository/mongo/UserMongoRepository";
@@ -12,34 +12,38 @@ describe("UserServiceTest", function () {
12
12
  let userService = new UserService(userRepository)
13
13
  let adminRole: IRole
14
14
  let userAdminData: any
15
+ let mongoInMemory: MongoInMemory = new MongoInMemory()
15
16
 
16
17
  beforeAll(async () => {
17
- await MongoInMemory.connect()
18
+ await mongoInMemory.connect()
18
19
  adminRole = await RoleMongoInitializer.initAdminRole()
19
20
  userAdminData = (await import("../data-obj/users/root-mongo-user")).default
20
- console.log("BEFORE USER", MongoInMemory.mongooseStatus, MongoInMemory.serverStatus)
21
21
  return
22
22
  })
23
23
 
24
24
  afterAll(async () => {
25
- await MongoInMemory.DropAndClose()
26
- console.log("AFTER USER", MongoInMemory.status, MongoInMemory.serverStatus)
25
+ await mongoInMemory.DropAndClose()
27
26
  return
28
27
  })
29
28
 
30
29
  it("should create user", async function () {
31
- const user = {...userAdminData}
32
- let userCreated = await userService.create(user)
30
+ const userData = {...userAdminData}
31
+ let userCreated = await userService.create(userData)
33
32
  expect(userCreated.username).toBe(userAdminData.username)
34
33
  })
35
34
 
36
35
 
36
+ it("should find one user", async function () {
37
+ let user = await userService.findById(userAdminData._id)
38
+ expect(user.username).toBe(userAdminData.username)
39
+ })
37
40
 
38
- it("should changeUserPassword user", async function () {
39
- const userId = userAdminData._id
40
- const newPassword = "123"
41
- let userPasswordChanged = await userService.changeUserPassword(userId, newPassword)
42
- expect(userPasswordChanged._id.toString()).toBe(userId)
41
+ it("should modify user", async function () {
42
+ const userData = {...userAdminData}
43
+ const newName = "AdminUpdated"
44
+ userData.name = newName
45
+ let userUpdated = await userService.update(userAdminData._id, userData)
46
+ expect(userUpdated.name).toBe(newName)
43
47
  })
44
48
 
45
49
  it("should fail create user with short password", async function () {
@@ -55,8 +59,14 @@ describe("UserServiceTest", function () {
55
59
  });
56
60
  })
57
61
 
58
- it("should find one user", async function () {
59
- let user = await userService.findById(userAdminData._id)
60
- expect(user.username).toBe(userAdminData.username)
62
+
63
+ it("should changeUserPassword user", async function () {
64
+ const userId = userAdminData._id
65
+ const newPassword = "123"
66
+ let userPasswordChanged = await userService.changeUserPassword(userId, newPassword)
67
+ expect(userPasswordChanged._id.toString()).toBe(userId)
61
68
  })
69
+
70
+
71
+
62
72
  })
@@ -0,0 +1,44 @@
1
+ import {mongoose} from '@drax/common-back';
2
+ import { MongoMemoryServer } from 'mongodb-memory-server';
3
+
4
+ class MongoInMemory{
5
+
6
+ mongoServer: MongoMemoryServer
7
+
8
+ async connect(){
9
+ this.mongoServer = await MongoMemoryServer.create();
10
+ if(this.mongoServer.state == "new"){
11
+ await this.mongoServer.start()
12
+ }
13
+ if(!mongoose.connection.readyState){
14
+ await mongoose.connect(this.mongoServer.getUri(), { dbName: "verifyMASTER" });
15
+ }
16
+ return
17
+ }
18
+
19
+ get mongooseStatus(){
20
+ return mongoose.connection.readyState
21
+ }
22
+
23
+ get serverStatus(){
24
+ return this.mongoServer.state
25
+ }
26
+
27
+ get status(){
28
+ return mongoose.connection.readyState
29
+ }
30
+
31
+ async disconnect(){
32
+ await mongoose.disconnect();
33
+ }
34
+
35
+ async DropAndClose(){
36
+ if (this.mongoServer) {
37
+ await mongoose.connection.dropDatabase();
38
+ await mongoose.connection.close();
39
+ await this.mongoServer.stop();
40
+ }
41
+ }
42
+ }
43
+
44
+ export default MongoInMemory
@@ -0,0 +1,153 @@
1
+ import Fastify, {FastifyInstance} from "fastify";
2
+ import {LoadCommonConfigFromEnv} from "@drax/common-back";
3
+ import {
4
+ LoadIdentityConfigFromEnv,
5
+ CreateOrUpdateRole,
6
+ CreateUserIfNotExist,
7
+ jwtMiddleware,
8
+ rbacMiddleware,
9
+ apiKeyMiddleware,
10
+ UserRoutes, RoleRoutes, TenantRoutes, UserApiKeyRoutes,
11
+ UserPermissions, RolePermissions, TenantPermissions, UserApiKeyPermissions,
12
+ LoadPermissions
13
+ } from "@drax/identity-back";
14
+ import rootUserData from "./data/root-user";
15
+ import adminRoleData from "./data/admin-role";
16
+ import {IUser, IRole} from "@drax/identity-share";
17
+ import MongoInMemory from "./MongoInMemory";
18
+
19
+ class TestSetup {
20
+
21
+ private _fastifyInstance: FastifyInstance;
22
+ private _mongoInMemory: MongoInMemory;
23
+ private _rootUser: IUser;
24
+ private _adminRole: IRole;
25
+
26
+ constructor() {
27
+ }
28
+
29
+ async setup() {
30
+ this.setupEnvironmentVariables();
31
+ this.setupConfig();
32
+ this.setupPermissions();
33
+ this.setupFastifyInstance();
34
+ await this.setupMongoInMemoryAndConnect();
35
+ await this.setupRootUserAndAdminRole();
36
+ }
37
+
38
+ setupEnvironmentVariables() {
39
+ // Define environment variables
40
+ process.env.DRAX_DB_ENGINE = "mongo";
41
+ process.env.DRAX_JWT_SECRET = "xxx";
42
+ }
43
+
44
+ setupConfig() {
45
+ LoadCommonConfigFromEnv();
46
+ LoadIdentityConfigFromEnv();
47
+ }
48
+
49
+ setupPermissions() {
50
+ //Merge All Permissions
51
+ const permissions = [
52
+ ...Object.values(UserPermissions),
53
+ ...Object.values(RolePermissions),
54
+ ...Object.values(TenantPermissions),
55
+ ...Object.values(UserApiKeyPermissions),
56
+ ]
57
+
58
+ //Load All Permissions
59
+ LoadPermissions(permissions)
60
+ }
61
+
62
+ setupFastifyInstance() {
63
+ this._fastifyInstance = Fastify()
64
+ this._fastifyInstance.setValidatorCompiler(() => () => true)
65
+ this._fastifyInstance.addHook('onRequest', jwtMiddleware)
66
+ this._fastifyInstance.addHook('onRequest', rbacMiddleware)
67
+ this._fastifyInstance.addHook('onRequest', apiKeyMiddleware)
68
+ this._fastifyInstance.register(UserRoutes)
69
+ this._fastifyInstance.register(RoleRoutes)
70
+ this._fastifyInstance.register(TenantRoutes)
71
+ this._fastifyInstance.register(UserApiKeyRoutes)
72
+ }
73
+
74
+ async setupMongoInMemoryAndConnect() {
75
+ this._mongoInMemory = new MongoInMemory();
76
+ await this._mongoInMemory.connect();
77
+ }
78
+
79
+ async setupRootUserAndAdminRole() {
80
+ this._adminRole = await CreateOrUpdateRole({...adminRoleData})
81
+ this._rootUser = await CreateUserIfNotExist({...rootUserData})
82
+ }
83
+
84
+ async login(username: string= rootUserData.username, password: string= rootUserData.password): Promise<{accessToken: string}> {
85
+
86
+ const resp = await this._fastifyInstance.inject({
87
+ method: 'POST',
88
+ url: '/api/auth/login',
89
+ payload: {username: username, password: password}
90
+ });
91
+
92
+ let body = resp.json()
93
+
94
+ if(resp.statusCode === 200 && body.accessToken){
95
+ return {accessToken: body.accessToken}
96
+ }else{
97
+ throw new Error(`Failed to login. Status Code: ${resp.statusCode} body: ${resp.body}`)
98
+ }
99
+
100
+ }
101
+
102
+ async me(accessToken:string): Promise<IUser> {
103
+
104
+ const resp = await this._fastifyInstance.inject({
105
+ method: 'GET',
106
+ url: '/api/auth/me',
107
+ headers: {Authorization: `Bearer ${accessToken}`}
108
+ });
109
+
110
+ if(resp.statusCode === 200){
111
+ let user : IUser = resp.json() as IUser
112
+ return user
113
+ }else{
114
+ throw new Error(`Failed to get me. Status Code: ${resp.statusCode} body: ${resp.body}`)
115
+ }
116
+
117
+
118
+ }
119
+
120
+
121
+ get adminRoleData() {
122
+ return {...adminRoleData};
123
+ }
124
+
125
+ get rootUserData() {
126
+ return {...rootUserData};
127
+ }
128
+
129
+ get rootUser() {
130
+ return this._rootUser;
131
+ }
132
+
133
+ get adminRole() {
134
+ return this._adminRole;
135
+ }
136
+
137
+ get fastifyInstance() {
138
+ return this._fastifyInstance;
139
+ }
140
+
141
+ get mongoInMemory() {
142
+ return this._mongoInMemory;
143
+ }
144
+
145
+
146
+ }
147
+
148
+
149
+ export default TestSetup
150
+
151
+ export {
152
+ TestSetup
153
+ }
@@ -1,4 +1,4 @@
1
- import {PermissionService} from "../../../src/services/PermissionService.js"
1
+ import {PermissionService} from "@drax/identity-back"
2
2
 
3
3
  const role = {
4
4
  name: "Admin",