From 374039778993fd731e1611abd9d173a8cb1b3494 Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Sun, 19 May 2019 22:38:31 +0300 Subject: [PATCH] =?UTF-8?q?typescript(multiplayer-backend):=20=F0=9F=98=83?= =?UTF-8?q?=20Started=20rewriting=20the=20auth=20code=20using=20stateless?= =?UTF-8?q?=20tokens.=20typescript(multiplayer-backend):=20(now=20i=20=20h?= =?UTF-8?q?ate=20JWTs,=20thanks=20to=20some=20random=20discrod=20user).=20?= =?UTF-8?q?typescript(multiplayer-backend):=20Most=20of=20it=20typescript(?= =?UTF-8?q?multiplayer-backend):=20doesnt=20work,=20its=20more=20of=20a=20?= =?UTF-8?q?prototype.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: prescientmoon --- .../multiplayer-backend/src/createServer.ts | 19 +------ .../src/middleware/sessions/sessions.ts | 50 ++++++++++++++++++- .../src/models/SessionData.ts | 9 ++++ .../src/routes/auth/auth.ts | 8 +-- .../src/routes/auth/index.ts | 3 +- .../src/routes/auth/token.ts | 30 +++++++++++ .../multiplayer-backend/src/routes/index.ts | 5 +- 7 files changed, 97 insertions(+), 27 deletions(-) create mode 100644 typescript/multiplayer-backend/src/models/SessionData.ts create mode 100644 typescript/multiplayer-backend/src/routes/auth/token.ts diff --git a/typescript/multiplayer-backend/src/createServer.ts b/typescript/multiplayer-backend/src/createServer.ts index 96c8a8e..8783883 100644 --- a/typescript/multiplayer-backend/src/createServer.ts +++ b/typescript/multiplayer-backend/src/createServer.ts @@ -1,20 +1,12 @@ import * as express from "express" -import * as sessions from "express-session" import chalk from "chalk"; import { staticRoutes } from "../config"; import { routes } from "./routes" import { urlencoded } from "body-parser"; -import { database } from "./services/db/firestore" import { morganChalk } from "./middleware/morgan"; import { sessionMiddleware } from "./middleware/sessions" - -// @ts-ignore no declaration file -// import * as store from "firestore-store" -import * as store from "connect-mongo" -import { connection, connected } from "./services/db/mongo"; - // const firestore = store(sessions) export interface serverSetupResults { app: express.Application @@ -23,19 +15,10 @@ export interface serverSetupResults { export const setupServer = (): Promise => new Promise(async (res, rej) => { try { - let MongoStore = store(sessions) - - await connected - //create express app const app = express() - app.use(urlencoded({ extended: true }), sessions({ - secret: process.env.SESSION_SECRET, - saveUninitialized: false, - resave: false, - store: new MongoStore({ mongooseConnection: connection }) - }), morganChalk, sessionMiddleware) + app.use(urlencoded({ extended: true }), morganChalk, sessionMiddleware) //load static routes staticRoutes.forEach(route => { diff --git a/typescript/multiplayer-backend/src/middleware/sessions/sessions.ts b/typescript/multiplayer-backend/src/middleware/sessions/sessions.ts index ef1df2a..5c02607 100644 --- a/typescript/multiplayer-backend/src/middleware/sessions/sessions.ts +++ b/typescript/multiplayer-backend/src/middleware/sessions/sessions.ts @@ -1,4 +1,5 @@ import { Response, Request } from "express"; +import { SessionDataDoc, SessionData } from "../../models/SessionData" const getToken = (req: Request) => { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { // Authorization: Bearer g1jipjgi1ifjioj @@ -16,9 +17,54 @@ const getToken = (req: Request) => { return null; } -export const sessionMiddleware = (req: Request, res: Response, next: Function) => { +export const sessionMiddleware = async (req: Request, res: Response, next: Function) => { const token = getToken(req) - console.log(token) + + //if we are trying to get an token, allow this + if (req.path === "/token") + return next() + + //if we dont have any token + if (!token) + return res.json({ succes: false }).status(400) + + //try searching for the object in the database + const result = await SessionData.findOne({ token }) + + if (!result) + return res.json({ succes: false }).status(400) + + const data = JSON.parse(result.data) + + if (!req.session) + //@ts-ignore + req.session = {} + + for (let i in data) + req.session[i] = data[i] + + req.session.save = async () => { + const toSave:any = {} + + for (let i in req.session) { + if (i == "save") continue + + toSave[i] = req.session[i] + } + + const data:string = JSON.stringify(toSave) + + return await result.updateOne({ + token, + data + }) + } + + req.session.rainbow = "unicorn" + + //TODO: remove types for express-session + //@ts-ignore expects callback + req.session.save() next() } \ No newline at end of file diff --git a/typescript/multiplayer-backend/src/models/SessionData.ts b/typescript/multiplayer-backend/src/models/SessionData.ts new file mode 100644 index 0000000..ed5b5a2 --- /dev/null +++ b/typescript/multiplayer-backend/src/models/SessionData.ts @@ -0,0 +1,9 @@ +import { createSchema, Type, typedModel, ExtractDoc } from "ts-mongoose" + +const SessionDataSchema = createSchema({ + token: Type.string(), + data: Type.string() +}) + +export const SessionData = typedModel("SessionData", SessionDataSchema) +export type SessionDataDoc = ExtractDoc; \ No newline at end of file diff --git a/typescript/multiplayer-backend/src/routes/auth/auth.ts b/typescript/multiplayer-backend/src/routes/auth/auth.ts index 5066a8b..34a3878 100644 --- a/typescript/multiplayer-backend/src/routes/auth/auth.ts +++ b/typescript/multiplayer-backend/src/routes/auth/auth.ts @@ -33,14 +33,14 @@ const loginHtml = (req: Request, res: Response) => { - - + })">send `) } diff --git a/typescript/multiplayer-backend/src/routes/auth/index.ts b/typescript/multiplayer-backend/src/routes/auth/index.ts index 63978cd..9c8c2fd 100644 --- a/typescript/multiplayer-backend/src/routes/auth/index.ts +++ b/typescript/multiplayer-backend/src/routes/auth/index.ts @@ -1 +1,2 @@ -export * from "./auth" \ No newline at end of file +export * from "./auth" +export * from "./token" \ No newline at end of file diff --git a/typescript/multiplayer-backend/src/routes/auth/token.ts b/typescript/multiplayer-backend/src/routes/auth/token.ts new file mode 100644 index 0000000..9db42cd --- /dev/null +++ b/typescript/multiplayer-backend/src/routes/auth/token.ts @@ -0,0 +1,30 @@ +import { Router, Response, Request } from "express" +import { randomBytes } from "crypto" +import { SessionData,SessionDataDoc } from "../../models/SessionData"; + +const router = Router() + + +const getToken = async (req: Request, res: Response) => { + //generate token + const token = randomBytes(16).toString("hex") + + //save token into db + const data = new SessionData({ + token, + data:"{}" + } as SessionDataDoc) + + await data.save() + + res.json({ + succes:true, + data:{ + token + } + }) +} + +router.get("/", getToken) + +export const token = router \ No newline at end of file diff --git a/typescript/multiplayer-backend/src/routes/index.ts b/typescript/multiplayer-backend/src/routes/index.ts index f2851f8..f80361e 100644 --- a/typescript/multiplayer-backend/src/routes/index.ts +++ b/typescript/multiplayer-backend/src/routes/index.ts @@ -1,8 +1,9 @@ -import { auth } from "./auth" +import { auth, token } from "./auth" import { logs } from "./logging" import { Router } from "express"; export const routes:{[key:string]:Router} = { auth, - logs + logs, + token }