authkit-api 0.0.0-stage → 1.0.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.
- package/CHANGELOG.md +26 -0
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/bin/cli.js +8 -0
- package/package.json +69 -4
- package/src/constants.js +24 -0
- package/src/generator.js +112 -0
- package/src/index.js +89 -0
- package/src/prompts.js +43 -0
- package/src/utils/fs.js +36 -0
- package/src/utils/logger.js +8 -0
- package/src/utils/packageJson.js +16 -0
- package/src/utils/validateProjectName.js +19 -0
- package/templates/base/Dockerfile +22 -0
- package/templates/base/README.md +108 -0
- package/templates/base/_dockerignore +16 -0
- package/templates/base/_env.example +25 -0
- package/templates/base/_gitignore +5 -0
- package/templates/base/_husky/pre-commit +1 -0
- package/templates/base/_prettierignore +5 -0
- package/templates/base/_prettierrc +1 -0
- package/templates/base/eslint.config.js +23 -0
- package/templates/base/package.json +62 -0
- package/templates/base/scripts/docker-entrypoint.sh +9 -0
- package/templates/base/scripts/generate-postman.js +70 -0
- package/templates/base/scripts/seed-admin.js +61 -0
- package/templates/base/src/app.js +46 -0
- package/templates/base/src/config/env.js +15 -0
- package/templates/base/src/config/env.schema.js +85 -0
- package/templates/base/src/config/logger.js +20 -0
- package/templates/base/src/constants/examples.js +3 -0
- package/templates/base/src/constants/roles.js +2 -0
- package/templates/base/src/constants/user.rules.js +16 -0
- package/templates/base/src/docs/openapi.js +26 -0
- package/templates/base/src/docs/openapi.registry.js +81 -0
- package/templates/base/src/docs/paths/auth.paths.js +87 -0
- package/templates/base/src/docs/paths/user.paths.js +87 -0
- package/templates/base/src/middlewares/authenticate.js +19 -0
- package/templates/base/src/middlewares/authorize.js +11 -0
- package/templates/base/src/middlewares/errorHandler.js +35 -0
- package/templates/base/src/middlewares/notFound.js +5 -0
- package/templates/base/src/middlewares/rateLimiter.js +20 -0
- package/templates/base/src/middlewares/validate.js +31 -0
- package/templates/base/src/modules/auth/auth.controller.js +40 -0
- package/templates/base/src/modules/auth/auth.cookie.js +21 -0
- package/templates/base/src/modules/auth/auth.routes.js +12 -0
- package/templates/base/src/modules/auth/auth.service.js +79 -0
- package/templates/base/src/modules/auth/auth.validation.js +41 -0
- package/templates/base/src/modules/user/user.controller.js +21 -0
- package/templates/base/src/modules/user/user.routes.js +22 -0
- package/templates/base/src/modules/user/user.service.js +19 -0
- package/templates/base/src/modules/user/user.validation.js +24 -0
- package/templates/base/src/routes/docs.routes.js +16 -0
- package/templates/base/src/routes/health.routes.js +17 -0
- package/templates/base/src/routes/index.js +13 -0
- package/templates/base/src/server.js +50 -0
- package/templates/base/src/utils/ApiError.js +32 -0
- package/templates/base/src/utils/apiResponse.js +8 -0
- package/templates/base/src/utils/password.js +14 -0
- package/templates/base/src/utils/token.js +46 -0
- package/templates/base/src/utils/zod.js +5 -0
- package/templates/base/tests/app.test.js +67 -0
- package/templates/base/tests/auth.test.js +185 -0
- package/templates/base/tests/authenticate.test.js +61 -0
- package/templates/base/tests/docs.test.js +115 -0
- package/templates/base/tests/env.test.js +94 -0
- package/templates/base/tests/health.test.js +21 -0
- package/templates/base/tests/helpers/auth.helper.js +41 -0
- package/templates/base/tests/password.test.js +18 -0
- package/templates/base/tests/postman.test.js +31 -0
- package/templates/base/tests/rateLimiter.test.js +27 -0
- package/templates/base/tests/seedAdmin.test.js +42 -0
- package/templates/base/tests/token.test.js +69 -0
- package/templates/base/tests/trustProxy.test.js +24 -0
- package/templates/base/tests/user.repository.test.js +210 -0
- package/templates/base/tests/user.test.js +144 -0
- package/templates/base/tests/validate.test.js +35 -0
- package/templates/base/tests/validation.test.js +61 -0
- package/templates/base/vitest.config.js +16 -0
- package/templates/databases/mongodb/README.part.md +23 -0
- package/templates/databases/mongodb/_github/workflows/ci.yml +29 -0
- package/templates/databases/mongodb/docker-compose.yml +30 -0
- package/templates/databases/mongodb/env.part +2 -0
- package/templates/databases/mongodb/package.part.json +4 -0
- package/templates/databases/mongodb/src/database/connection.js +39 -0
- package/templates/databases/mongodb/src/database/env.schema.js +3 -0
- package/templates/databases/mongodb/src/database/id.schema.js +3 -0
- package/templates/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
- package/templates/databases/mongodb/src/database/models/user.model.js +41 -0
- package/templates/databases/mongodb/src/modules/user/user.repository.js +68 -0
- package/templates/databases/mongodb/tests/globalSetup.js +13 -0
- package/templates/databases/mongodb/tests/setup.js +17 -0
- package/templates/databases/postgres/README.part.md +31 -0
- package/templates/databases/postgres/_github/workflows/ci.yml +46 -0
- package/templates/databases/postgres/docker-compose.yml +34 -0
- package/templates/databases/postgres/env.part +2 -0
- package/templates/databases/postgres/package.part.json +15 -0
- package/templates/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
- package/templates/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
- package/templates/databases/postgres/prisma/schema.prisma +39 -0
- package/templates/databases/postgres/prisma.config.js +14 -0
- package/templates/databases/postgres/src/database/connection.js +61 -0
- package/templates/databases/postgres/src/database/env.schema.js +3 -0
- package/templates/databases/postgres/src/database/id.schema.js +3 -0
- package/templates/databases/postgres/src/database/prisma.js +9 -0
- package/templates/databases/postgres/src/modules/user/user.repository.js +88 -0
- package/templates/databases/postgres/tests/connection.test.js +17 -0
- package/templates/databases/postgres/tests/globalSetup.js +60 -0
- package/templates/databases/postgres/tests/prismaSchema.test.js +27 -0
- package/templates/databases/postgres/tests/setup.js +15 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import request from 'supertest';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { createApp } from '../src/app.js';
|
|
4
|
+
import * as userRepository from '../src/modules/user/user.repository.js';
|
|
5
|
+
import { createAdmin, createUser, loginAs } from './helpers/auth.helper.js';
|
|
6
|
+
|
|
7
|
+
const app = createApp();
|
|
8
|
+
|
|
9
|
+
// Every response in this file must be free of password data.
|
|
10
|
+
function expectNoPassword(res) {
|
|
11
|
+
expect(JSON.stringify(res.body)).not.toContain('"password"');
|
|
12
|
+
return res;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const api = (method, path, token) => {
|
|
16
|
+
const req = request(app)[method](`/api/v1/users${path}`);
|
|
17
|
+
return (token ? req.set('Authorization', `Bearer ${token}`) : req).then(expectNoPassword);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// A valid id (for either database) that no longer exists.
|
|
21
|
+
async function unknownId() {
|
|
22
|
+
const { user } = await createUser();
|
|
23
|
+
await userRepository.deleteById(user.id);
|
|
24
|
+
return user.id;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function login(factory = createUser) {
|
|
28
|
+
const { user, password } = await factory();
|
|
29
|
+
const session = await loginAs(app, { email: user.email, password });
|
|
30
|
+
return { user, token: session.accessToken };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('GET /users/me', () => {
|
|
34
|
+
it('returns the logged in profile', async () => {
|
|
35
|
+
const { user, token } = await login();
|
|
36
|
+
const res = await api('get', '/me', token);
|
|
37
|
+
expect(res.status).toBe(200);
|
|
38
|
+
expect(res.body.data.user.email).toBe(user.email);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('requires authentication', async () => {
|
|
42
|
+
expect((await api('get', '/me')).status).toBe(401);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('GET /users', () => {
|
|
47
|
+
it('is forbidden for a normal user', async () => {
|
|
48
|
+
const { token } = await login();
|
|
49
|
+
const res = await api('get', '', token);
|
|
50
|
+
expect(res.status).toBe(403);
|
|
51
|
+
expect(res.body.message).toBe('You do not have permission to perform this action');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('lists users with pagination meta for an admin', async () => {
|
|
55
|
+
const { token } = await login(createAdmin);
|
|
56
|
+
await createUser();
|
|
57
|
+
const res = await api('get', '', token);
|
|
58
|
+
expect(res.status).toBe(200);
|
|
59
|
+
expect(res.body.data.users).toHaveLength(2);
|
|
60
|
+
expect(res.body.meta).toEqual({ page: 1, limit: 20, total: 2, totalPages: 1 });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('pages through results', async () => {
|
|
64
|
+
const { token } = await login(createAdmin);
|
|
65
|
+
await createUser();
|
|
66
|
+
await createUser();
|
|
67
|
+
const first = await api('get', '?limit=1&page=1', token);
|
|
68
|
+
const second = await api('get', '?limit=1&page=2', token);
|
|
69
|
+
expect(second.status).toBe(200);
|
|
70
|
+
expect(second.body.data.users).toHaveLength(1);
|
|
71
|
+
expect(second.body.data.users[0].id).not.toBe(first.body.data.users[0].id);
|
|
72
|
+
expect(second.body.meta).toEqual({ page: 2, limit: 1, total: 3, totalPages: 3 });
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('returns an empty page past the end and keeps the total', async () => {
|
|
76
|
+
const { token } = await login(createAdmin);
|
|
77
|
+
await createUser();
|
|
78
|
+
const res = await api('get', '?page=999', token);
|
|
79
|
+
expect(res.status).toBe(200);
|
|
80
|
+
expect(res.body.data.users).toEqual([]);
|
|
81
|
+
expect(res.body.meta).toMatchObject({ page: 999, total: 2 });
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('rejects a limit above the maximum', async () => {
|
|
85
|
+
const { token } = await login(createAdmin);
|
|
86
|
+
expect((await api('get', '?limit=500', token)).status).toBe(400);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe('GET /users/:id', () => {
|
|
91
|
+
it('returns a user for an admin', async () => {
|
|
92
|
+
const { token } = await login(createAdmin);
|
|
93
|
+
const { user } = await createUser();
|
|
94
|
+
const res = await api('get', `/${user.id}`, token);
|
|
95
|
+
expect(res.status).toBe(200);
|
|
96
|
+
expect(res.body.data.user.id).toBe(user.id);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('is forbidden for a normal user', async () => {
|
|
100
|
+
const { user, token } = await login();
|
|
101
|
+
expect((await api('get', `/${user.id}`, token)).status).toBe(403);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('returns 404 for an unknown id', async () => {
|
|
105
|
+
const { token } = await login(createAdmin);
|
|
106
|
+
const res = await api('get', `/${await unknownId()}`, token);
|
|
107
|
+
expect(res.status).toBe(404);
|
|
108
|
+
expect(res.body.message).toBe('User not found');
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('returns 400 for a malformed id', async () => {
|
|
112
|
+
const { token } = await login(createAdmin);
|
|
113
|
+
expect((await api('get', '/abc', token)).status).toBe(400);
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
describe('DELETE /users/:id', () => {
|
|
118
|
+
it('deletes a user and locks them out', async () => {
|
|
119
|
+
const admin = await login(createAdmin);
|
|
120
|
+
const target = await login();
|
|
121
|
+
const res = await api('delete', `/${target.user.id}`, admin.token);
|
|
122
|
+
expect(res.status).toBe(204);
|
|
123
|
+
expect((await api('get', `/${target.user.id}`, admin.token)).status).toBe(404);
|
|
124
|
+
expect((await api('get', '/me', target.token)).status).toBe(401);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('refuses to delete yourself', async () => {
|
|
128
|
+
const admin = await login(createAdmin);
|
|
129
|
+
const res = await api('delete', `/${admin.user.id}`, admin.token);
|
|
130
|
+
expect(res.status).toBe(400);
|
|
131
|
+
expect(res.body.message).toBe('You cannot delete your own account');
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('is forbidden for a normal user', async () => {
|
|
135
|
+
const { token } = await login();
|
|
136
|
+
const { user } = await createUser();
|
|
137
|
+
expect((await api('delete', `/${user.id}`, token)).status).toBe(403);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('returns 404 for an unknown id', async () => {
|
|
141
|
+
const { token } = await login(createAdmin);
|
|
142
|
+
expect((await api('delete', `/${await unknownId()}`, token)).status).toBe(404);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { validate } from '../src/middlewares/validate.js';
|
|
3
|
+
import { registerSchema } from '../src/modules/auth/auth.validation.js';
|
|
4
|
+
import { listUsersSchema } from '../src/modules/user/user.validation.js';
|
|
5
|
+
|
|
6
|
+
const run = (schema, req) => {
|
|
7
|
+
const next = vi.fn();
|
|
8
|
+
validate(schema)(req, {}, next);
|
|
9
|
+
return next;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
describe('validate middleware', () => {
|
|
13
|
+
it('sets req.validated and calls next() on success', () => {
|
|
14
|
+
const req = { body: undefined, params: {}, query: { page: '3' } };
|
|
15
|
+
const next = run(listUsersSchema, req);
|
|
16
|
+
expect(next).toHaveBeenCalledWith();
|
|
17
|
+
expect(req.validated.query).toEqual({ page: 3, limit: 20 });
|
|
18
|
+
});
|
|
19
|
+
it('maps issues to field errors', () => {
|
|
20
|
+
const req = { body: { name: 'N', email: 'bad', password: 'Passw0rd' }, params: {}, query: {} };
|
|
21
|
+
const err = run(registerSchema, req).mock.calls[0][0];
|
|
22
|
+
expect(err.statusCode).toBe(400);
|
|
23
|
+
expect(err.message).toBe('Validation failed');
|
|
24
|
+
expect(err.errors.map((e) => e.field)).toEqual(expect.arrayContaining(['name', 'email']));
|
|
25
|
+
});
|
|
26
|
+
it('emits one entry per unrecognized key', () => {
|
|
27
|
+
const req = {
|
|
28
|
+
body: { name: 'Nitish', email: 'a@b.com', password: 'Passw0rd', role: 'admin' },
|
|
29
|
+
params: {},
|
|
30
|
+
query: {},
|
|
31
|
+
};
|
|
32
|
+
const err = run(registerSchema, req).mock.calls[0][0];
|
|
33
|
+
expect(err.errors[0]).toEqual({ field: 'role', message: 'Unrecognized field "role"' });
|
|
34
|
+
});
|
|
35
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { registerSchema, loginSchema } from '../src/modules/auth/auth.validation.js';
|
|
3
|
+
import { listUsersSchema, userIdParamSchema } from '../src/modules/user/user.validation.js';
|
|
4
|
+
|
|
5
|
+
const valid = { name: 'Nitish', email: ' Foo@X.com ', password: 'Passw0rd' };
|
|
6
|
+
const register = (body) => registerSchema.safeParse({ body, params: {}, query: {} });
|
|
7
|
+
const list = (query) => listUsersSchema.safeParse({ body: {}, params: {}, query });
|
|
8
|
+
const fields = (r) => r.error.issues.map((i) => i.path.slice(1).join('.'));
|
|
9
|
+
|
|
10
|
+
describe('registerSchema', () => {
|
|
11
|
+
it('accepts valid input and normalises the email', () => {
|
|
12
|
+
const r = register(valid);
|
|
13
|
+
expect(r.success).toBe(true);
|
|
14
|
+
expect(r.data.body.email).toBe('foo@x.com');
|
|
15
|
+
});
|
|
16
|
+
it('rejects a weak password on field password', () => {
|
|
17
|
+
const r = register({ ...valid, password: 'password' });
|
|
18
|
+
expect(r.success).toBe(false);
|
|
19
|
+
expect(fields(r)).toContain('password');
|
|
20
|
+
});
|
|
21
|
+
it('rejects too short and too long names', () => {
|
|
22
|
+
expect(register({ ...valid, name: 'N' }).success).toBe(false);
|
|
23
|
+
expect(register({ ...valid, name: 'a'.repeat(51) }).success).toBe(false);
|
|
24
|
+
});
|
|
25
|
+
it('rejects unknown keys such as role', () => {
|
|
26
|
+
const r = register({ ...valid, role: 'admin' });
|
|
27
|
+
expect(r.success).toBe(false);
|
|
28
|
+
expect(r.error.issues[0].code).toBe('unrecognized_keys');
|
|
29
|
+
});
|
|
30
|
+
it('works without params and query', () => {
|
|
31
|
+
expect(registerSchema.safeParse({ body: valid }).success).toBe(true);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe('loginSchema', () => {
|
|
36
|
+
it('only requires a non-empty password', () => {
|
|
37
|
+
const r = loginSchema.safeParse({ body: { email: 'a@b.com', password: 'x' } });
|
|
38
|
+
expect(r.success).toBe(true);
|
|
39
|
+
expect(loginSchema.safeParse({ body: { email: 'a@b.com', password: '' } }).success).toBe(false);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('listUsersSchema', () => {
|
|
44
|
+
it('coerces page and limit', () => {
|
|
45
|
+
expect(list({ page: '2', limit: '10' }).data.query).toEqual({ page: 2, limit: 10 });
|
|
46
|
+
});
|
|
47
|
+
it('applies defaults', () => {
|
|
48
|
+
expect(list({}).data.query).toEqual({ page: 1, limit: 20 });
|
|
49
|
+
});
|
|
50
|
+
it('rejects bad values', () => {
|
|
51
|
+
expect(list({ limit: '101' }).success).toBe(false);
|
|
52
|
+
expect(list({ limit: 'abc' }).success).toBe(false);
|
|
53
|
+
expect(list({ page: '0' }).success).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe('userIdParamSchema', () => {
|
|
58
|
+
it('rejects an invalid id', () => {
|
|
59
|
+
expect(userIdParamSchema.safeParse({ params: { id: 'nope' } }).success).toBe(false);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { defineConfig } from 'vitest/config';
|
|
2
|
+
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
test: {
|
|
5
|
+
env: {
|
|
6
|
+
NODE_ENV: 'test',
|
|
7
|
+
JWT_ACCESS_SECRET: 'test-access-secret-at-least-32-characters',
|
|
8
|
+
JWT_REFRESH_SECRET: 'test-refresh-secret-at-least-32-characters',
|
|
9
|
+
AUTH_RATE_LIMIT_MAX: '1000',
|
|
10
|
+
},
|
|
11
|
+
globalSetup: ['./tests/globalSetup.js'],
|
|
12
|
+
setupFiles: ['./tests/setup.js'],
|
|
13
|
+
// Database tests share one database, so test files run one at a time.
|
|
14
|
+
fileParallelism: false,
|
|
15
|
+
},
|
|
16
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
## Quick start
|
|
2
|
+
|
|
3
|
+
```bash
|
|
4
|
+
cd {{projectName}}
|
|
5
|
+
cp .env.example .env
|
|
6
|
+
npm install
|
|
7
|
+
docker compose up -d --wait db
|
|
8
|
+
npm run dev
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The API is on <http://localhost:3000>. `docker compose up -d --wait db` starts a MongoDB at the default `MONGODB_URI` (or point it at your own). `npm test` needs nothing installed: it uses an in-memory MongoDB.
|
|
12
|
+
|
|
13
|
+
## Database
|
|
14
|
+
|
|
15
|
+
MongoDB with Mongoose.
|
|
16
|
+
|
|
17
|
+
| Variable | Meaning |
|
|
18
|
+
| ------------- | --------------------------------- |
|
|
19
|
+
| `MONGODB_URI` | Connection string of your MongoDB |
|
|
20
|
+
|
|
21
|
+
**Docker port.** The compose database is published on host port `27017`. If you already run MongoDB there, pick another port: `MONGO_PORT=27018 npm run docker:up`.
|
|
22
|
+
|
|
23
|
+
**Adding a user field.** Add it to the schema in `src/database/models/user.model.js` and to `create` in `src/modules/user/user.repository.js`. Mongoose adds the field to responses automatically.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on: [push, pull_request]
|
|
4
|
+
|
|
5
|
+
jobs:
|
|
6
|
+
test:
|
|
7
|
+
runs-on: ubuntu-latest
|
|
8
|
+
steps:
|
|
9
|
+
- uses: actions/checkout@v7
|
|
10
|
+
- uses: actions/setup-node@v7
|
|
11
|
+
with:
|
|
12
|
+
node-version: 24
|
|
13
|
+
cache: npm
|
|
14
|
+
- run: npm ci
|
|
15
|
+
- run: npm run lint
|
|
16
|
+
- run: npm run format:check
|
|
17
|
+
- run: npm test
|
|
18
|
+
|
|
19
|
+
docker:
|
|
20
|
+
needs: test
|
|
21
|
+
runs-on: ubuntu-latest
|
|
22
|
+
steps:
|
|
23
|
+
- uses: actions/checkout@v7
|
|
24
|
+
- uses: docker/setup-buildx-action@v4
|
|
25
|
+
- uses: docker/build-push-action@v7
|
|
26
|
+
with:
|
|
27
|
+
context: .
|
|
28
|
+
push: false
|
|
29
|
+
tags: app:ci
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
name: '{{projectName}}'
|
|
2
|
+
|
|
3
|
+
services:
|
|
4
|
+
app:
|
|
5
|
+
build: .
|
|
6
|
+
env_file: .env
|
|
7
|
+
environment:
|
|
8
|
+
NODE_ENV: production
|
|
9
|
+
PORT: 3000
|
|
10
|
+
MONGODB_URI: mongodb://db:27017/{{databaseName}}
|
|
11
|
+
depends_on:
|
|
12
|
+
db:
|
|
13
|
+
condition: service_healthy
|
|
14
|
+
ports:
|
|
15
|
+
- '${PORT:-3000}:3000'
|
|
16
|
+
|
|
17
|
+
db:
|
|
18
|
+
image: mongo:8
|
|
19
|
+
ports:
|
|
20
|
+
- '${MONGO_PORT:-27017}:27017'
|
|
21
|
+
volumes:
|
|
22
|
+
- mongodata:/data/db
|
|
23
|
+
healthcheck:
|
|
24
|
+
test: ['CMD', 'mongosh', '--quiet', '--eval', "db.adminCommand('ping').ok"]
|
|
25
|
+
interval: 5s
|
|
26
|
+
timeout: 5s
|
|
27
|
+
retries: 10
|
|
28
|
+
|
|
29
|
+
volumes:
|
|
30
|
+
mongodata:
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import { env } from '../config/env.js';
|
|
3
|
+
import { logger } from '../config/logger.js';
|
|
4
|
+
import { ApiError } from '../utils/ApiError.js';
|
|
5
|
+
|
|
6
|
+
const CONNECTED = 1;
|
|
7
|
+
const DUPLICATE_KEY = 11000;
|
|
8
|
+
|
|
9
|
+
export async function connectDatabase() {
|
|
10
|
+
await mongoose.connect(env.MONGODB_URI);
|
|
11
|
+
logger.info('Connected to MongoDB');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function disconnectDatabase() {
|
|
15
|
+
await mongoose.disconnect();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Async like the Postgres version, so the health route treats both the same way.
|
|
19
|
+
export async function isDatabaseConnected() {
|
|
20
|
+
return mongoose.connection.readyState === CONNECTED;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Turns driver errors into ApiErrors. Returns null for anything it does not know.
|
|
24
|
+
export function mapDatabaseError(err) {
|
|
25
|
+
if (err?.code === DUPLICATE_KEY) {
|
|
26
|
+
const duplicatedKeys = Object.keys(err.keyPattern ?? err.keyValue ?? {});
|
|
27
|
+
return duplicatedKeys.includes('email')
|
|
28
|
+
? ApiError.conflict('Email is already registered')
|
|
29
|
+
: ApiError.conflict('Resource already exists');
|
|
30
|
+
}
|
|
31
|
+
if (err instanceof mongoose.Error.CastError) {
|
|
32
|
+
return ApiError.badRequest('Invalid id');
|
|
33
|
+
}
|
|
34
|
+
if (err instanceof mongoose.Error.ValidationError) {
|
|
35
|
+
const errors = Object.values(err.errors).map((e) => ({ field: e.path, message: e.message }));
|
|
36
|
+
return ApiError.badRequest('Validation failed', errors);
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
|
|
3
|
+
const refreshTokenSchema = new mongoose.Schema(
|
|
4
|
+
{
|
|
5
|
+
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, index: true },
|
|
6
|
+
// SHA-256 of the token. The raw token is never stored.
|
|
7
|
+
tokenHash: { type: String, required: true, unique: true },
|
|
8
|
+
// TTL index: MongoDB removes the document once this date has passed.
|
|
9
|
+
expiresAt: { type: Date, required: true, expires: 0 },
|
|
10
|
+
revokedAt: { type: Date, default: null },
|
|
11
|
+
},
|
|
12
|
+
{ timestamps: { createdAt: true, updatedAt: false } },
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
export const RefreshToken = mongoose.model('RefreshToken', refreshTokenSchema);
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import { ROLE_VALUES, ROLES } from '../../constants/roles.js';
|
|
3
|
+
import { USER_RULES } from '../../constants/user.rules.js';
|
|
4
|
+
|
|
5
|
+
const userSchema = new mongoose.Schema(
|
|
6
|
+
{
|
|
7
|
+
name: {
|
|
8
|
+
type: String,
|
|
9
|
+
required: true,
|
|
10
|
+
trim: true,
|
|
11
|
+
minlength: USER_RULES.NAME.MIN,
|
|
12
|
+
maxlength: USER_RULES.NAME.MAX,
|
|
13
|
+
},
|
|
14
|
+
email: {
|
|
15
|
+
type: String,
|
|
16
|
+
required: true,
|
|
17
|
+
unique: true,
|
|
18
|
+
lowercase: true,
|
|
19
|
+
trim: true,
|
|
20
|
+
maxlength: USER_RULES.EMAIL.MAX,
|
|
21
|
+
},
|
|
22
|
+
// Select: false keeps the hash out of every query unless asked for.
|
|
23
|
+
password: { type: String, required: true, select: false },
|
|
24
|
+
role: { type: String, enum: ROLE_VALUES, default: ROLES.USER },
|
|
25
|
+
},
|
|
26
|
+
{ timestamps: true },
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
// The only shape a user ever leaves the database layer in.
|
|
30
|
+
function toPublic(_doc, ret) {
|
|
31
|
+
ret.id = ret._id.toString();
|
|
32
|
+
delete ret._id;
|
|
33
|
+
delete ret.__v;
|
|
34
|
+
delete ret.password;
|
|
35
|
+
return ret;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
userSchema.set('toJSON', { transform: toPublic });
|
|
39
|
+
userSchema.set('toObject', { transform: toPublic });
|
|
40
|
+
|
|
41
|
+
export const User = mongoose.model('User', userSchema);
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { RefreshToken } from '../../database/models/refreshToken.model.js';
|
|
2
|
+
import { User } from '../../database/models/user.model.js';
|
|
3
|
+
|
|
4
|
+
// The one place a Mongoose document becomes a plain public user.
|
|
5
|
+
const toPublicUser = (doc) => (doc ? doc.toJSON() : null);
|
|
6
|
+
|
|
7
|
+
export async function findById(id) {
|
|
8
|
+
return toPublicUser(await User.findById(id));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function findByEmail(email, { withPassword = false } = {}) {
|
|
12
|
+
const query = User.findOne({ email: email.trim().toLowerCase() });
|
|
13
|
+
if (withPassword) query.select('+password');
|
|
14
|
+
const doc = await query;
|
|
15
|
+
if (!doc) return null;
|
|
16
|
+
const user = toPublicUser(doc);
|
|
17
|
+
return withPassword ? { ...user, password: doc.password } : user;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function create({ name, email, password, role }) {
|
|
21
|
+
return toPublicUser(await User.create({ name, email, password, role }));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function findMany({ page, limit }) {
|
|
25
|
+
const [docs, total] = await Promise.all([
|
|
26
|
+
User.find()
|
|
27
|
+
.sort({ createdAt: -1, _id: -1 })
|
|
28
|
+
.skip((page - 1) * limit)
|
|
29
|
+
.limit(limit),
|
|
30
|
+
User.countDocuments(),
|
|
31
|
+
]);
|
|
32
|
+
return { users: docs.map(toPublicUser), total };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function updateRole(id, role) {
|
|
36
|
+
return toPublicUser(
|
|
37
|
+
await User.findByIdAndUpdate(id, { role }, { runValidators: true, returnDocument: 'after' }),
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function deleteById(id) {
|
|
42
|
+
const deleted = await User.findByIdAndDelete(id);
|
|
43
|
+
if (!deleted) return false;
|
|
44
|
+
await RefreshToken.deleteMany({ userId: id });
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function saveRefreshToken({ userId, tokenHash, expiresAt }) {
|
|
49
|
+
await RefreshToken.create({ userId, tokenHash, expiresAt });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function findRefreshToken(tokenHash) {
|
|
53
|
+
const doc = await RefreshToken.findOne({ tokenHash });
|
|
54
|
+
if (!doc) return null;
|
|
55
|
+
return { userId: doc.userId.toString(), expiresAt: doc.expiresAt, revokedAt: doc.revokedAt };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function revokeRefreshToken(tokenHash) {
|
|
59
|
+
const result = await RefreshToken.updateOne(
|
|
60
|
+
{ tokenHash, revokedAt: null },
|
|
61
|
+
{ revokedAt: new Date() },
|
|
62
|
+
);
|
|
63
|
+
return result.modifiedCount > 0;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function revokeAllRefreshTokens(userId) {
|
|
67
|
+
await RefreshToken.updateMany({ userId, revokedAt: null }, { revokedAt: new Date() });
|
|
68
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { MongoMemoryServer } from 'mongodb-memory-server';
|
|
2
|
+
|
|
3
|
+
let mongoServer;
|
|
4
|
+
|
|
5
|
+
// Starts one in-memory MongoDB for the whole test run, so no local MongoDB is needed.
|
|
6
|
+
export async function setup() {
|
|
7
|
+
mongoServer = await MongoMemoryServer.create();
|
|
8
|
+
process.env.MONGODB_URI = mongoServer.getUri('test');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function teardown() {
|
|
12
|
+
await mongoServer?.stop();
|
|
13
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import { afterAll, afterEach, beforeAll } from 'vitest';
|
|
3
|
+
import { connectDatabase, disconnectDatabase } from '../src/database/connection.js';
|
|
4
|
+
|
|
5
|
+
beforeAll(async () => {
|
|
6
|
+
await connectDatabase();
|
|
7
|
+
// Build the unique indexes before the first test so duplicate checks are reliable.
|
|
8
|
+
await Promise.all(Object.values(mongoose.models).map((model) => model.syncIndexes()));
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
afterEach(async () => {
|
|
12
|
+
await Promise.all(Object.values(mongoose.connection.collections).map((c) => c.deleteMany({})));
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
afterAll(async () => {
|
|
16
|
+
await disconnectDatabase();
|
|
17
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
## Quick start
|
|
2
|
+
|
|
3
|
+
```bash
|
|
4
|
+
cd {{projectName}}
|
|
5
|
+
cp .env.example .env
|
|
6
|
+
npm install
|
|
7
|
+
docker compose up -d --wait db
|
|
8
|
+
npm run db:deploy
|
|
9
|
+
npm run dev
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The API is on <http://localhost:3000>. `npm test` needs the same running server: it takes `DATABASE_URL` from the environment, else from `.env` (else `postgresql://postgres:postgres@localhost:5432/app`), and creates and migrates a separate `<database>_test` database for itself.
|
|
13
|
+
|
|
14
|
+
## Database
|
|
15
|
+
|
|
16
|
+
PostgreSQL with Prisma. The generated client lives in `src/generated/prisma` and is rebuilt by `npm install` and `npm run db:generate`.
|
|
17
|
+
|
|
18
|
+
| Variable | Meaning |
|
|
19
|
+
| -------------- | ---------------------------------- |
|
|
20
|
+
| `DATABASE_URL` | Connection string of your Postgres |
|
|
21
|
+
|
|
22
|
+
| Script | Does |
|
|
23
|
+
| --------------------- | ------------------------------------------ |
|
|
24
|
+
| `npm run db:migrate` | Create and apply a migration (development) |
|
|
25
|
+
| `npm run db:deploy` | Apply existing migrations |
|
|
26
|
+
| `npm run db:generate` | Regenerate the Prisma client |
|
|
27
|
+
| `npm run db:studio` | Open Prisma Studio |
|
|
28
|
+
|
|
29
|
+
**Docker port.** The compose database is published on host port `5432`. If you already run Postgres there, pick another port, for example `POSTGRES_PORT=5433`: set it when you run `docker compose up -d --wait db` or `npm run docker:up`, and put the same port in `DATABASE_URL` in `.env` (tests read it too). In Docker, the container applies migrations itself on start.
|
|
30
|
+
|
|
31
|
+
**Adding a user field.** Add the column to `model User` in `prisma/schema.prisma`, run `npm run db:migrate -- --name add_phone`, then add the field to `publicUserSelect` and to `create` in `src/modules/user/user.repository.js`.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on: [push, pull_request]
|
|
4
|
+
|
|
5
|
+
jobs:
|
|
6
|
+
test:
|
|
7
|
+
runs-on: ubuntu-latest
|
|
8
|
+
services:
|
|
9
|
+
postgres:
|
|
10
|
+
image: postgres:17-alpine
|
|
11
|
+
env:
|
|
12
|
+
POSTGRES_USER: postgres
|
|
13
|
+
POSTGRES_PASSWORD: postgres
|
|
14
|
+
POSTGRES_DB: app
|
|
15
|
+
ports:
|
|
16
|
+
- 5432:5432
|
|
17
|
+
options: >-
|
|
18
|
+
--health-cmd "pg_isready -U postgres"
|
|
19
|
+
--health-interval 5s
|
|
20
|
+
--health-timeout 5s
|
|
21
|
+
--health-retries 10
|
|
22
|
+
env:
|
|
23
|
+
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/app
|
|
24
|
+
steps:
|
|
25
|
+
- uses: actions/checkout@v7
|
|
26
|
+
- uses: actions/setup-node@v7
|
|
27
|
+
with:
|
|
28
|
+
node-version: 24
|
|
29
|
+
cache: npm
|
|
30
|
+
- run: npm ci
|
|
31
|
+
- run: npm run lint
|
|
32
|
+
- run: npm run format:check
|
|
33
|
+
- run: npm run db:deploy
|
|
34
|
+
- run: npm test
|
|
35
|
+
|
|
36
|
+
docker:
|
|
37
|
+
needs: test
|
|
38
|
+
runs-on: ubuntu-latest
|
|
39
|
+
steps:
|
|
40
|
+
- uses: actions/checkout@v7
|
|
41
|
+
- uses: docker/setup-buildx-action@v4
|
|
42
|
+
- uses: docker/build-push-action@v7
|
|
43
|
+
with:
|
|
44
|
+
context: .
|
|
45
|
+
push: false
|
|
46
|
+
tags: app:ci
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
name: '{{projectName}}'
|
|
2
|
+
|
|
3
|
+
services:
|
|
4
|
+
app:
|
|
5
|
+
build: .
|
|
6
|
+
env_file: .env
|
|
7
|
+
environment:
|
|
8
|
+
NODE_ENV: production
|
|
9
|
+
PORT: 3000
|
|
10
|
+
DATABASE_URL: postgresql://postgres:postgres@db:5432/{{databaseName}}
|
|
11
|
+
depends_on:
|
|
12
|
+
db:
|
|
13
|
+
condition: service_healthy
|
|
14
|
+
ports:
|
|
15
|
+
- '${PORT:-3000}:3000'
|
|
16
|
+
|
|
17
|
+
db:
|
|
18
|
+
image: postgres:17-alpine
|
|
19
|
+
environment:
|
|
20
|
+
POSTGRES_USER: postgres
|
|
21
|
+
POSTGRES_PASSWORD: postgres
|
|
22
|
+
POSTGRES_DB: '{{databaseName}}'
|
|
23
|
+
ports:
|
|
24
|
+
- '${POSTGRES_PORT:-5432}:5432'
|
|
25
|
+
volumes:
|
|
26
|
+
- pgdata:/var/lib/postgresql/data
|
|
27
|
+
healthcheck:
|
|
28
|
+
test: ['CMD-SHELL', 'pg_isready -U postgres']
|
|
29
|
+
interval: 5s
|
|
30
|
+
timeout: 5s
|
|
31
|
+
retries: 10
|
|
32
|
+
|
|
33
|
+
volumes:
|
|
34
|
+
pgdata:
|