Compare commits
187 Commits
34acea15a2
...
0.0.37
| Author | SHA1 | Date | |
|---|---|---|---|
| 0d2ffe0f54 | |||
|
991dc32ce4
|
|||
|
d6a72ace83
|
|||
|
7a0d5dc48c
|
|||
|
4ed4b6e5f4
|
|||
|
4499e20e77
|
|||
|
fbc1e55e5c
|
|||
|
653fc7d52f
|
|||
|
84881edb61
|
|||
|
c8b1b72694
|
|||
|
73cd1d794a
|
|||
|
28ac23d8f2
|
|||
|
71b7519a53
|
|||
|
28ee1a9d1e
|
|||
|
f327c6e06e
|
|||
|
799ff00f9c
|
|||
|
369e3f4b5c
|
|||
|
3788de2609
|
|||
|
0f9aafe418
|
|||
|
13b90e9ee6
|
|||
|
6e19a6217d
|
|||
|
34fd4e7304
|
|||
|
5e04012aa4
|
|||
|
e8f2928543
|
|||
|
91a3b2fabf
|
|||
|
964b9a03ef
|
|||
|
bf693645d4
|
|||
|
082b4826c2
|
|||
|
e68c3002d8
|
|||
|
30d2f4a644
|
|||
|
875a45f2b8
|
|||
|
6bf7afbe09
|
|||
|
5c94dbbff5
|
|||
|
cb44eb1fab
|
|||
|
df63d7947f
|
|||
|
01a5ff907c
|
|||
|
e22e3d8bc3
|
|||
|
efecd78355
|
|||
|
ed4246ba0e
|
|||
|
4acc228fe3
|
|||
|
42279b0592
|
|||
|
e417ab64d8
|
|||
|
93b11c3a35
|
|||
|
1ef2c4919e
|
|||
|
6ff8f74317
|
|||
|
bf70ca98f3
|
|||
|
52e5befd93
|
|||
|
a047b49073
|
|||
|
59b20578bb
|
|||
|
cdd6c6a72a
|
|||
|
1d16473d2d
|
|||
|
cd2bef9811
|
|||
|
62118b6d64
|
|||
|
8290b332fb
|
|||
|
61236719f4
|
|||
|
aa699d5009
|
|||
|
9a4f9cdf4c
|
|||
|
5532fc51a9
|
|||
|
99db648a36
|
|||
|
adcab6afcb
|
|||
|
8e40c0a06c
|
|||
|
db5e4858b8
|
|||
|
d800311ae7
|
|||
|
32fdde5d90
|
|||
|
2eacdaeece
|
|||
|
827bce6e1b
|
|||
|
50c74fdb71
|
|||
|
42f091489e
|
|||
|
995dd9a015
|
|||
|
5b0c9ba72d
|
|||
|
d745869cc0
|
|||
|
e6389d8b9b
|
|||
|
47f1bdf485
|
|||
|
bc96664b7c
|
|||
|
04ec6e2de3
|
|||
|
ba31f4b8be
|
|||
|
d5f9bc4d05
|
|||
|
ad9ffc89b5
|
|||
|
f482750d08
|
|||
|
7b77df0c4c
|
|||
|
8ee5d627aa
|
|||
|
775dd60b56
|
|||
|
b3365607c5
|
|||
|
96058995be
|
|||
|
1d43b78590
|
|||
|
243682758a
|
|||
|
695c4d84e8
|
|||
|
25908dd9d7
|
|||
|
34a28b8134
|
|||
|
7e1f9a1f33
|
|||
|
f0ba205a58
|
|||
|
1a717cd83e
|
|||
|
1e932d97c8
|
|||
|
d879de2a6b
|
|||
|
34e3eb04af
|
|||
|
ff5f88588e
|
|||
|
ac5c09b7da
|
|||
|
d1b42fe79f
|
|||
|
3d32c77bd1
|
|||
|
8e077810f5
|
|||
|
5e0621e37d
|
|||
|
e6f9f9b523
|
|||
|
1c5fdabca6
|
|||
|
7bbb4bb036
|
|||
|
159f87d07e
|
|||
|
244db86113
|
|||
|
00d9a4f734
|
|||
|
b7a3c12eff
|
|||
|
8e263d7ace
|
|||
|
641cbcfd47
|
|||
|
8af84d42e5
|
|||
|
d31a47f46c
|
|||
|
ddb8ad0948
|
|||
|
73cb0c23f5
|
|||
|
59738f5711
|
|||
|
f3ff19098b
|
|||
|
8bc852fa7d
|
|||
|
8e06b98695
|
|||
|
809255baa6
|
|||
|
21e80ca883
|
|||
|
cfb7c7e453
|
|||
|
82498e7714
|
|||
|
87a611459a
|
|||
|
0a09208766
|
|||
|
99ce364dc4
|
|||
|
2daa33f3ac
|
|||
|
2814c6820b
|
|||
|
d9cafe009d
|
|||
|
d011f15136
|
|||
|
ee398feeb9
|
|||
|
c2d9f8be5a
|
|||
|
5f69193b81
|
|||
|
2a13a433e1
|
|||
|
b094ae2c9a
|
|||
|
e48037a7d4
|
|||
|
ecfa12154d
|
|||
|
aa2611b68d
|
|||
|
0a7bbb96c0
|
|||
|
96c7061ace
|
|||
|
6b39d138de
|
|||
|
0d3571e859
|
|||
|
2a7172ddfe
|
|||
|
97ed5f1f43
|
|||
|
0e53dd8132
|
|||
|
06c9c1d896
|
|||
|
f29b50120f
|
|||
|
cb75c651b9
|
|||
|
c83db307ad
|
|||
|
45964e4f13
|
|||
|
0e3ff90e09
|
|||
|
8031b12940
|
|||
|
9073408f6d
|
|||
|
943ffe96d1
|
|||
|
6d07bbd9ad
|
|||
|
51b3d2c7c6
|
|||
|
32bfbd7adc
|
|||
|
dc72cefece
|
|||
|
27a78dd471
|
|||
|
8ca639058b
|
|||
|
39ba4965e0
|
|||
|
e3a0e36560
|
|||
|
68f58329e8
|
|||
|
5fba4c6643
|
|||
|
f105ce537f
|
|||
|
adb3866700
|
|||
|
d47c229178
|
|||
|
a6634bc939
|
|||
|
52870d9bf8
|
|||
|
5a35f3fef5
|
|||
|
3f0d476885
|
|||
|
9c06dbed5b
|
|||
|
add0b91fdd
|
|||
|
ef860f3bbe
|
|||
|
85e7839f21
|
|||
|
c76251bbe3
|
|||
|
5a53f486f6
|
|||
|
136c7acb47
|
|||
|
ae015ccd56
|
|||
|
b95dfb8cf3
|
|||
|
52454649f5
|
|||
|
31aa388c69
|
|||
|
0a9d37c9e8
|
|||
|
92d43edd7a
|
|||
|
4176b0be51
|
|||
|
63dd15ea83
|
|||
|
43e5920658
|
|||
|
7f5765aaaa
|
203
.drone.yml
203
.drone.yml
@@ -1,19 +1,214 @@
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: default
|
||||
name: Test Pipeline
|
||||
|
||||
workspace:
|
||||
path: /drone/src
|
||||
path: /drone/grow
|
||||
|
||||
steps:
|
||||
- name: Lint
|
||||
- name: yarn install
|
||||
image: node:latest
|
||||
commands:
|
||||
- yarn install
|
||||
- name: Code Style Checks
|
||||
image: node:latest
|
||||
commands:
|
||||
- yarn prettier
|
||||
- name: Lint
|
||||
image: node:latest
|
||||
commands:
|
||||
- yarn lint
|
||||
- name: Unit Tests
|
||||
image: node:latest
|
||||
commands:
|
||||
- yarn test
|
||||
- name: Send Test Status Notification
|
||||
image: plugins/webhook
|
||||
settings:
|
||||
urls: https://lab.mifi.dev/hooks/9p65zpagctgkmndo8nwwm4199r
|
||||
content_type: application/json
|
||||
template: |
|
||||
{
|
||||
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
|
||||
"text": "[{{ repo.name }} - Build # {{ build.number }}] Code Quality Checks {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
|
||||
"username":"DroneBot"
|
||||
}
|
||||
when:
|
||||
status:
|
||||
- success
|
||||
- failure
|
||||
- name: Build
|
||||
image: node:latest
|
||||
commands:
|
||||
- yarn build
|
||||
- name: Send Build Status Notifications
|
||||
image: plugins/webhook
|
||||
settings:
|
||||
urls: https://lab.mifi.dev/hooks/9p65zpagctgkmndo8nwwm4199r
|
||||
content_type: application/json
|
||||
template: |
|
||||
{
|
||||
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
|
||||
"text": "[{{ repo.name }} - Build # {{ build.number }}] Build package {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
|
||||
"username":"DroneBot"
|
||||
}
|
||||
when:
|
||||
status:
|
||||
- success
|
||||
- failure
|
||||
|
||||
trigger:
|
||||
branch:
|
||||
- main
|
||||
event:
|
||||
- push
|
||||
- pull_request
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: Publish Pipeline
|
||||
|
||||
workspace:
|
||||
path: /drone/grow
|
||||
|
||||
steps:
|
||||
- name: Build Package
|
||||
image: node:latest
|
||||
commands:
|
||||
- yarn install
|
||||
- yarn build
|
||||
- name: Publish NPM
|
||||
image: node:20-alpine
|
||||
failure: ignore
|
||||
commands:
|
||||
- yarn publish -t ${DRONE_TAG}
|
||||
volumes:
|
||||
- name: npmrc
|
||||
path: /drone/grow/.npmrc
|
||||
- name: Report NPM Publish Status
|
||||
image: plugins/webhook
|
||||
settings:
|
||||
urls: https://lab.mifi.dev/hooks/ccw34hdf7tgbjmzp96nptn938r
|
||||
content_type: application/json
|
||||
template: |
|
||||
{
|
||||
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
|
||||
"text": "[{{ repo.name }} - New npm package release {{tag}} from # {{ build.number }}] Deploy {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
|
||||
"username":"DroneBot"
|
||||
}
|
||||
when:
|
||||
status:
|
||||
- success
|
||||
- failure
|
||||
- name: Publish Image
|
||||
image: plugins/docker
|
||||
settings:
|
||||
auto_tag: true
|
||||
repo: git.mifi.dev/mifi/mifi/auth
|
||||
registry: git.mifi.dev
|
||||
debug: true
|
||||
ssh-agent-key:
|
||||
from_secret: reg_token
|
||||
username: <token>
|
||||
password:
|
||||
from_secret: reg_token
|
||||
secrets: [reg_token]
|
||||
- name: Report Image Publish Status
|
||||
image: plugins/webhook
|
||||
settings:
|
||||
urls: https://lab.mifi.dev/hooks/ccw34hdf7tgbjmzp96nptn938r
|
||||
content_type: application/json
|
||||
template: |
|
||||
{
|
||||
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
|
||||
"text": "[{{ repo.name }} - New docker image release {{tag}} from # {{ build.number }}] Deploy {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
|
||||
"username":"DroneBot"
|
||||
}
|
||||
when:
|
||||
status:
|
||||
- success
|
||||
- failure
|
||||
|
||||
volumes:
|
||||
- name: dockerconfig
|
||||
host:
|
||||
path: /volume1/docker/dockerconfig.json
|
||||
- name: dockersock
|
||||
host:
|
||||
path: /var/run/docker.sock
|
||||
- name: npmrc
|
||||
host:
|
||||
path: /volume1/docker/beethoven/labs-auth/.npmrc
|
||||
|
||||
depends_on:
|
||||
- Test Pipeline
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- tag
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: Deploy Pipeline
|
||||
|
||||
workspace:
|
||||
path: /drone/grow
|
||||
|
||||
steps:
|
||||
- name: Deploy Container
|
||||
image: docker
|
||||
privileged: true
|
||||
environment:
|
||||
CONTAINER_PREFIX: staging
|
||||
HOST: area51.mifi.dev
|
||||
ROUTE_PREFIX: /auth
|
||||
PORT: 9001
|
||||
commands:
|
||||
- docker compose -f docker-compose.staging.yml pull
|
||||
- docker compose -f docker-compose.staging.yml build --no-cache
|
||||
- docker compose -f docker-compose.staging.yml rm --stop
|
||||
- docker compose -f docker-compose.staging.yml up --wait
|
||||
volumes:
|
||||
- name: env-secrets
|
||||
path: /drone/grow/staging.env
|
||||
- name: dockersock
|
||||
path: /var/run/docker.sock
|
||||
- name: dockerconfig
|
||||
path: /drone/grow/.docker/config.json
|
||||
- name: Send Status Notifications
|
||||
image: plugins/webhook
|
||||
privileged: true
|
||||
settings:
|
||||
urls: https://lab.mifi.dev/hooks/ccw34hdf7tgbjmzp96nptn938r
|
||||
content_type: application/json
|
||||
template: |
|
||||
{
|
||||
"icon_url":"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/198/freezing-face_1f976.png",
|
||||
"text": "[{{ repo.name }} - Build # {{ build.number }}] Deploy {{ build.status }} {{#success build.status}}:tada:{{else}}:poop:{{/success}}",
|
||||
"username":"DroneBot"
|
||||
}
|
||||
when:
|
||||
status:
|
||||
- success
|
||||
- failure
|
||||
|
||||
volumes:
|
||||
- name: dockerconfig
|
||||
host:
|
||||
path: /volume1/docker/dockerconfig.json
|
||||
- name: dockersock
|
||||
host:
|
||||
path: /var/run/docker.sock
|
||||
- name: env-secrets
|
||||
host:
|
||||
path: /volume1/docker/beethoven/labs-auth/staging.env
|
||||
|
||||
depends_on:
|
||||
- Test Pipeline
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- promote
|
||||
target:
|
||||
- production
|
||||
29
.env.dev
Normal file
29
.env.dev
Normal file
@@ -0,0 +1,29 @@
|
||||
HOST=localhost
|
||||
PORT=9001
|
||||
|
||||
ROUTE_PREFIX=/auth
|
||||
|
||||
LOGIN_ROUTE=/login
|
||||
RESET_ROUTE=/reset
|
||||
|
||||
DB_ADMIN_USERNAME=root
|
||||
DB_ADMIN_PASSWORD=password
|
||||
DB_USERNAME=user
|
||||
DB_PASSWORD=password
|
||||
DB_NAME=auth
|
||||
|
||||
MONGO_INITDB_ROOT_USERNAME=$DB_ADMIN_USERNAME
|
||||
MONGO_INITDB_ROOT_PASSWORD=$DB_ADMIN_PASSWORD
|
||||
MONGO_INITDB_DATABASE=$DB_NAME
|
||||
|
||||
SESSION_KEY=shjhakjfhfjdshjksdhfdshfhfduyeyb73te4
|
||||
|
||||
JWT_AUDIENCE=Grow.io
|
||||
JWT_ISSUER=Grow Latch
|
||||
JWT_SECRET=Th!sIs a d3v3lopm3nt server SEcr¢T.
|
||||
|
||||
LOGIN_VALID_TIME=12H
|
||||
RESET_VALID_MINUTES=15
|
||||
DEFAULT_TOKEN_DAYS=1
|
||||
|
||||
CONTAINER_PREFIX=dev
|
||||
18
.eslintrc.js
18
.eslintrc.js
@@ -1,5 +1,19 @@
|
||||
/* eslint-env node */
|
||||
module.exports = {
|
||||
extends: [
|
||||
'semistandard'
|
||||
]
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:import/errors',
|
||||
'plugin:prettier/recommended',
|
||||
'prettier',
|
||||
],
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['@typescript-eslint'],
|
||||
settings: {
|
||||
'import/parsers': {
|
||||
'@typescript-eslint/parser': [".ts", ".tsx"],
|
||||
},
|
||||
'import/resolver': 'typescript',
|
||||
},
|
||||
root: true,
|
||||
};
|
||||
|
||||
7
.prettierrc.js
Normal file
7
.prettierrc.js
Normal file
@@ -0,0 +1,7 @@
|
||||
module.exports = {
|
||||
parser: 'typescript',
|
||||
printWidth: 120,
|
||||
trailingComma: 'all',
|
||||
tabWidth: 4,
|
||||
singleQuote: true,
|
||||
};
|
||||
18
Dockerfile
Normal file
18
Dockerfile
Normal file
@@ -0,0 +1,18 @@
|
||||
FROM node:20-alpine AS build
|
||||
WORKDIR /home/node/app
|
||||
COPY package*.json ./
|
||||
COPY tsconfig.json ./
|
||||
COPY lib ./lib
|
||||
RUN ls -a
|
||||
RUN yarn install
|
||||
RUN yarn build
|
||||
|
||||
## this is stage two , where the app actually runs
|
||||
FROM node:20-alpine AS containerize
|
||||
ENV NODE_ENV ${ENV:-production}
|
||||
WORKDIR /home/node/app
|
||||
COPY package*.json ./
|
||||
RUN yarn install --frozen-lockfile --production
|
||||
COPY --from=0 /home/node/app/dist .
|
||||
EXPOSE ${PORT}
|
||||
CMD ["node","server/index.js"]
|
||||
6
babel.config.js
Normal file
6
babel.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
presets: [
|
||||
['@babel/preset-env', { targets: { node: 'current' } }],
|
||||
'@babel/preset-typescript',
|
||||
],
|
||||
};
|
||||
41
docker-compose.dev.yml
Normal file
41
docker-compose.dev.yml
Normal file
@@ -0,0 +1,41 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
auth-service_mongo:
|
||||
env_file: .env.dev
|
||||
build:
|
||||
args:
|
||||
- CONTAINER_PREFIX=${CONTAINER_PREFIX}
|
||||
container_name: ${CONTAINER_PREFIX:-dev}-auth-service_mongo
|
||||
ports:
|
||||
- 27017:27017
|
||||
networks:
|
||||
- labs-net
|
||||
volumes:
|
||||
- /var/tmp/labs:/data/db
|
||||
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
|
||||
restart: unless-stopped
|
||||
image: mongo:latest
|
||||
auth-service:
|
||||
env_file: .env.dev
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
- HOST=${HOST}
|
||||
- PORT=${PORT}
|
||||
- ROUTE_PREFIX=${ROUTE_PREFIX}
|
||||
- CONTAINER_PREFIX=${CONTAINER_PREFIX}
|
||||
container_name: ${CONTAINER_PREFIX:-dev}-auth-service
|
||||
ports:
|
||||
- 9001:9001
|
||||
environment:
|
||||
- DB_HOST=${CONTAINER_PREFIX:-dev}-auth-service_mongo
|
||||
networks:
|
||||
- labs-net
|
||||
restart: unless-stopped
|
||||
image: node:20-alpine
|
||||
depends_on:
|
||||
- auth-service_mongo
|
||||
networks:
|
||||
labs-net:
|
||||
name: labs-net
|
||||
39
docker-compose.staging.yml
Normal file
39
docker-compose.staging.yml
Normal file
@@ -0,0 +1,39 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
auth-service_mongo:
|
||||
container_name: ${CONTAINER_PREFIX}-auth-service_mongo
|
||||
env_file:
|
||||
- staging.env
|
||||
networks:
|
||||
- docknet
|
||||
volumes:
|
||||
- '/volume1/docker/labs/auth/mongo:/data/db'
|
||||
# - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
|
||||
restart: unless-stopped
|
||||
image: mongo:latest
|
||||
auth-service:
|
||||
env_file:
|
||||
- staging.env
|
||||
build: .
|
||||
container_name: ${CONTAINER_PREFIX}-auth-service
|
||||
environment:
|
||||
- DB_HOST=${CONTAINER_PREFIX}-auth-service_mongo
|
||||
labels:
|
||||
- 'traefik.enable=true'
|
||||
- 'traefik.http.routers.grow.rule=Host(`${HOST}`) && Path(`${ROUTE_PREFIX}`)'
|
||||
- 'traefik.http.routers.grow.entrypoints=websecure'
|
||||
- 'traefik.http.routers.grow.tls=true'
|
||||
- 'traefik.http.routers.grow.tls.certresolver=letsencrypt'
|
||||
- 'traefik.http.routers.grow.service=grow-service'
|
||||
- 'traefik.http.services.grow-service.loadbalancer.server.port=${PORT}'
|
||||
networks:
|
||||
- docknet
|
||||
restart: unless-stopped
|
||||
image: node:20-alpine
|
||||
depends_on:
|
||||
- auth-service_mongo
|
||||
networks:
|
||||
docknet:
|
||||
name: docknet
|
||||
external: true
|
||||
39
docker-compose.staging_image.yml
Normal file
39
docker-compose.staging_image.yml
Normal file
@@ -0,0 +1,39 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
auth-service_mongo:
|
||||
container_name: ${CONTAINER_PREFIX}-auth-service_mongo
|
||||
env_file:
|
||||
- staging.env
|
||||
networks:
|
||||
- docknet
|
||||
volumes:
|
||||
- '/volume1/docker/labs/auth/mongo:/data/db'
|
||||
# - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
|
||||
restart: unless-stopped
|
||||
image: mongo:latest
|
||||
auth-service:
|
||||
env_file:
|
||||
- staging.env
|
||||
build: .
|
||||
container_name: ${CONTAINER_PREFIX}-auth-service
|
||||
environment:
|
||||
- DB_HOST=${CONTAINER_PREFIX}-auth-service_mongo
|
||||
labels:
|
||||
- 'traefik.enable=true'
|
||||
- 'traefik.http.routers.grow.rule=Host(`${HOST}`) && Path(`${ROUTE_PREFIX}`)'
|
||||
- 'traefik.http.routers.grow.entrypoints=websecure'
|
||||
- 'traefik.http.routers.grow.tls=true'
|
||||
- 'traefik.http.routers.grow.tls.certresolver=letsencrypt'
|
||||
- 'traefik.http.routers.grow.service=grow-service'
|
||||
- 'traefik.http.services.grow-service.loadbalancer.server.port=${PORT}'
|
||||
networks:
|
||||
- docknet
|
||||
restart: unless-stopped
|
||||
image: node:20-alpine
|
||||
depends_on:
|
||||
- auth-service_mongo
|
||||
networks:
|
||||
docknet:
|
||||
name: docknet
|
||||
external: true
|
||||
195
jest.config.ts
Normal file
195
jest.config.ts
Normal file
@@ -0,0 +1,195 @@
|
||||
/*
|
||||
* For a detailed explanation regarding each configuration property and type check, visit:
|
||||
* https://jestjs.io/docs/configuration
|
||||
*/
|
||||
|
||||
export default {
|
||||
// All imported modules in your tests should be mocked automatically
|
||||
// automock: false,
|
||||
|
||||
// Stop running tests after `n` failures
|
||||
// bail: 0,
|
||||
|
||||
// The directory where Jest should store its cached dependency information
|
||||
// cacheDirectory: "/private/var/folders/75/3cyx0pq133n7gk3ysqf0mj4r0000gn/T/jest_dx",
|
||||
|
||||
// Automatically clear mock calls, instances, contexts and results before every test
|
||||
clearMocks: true,
|
||||
|
||||
// Indicates whether the coverage information should be collected while executing the test
|
||||
collectCoverage: true,
|
||||
|
||||
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
||||
// collectCoverageFrom: undefined,
|
||||
|
||||
// The directory where Jest should output its coverage files
|
||||
coverageDirectory: "coverage",
|
||||
|
||||
// An array of regexp pattern strings used to skip coverage collection
|
||||
// coveragePathIgnorePatterns: [
|
||||
// "/node_modules/"
|
||||
// ],
|
||||
|
||||
// Indicates which provider should be used to instrument code for coverage
|
||||
// coverageProvider: "babel",
|
||||
|
||||
// A list of reporter names that Jest uses when writing coverage reports
|
||||
// coverageReporters: [
|
||||
// "json",
|
||||
// "text",
|
||||
// "lcov",
|
||||
// "clover"
|
||||
// ],
|
||||
|
||||
// An object that configures minimum threshold enforcement for coverage results
|
||||
// coverageThreshold: undefined,
|
||||
|
||||
// A path to a custom dependency extractor
|
||||
// dependencyExtractor: undefined,
|
||||
|
||||
// Make calling deprecated APIs throw helpful error messages
|
||||
// errorOnDeprecated: false,
|
||||
|
||||
// The default configuration for fake timers
|
||||
// fakeTimers: {
|
||||
// "enableGlobally": false
|
||||
// },
|
||||
|
||||
// Force coverage collection from ignored files using an array of glob patterns
|
||||
// forceCoverageMatch: [],
|
||||
|
||||
// A path to a module which exports an async function that is triggered once before all test suites
|
||||
// globalSetup: undefined,
|
||||
|
||||
// A path to a module which exports an async function that is triggered once after all test suites
|
||||
// globalTeardown: undefined,
|
||||
|
||||
// A set of global variables that need to be available in all test environments
|
||||
// globals: {},
|
||||
|
||||
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
||||
// maxWorkers: "50%",
|
||||
|
||||
// An array of directory names to be searched recursively up from the requiring module's location
|
||||
// moduleDirectories: [
|
||||
// "node_modules"
|
||||
// ],
|
||||
|
||||
// An array of file extensions your modules use
|
||||
// moduleFileExtensions: [
|
||||
// "js",
|
||||
// "mjs",
|
||||
// "cjs",
|
||||
// "jsx",
|
||||
// "ts",
|
||||
// "tsx",
|
||||
// "json",
|
||||
// "node"
|
||||
// ],
|
||||
|
||||
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
||||
// moduleNameMapper: {},
|
||||
|
||||
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
||||
// modulePathIgnorePatterns: [],
|
||||
|
||||
// Activates notifications for test results
|
||||
// notify: false,
|
||||
|
||||
// An enum that specifies notification mode. Requires { notify: true }
|
||||
// notifyMode: "failure-change",
|
||||
|
||||
// A preset that is used as a base for Jest's configuration
|
||||
// preset: undefined,
|
||||
|
||||
// Run tests from one or more projects
|
||||
// projects: undefined,
|
||||
|
||||
// Use this configuration option to add custom reporters to Jest
|
||||
// reporters: undefined,
|
||||
|
||||
// Automatically reset mock state before every test
|
||||
// resetMocks: false,
|
||||
|
||||
// Reset the module registry before running each individual test
|
||||
// resetModules: false,
|
||||
|
||||
// A path to a custom resolver
|
||||
// resolver: undefined,
|
||||
|
||||
// Automatically restore mock state and implementation before every test
|
||||
// restoreMocks: false,
|
||||
|
||||
// The root directory that Jest should scan for tests and modules within
|
||||
// rootDir: undefined,
|
||||
|
||||
// A list of paths to directories that Jest should use to search for files in
|
||||
// roots: [
|
||||
// "<rootDir>"
|
||||
// ],
|
||||
|
||||
// Allows you to use a custom runner instead of Jest's default test runner
|
||||
// runner: "jest-runner",
|
||||
|
||||
// The paths to modules that run some code to configure or set up the testing environment before each test
|
||||
// setupFiles: [],
|
||||
|
||||
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
||||
// setupFilesAfterEnv: [],
|
||||
|
||||
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
||||
// slowTestThreshold: 5,
|
||||
|
||||
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
||||
// snapshotSerializers: [],
|
||||
|
||||
// The test environment that will be used for testing
|
||||
// testEnvironment: "jest-environment-node",
|
||||
|
||||
// Options that will be passed to the testEnvironment
|
||||
// testEnvironmentOptions: {},
|
||||
|
||||
// Adds a location field to test results
|
||||
// testLocationInResults: false,
|
||||
|
||||
// The glob patterns Jest uses to detect test files
|
||||
// testMatch: [
|
||||
// "**/__tests__/**/*.[jt]s?(x)",
|
||||
// "**/?(*.)+(spec|test).[tj]s?(x)"
|
||||
// ],
|
||||
|
||||
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
||||
// testPathIgnorePatterns: [
|
||||
// "/node_modules/"
|
||||
// ],
|
||||
|
||||
// The regexp pattern or array of patterns that Jest uses to detect test files
|
||||
// testRegex: [],
|
||||
|
||||
// This option allows the use of a custom results processor
|
||||
// testResultsProcessor: undefined,
|
||||
|
||||
// This option allows use of a custom test runner
|
||||
// testRunner: "jest-circus/runner",
|
||||
|
||||
// A map from regular expressions to paths to transformers
|
||||
// transform: undefined,
|
||||
|
||||
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
||||
// transformIgnorePatterns: [
|
||||
// "/node_modules/",
|
||||
// "\\.pnp\\.[^\\/]+$"
|
||||
// ],
|
||||
|
||||
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
||||
// unmockedModulePathPatterns: undefined,
|
||||
|
||||
// Indicates whether each individual test should be reported during the run
|
||||
// verbose: undefined,
|
||||
|
||||
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
||||
// watchPathIgnorePatterns: [],
|
||||
|
||||
// Whether to use watchman for file crawling
|
||||
// watchman: true,
|
||||
};
|
||||
16
lib/auth.ts
16
lib/auth.ts
@@ -1,16 +0,0 @@
|
||||
import passport from 'koa-passport';
|
||||
|
||||
// import Users from 'grow-db/lib/models/users';
|
||||
// import { User } from 'grow-db/lib/schemas/user';
|
||||
|
||||
// passport.serializeUser((user: User, done) => { done(null, user._id); });
|
||||
|
||||
// passport.deserializeUser(async (id, done) => {
|
||||
// const user = await Users.findById(id);
|
||||
|
||||
// if (user) {
|
||||
// done(null, user);
|
||||
// }
|
||||
|
||||
// done('user not found', null);
|
||||
// });
|
||||
8
lib/constants/auth.ts
Normal file
8
lib/constants/auth.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export enum Status {
|
||||
ACTIVE,
|
||||
BLOCK_HARD,
|
||||
BLOCK_SOFT,
|
||||
DELETED,
|
||||
INACTIVE,
|
||||
UNVERIFIED,
|
||||
}
|
||||
5
lib/constants/db.ts
Normal file
5
lib/constants/db.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export const DB_HOST = process.env.DB_HOST || 'not_set';
|
||||
export const DB_PORT = process.env.DB_PORT || 27017;
|
||||
export const DB_USERNAME = process.env.DB_USERNAME || 'not_set';
|
||||
export const DB_PASSWORD = process.env.DB_PASSWORD || 'not_set';
|
||||
export const DB_NAME = process.env.DB_NAME || 'not_set';
|
||||
16
lib/constants/env.ts
Normal file
16
lib/constants/env.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
export const PACKAGE_NAME = '@mifi/auth';
|
||||
export const PORT = process.env.PORT || 9000;
|
||||
|
||||
export const SESSION_KEY = process.env.SESSION_KEY || 'secret-key';
|
||||
|
||||
export const JWT_AUDIENCE = process.env.JWT_AUDIENCE || 'mifi.dev';
|
||||
export const JWT_ISSUER = process.env.JWT_ISSUER || PACKAGE_NAME;
|
||||
export const JWT_SECRET = process.env.JWT_SECRET || 'secret';
|
||||
|
||||
export const LOGIN_VALID_TIME = process.env.LOGIN_VALID_TIME || '12H'; // ###D|H|M
|
||||
export const RESET_VALID_MINUTES = process.env.RESET_VALID_MINUTES || 24;
|
||||
export const DEFAULT_TOKEN_DAYS = process.env.DEFAULT_TOKEN_DAYS || 365;
|
||||
|
||||
export const ROUTE_PREFIX = process.env.ROUTE_PREFIX || '/auth';
|
||||
export const LOGIN_ROUTE = process.env.LOGIN_ROUTE || '/login';
|
||||
export const RESET_ROUTE = process.env.RESET_ROUTE || '/reset';
|
||||
12
lib/constants/errors.ts
Normal file
12
lib/constants/errors.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export enum ErrorCodes {
|
||||
RESET_REQUEST_DATA = 'RESET_REQUEST_DATA',
|
||||
}
|
||||
|
||||
export const ErrorMessages = {
|
||||
[ErrorCodes.RESET_REQUEST_DATA]: 'A valid username and password must be provided',
|
||||
};
|
||||
|
||||
export const getErrorBody = (code: ErrorCodes) => ({
|
||||
code,
|
||||
message: ErrorMessages[code],
|
||||
});
|
||||
@@ -1,227 +0,0 @@
|
||||
// // const errors = require('restify-errors');
|
||||
|
||||
// // const config = require('../config');
|
||||
|
||||
// // const handlePassportResponse = (req, res, next) => (err, user, info) => {
|
||||
// // if (err) {
|
||||
// // return next(err);
|
||||
// // }
|
||||
|
||||
// // const isVerifiedUser = user &&
|
||||
// // user.isRegistrationVerified();
|
||||
|
||||
// // if (user && isVerifiedUser) {
|
||||
// // return res.send({ ...user.toAuthJSON() });
|
||||
// // } else if (user && !isVerifiedUser){
|
||||
// // return res.send({
|
||||
// // registrationSuccess: true,
|
||||
// // nextSteps: 'Check your email for our confirmation email, you will not be able to login without confirming.'
|
||||
// // });
|
||||
// // }
|
||||
|
||||
// // return res.send(400, info);
|
||||
// // };
|
||||
|
||||
// // module.exports = function (server, auth) {
|
||||
// // const { passport } = auth;
|
||||
|
||||
// // /* Local Auth */
|
||||
// // server.post('/auth', (req, res, next) => {
|
||||
// // const { body: { username = null, password = null } = {} } = req;
|
||||
|
||||
// // if (!username || !password) {
|
||||
// // let errors = {};
|
||||
|
||||
// // if (!username) {
|
||||
// // errors.username = 'is required';
|
||||
// // }
|
||||
|
||||
// // if (!password) {
|
||||
// // errors.password = 'is required';
|
||||
// // }
|
||||
|
||||
// // return res.send(422, { errors });
|
||||
// // }
|
||||
|
||||
// // const callback = handlePassportResponse(req, res, next);
|
||||
// // return passport.authenticate('local', { session: false }.then(callback)(req, res, next);
|
||||
// // });
|
||||
|
||||
// // /**
|
||||
// // * SERVICES
|
||||
// // */
|
||||
|
||||
// // /* Google */
|
||||
// // server.get(
|
||||
// // '/auth/google',
|
||||
// // passport.authenticate('google', { scope: 'profile email', session: false }),
|
||||
// // );
|
||||
|
||||
// // server.get(
|
||||
// // '/auth/google/callback',
|
||||
// // (req, res, next) => {
|
||||
// // const callback = handlePassportResponse(req, res, next);
|
||||
// // return passport.authenticate(
|
||||
// // 'google',
|
||||
// // { failureRedirect: '/login' },
|
||||
// // callback,
|
||||
// // )(req, res, next);
|
||||
// // },
|
||||
// // );
|
||||
|
||||
// // /* Facebook */
|
||||
// // server.get(
|
||||
// // '/auth/facebook/login',
|
||||
// // passport.authenticate('facebook', {
|
||||
// // scope: ['email', 'public_profile'],
|
||||
// // session: false,
|
||||
// // }),
|
||||
// // );
|
||||
|
||||
// // server.get(
|
||||
// // '/auth/facebook/loggedin',
|
||||
// // (req, res, next) => {
|
||||
// // const callback = handlePassportResponse(req, res, next);
|
||||
// // return passport.authenticate(
|
||||
// // 'facebook',
|
||||
// // { failureRedirect: '/login' },
|
||||
// // callback,
|
||||
// // )(req, res, next);
|
||||
// // }
|
||||
// // );
|
||||
|
||||
// // server.get(
|
||||
// // '/auth/facebook/link',
|
||||
// // auth.secure,
|
||||
// // (req, res, next) => {
|
||||
// // req.user.record.setLinkCheckBit((err, linkCheckBit) => {
|
||||
// // passport.authenticate('facebookLink', {
|
||||
// // scope: ['email', 'public_profile'],
|
||||
// // session: false,
|
||||
// // state: linkCheckbit,
|
||||
// // })(req, res, next);
|
||||
// // });
|
||||
// // },
|
||||
// // );
|
||||
// //
|
||||
// // server.get(
|
||||
// // '/auth/facebook/linked',
|
||||
// // (req, res, next) => {
|
||||
// // const linkCheckBit = req.query.state;
|
||||
// //
|
||||
// // return passport.authenticate(
|
||||
// // 'facebook',
|
||||
// // { failureRedirect: '/profile' },
|
||||
// // (err, profile) => {
|
||||
// // if (err) {
|
||||
// // return next(err);
|
||||
// // }
|
||||
// //
|
||||
// // User.linkFacebookProfile(linkCheckBit, profile, (err, user) => {
|
||||
// // if (err) {
|
||||
// // return next(err);
|
||||
// // }
|
||||
// //
|
||||
// // if (!user) {
|
||||
// // return next(err, false, 'Linking the account to Facebook was unsuccessful, please try again.');
|
||||
// // }
|
||||
// //
|
||||
// // res.send({
|
||||
// // success: true,
|
||||
// // info: 'Facerbook account successfully linked',
|
||||
// // });
|
||||
// // });
|
||||
// // },
|
||||
// // )(req, res, next);
|
||||
// // }
|
||||
// // );
|
||||
// };
|
||||
|
||||
// import Koa from 'koa';
|
||||
// import Router from 'koa-router';
|
||||
// import { StatusCodes } from 'http-status-codes';
|
||||
|
||||
// import Users from 'grow-db/lib/models/users';
|
||||
|
||||
// const handlePassportResponse = (ctx: Koa.Context) => (err, user, info) => {
|
||||
// if (err) {
|
||||
// return next(err);
|
||||
// }
|
||||
|
||||
// const isVerifiedUser = user &&
|
||||
// user.isRegistrationVerified();
|
||||
|
||||
// if (user && isVerifiedUser) {
|
||||
// return res.send({ ...user.toAuthJSON() });
|
||||
// } else if (user && !isVerifiedUser){
|
||||
// return res.send({
|
||||
// registrationSuccess: true,
|
||||
// nextSteps: 'Check your email for our confirmation email, you will not be able to login without confirming.'
|
||||
// });
|
||||
// }
|
||||
|
||||
// return res.send(400, info);
|
||||
// };
|
||||
|
||||
// const routerOpts: Router.IRouterOptions = {
|
||||
// prefix: '/auth',
|
||||
// };
|
||||
|
||||
// const router: Router = new Router(routerOpts);
|
||||
|
||||
// router.get('/', async (ctx: Koa.Context) => {
|
||||
// const data = await Customers.find({}).exec();
|
||||
// ctx.body = { data };
|
||||
// });
|
||||
|
||||
// router.get('/:customer_id', async (ctx: Koa.Context) => {
|
||||
// const data = await Customers.findById(ctx.params.customer_id).populate('person').exec();
|
||||
// if (!data) {
|
||||
// ctx.throw(StatusCodes.NOT_FOUND);
|
||||
// }
|
||||
// ctx.body = { data };
|
||||
// });
|
||||
|
||||
// router.delete('/:customer_id', async (ctx: Koa.Context) => {
|
||||
// const data = await Customers.findByIdAndDelete(ctx.params.customer_id).exec();
|
||||
// if (!data) {
|
||||
// ctx.throw(StatusCodes.NOT_FOUND);
|
||||
// }
|
||||
// ctx.body = { success: true, data };
|
||||
// });
|
||||
|
||||
// router.post('/', async (ctx: Koa.Context) => {
|
||||
// const data = await Customers.create(ctx.body);
|
||||
// data.save();
|
||||
// ctx.body = { success: true, data };
|
||||
// });
|
||||
|
||||
// router.post('/', async (ctx: Koa.Context) => {
|
||||
// const { body: { username = null, password = null } = {} } = ctx;
|
||||
|
||||
// if (!username || !password) {
|
||||
// let errors = {};
|
||||
|
||||
// if (!username) {
|
||||
// errors.username = 'is required';
|
||||
// }
|
||||
|
||||
// if (!password) {
|
||||
// errors.password = 'is required';
|
||||
// }
|
||||
|
||||
// ctx.status = StatusCodes.UNPROCESSABLE_ENTITY;
|
||||
// ctx.throw(422, { errors });
|
||||
// }
|
||||
|
||||
// const callback = handlePassportResponse(req, res, next);
|
||||
// return passport.authenticate('local', { session: false }, callback)(req, res, next);
|
||||
// });
|
||||
|
||||
// router.patch('/:customer_id', async (ctx: Koa.Context) => {
|
||||
// const data = await Customers.findByIdAndUpdate(ctx.params.customer_id);
|
||||
// if (!data) {
|
||||
// ctx.throw(StatusCodes.NOT_FOUND);
|
||||
// }
|
||||
// ctx.body = { success: true, data };
|
||||
// });
|
||||
@@ -1,11 +0,0 @@
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
const DB_USER = process.env.DB_USER || 'test';
|
||||
const DB_PASS = process.env.DB_PASSWORD || 'test';
|
||||
const DB_HOST = process.env.DB_HOST || 'mongodb';
|
||||
const DB_PORT = process.env.DB_PORT || 27017;
|
||||
const DB_NAME = process.env.DB_NAME || 'auth';
|
||||
|
||||
export const connection = mongoose.connect(
|
||||
`${DB_USER}:${DB_PASS}@${DB_HOST}:${DB_PORT}/${DB_NAME}`
|
||||
);
|
||||
5
lib/db/index.ts
Normal file
5
lib/db/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
import { DB_HOST, DB_NAME, DB_PASSWORD, DB_PORT, DB_USERNAME } from '../constants/db';
|
||||
|
||||
export const connection = mongoose.connect(`mongodb://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}`);
|
||||
146
lib/db/schema/auth.ts
Normal file
146
lib/db/schema/auth.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { JwtPayload } from 'jsonwebtoken';
|
||||
import { InferSchemaType, Model, Schema, StringSchemaDefinition, Types } from 'mongoose';
|
||||
|
||||
import { Strategy } from './strategy';
|
||||
import { STRATEGIES } from '../../constants/strategies';
|
||||
import { TokenProps, verify as verifyJwt } from '../../utils/jwt';
|
||||
import { encrypt, verify as verifyPassword } from '../../utils/password';
|
||||
import { generateLoginToken, generateResetToken } from '../../utils/tokens';
|
||||
import { getPasswordResetPath } from '../../utils/links';
|
||||
import { Status } from '../../constants/auth';
|
||||
|
||||
export type Auth = {
|
||||
is2FA?: boolean;
|
||||
record: StringSchemaDefinition;
|
||||
username: string;
|
||||
};
|
||||
|
||||
export type AuthPrivate = Auth & {
|
||||
status: Status;
|
||||
strategies: Types.ArraySubdocument<Strategy>;
|
||||
};
|
||||
|
||||
export interface AuthMethods {
|
||||
authenticate(password: string): boolean;
|
||||
getAuthStrategy(method?: STRATEGIES): Strategy | false;
|
||||
getResetLink(route: string): Promise<string | undefined>;
|
||||
getResetToken(): Promise<string | undefined>;
|
||||
getToken(props?: Omit<TokenProps, 'sub'> | void): string;
|
||||
isActive(): boolean;
|
||||
setPassword(password: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
export interface AuthModel extends Model<AuthPrivate, void, AuthMethods> {
|
||||
authenticate(username: string, password?: string): string | false;
|
||||
findByUsername(username: string): Promise<AuthModel & AuthPrivate>;
|
||||
isUsernameAvailable(username: string): Promise<boolean>;
|
||||
findUserForReset(strategy: STRATEGIES, token: string): Promise<Strategy | undefined>;
|
||||
resetPassword(token: string, password: string): Promise<string | false>;
|
||||
}
|
||||
|
||||
export const AuthSchema = new Schema<AuthPrivate, AuthModel, AuthMethods>(
|
||||
{
|
||||
is2FA: { type: Boolean, default: false },
|
||||
record: { type: Types.ObjectId },
|
||||
strategies: { type: Array<Strategy>, required: true },
|
||||
status: { type: Number, enum: Object.values(Status), default: Status.UNVERIFIED },
|
||||
username: { type: String, required: true, unique: true },
|
||||
},
|
||||
{
|
||||
minimize: true,
|
||||
timestamps: true,
|
||||
},
|
||||
);
|
||||
|
||||
AuthSchema.methods = {
|
||||
authenticate(password: string) {
|
||||
const strategy = this.getAuthStrategy(STRATEGIES.LOCAL);
|
||||
return !!strategy && verifyPassword(password, strategy.key);
|
||||
},
|
||||
|
||||
getAuthStrategy(method = STRATEGIES.LOCAL) {
|
||||
return this.strategies.filter((strategy: Strategy) => strategy.method === method).pop() || false;
|
||||
},
|
||||
|
||||
getToken(props = {}) {
|
||||
return generateLoginToken(this._id, this.status);
|
||||
},
|
||||
|
||||
async getResetLink(route) {
|
||||
const token = await this.getResetToken();
|
||||
if (token) {
|
||||
const resetUrl = getPasswordResetPath(token);
|
||||
console.log('[sendPasswordReset] resetUrl:', resetUrl);
|
||||
return resetUrl;
|
||||
}
|
||||
},
|
||||
|
||||
async getResetToken() {
|
||||
const { key, token } = generateResetToken(this._id);
|
||||
this.resetCheckBit = key;
|
||||
await this.save().catch(() => undefined);
|
||||
return token;
|
||||
},
|
||||
|
||||
isActive() {
|
||||
return this.status === Status.ACTIVE;
|
||||
},
|
||||
|
||||
async setPassword(password) {
|
||||
const key = encrypt(password);
|
||||
const hasLocalStrategy = !!this.getAuthStrategy(STRATEGIES.LOCAL);
|
||||
const strategy = {
|
||||
key,
|
||||
method: STRATEGIES.LOCAL,
|
||||
resetToken: undefined,
|
||||
};
|
||||
|
||||
if (hasLocalStrategy) {
|
||||
await this.model('User')
|
||||
.findOneAndUpdate(
|
||||
{ _id: this._id, 'strategies.method': STRATEGIES.LOCAL },
|
||||
{ $set: { 'strategies.$': strategy } },
|
||||
{ upsert: true },
|
||||
)
|
||||
.catch();
|
||||
return true;
|
||||
}
|
||||
this.credentials.push(strategy);
|
||||
await this.save().catch(() => false);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
AuthSchema.statics = {
|
||||
authenticate: async function (username, password) {
|
||||
const auth = await this.findByUsername(username);
|
||||
if (auth && auth.authenticate(password)) {
|
||||
return auth.record;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
async findByUsername(username) {
|
||||
return this.findOne({ username });
|
||||
},
|
||||
|
||||
async isUsernameAvailable(username) {
|
||||
return !this.findByUsername(username);
|
||||
},
|
||||
|
||||
async resetPassword(token, password) {
|
||||
const decoded = verifyJwt(token);
|
||||
const { sub, key } = decoded as JwtPayload;
|
||||
const auth = await this.findOne({
|
||||
_id: sub,
|
||||
'strategies.resetToken': key,
|
||||
}).catch();
|
||||
if (auth) {
|
||||
await auth.setPassword(password).catch();
|
||||
return auth.getToken();
|
||||
}
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
export type AuthSchema = InferSchemaType<typeof AuthSchema>;
|
||||
25
lib/db/schema/strategy.ts
Normal file
25
lib/db/schema/strategy.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { InferSchemaType, Schema, Types } from 'mongoose';
|
||||
import { STRATEGIES } from '../../constants/strategies';
|
||||
|
||||
export const Strategy = new Schema(
|
||||
{
|
||||
method: {
|
||||
type: Number,
|
||||
enum: Object.values(STRATEGIES),
|
||||
index: true,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
externalId: { type: String, index: true },
|
||||
key: { type: String, required: true, trim: true },
|
||||
profile: {},
|
||||
resetToken: { type: String },
|
||||
forceReset: { type: Boolean },
|
||||
},
|
||||
{
|
||||
minimize: true,
|
||||
timestamps: true,
|
||||
},
|
||||
);
|
||||
|
||||
export type Strategy = InferSchemaType<typeof Strategy>;
|
||||
@@ -1,14 +0,0 @@
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import { Context, Next } from 'koa';
|
||||
|
||||
export const errorHandler = async (ctx: Context, next: Next) => {
|
||||
try {
|
||||
await next();
|
||||
} catch (error: any) {
|
||||
ctx.status =
|
||||
error.statusCode || error.status || StatusCodes.INTERNAL_SERVER_ERROR;
|
||||
error.status = ctx.status;
|
||||
ctx.body = { error };
|
||||
ctx.app.emit('error', error, ctx);
|
||||
}
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
import { Next } from 'koa';
|
||||
import { KoaContext } from '../types/KoaContext';
|
||||
|
||||
export const performanceLogger = async (ctx: KoaContext, next: Next) => {
|
||||
await next();
|
||||
const rt = ctx.response.get('X-Response-Time');
|
||||
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
|
||||
};
|
||||
|
||||
export const perfromanceTimer = async (ctx: KoaContext, next: Next) => {
|
||||
const start = Date.now();
|
||||
await next();
|
||||
const ms = Date.now() - start;
|
||||
ctx.set('X-Response-Time', `${ms}ms`);
|
||||
};
|
||||
@@ -1,152 +0,0 @@
|
||||
import { JwtPayload } from 'jsonwebtoken';
|
||||
import {
|
||||
InferSchemaType,
|
||||
Model,
|
||||
Schema,
|
||||
StringSchemaDefinition,
|
||||
Types,
|
||||
} from 'mongoose';
|
||||
|
||||
import { Strategy } from './strategy';
|
||||
import { STRATEGIES } from '../constants/strategies';
|
||||
import { TokenProps, sign, verify as verifyJwt } from '../utils/jwt';
|
||||
import { encrypt, verify as verifyPassword } from '../utils/password';
|
||||
import { generateResetToken } from '../utils/tokens';
|
||||
|
||||
export type Auth = {
|
||||
is2FA?: boolean;
|
||||
record: StringSchemaDefinition;
|
||||
username: string;
|
||||
};
|
||||
|
||||
export type AuthPrivate = Auth & {
|
||||
strategies: Types.ArraySubdocument<Strategy>;
|
||||
};
|
||||
|
||||
export interface AuthMethods {
|
||||
authenticate(password: string): boolean;
|
||||
getAuthStrategy(method?: STRATEGIES): Strategy | false;
|
||||
getResetLink(route: string): Promise<string | undefined>;
|
||||
getResetToken(): Promise<string | undefined>;
|
||||
getToken(props?: Omit<TokenProps, 'sub'>): string;
|
||||
setPassword(password: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
export interface AuthModel extends Model<AuthPrivate, {}, AuthMethods> {
|
||||
authenticate(password: any): boolean;
|
||||
findByUsername(username: string): Promise<AuthModel & AuthPrivate>;
|
||||
isUsernameAvailable(username: string): Promise<boolean>;
|
||||
findUserForReset(
|
||||
strategy: STRATEGIES,
|
||||
token: string
|
||||
): Promise<Strategy | undefined>;
|
||||
resetPassword(token: string, password: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
export const AuthSchema = new Schema<AuthPrivate, AuthModel, AuthMethods>(
|
||||
{
|
||||
is2FA: { type: Boolean, default: false },
|
||||
record: { type: Types.ObjectId },
|
||||
strategies: { type: Types.ArraySubdocument<Strategy>, required: true },
|
||||
username: { type: String, required: true, unique: true },
|
||||
},
|
||||
{
|
||||
minimize: true,
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
AuthSchema.methods = {
|
||||
authenticate: function (password: string) {
|
||||
const strategy = this.getAuthStrategy(STRATEGIES.LOCAL);
|
||||
return !!strategy && verifyPassword(password, strategy.key);
|
||||
},
|
||||
|
||||
getAuthStrategy: function (method = STRATEGIES.LOCAL) {
|
||||
return (
|
||||
this.strategies
|
||||
.filter((strategy: Strategy) => strategy.method === method)
|
||||
.pop() || false
|
||||
);
|
||||
},
|
||||
|
||||
getToken: function (props = {}) {
|
||||
return sign({
|
||||
sub: this._id,
|
||||
...props,
|
||||
});
|
||||
},
|
||||
|
||||
getResetLink: async function (route) {
|
||||
const resetToken = await this.getResetToken();
|
||||
if (resetToken) {
|
||||
let resetRoute = route;
|
||||
resetRoute = resetRoute.replace(':user_id', this._id);
|
||||
resetRoute = resetRoute.replace(':reset_token?', resetToken);
|
||||
const resetUrl = `${process.env.URL}${resetRoute}`;
|
||||
console.log('[sendPasswordReset] resetUrl:', resetUrl);
|
||||
return resetUrl;
|
||||
}
|
||||
},
|
||||
|
||||
getResetToken: async function () {
|
||||
const { key, token } = generateResetToken(this._id);
|
||||
this.resetCheckBit = key;
|
||||
await this.save().catch(() => undefined);
|
||||
return token;
|
||||
},
|
||||
|
||||
setPassword: async function (password) {
|
||||
const key = encrypt(password);
|
||||
const hasLocalStrategy = !!this.getAuthStrategy(STRATEGIES.LOCAL);
|
||||
const strategy = {
|
||||
key,
|
||||
method: STRATEGIES.LOCAL,
|
||||
resetToken: undefined,
|
||||
};
|
||||
|
||||
if (hasLocalStrategy) {
|
||||
await this.model('User')
|
||||
.findOneAndUpdate(
|
||||
{ _id: this._id, 'strategies.method': STRATEGIES.LOCAL },
|
||||
{ $set: { 'strategies.$': strategy } },
|
||||
{ upsert: true },
|
||||
)
|
||||
.catch();
|
||||
return true;
|
||||
}
|
||||
this.credentials.push(strategy);
|
||||
await this.save().catch(() => false);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
AuthSchema.statics = {
|
||||
// authenticateAndGetRecordLocator: async function (username, password) {
|
||||
// const auth = await this.findByUserName(username);
|
||||
// if (auth && auth.authenticate(password)) {
|
||||
// return auth?.record;
|
||||
// }
|
||||
// return false;
|
||||
// },
|
||||
|
||||
findByUsername: async function (username) {
|
||||
return this.findOne({ username });
|
||||
},
|
||||
|
||||
isUsernameAvailable: async function (username) {
|
||||
return !this.findByUsername(username);
|
||||
},
|
||||
|
||||
resetPassword: async function (token, password) {
|
||||
const decoded = verifyJwt(token);
|
||||
const { sub, key } = decoded as JwtPayload;
|
||||
const auth = await this.findOne({
|
||||
_id: sub,
|
||||
'strategies.resetToken': key,
|
||||
}).catch();
|
||||
return !!auth && auth.setPassword(password);
|
||||
}
|
||||
};
|
||||
|
||||
export type AuthSchema = InferSchemaType<typeof AuthSchema>;
|
||||
@@ -1,25 +0,0 @@
|
||||
import { InferSchemaType, Schema, Types } from 'mongoose';
|
||||
import { STRATEGIES } from '../constants/strategies';
|
||||
|
||||
export const Strategy = new Schema(
|
||||
{
|
||||
method: {
|
||||
type: Number,
|
||||
enum: Object.values(STRATEGIES),
|
||||
index: true,
|
||||
required: true,
|
||||
unique: true
|
||||
},
|
||||
externalId: { type: String, index: true },
|
||||
key: { type: String, required: true, trim: true },
|
||||
profile: {},
|
||||
resetToken: { type: String },
|
||||
forceReset: { type: Boolean }
|
||||
},
|
||||
{
|
||||
minimize: true,
|
||||
timestamps: true
|
||||
}
|
||||
);
|
||||
|
||||
export type Strategy = InferSchemaType<typeof Strategy>;
|
||||
@@ -1,12 +0,0 @@
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
import app from './app';
|
||||
import { connection } from './database/database.connection';
|
||||
dotenv.config();
|
||||
|
||||
const PORT: number = Number(process.env.PORT) || 9000;
|
||||
|
||||
connection.then(
|
||||
() => app.listen(PORT),
|
||||
(err) => console.error('ERROR!', err),
|
||||
);
|
||||
@@ -1,26 +1,31 @@
|
||||
import Koa from 'koa';
|
||||
import bodyParser from 'koa-bodyparser';
|
||||
import bodyparser from 'koa-bodyparser';
|
||||
import cookie from 'koa-cookie';
|
||||
import passport from 'koa-passport';
|
||||
import session from 'koa-session';
|
||||
|
||||
import passport from './passport';
|
||||
import { performanceLogger, perfromanceTimer } from './middleware/performance';
|
||||
import { errorHandler } from './middleware/errorHandler';
|
||||
import { authRouter } from './controllers/auth';
|
||||
import { SESSION_KEY } from '../constants/env';
|
||||
|
||||
const app: Koa = new Koa();
|
||||
|
||||
app.use(errorHandler);
|
||||
app.use(perfromanceTimer);
|
||||
app.use(performanceLogger);
|
||||
app.use(bodyParser());
|
||||
app.use(bodyparser());
|
||||
app.use(cookie());
|
||||
|
||||
app.keys = [process.env.SESSION_KEYS as string];
|
||||
app.keys = [SESSION_KEY];
|
||||
app.use(session({}, app));
|
||||
|
||||
app.use(passport.initialize());
|
||||
app.use(passport.session());
|
||||
|
||||
app.use(authRouter.routes());
|
||||
app.use(authRouter.allowedMethods());
|
||||
|
||||
// Application error logging.
|
||||
app.on('error', console.error);
|
||||
|
||||
58
lib/server/controllers/auth.ts
Normal file
58
lib/server/controllers/auth.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import Koa from 'koa';
|
||||
import Router from 'koa-router';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
|
||||
import { ROUTE_PREFIX as prefix, RESET_ROUTE } from '../../constants/env';
|
||||
import Auth from '../../db/model/auth';
|
||||
import { sign } from '../../utils/jwt';
|
||||
import passport from '../passport';
|
||||
import { ErrorCodes, getErrorBody } from '../../constants/errors';
|
||||
import { authenticated } from '../middleware/authenication';
|
||||
|
||||
const routerOpts: Router.IRouterOptions = { prefix };
|
||||
const router: Router = new Router(routerOpts);
|
||||
|
||||
router.get('/info', (ctx) => {
|
||||
ctx.body = {
|
||||
service: process.env.SERVICE_NAME,
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/', async (ctx) => {
|
||||
const data = (await Auth.create(ctx.body)).save();
|
||||
ctx.body = { success: true, data: { ...data, strategies: undefined } };
|
||||
});
|
||||
|
||||
router.post('/login', async (ctx, next) => {
|
||||
return passport.authenticate('local', (err, user) => {
|
||||
if (user === false) {
|
||||
ctx.body = { token: null };
|
||||
ctx.throw(StatusCodes.UNAUTHORIZED);
|
||||
}
|
||||
ctx.body = { token: sign(user) };
|
||||
return ctx.login(user);
|
||||
})(ctx, next);
|
||||
});
|
||||
|
||||
router.post(process.env.RESET_ROUTE || RESET_ROUTE, async (ctx, next) => {
|
||||
const { token = null, password = null } = ctx.request.body as { token?: string; password?: string };
|
||||
if (token && password) {
|
||||
const loginToken = await Auth.resetPassword(token, password).catch();
|
||||
ctx.body({ token: loginToken });
|
||||
next();
|
||||
}
|
||||
ctx.body = { success: false, ...getErrorBody(ErrorCodes.RESET_REQUEST_DATA) };
|
||||
});
|
||||
|
||||
router.patch('/:record', authenticated(), (ctx: Koa.Context) => {
|
||||
if (ctx.user !== ctx.param.record) {
|
||||
ctx.throw(StatusCodes.UNAUTHORIZED);
|
||||
}
|
||||
const data = Auth.findOneAndUpdate({ record: ctx.params.record });
|
||||
if (!data) {
|
||||
ctx.throw(StatusCodes.NOT_FOUND);
|
||||
}
|
||||
ctx.body = { success: true, data };
|
||||
});
|
||||
|
||||
export { router as authRouter };
|
||||
11
lib/server/index.ts
Normal file
11
lib/server/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import app from './app';
|
||||
import { connection } from '../db';
|
||||
import { PORT } from '../constants/env';
|
||||
|
||||
connection.then(
|
||||
() => {
|
||||
app.listen(PORT);
|
||||
console.log('LISTENING', process.env);
|
||||
},
|
||||
(err) => console.error('SERVER ERROR!', { err, env: process.env }),
|
||||
);
|
||||
12
lib/server/middleware/authenication.ts
Normal file
12
lib/server/middleware/authenication.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Middleware } from 'koa';
|
||||
import { LOGIN_ROUTE } from '../../constants/env';
|
||||
|
||||
export const authenticated = (): Middleware => {
|
||||
return (ctx, next) => {
|
||||
if (ctx.isAuthenticated()) {
|
||||
return next();
|
||||
} else {
|
||||
ctx.redirect(process.env.LOGIN_ROUTE || LOGIN_ROUTE);
|
||||
}
|
||||
};
|
||||
};
|
||||
13
lib/server/middleware/errorHandler.ts
Normal file
13
lib/server/middleware/errorHandler.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import { Context, Next } from 'koa';
|
||||
|
||||
export const errorHandler = async (ctx: Context, next: Next) => {
|
||||
try {
|
||||
await next();
|
||||
} catch (error: any) {
|
||||
ctx.status = error.statusCode || error.status || StatusCodes.INTERNAL_SERVER_ERROR;
|
||||
error.status = ctx.status;
|
||||
ctx.body = { error };
|
||||
ctx.app.emit('error', error, ctx);
|
||||
}
|
||||
};
|
||||
14
lib/server/middleware/performance.ts
Normal file
14
lib/server/middleware/performance.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Context, Next } from 'koa';
|
||||
|
||||
export const performanceLogger = async (ctx: Context, next: Next) => {
|
||||
await next();
|
||||
const rt = ctx.response.get('X-Response-Time');
|
||||
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
|
||||
};
|
||||
|
||||
export const perfromanceTimer = async (ctx: Context, next: Next) => {
|
||||
const start = Date.now();
|
||||
await next();
|
||||
const ms = Date.now() - start;
|
||||
ctx.set('X-Response-Time', `${ms}ms`);
|
||||
};
|
||||
23
lib/server/passport/index.ts
Normal file
23
lib/server/passport/index.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import passport from 'koa-passport';
|
||||
|
||||
import Auth from '../../db/model/auth';
|
||||
import { Auth as AuthRecord } from '../../db/schema/auth';
|
||||
import LocalStrategy from './strategies/local';
|
||||
import JwtStrategy from './strategies/jwt';
|
||||
|
||||
passport.serializeUser((user, done) => done(null, (user as AuthRecord).record));
|
||||
|
||||
passport.deserializeUser(async (id, done) => {
|
||||
const user = await Auth.findOne({ record: id });
|
||||
|
||||
if (user) {
|
||||
done(null, user);
|
||||
}
|
||||
|
||||
done('user not found', null);
|
||||
});
|
||||
|
||||
passport.use(LocalStrategy);
|
||||
passport.use(JwtStrategy);
|
||||
|
||||
export default passport;
|
||||
22
lib/server/passport/strategies/jwt.ts
Normal file
22
lib/server/passport/strategies/jwt.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
// eslint-disable-next-line import/named
|
||||
import { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';
|
||||
|
||||
import Auth from '../../../db/model/auth';
|
||||
import { JWT_SECRET } from '../../../constants/env';
|
||||
|
||||
const opts = {
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: JWT_SECRET,
|
||||
issuer: process.env.JWT_ISSUER,
|
||||
audience: process.env.JWT_AUDIENCE,
|
||||
};
|
||||
|
||||
export default new JwtStrategy(opts, async (jwt_payload, done) => {
|
||||
const auth = await Auth.findOne({ record: jwt_payload.sub }).catch();
|
||||
|
||||
if (auth) {
|
||||
return done(null, auth);
|
||||
}
|
||||
|
||||
return done(null, false);
|
||||
});
|
||||
17
lib/server/passport/strategies/local.ts
Normal file
17
lib/server/passport/strategies/local.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
// eslint-disable-next-line import/named
|
||||
import { Strategy as LocalStrategy } from 'passport-local';
|
||||
|
||||
import Auth from '../../../db/model/auth';
|
||||
|
||||
export default new LocalStrategy(async (username: string, password: string, done: any) => {
|
||||
const user = await Auth.findOne({
|
||||
where: {
|
||||
username,
|
||||
},
|
||||
}).catch();
|
||||
if (user && user.authenticate(password)) {
|
||||
done(null, user);
|
||||
} else {
|
||||
done(null, false);
|
||||
}
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import passport from 'koa-passport';
|
||||
import { Strategy } from 'passport-local';
|
||||
|
||||
import Auth from '../model/auth';
|
||||
|
||||
export const localStrategy = passport.use(
|
||||
new Strategy(async (username, password, done) => {
|
||||
const user = await Auth.findOne({
|
||||
where: {
|
||||
username,
|
||||
}
|
||||
}).catch();
|
||||
if (user && user.authenticate(password)) {
|
||||
done(null, user);
|
||||
} else {
|
||||
done(null, false);
|
||||
}
|
||||
})
|
||||
);
|
||||
@@ -1,15 +1,12 @@
|
||||
import Auth from '../model/auth';
|
||||
import { AuthModel, AuthPrivate } from '../schema/auth';
|
||||
import Auth from '../db/model/auth';
|
||||
import { AuthModel, AuthPrivate } from '../db/schema/auth';
|
||||
import { sign } from './jwt';
|
||||
|
||||
export const getAuthenticationBundle = async (
|
||||
username: string,
|
||||
password: string,
|
||||
) => {
|
||||
export const getAuthenticationBundle = async (username: string, password: string) => {
|
||||
const auth = await Auth.findByUsername(username).catch();
|
||||
const isAuthenticated = !!auth && (auth as AuthModel).authenticate(password);
|
||||
const record = isAuthenticated ? (auth as AuthPrivate).record : null;
|
||||
const token = isAuthenticated ? (auth as AuthModel).getToken() : sign();
|
||||
const isAuthenticated = !!auth && (<AuthModel>auth).authenticate(password);
|
||||
const record = isAuthenticated ? <string>(<AuthPrivate>auth).record : null;
|
||||
const token = sign(record || undefined);
|
||||
return {
|
||||
record,
|
||||
token,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import jwt, { JwtPayload } from 'jsonwebtoken';
|
||||
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { JWT_AUDIENCE, JWT_ISSUER, JWT_SECRET } from '../constants/env';
|
||||
export interface TokenProps {
|
||||
aud?: string;
|
||||
exp?: number | Date;
|
||||
@@ -13,28 +13,23 @@ export type SignProps = string | TokenProps | void;
|
||||
export const sign = (props: SignProps) => {
|
||||
const today = new Date();
|
||||
const { sub = null, ...rest }: TokenProps =
|
||||
typeof props === 'string' || typeof props === 'undefined'
|
||||
? { sub: props || null }
|
||||
: props;
|
||||
let exp = rest.exp;
|
||||
typeof props === 'string' || typeof props === 'undefined' ? { sub: props || null } : props;
|
||||
let { exp } = rest;
|
||||
if (!exp) {
|
||||
exp = new Date(today);
|
||||
exp.setDate(
|
||||
today.getDate() + parseInt(process.env.JWT_DAYS_VALID as string),
|
||||
);
|
||||
exp.setDate(today.getDate() + parseInt(process.env.JWT_DAYS_VALID as string));
|
||||
exp = exp.getTime() / 1000;
|
||||
}
|
||||
return jwt.sign(
|
||||
{
|
||||
exp,
|
||||
sub,
|
||||
aud: rest.aud || process.env.JWT_AUDIENCE,
|
||||
aud: rest.aud || JWT_AUDIENCE,
|
||||
iat: today.getTime(),
|
||||
iss: rest.iss || process.env.JWT_ISSUER,
|
||||
iss: rest.iss || JWT_ISSUER,
|
||||
},
|
||||
process.env.JWT_SECRET || 'secret',
|
||||
JWT_SECRET,
|
||||
);
|
||||
};
|
||||
|
||||
export const verify = (token: string) =>
|
||||
jwt.verify(token, process.env.JWT_SECRET || 'secret');
|
||||
export const verify = (token: string) => jwt.verify(token, JWT_SECRET);
|
||||
|
||||
3
lib/utils/links.ts
Normal file
3
lib/utils/links.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { RESET_ROUTE, ROUTE_PREFIX } from '../constants/env';
|
||||
|
||||
export const getPasswordResetPath = (token: string) => `${ROUTE_PREFIX}${RESET_ROUTE}?t=${token}`;
|
||||
@@ -1,13 +1,34 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
import { sign } from './jwt';
|
||||
import { LOGIN_VALID_TIME, RESET_VALID_MINUTES } from '../constants/env';
|
||||
import { Status } from '../constants/auth';
|
||||
|
||||
const parseLoginValid = () => {
|
||||
const [number, unit] = process.env.LOGIN_VALID_TIME || LOGIN_VALID_TIME;
|
||||
return [
|
||||
unit === 'd' ? parseInt(number) : 1,
|
||||
unit === 'h' ? parseInt(number) : (unit === 'm' && 1) || 24,
|
||||
unit === 'm' ? parseInt(number) : 60,
|
||||
];
|
||||
};
|
||||
|
||||
export const generateLoginToken = (sub: string, status: Status) => {
|
||||
const [days, hours, mins] = parseLoginValid();
|
||||
return sign({
|
||||
sub,
|
||||
status,
|
||||
exp: Date.now() + days * hours * mins * 60 * 1000,
|
||||
});
|
||||
};
|
||||
|
||||
export const generateResetToken = (sub: string) => {
|
||||
const hoursValid = <number>(process.env.RESET_VALID_HOURS || RESET_VALID_MINUTES);
|
||||
const key = crypto.randomBytes(16).toString('hex');
|
||||
const token = sign({
|
||||
sub,
|
||||
key,
|
||||
exp: Date.now() + 24 * 60 * 60 * 1000,
|
||||
exp: Date.now() + hoursValid * 60 * 60 * 1000,
|
||||
});
|
||||
return { key, token };
|
||||
};
|
||||
|
||||
12
mongo-init.js
Normal file
12
mongo-init.js
Normal file
@@ -0,0 +1,12 @@
|
||||
/* eslint-disable no-undef */
|
||||
db = db.getSiblingDB(process.env.DB_NAME);
|
||||
db.createUser({
|
||||
user: process.env.DB_USERNAME,
|
||||
pwd: process.env.DB_PASSWORD,
|
||||
roles: [
|
||||
{
|
||||
role: 'readWrite',
|
||||
db: process.env.DB_NAME,
|
||||
},
|
||||
],
|
||||
});
|
||||
39
package.json
39
package.json
@@ -1,19 +1,26 @@
|
||||
{
|
||||
"name": "@mifi/auth",
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.37",
|
||||
"author": "mifi (Mike Fitzpatrick)",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"lint": "tslint --project tsconfig.json --format stylish",
|
||||
"prettier:fix": "prettier-eslint --write '**/*.ts'",
|
||||
"serve": "ts-node src/server.ts",
|
||||
"start": "nodemon"
|
||||
"build:production": "tsc -p .",
|
||||
"format": "prettier:fix && lint:fix",
|
||||
"lint": "eslint --ext .ts,.tsx lib/",
|
||||
"lint:fix": "eslint --fix --ext .ts,.tsx lib/",
|
||||
"prettier": "prettier --check 'lib/**/*.ts'",
|
||||
"prettier:fix": "prettier --write 'lib/**/*.ts'",
|
||||
"serve": "node dist/lib/server/index.js",
|
||||
"start": "nodemon",
|
||||
"test": "jest --passWithNoTests"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.21.8",
|
||||
"@babel/preset-env": "^7.21.5",
|
||||
"@babel/preset-typescript": "^7.21.5",
|
||||
"@tsconfig/node16": "^1.0.3",
|
||||
"@types/dotenv": "^8.2.0",
|
||||
"@types/http-status-codes": "^1.2.0",
|
||||
"@types/jest": "^29.5.1",
|
||||
"@types/jsonwebtoken": "^9.0.1",
|
||||
"@types/koa": "^2.13.5",
|
||||
"@types/koa-bodyparser": "^4.3.10",
|
||||
@@ -22,7 +29,6 @@
|
||||
"@types/koa-router": "^7.4.4",
|
||||
"@types/koa-session": "^5.10.6",
|
||||
"@types/luxon": "^3.2.0",
|
||||
"@types/mongoose": "^5.11.97",
|
||||
"@types/node": "^18.14.0",
|
||||
"@types/passport": "^1.0.12",
|
||||
"@types/passport-facebook": "^2.1.11",
|
||||
@@ -30,21 +36,23 @@
|
||||
"@types/passport-google-oauth": "^1.0.42",
|
||||
"@types/passport-jwt": "^3.0.8",
|
||||
"@types/passport-local": "^1.0.35",
|
||||
"eslint": "^8.13.0",
|
||||
"eslint-config-semistandard": "latest",
|
||||
"eslint-config-standard": "^17.0.0",
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.59.2",
|
||||
"@typescript-eslint/parser": "^5.59.2",
|
||||
"babel-jest": "^29.5.0",
|
||||
"eslint": "^8.39.0",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
"eslint-import-resolver-typescript": "^3.5.5",
|
||||
"eslint-plugin-import": "^2.27.5",
|
||||
"eslint-plugin-n": "^15.0.0",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"eslint-plugin-promise": "^6.0.0",
|
||||
"jest": "^29.4.2",
|
||||
"jest": "^29.5.0",
|
||||
"nodemon": "^2.0.20",
|
||||
"prettier": "^2.8.4",
|
||||
"prettier-eslint": "^15.0.1",
|
||||
"prettier-eslint-cli": "^7.1.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"ts-node": "^10.9.1",
|
||||
"tslint": "^6.1.3",
|
||||
"tslint-config-airbnb": "^5.11.2",
|
||||
"typescript": "^4.9.5"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -64,6 +72,7 @@
|
||||
"passport-facebook": "^3.0.0",
|
||||
"passport-fido2-webauthn": "^0.1.0",
|
||||
"passport-google-oauth": "^2.0.0",
|
||||
"passport-http-bearer": "^1.0.1",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"passport-local": "^1.0.0"
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"emitDecoratorMetadata": true,
|
||||
"noImplicitAny": true,
|
||||
"outDir": "./dist/",
|
||||
"rootDirs": ["src", "../"],
|
||||
"rootDirs": ["lib"],
|
||||
"sourceMap": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"extends": "tslint-config-airbnb",
|
||||
"rules": {
|
||||
"import-name": false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user