1
Fork 0

typescript(multiplayer-backend): 😃 Started rewriting the auth code using stateless tokens.

typescript(multiplayer-backend): (now i  hate JWTs, thanks to some random discrod user).
typescript(multiplayer-backend): Most of it
typescript(multiplayer-backend): doesnt work, its more of a prototype.

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-05-19 22:38:31 +03:00 committed by prescientmoon
parent da0a55fd84
commit 3740397789
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
7 changed files with 97 additions and 27 deletions

View file

@ -1,20 +1,12 @@
import * as express from "express" import * as express from "express"
import * as sessions from "express-session"
import chalk from "chalk"; import chalk from "chalk";
import { staticRoutes } from "../config"; import { staticRoutes } from "../config";
import { routes } from "./routes" import { routes } from "./routes"
import { urlencoded } from "body-parser"; import { urlencoded } from "body-parser";
import { database } from "./services/db/firestore"
import { morganChalk } from "./middleware/morgan"; import { morganChalk } from "./middleware/morgan";
import { sessionMiddleware } from "./middleware/sessions" 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) // const firestore = store(sessions)
export interface serverSetupResults { export interface serverSetupResults {
app: express.Application app: express.Application
@ -23,19 +15,10 @@ export interface serverSetupResults {
export const setupServer = (): Promise<serverSetupResults> => export const setupServer = (): Promise<serverSetupResults> =>
new Promise(async (res, rej) => { new Promise(async (res, rej) => {
try { try {
let MongoStore = store(sessions)
await connected
//create express app //create express app
const app = express() const app = express()
app.use(urlencoded({ extended: true }), sessions({ app.use(urlencoded({ extended: true }), morganChalk, sessionMiddleware)
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
store: new MongoStore({ mongooseConnection: connection })
}), morganChalk, sessionMiddleware)
//load static routes //load static routes
staticRoutes.forEach(route => { staticRoutes.forEach(route => {

View file

@ -1,4 +1,5 @@
import { Response, Request } from "express"; import { Response, Request } from "express";
import { SessionDataDoc, SessionData } from "../../models/SessionData"
const getToken = (req: Request) => { const getToken = (req: Request) => {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { // Authorization: Bearer g1jipjgi1ifjioj if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { // Authorization: Bearer g1jipjgi1ifjioj
@ -16,9 +17,54 @@ const getToken = (req: Request) => {
return null; 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) 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() next()
} }

View file

@ -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<typeof SessionDataSchema>;

View file

@ -33,14 +33,14 @@ const loginHtml = (req: Request, res: Response) => {
<label for=name>name</label> <label for=name>name</label>
<input type=name id=name name=name> <input type=name id=name name=name>
</div> </div>
<button type=submit onclick=" <button type=submit>Submit</button>
alert('click') </form>
<button onclick="
fetch('/',{ fetch('/',{
headers: { headers: {
authorization: 'do u see this?' authorization: 'do u see this?'
} }
})">Submit</button> })">send</button>
</form>
`) `)
} }

View file

@ -1 +1,2 @@
export * from "./auth" export * from "./auth"
export * from "./token"

View file

@ -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

View file

@ -1,8 +1,9 @@
import { auth } from "./auth" import { auth, token } from "./auth"
import { logs } from "./logging" import { logs } from "./logging"
import { Router } from "express"; import { Router } from "express";
export const routes:{[key:string]:Router} = { export const routes:{[key:string]:Router} = {
auth, auth,
logs logs,
token
} }