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,22 @@
//public config
//interfaces
export interface routeList {
[key: string]: string
}
export interface whiteListUrl {
url: string
methods?: string
}
//routes
export const baseUrl = "./src/routes/"
export const routes: routeList = {
"/logs": "logging/logs.ts",
"/auth": "auth/auth.ts"
}
//whitelist of urls
export const whiteList = [{
url: "http://localhost:4200"
}]

View file

@ -0,0 +1,12 @@
{
"type": "service_account",
"project_id": "planets-io",
"private_key_id": "64f5c2a6dab6521e5a7236332aca1b72bc49cd4b",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCsQqNWLgveNEud\nvPbYNStN3+KXGqnV2km6JUDQ431oQ4uObKZ8neG6T0cSbQv5j7BmBjLAZIkIGKCc\nLEfRDyUOPlP3l1eBf1txpBoj5YsnH7dBBbi1TqbKihJF0nuCzrYn0zUpVqVIVH8q\nKbs1twFecxd9OIxBY+MaGUI2FQsu8O1m7Xs2RCsur61CAFTvtKeJFdsDAOAuK33b\nws5Nu3WY0cw7yDNGQAY7kDmWNIL4pfbcN1aVsOAQZcF/W/QtEfnaZSfcE1M410tE\n8H0NCXuupsyyoWWuOt/crFmFK3Fd6bg2MHbHJt3y7Xl12xI7OZWdeOiQ0zdri8+j\n6CULzRNLAgMBAAECggEAPtjvK8WP+el9fxbOvpIjcv2Qd424UfgatwnZbHzbJ7uh\nAnz8fvHBRc6fwQa8/Dei5Y40XQIxBp2pl2EGcK1EWT5/NxFl0S7Mh5kWGmuoicUm\nAFici7We371hLk09V7ugNMZ3mlXs5odBf/oKve2/V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JTp16547IvSrR4a8+TecWTg\n3QpvQ5GdifLzmzTL4MGDCg==\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-ssnid@planets-io.iam.gserviceaccount.com",
"client_id": "112323453968848896098",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-ssnid%40planets-io.iam.gserviceaccount.com"
}

View file

@ -0,0 +1,6 @@
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/main.ts"
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,34 @@
{
"name": "mp-game-back-end",
"version": "1.0.0",
"description": "a multiplayer game (idk for now)",
"main": "src/main.ts",
"scripts": {
"dev": "nodemon"
},
"repository": {
"type": "git",
"url": "\u0016https://github.com/Mateiadrielrafael/mp-game-server"
},
"keywords": [
"mp"
],
"author": "Matei Adriel",
"license": "ISC",
"devDependencies": {
"@types/dotenv": "^6.1.1",
"@types/express": "^4.16.1",
"@types/express-session": "^1.15.12",
"@types/express-validator": "^3.0.0",
"nodemon": "^1.18.10",
"ts-node": "^8.0.3"
},
"dependencies": {
"dotenv": "^7.0.0",
"express": "^4.16.4",
"express-session": "^1.16.1",
"express-validator": "^5.3.1",
"firebase-admin": "^7.2.0",
"typescript": "^3.4.1"
}
}

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 }

View file

@ -0,0 +1,31 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": [
"types/*"
]
},
"module": "commonjs",
"removeComments": true,
"lib": [
"es2015",
"es2017",
"dom"
],
"noImplicitAny": true,
"alwaysStrict": true,
"moduleResolution": "Node",
"experimentalDecorators": true,
"downlevelIteration": true,
"target": "ESNext",
"resolveJsonModule": true
},
"include": [
"src"
],
"exclude": [
"node_modules",
"dist"
]
}