1
Fork 0

typescript(multiplayer-backend): email validation tests

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-04-15 18:59:30 +03:00 committed by prescientmoon
parent 87d8999c68
commit 1544ca69e2
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
14 changed files with 5236 additions and 0 deletions

View file

@ -0,0 +1,26 @@
import * as express from "express"
import { baseUrl, routes } from "../config";
import { performance } from "perf_hooks"
import { shortLogger } from "./routes/logging/shortLog";
export interface serverSetupResults{
time:number;
app:express.Application
}
export const setupServer = ():serverSetupResults => {
const start = performance.now()
const app = express()
for (let i in routes) {
const route = require(`${process.cwd()}/${baseUrl}${routes[i]}`)
app.use(i, route.router)
}
const time = performance.now() - start
const message = `Server created in: ${Math.floor(time)}ms`
shortLogger.log("Server created",message)
return {app,time}
}

View file

@ -0,0 +1,11 @@
import { config } from "dotenv"
import { setupServer } from "./createServer";
//extract env variables
config()
//create the server
const {app} = setupServer()
//start listeing to requests
app.listen(process.env.PORT)

View file

@ -0,0 +1,29 @@
import { Request, Response } from "express"
import { whiteList, whiteListUrl } from "../../config"
//TODO: remove from here
const defaultMethods = "GET, POST, OPTIONS, PUT, PATCH, DELETE"
/**
* used to fix the cors errors things
* @param url the url to allow
* @param methods the methods to allow the url to do
*/
export const corsErrorFixer = ({url,methods}:whiteListUrl) => {
return (req: Request, res: Response, next: any) => {
res.setHeader('Access-Control-Allow-Origin', url) // Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Methods', methods || defaultMethods) //// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type') // Request headers you wish to allow
// Pass to next layer of middleware
next();
}
}
/**
* used to allow all urls on the whitelist
*/
export const allowWhitelist = () => {
return whiteList.map(value => corsErrorFixer(value))
}

View file

@ -0,0 +1,12 @@
import { Request, Response } from "express"
/**
* boilerplate for reddirecting
* @param url the url to reddirect to
* @returns the middleware
*/
export const reddirect = (url: string) =>
(req: Request, res: Response, next: any) => {
res.redirect(url)
next()
}

View file

@ -0,0 +1,46 @@
import { Router, Response, Request, urlencoded } from "express"
import { reddirect } from "../../middleware/reddirect";
import { allowWhitelist } from "../../middleware/corsErrorMiddleware";
import * as sessions from "express-session"
import * as validator from "express-validator"
const router = Router()
const sayHello = (req: Request, res: Response) => {
res.send(`
<form action="/auth" method=post>
<div>
<label for=email>email</label>
<input type=text id=email name=email>
</div>
<button type=submit>Submit</button>
</form>
`)
}
const auth = (req: Request, res: Response, next: any) => {
//validate
req.check("email", "email isnt valid").isEmail()
const errors = req.validationErrors()
//if we have erros mark it
if (errors)
req.session.errors = errors
//reddirect to page
res.send(errors || "Succes!!!")
}
router.use(...allowWhitelist())
router.use("*", urlencoded({ extended: true }), validator(), sessions({
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false
}))
router.get("/", sayHello)
router.post("/", auth)
router.use("/*", reddirect("/auth"))
export { router }

View file

@ -0,0 +1,10 @@
export interface log{
title:string;
body:string;
time:Date;
elapsed?:number;
}
export interface shortConsole{
logs:log[];
log:(name:string,body:string) => any;
}

View file

@ -0,0 +1,16 @@
import { Router, Response, Request } from "express"
import { shortLogger } from "./shortLog";
import { reddirect } from "../../middleware/reddirect";
import { allowWhitelist } from "../../middleware/corsErrorMiddleware";
const router = Router()
const getShortLogs = (req: Request, res: Response) => {
res.json(shortLogger.logs)
}
router.use(...allowWhitelist())
router.get("/", getShortLogs)
router.use("/*", reddirect("/logs"))
export { router }

View file

@ -0,0 +1,32 @@
import { performance } from "perf_hooks"
import { config } from "dotenv";
import { shortConsole } from "./interfaces";
config()
//clear the console
if (process.env.MODE == "DEV")
console.clear()
//used to log things
const shortLogger: shortConsole = {
//holds all the logs
logs: [],
//log a new message
log: (title: string, body: string) => {
//push the logs to the log array
shortLogger.logs.push({
title,
body,
time: new Date(),
elapsed: Math.floor(performance.now())
})
//if we are in dev mode log it
if (process.env.MODE == "DEV")
console.log(body)
}
}
export { shortLogger }