Initial commit
continuous-integration/drone/push Build is passing Details

main
Filip Borum Poulsen 3 years ago
commit f9d88506f7

@ -0,0 +1,81 @@
kind: pipeline
type: docker
name: backend
volumes:
- name: dockersock
host:
path: /var/run/docker.sock
steps:
- name: build
image: docker:dind
volumes:
- name: dockersock
path: "/var/run/docker.sock" # Mandatory
commands:
- cd server
- docker build . -t merit/backend:$DRONE_COMMIT_SHA
- docker tag merit/backend:$DRONE_COMMIT_SHA 10.0.1.16:5000/merit/backend:latest
- docker push 10.0.1.16:5000/merit/backend:latest
---
kind: pipeline
type: docker
name: frontend
volumes:
- name: dockersock
host:
path: /var/run/docker.sock
steps:
- name: build
image: docker:dind
volumes:
- name: dockersock
path: "/var/run/docker.sock" # Mandatory
commands:
- cd client
- docker build . -t merit/frontend:$DRONE_COMMIT_SHA
- docker tag merit/frontend:$DRONE_COMMIT_SHA 10.0.1.16:5000/merit/frontend:latest
- docker push 10.0.1.16:5000/merit/frontend:latest
---
kind: pipeline
type: exec
name: deploy
platform:
os: linux
arch: amd64
clone:
disable: true
steps:
- name: deploy test
commands:
- cd /srv/merit-test
- docker pull 10.0.1.16:5000/merit/backend:latest
- docker pull 10.0.1.16:5000/merit/frontend:latest
- docker compose down
- docker compose up -d
when:
branch:
- main
- name: deploy production
commands:
- cd /srv/merit
- docker pull 10.0.1.16:5000/merit/backend:latest
- docker pull 10.0.1.16:5000/merit/frontend:latest
- docker compose down
- docker compose up -d
when:
ref:
- refs/tags/*
depends_on:
- backend
- frontend

1
.gitignore vendored

@ -0,0 +1 @@
node_modules

@ -0,0 +1,6 @@
FROM nginx:1.23.4-alpine
WORKDIR /var/www/html
COPY ./index.html ./index.html
COPY ./nginx.conf /etc/nginx/conf.d/default.conf

@ -0,0 +1 @@
Hello, World!

@ -0,0 +1,8 @@
server {
listen 80;
root /var/www/html;
gzip on;
gzip_static on;
}

5
server/.gitignore vendored

@ -0,0 +1,5 @@
node_modules
.env
dist
__generated__
*.pem

@ -0,0 +1,58 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Build & Launch Project",
"program": "${workspaceFolder}\\src\\index.ts",
"preLaunchTask": "npm: build",
"sourceMaps": true,
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
]
},
{
"name": "Debug",
"type": "node",
"request": "launch",
"runtimeExecutable": "node",
"runtimeArgs": ["--nolazy", "-r", "ts-node/register/transpile-only"],
"args": ["src/index.ts"],
"cwd": "${workspaceRoot}",
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": ["<node_internals>/**", "node_modules/**"]
},
{
"name": "Dev",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev"],
"cwd": "${workspaceRoot}",
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": ["<node_internals>/**", "node_modules/**"]
},
{
"name": "Migrations",
"type": "node",
"request": "launch",
"runtimeExecutable": "node",
"runtimeArgs": ["--nolazy", "-r", "ts-node/register/transpile-only"],
"args": ["src/migrations/index.ts"],
"cwd": "${workspaceRoot}",
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": ["<node_internals>/**", "node_modules/**"]
}
]
}

@ -0,0 +1,8 @@
FROM node:lts-alpine
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
CMD ["npm", "start"]

@ -0,0 +1,158 @@
<mxfile host="65bd71144e">
<diagram id="R2lEEEUBdFMjLlhIrx00" name="Page-1">
<mxGraphModel dx="1059" dy="437" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0" extFonts="Permanent Marker^https://fonts.googleapis.com/css?family=Permanent+Marker">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-1" value="" style="edgeStyle=entityRelationEdgeStyle;endArrow=ERzeroToMany;startArrow=ERone;endFill=1;startFill=0;" parent="1" source="C-vyLk0tnHw3VtMMgP7b-24" target="C-vyLk0tnHw3VtMMgP7b-6" edge="1">
<mxGeometry width="100" height="100" relative="1" as="geometry">
<mxPoint x="340" y="720" as="sourcePoint"/>
<mxPoint x="440" y="620" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-2" value="Bookings" style="shape=table;startSize=30;container=1;collapsible=1;childLayout=tableLayout;fixedRows=1;rowLines=0;fontStyle=1;align=center;resizeLast=1;" parent="1" vertex="1">
<mxGeometry x="450" y="120" width="250" height="190" as="geometry"/>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-3" value="" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=1;" parent="C-vyLk0tnHw3VtMMgP7b-2" vertex="1">
<mxGeometry y="30" width="250" height="30" as="geometry"/>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-4" value="PK" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;fontStyle=1;" parent="C-vyLk0tnHw3VtMMgP7b-3" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-5" value="booking_id serial" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;fontStyle=1;" parent="C-vyLk0tnHw3VtMMgP7b-3" vertex="1">
<mxGeometry x="30" width="220" height="30" as="geometry">
<mxRectangle width="220" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-6" value="" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-2" vertex="1">
<mxGeometry y="60" width="250" height="30" as="geometry"/>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-7" value="FK" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="C-vyLk0tnHw3VtMMgP7b-6" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-8" value="trainer_id int" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="C-vyLk0tnHw3VtMMgP7b-6" vertex="1">
<mxGeometry x="30" width="220" height="30" as="geometry">
<mxRectangle width="220" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-9" value="" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-2" vertex="1">
<mxGeometry y="90" width="250" height="30" as="geometry"/>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-10" value="FK" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="C-vyLk0tnHw3VtMMgP7b-9" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-11" value="user_id int" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="C-vyLk0tnHw3VtMMgP7b-9" vertex="1">
<mxGeometry x="30" width="220" height="30" as="geometry">
<mxRectangle width="220" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-10" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-2" vertex="1">
<mxGeometry y="120" width="250" height="30" as="geometry"/>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-11" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="VXEZj9PDGR0_IzT7xE4M-10" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-12" value="time timestamp" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="VXEZj9PDGR0_IzT7xE4M-10" vertex="1">
<mxGeometry x="30" width="220" height="30" as="geometry">
<mxRectangle width="220" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-15" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-2" vertex="1">
<mxGeometry y="150" width="250" height="30" as="geometry"/>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-16" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="VXEZj9PDGR0_IzT7xE4M-15" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-17" value="duration interval" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="VXEZj9PDGR0_IzT7xE4M-15" vertex="1">
<mxGeometry x="30" width="220" height="30" as="geometry">
<mxRectangle width="220" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-23" value="User" style="shape=table;startSize=30;container=1;collapsible=1;childLayout=tableLayout;fixedRows=1;rowLines=0;fontStyle=1;align=center;resizeLast=1;" parent="1" vertex="1">
<mxGeometry x="110" y="120" width="270" height="190" as="geometry"/>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-24" value="" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=1;" parent="C-vyLk0tnHw3VtMMgP7b-23" vertex="1">
<mxGeometry y="30" width="270" height="30" as="geometry"/>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-25" value="PK" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;fontStyle=1;" parent="C-vyLk0tnHw3VtMMgP7b-24" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-26" value="user_id serial" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;fontStyle=1;" parent="C-vyLk0tnHw3VtMMgP7b-24" vertex="1">
<mxGeometry x="30" width="240" height="30" as="geometry">
<mxRectangle width="240" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-27" value="" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-23" vertex="1">
<mxGeometry y="60" width="270" height="30" as="geometry"/>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-28" value="" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="C-vyLk0tnHw3VtMMgP7b-27" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="C-vyLk0tnHw3VtMMgP7b-29" value="name text" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="C-vyLk0tnHw3VtMMgP7b-27" vertex="1">
<mxGeometry x="30" width="240" height="30" as="geometry">
<mxRectangle width="240" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-1" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-23" vertex="1">
<mxGeometry y="90" width="270" height="30" as="geometry"/>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-2" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="VXEZj9PDGR0_IzT7xE4M-1" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-3" value="email text" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="VXEZj9PDGR0_IzT7xE4M-1" vertex="1">
<mxGeometry x="30" width="240" height="30" as="geometry">
<mxRectangle width="240" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-4" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-23" vertex="1">
<mxGeometry y="120" width="270" height="30" as="geometry"/>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-5" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="VXEZj9PDGR0_IzT7xE4M-4" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-6" value="password_hash text" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="VXEZj9PDGR0_IzT7xE4M-4" vertex="1">
<mxGeometry x="30" width="240" height="30" as="geometry">
<mxRectangle width="240" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-7" style="shape=partialRectangle;collapsible=0;dropTarget=0;pointerEvents=0;fillColor=none;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;top=0;left=0;right=0;bottom=0;" parent="C-vyLk0tnHw3VtMMgP7b-23" vertex="1">
<mxGeometry y="150" width="270" height="30" as="geometry"/>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-8" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;" parent="VXEZj9PDGR0_IzT7xE4M-7" vertex="1">
<mxGeometry width="30" height="30" as="geometry">
<mxRectangle width="30" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-9" value="user_type UserType" style="shape=partialRectangle;overflow=hidden;connectable=0;fillColor=none;top=0;left=0;bottom=0;right=0;align=left;spacingLeft=6;" parent="VXEZj9PDGR0_IzT7xE4M-7" vertex="1">
<mxGeometry x="30" width="240" height="30" as="geometry">
<mxRectangle width="240" height="30" as="alternateBounds"/>
</mxGeometry>
</mxCell>
<mxCell id="VXEZj9PDGR0_IzT7xE4M-14" value="" style="edgeStyle=entityRelationEdgeStyle;endArrow=ERzeroToMany;startArrow=ERone;endFill=1;startFill=0;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" parent="1" source="C-vyLk0tnHw3VtMMgP7b-24" target="C-vyLk0tnHw3VtMMgP7b-9" edge="1">
<mxGeometry width="100" height="100" relative="1" as="geometry">
<mxPoint x="440" y="390" as="sourcePoint"/>
<mxPoint x="510" y="420" as="targetPoint"/>
</mxGeometry>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

@ -0,0 +1,8 @@
PORT=8080
PGUSER=dbuser
PGHOST=database.server.com
PGPASSWORD=secretpassword
PGDATABASE=mydb
PGPORT=5432
PUBLIC_KEY_LOCATION=/data/cert/public.pem
PRIVATE_KEY_LOCATION=/data/cert/private.pem

@ -0,0 +1 @@
npx @databases/pg-schema-cli --database postgres://user:superdupermegasecretpassword123456!@localhost:5432/merit --directory src/__generated__

File diff suppressed because it is too large Load Diff

@ -0,0 +1,37 @@
{
"name": "merit-opgave",
"version": "1.0.0",
"description": "",
"main": "src/index.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc",
"start": "node dist/index.js",
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\"",
"migrate": "ts-node src/migrations/index.ts",
"populate": "ts-node src/migrations/populate.ts"
},
"author": "fbp",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.0",
"cookie-parser": "^1.4.6",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"joi": "^17.9.1",
"jsonwebtoken": "^9.0.0",
"pg": "^8.10.0"
},
"devDependencies": {
"@types/bcrypt": "^5.0.0",
"@types/cookie-parser": "^1.4.3",
"@types/express": "^4.17.17",
"@types/jsonwebtoken": "^9.0.1",
"@types/node": "^18.15.11",
"@types/pg": "^8.6.6",
"concurrently": "^8.0.1",
"nodemon": "^2.0.22",
"ts-node": "^10.9.1",
"typescript": "^5.0.4"
}
}

@ -0,0 +1,3 @@
import { Client } from 'pg';
export const client = new Client();
client.connect();

@ -0,0 +1,22 @@
import fs from "fs";
import dotenv from "dotenv";
dotenv.config();
if (process.env.PORT === undefined) {
throw ("The environment variable 'PORT' has not been set");
}
if (process.env.PUBLIC_KEY_LOCATION === undefined) {
throw ("The environment variable 'PUBLIC_KEY_LOCATION' has not been set");
}
if (process.env.PRIVATE_KEY_LOCATION === undefined) {
throw ("The environment variable 'PRIVATE_KEY_LOCATION' has not been set");
}
export const public_key: string = fs.readFileSync(process.env.PUBLIC_KEY_LOCATION, {encoding: "utf-8"});
export const private_key: string = fs.readFileSync(process.env.PRIVATE_KEY_LOCATION, {encoding: "utf-8"});
export const port: string = process.env.PORT;

@ -0,0 +1,34 @@
import { port } from "./environment"
import express, { Express, NextFunction, Request, Response } from "express";
import cookieParser from "cookie-parser";
import { client } from "./db";
import router from "./routes";
import { UserAuth } from "./middlewares/auth";
import { AuthedRequest } from "./interfaces/auth";
const app: Express = express();
app.use(cookieParser());
app.use(express.json());
app.use(router);
app.get("/", async (req: Request, res: Response) => {
const data = await client.query("SELECT CURRENT_DATE ;")
res.send(data);
});
app.get("/test", UserAuth, async (req: AuthedRequest, res: Response) => {
res.send(req.user);
});
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack)
res.status(500).send('Something went wrong!')
})
app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
});

@ -0,0 +1,12 @@
import { Request } from "express";
import User, { UserType } from './user'
import { JwtPayload } from "jsonwebtoken";
export interface UserTokenData {
userId: User["id"]
user_type: UserType
}
export interface AuthedRequest extends Request {
user?: UserTokenData | JwtPayload | string | undefined
}

@ -0,0 +1,13 @@
import User from './user'
interface Booking {
/**
* Number of minutes
*/
duration: number
id: number
time: Date
trainer_id: User['id']
user_id: User['id']
}
export default Booking;

@ -0,0 +1,4 @@
export interface LoginBody {
email: string
password: string
}

@ -0,0 +1,6 @@
export interface RegisterBody {
first_name: string
last_name: string
email: string
password: string
}

@ -0,0 +1,12 @@
type UserType = 'Admin' | 'Trainer' | 'User';
export type { UserType }
interface User {
email: string
id: number
first_name: string
last_name: string
password_hash: string
user_type: UserType
}
export default User;

@ -0,0 +1,58 @@
import { Response, NextFunction } from "express";
import jsonwebtoken, { JsonWebTokenError } from "jsonwebtoken";
import { AuthedRequest } from "../interfaces/auth";
import { public_key } from "../environment"
export const UserAuth = (req: AuthedRequest, res: Response, next: NextFunction) => {
if (req.cookies["auth-token"] === undefined) return res.sendStatus(401);
try {
const data: any = jsonwebtoken.verify(req.cookies["auth-token"], public_key);
if (data.user_type !== "User") {
return res.sendStatus(403);
}
req.user = data;
return next();
} catch (error: JsonWebTokenError | Error | any) {
return res.sendStatus(403);
}
}
export const TrainerAuth = (req: AuthedRequest, res: Response, next: NextFunction) => {
if (req.cookies["auth-token"] === undefined) return res.sendStatus(401);
try {
const data: any = jsonwebtoken.verify(req.cookies["auth-token"], public_key);
if (data.user_type !== "Trainer") {
return res.sendStatus(403);
}
req.user = data;
return next();
} catch (error: JsonWebTokenError | Error | any) {
return res.sendStatus(403);
}
}
export const AdminAuth = (req: AuthedRequest, res: Response, next: NextFunction) => {
if (req.cookies["auth-token"] === undefined) return res.sendStatus(401);
try {
const data: any = jsonwebtoken.verify(req.cookies["auth-token"], public_key);
if (data.user_type !== "Admin") {
return res.sendStatus(403);
}
req.user = data;
return next();
} catch (error: JsonWebTokenError | Error | any) {
return res.sendStatus(403);
}
}

@ -0,0 +1,40 @@
import dotenv from "dotenv";
dotenv.config();
import { client } from "../db";
client.query(`
DROP TABLE IF EXISTS public.bookings;
DROP TABLE IF EXISTS public.users;
DROP TYPE IF EXISTS public."UserType";
CREATE TYPE public."UserType" AS ENUM
(
'User',
'Trainer',
'Admin'
);
CREATE TABLE public.users
(
id serial NOT NULL,
first_name text NOT NULL,
last_name text NOT NULL,
email text NOT NULL UNIQUE,
password_hash text NOT NULL,
user_type "UserType" NOT NULL DEFAULT 'User',
PRIMARY KEY (id)
);
CREATE TABLE public.bookings
(
id serial NOT NULL,
trainer_id int references users(id) NOT NULL,
user_id int references users(id) NOT NULL,
time timestamp with time zone NOT NULL,
duration interval NOT NULL
);
`)
.then(()=>{
return client.end();
})

@ -0,0 +1,15 @@
import dotenv from "dotenv";
dotenv.config();
import { client } from "../db";
client.query(`
INSERT INTO users (first_name, last_name, email, password_hash, user_type)
VALUES ('Filip', 'B P', 'fbp@example.com', '$2b$10$zxqwqZXo3DrLVTFx.hkQQ.uKeqhHMnok.G/4.Ivq1g647RaqYtgKC', 'Admin'),
('User1', 'Lastname', 'u1@test.com', '$2b$10$zxqwqZXo3DrLVTFx.hkQQ.uKeqhHMnok.G/4.Ivq1g647RaqYtgKC', 'User'),
('Trainer1', 'Lastname', 't1@test.com', '$2b$10$zxqwqZXo3DrLVTFx.hkQQ.uKeqhHMnok.G/4.Ivq1g647RaqYtgKC', 'Trainer'),
('Admin1', 'Lastname', 'a1@test.com', '$2b$10$zxqwqZXo3DrLVTFx.hkQQ.uKeqhHMnok.G/4.Ivq1g647RaqYtgKC', 'Admin');
`)
.then(()=>{
return client.end();
})

@ -0,0 +1,11 @@
import express, { Express, Router } from "express";
const router: Router = express.Router();
import login from "./login"
import register from "./register"
router.use(login);
router.use(register);
export default router;

@ -0,0 +1,65 @@
import express, { Express, Router, Request, Response } from "express";
import Joi from "joi"
import Bcrypt from "bcrypt"
import { client } from "../db";
import { LoginBody } from "../interfaces/loginBody";
import jsonwebtoken, { JsonWebTokenError } from "jsonwebtoken";
import { DatabaseError } from "pg";
import { UserTokenData } from "../interfaces/auth";
import { private_key } from "../environment"
import User from "../interfaces/user";
const router: Router = express.Router();
const loginSchema = Joi.object({
email: Joi.string().required(),
password: Joi.string().required()
});
interface DatabaseResult {
id: User['id']
user_type: User['user_type']
password_hash: string
}
router.post("/login", async (req: Request, res: Response) => {
const validation = loginSchema.validate(req.body, { abortEarly: false });
if (validation.error !== undefined) {
return res.status(400).send(validation.error.details);
}
const userData: LoginBody = req.body;
try {
const databaseResult = await client.query(`
SELECT id, user_type, password_hash FROM users WHERE email = $1;
`, [userData.email]);
if (databaseResult.rowCount !== 1) {
return res.status(400).send([{ message: "Invalid email or password", type: "login.invalid" }]);
}
const user: DatabaseResult = databaseResult.rows[0];
if (await Bcrypt.compare(userData.password, user.password_hash) !== true) {
return res.status(400).send([{ message: "Invalid email or password", type: "login.invalid" }]);
}
const jwtData: UserTokenData = {
user_type: user.user_type,
userId: user.id
};
const jwt: string = jsonwebtoken.sign(jwtData, private_key, { algorithm: "RS256", expiresIn: "4h" });
res.cookie("auth-token", jwt, { httpOnly: true, maxAge: 60 * 60 * 4 });
return res.sendStatus(204);
} catch (error: DatabaseError | Error | any) {
console.error(error);
return res.sendStatus(500);
}
})
export default router;

@ -0,0 +1,65 @@
import express, { Express, Router, Request, Response } from "express";
import Joi from "joi"
import Bcrypt from "bcrypt"
import { client } from "../db";
import { RegisterBody } from "../interfaces/registerBody";
import jsonwebtoken, { JsonWebTokenError } from "jsonwebtoken";
import { DatabaseError } from "pg";
import { UserTokenData } from "../interfaces/auth";
import { private_key } from "../environment"
const router: Router = express.Router();
const registerSchema = Joi.object({
first_name: Joi.string().min(2).required(),
last_name: Joi.string().min(1).required(),
email: Joi.string().email().required(),
password: Joi.string().min(8).required()
});
router.post("/register", async (req: Request, res: Response) => {
const validation = registerSchema.validate(req.body, { abortEarly: false });
if (validation.error !== undefined) {
return res.status(400).send(validation.error.details);
}
const userData: RegisterBody = req.body;
const password_hash: String = await Bcrypt.hash(userData.password, 10);
try {
const insertResult = await client.query(`
INSERT INTO users (first_name, last_name, email, password_hash)
VALUES ($1, $2, $3, $4)
RETURNING id, user_type;
`, [userData.first_name, userData.last_name, userData.email, password_hash]);
const user = insertResult.rows[0];
const jwtData: UserTokenData = {
user_type: user.user_type,
userId: user.id
};
const jwt: string = jsonwebtoken.sign(jwtData, private_key, { algorithm: "RS256", expiresIn: "4h" });
res.cookie("auth-token", jwt, { httpOnly: true, maxAge: 60 * 60 * 4 });
return res.sendStatus(204);
} catch (error: DatabaseError | Error | any) {
if (error.constraint == "users_email_key") {
return res.status(400).send([{
message: "\"email\" already exists",
path: [
"email"
],
type: "email.unique"
}]);
}
console.error(error);
return res.sendStatus(500);
}
})
export default router;

@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
Loading…
Cancel
Save