diff options
Diffstat (limited to 'src/server')
-rw-r--r-- | src/server/Client.ts | 15 | ||||
-rw-r--r-- | src/server/Message.ts | 125 | ||||
-rw-r--r-- | src/server/ServerUtil.ts | 55 | ||||
-rw-r--r-- | src/server/authentication/config/passport.ts | 49 | ||||
-rw-r--r-- | src/server/authentication/controllers/user.ts | 107 | ||||
-rw-r--r-- | src/server/authentication/models/User.ts | 89 | ||||
-rw-r--r-- | src/server/database.ts | 81 | ||||
-rw-r--r-- | src/server/index.ts | 155 |
8 files changed, 676 insertions, 0 deletions
diff --git a/src/server/Client.ts b/src/server/Client.ts new file mode 100644 index 000000000..6b8841658 --- /dev/null +++ b/src/server/Client.ts @@ -0,0 +1,15 @@ +import { computed } from "mobx"; + +export class Client { + constructor(guid: string) { + this.guid = guid + } + + private guid: string; + + @computed + public get GUID(): string { + return this.guid + } + +}
\ No newline at end of file diff --git a/src/server/Message.ts b/src/server/Message.ts new file mode 100644 index 000000000..340e9b34a --- /dev/null +++ b/src/server/Message.ts @@ -0,0 +1,125 @@ +import { Utils } from "../Utils"; + +export class Message<T> { + private name: string; + private guid: string; + + get Name(): string { + return this.name; + } + + get Message(): string { + return this.guid + } + + constructor(name: string) { + this.name = name; + this.guid = Utils.GenerateDeterministicGuid(name) + } + + GetValue() { + return this.Name; + } +} + +class TestMessageArgs { + hello: string = ""; +} + +export class SetFieldArgs { + field: string; + value: any; + + constructor(f: string, v: any) { + this.field = f + this.value = v + } +} + +export class GetFieldArgs { + field: string; + + constructor(f: string) { + this.field = f + } +} + +export enum Types { + Number, List, Key, Image, Web, Document, Text, RichText, DocumentReference, Html, PDF +} + +export class DocumentTransfer implements Transferable { + readonly type = Types.Document + _id: string + + constructor(readonly obj: { type: Types, data: [string, string][], _id: string }) { + this._id = obj._id + } +} + +export class ImageTransfer implements Transferable { + readonly type = Types.Image + + constructor(readonly _id: string) { } +} + +export class KeyTransfer implements Transferable { + name: string + readonly _id: string + readonly type = Types.Key + + constructor(i: string, n: string) { + this.name = n + this._id = i + } +} + +export class ListTransfer implements Transferable { + type = Types.List; + + constructor(readonly _id: string) { } +} + +export class NumberTransfer implements Transferable { + readonly type = Types.Number + + constructor(readonly value: number, readonly _id: string) { } +} + +export class TextTransfer implements Transferable { + value: string + readonly _id: string + readonly type = Types.Text + + constructor(t: string, i: string) { + this.value = t + this._id = i + } +} + +export class RichTextTransfer implements Transferable { + value: string + readonly _id: string + readonly type = Types.Text + + constructor(t: string, i: string) { + this.value = t + this._id = i + } +} + +export interface Transferable { + readonly _id: string + readonly type: Types +} + +export namespace MessageStore { + export const Foo = new Message<string>("Foo"); + export const Bar = new Message<string>("Bar"); + export const AddDocument = new Message<DocumentTransfer>("Add Document"); + export const SetField = new Message<{ _id: string, data: any, type: Types }>("Set Field") + export const GetField = new Message<string>("Get Field") + export const GetFields = new Message<string[]>("Get Fields") + export const GetDocument = new Message<string>("Get Document"); + export const DeleteAll = new Message<any>("Delete All"); +}
\ No newline at end of file diff --git a/src/server/ServerUtil.ts b/src/server/ServerUtil.ts new file mode 100644 index 000000000..a53fb5d2b --- /dev/null +++ b/src/server/ServerUtil.ts @@ -0,0 +1,55 @@ +import { Field } from './../fields/Field'; +import { TextField } from './../fields/TextField'; +import { NumberField } from './../fields/NumberField'; +import { RichTextField } from './../fields/RichTextField'; +import { Key } from './../fields/Key'; +import { ImageField } from './../fields/ImageField'; +import { ListField } from './../fields/ListField'; +import { Document } from './../fields/Document'; +import { Server } from './../client/Server'; +import { Types } from './Message'; +import { Utils } from '../Utils'; +import { HtmlField } from '../fields/HtmlField'; +import { WebField } from '../fields/WebField'; + +export class ServerUtils { + public static FromJson(json: any): Field { + let obj = json + let data: any = obj.data + let id: string = obj._id + let type: Types = obj.type + + if (!(data !== undefined && id && type !== undefined)) { + console.log("how did you manage to get an object that doesn't have a data or an id?") + return new TextField("Something to fill the space", Utils.GenerateGuid()); + } + + switch (type) { + case Types.Number: + return new NumberField(data, id, false) + case Types.Text: + return new TextField(data, id, false) + case Types.Html: + return new HtmlField(data, id, false) + case Types.Web: + return new WebField(new URL(data), id, false) + case Types.RichText: + return new RichTextField(data, id, false) + case Types.Key: + return new Key(data, id, false) + case Types.Image: + return new ImageField(new URL(data), id, false) + case Types.List: + return ListField.FromJson(id, data) + case Types.Document: + let doc: Document = new Document(id, false) + let fields: [string, string][] = data as [string, string][] + fields.forEach(element => { + doc._proxies.set(element[0], element[1]); + }); + return doc + default: + throw Error("Error, unrecognized field type received from server. If you just created a new field type, be sure to add it here"); + } + } +}
\ No newline at end of file diff --git a/src/server/authentication/config/passport.ts b/src/server/authentication/config/passport.ts new file mode 100644 index 000000000..05f6c3133 --- /dev/null +++ b/src/server/authentication/config/passport.ts @@ -0,0 +1,49 @@ +import * as passport from 'passport' +import * as passportLocal from 'passport-local'; +import * as mongodb from 'mongodb'; +import * as _ from "lodash"; +import { default as User } from '../models/User'; +import { Request, Response, NextFunction } from "express"; + +const LocalStrategy = passportLocal.Strategy; + +passport.serializeUser<any, any>((user, done) => { + done(undefined, user.id); +}); + +passport.deserializeUser<any, any>((id, done) => { + User.findById(id, (err, user) => { + done(err, user); + }); +}); + +// AUTHENTICATE JUST WITH EMAIL AND PASSWORD +passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => { + User.findOne({ email: email.toLowerCase() }, (error: any, user: any) => { + if (error) return done(error); + if (!user) return done(undefined, false, { message: "Invalid email or password" }) // invalid email + user.comparePassword(password, (error: Error, isMatch: boolean) => { + if (error) return done(error); + if (!isMatch) return done(undefined, false, { message: "Invalid email or password" }); // invalid password + // valid authentication HERE + return done(undefined, user); + }); + }); +})); + +export let isAuthenticated = (req: Request, res: Response, next: NextFunction) => { + if (req.isAuthenticated()) { + return next(); + } + return res.redirect("/login"); +} + +export let isAuthorized = (req: Request, res: Response, next: NextFunction) => { + const provider = req.path.split("/").slice(-1)[0]; + + if (_.find(req.user.tokens, { kind: provider })) { + next(); + } else { + res.redirect(`/auth/${provider}`); + } +};
\ No newline at end of file diff --git a/src/server/authentication/controllers/user.ts b/src/server/authentication/controllers/user.ts new file mode 100644 index 000000000..f74ff9039 --- /dev/null +++ b/src/server/authentication/controllers/user.ts @@ -0,0 +1,107 @@ +import { default as User, UserModel, AuthToken } from "../models/User"; +import { Request, Response, NextFunction } from "express"; +import * as passport from "passport"; +import { IVerifyOptions } from "passport-local"; +import "../config/passport"; +import * as request from "express-validator"; +const flash = require("express-flash"); +import * as session from "express-session"; +import * as pug from 'pug'; + +/** + * GET /signup + * Signup page. + */ +export let getSignup = (req: Request, res: Response) => { + if (req.user) { + return res.redirect("/"); + } + res.render("signup.pug", { + title: "Sign Up" + }); +}; + +/** + * POST /signup + * Create a new local account. + */ +export let postSignup = (req: Request, res: Response, next: NextFunction) => { + req.assert("email", "Email is not valid").isEmail(); + req.assert("password", "Password must be at least 4 characters long").len({ min: 4 }); + req.assert("confirmPassword", "Passwords do not match").equals(req.body.password); + req.sanitize("email").normalizeEmail({ gmail_remove_dots: false }); + + const errors = req.validationErrors(); + + if (errors) { + req.flash("errors", "Unable to facilitate sign up. Please try again."); + return res.redirect("/signup"); + } + + const user = new User({ + email: req.body.email, + password: req.body.password + }); + + User.findOne({ email: req.body.email }, (err, existingUser) => { + if (err) { return next(err); } + if (existingUser) { + req.flash("errors", "Account with that email address already exists."); + return res.redirect("/signup"); + } + user.save((err) => { + if (err) { return next(err); } + req.logIn(user, (err) => { + if (err) { + return next(err); + } + res.redirect("/"); + }); + }); + }); +}; + + +/** + * GET /login + * Login page. + */ +export let getLogin = (req: Request, res: Response) => { + if (req.user) { + return res.redirect("/"); + } + res.send("<p>dear lord please render</p>"); + // res.render("account/login", { + // title: "Login" + // }); +}; + +/** + * POST /login + * Sign in using email and password. + */ +export let postLogin = (req: Request, res: Response, next: NextFunction) => { + req.assert("email", "Email is not valid").isEmail(); + req.assert("password", "Password cannot be blank").notEmpty(); + req.sanitize("email").normalizeEmail({ gmail_remove_dots: false }); + + const errors = req.validationErrors(); + + if (errors) { + req.flash("errors", "Unable to login at this time. Please try again."); + return res.redirect("/login"); + } + + passport.authenticate("local", (err: Error, user: UserModel, info: IVerifyOptions) => { + if (err) { return next(err); } + if (!user) { + req.flash("errors", info.message); + return res.redirect("/login"); + } + req.logIn(user, (err) => { + if (err) { return next(err); } + req.flash("success", "Success! You are logged in."); + res.redirect("/"); + }); + })(req, res, next); +};
\ No newline at end of file diff --git a/src/server/authentication/models/User.ts b/src/server/authentication/models/User.ts new file mode 100644 index 000000000..9752c4260 --- /dev/null +++ b/src/server/authentication/models/User.ts @@ -0,0 +1,89 @@ +//@ts-ignore +import * as bcrypt from "bcrypt-nodejs"; +import * as crypto from "crypto"; +//@ts-ignore +import * as mongoose from "mongoose"; +var url = 'mongodb://localhost:27017/Dash' + +mongoose.connect(url, { useNewUrlParser: true }); + +mongoose.connection.on('connected', function () { + console.log('Stablished connection on ' + url); +}); +mongoose.connection.on('error', function (error) { + console.log('Something wrong happened: ' + error); +}); +mongoose.connection.on('disconnected', function () { + console.log('connection closed'); +}); +export type UserModel = mongoose.Document & { + email: string, + password: string, + passwordResetToken: string, + passwordResetExpires: Date, + tokens: AuthToken[], + + profile: { + name: string, + gender: string, + location: string, + website: string, + picture: string + }, + + comparePassword: comparePasswordFunction, +}; + +type comparePasswordFunction = (candidatePassword: string, cb: (err: any, isMatch: any) => {}) => void; + +export type AuthToken = { + accessToken: string, + kind: string +}; + +const userSchema = new mongoose.Schema({ + email: { type: String, unique: true }, + password: String, + passwordResetToken: String, + passwordResetExpires: Date, + + facebook: String, + twitter: String, + google: String, + tokens: Array, + + profile: { + name: String, + gender: String, + location: String, + website: String, + picture: String + } +}, { timestamps: true }); + +/** + * Password hash middleware. + */ +userSchema.pre("save", function save(next) { + const user = this as UserModel; + if (!user.isModified("password")) { return next(); } + bcrypt.genSalt(10, (err, salt) => { + if (err) { return next(err); } + bcrypt.hash(user.password, salt, () => void {}, (err: mongoose.Error, hash) => { + if (err) { return next(err); } + user.password = hash; + next(); + }); + }); +}); + +const comparePassword: comparePasswordFunction = function (this: UserModel, candidatePassword, cb) { + bcrypt.compare(candidatePassword, this.password, (err: mongoose.Error, isMatch: boolean) => { + cb(err, isMatch); + }); +}; + +userSchema.methods.comparePassword = comparePassword; + +const User = mongoose.model("User", userSchema); +export default User;
\ No newline at end of file diff --git a/src/server/database.ts b/src/server/database.ts new file mode 100644 index 000000000..07c5819ab --- /dev/null +++ b/src/server/database.ts @@ -0,0 +1,81 @@ +import { action, configure } from 'mobx'; +import * as mongodb from 'mongodb'; +import { ObjectID } from 'mongodb'; +import { Transferable } from './Message'; +import { Utils } from '../Utils'; + +export class Database { + public static Instance = new Database() + private MongoClient = mongodb.MongoClient; + private url = 'mongodb://localhost:27017/Dash'; + private db?: mongodb.Db; + + constructor() { + this.MongoClient.connect(this.url, (err, client) => { + this.db = client.db() + }) + } + + public update(id: string, value: any) { + if (this.db) { + let collection = this.db.collection('documents'); + collection.update({ _id: id }, { $set: value }, { + upsert: true + }); + } + } + + public delete(id: string) { + if (this.db) { + let collection = this.db.collection('documents'); + collection.remove({ _id: id }); + } + } + + public deleteAll() { + if (this.db) { + let collection = this.db.collection('documents'); + collection.deleteMany({}); + } + } + + public insert(kvpairs: any) { + if (this.db) { + let collection = this.db.collection('documents'); + collection.insertOne(kvpairs, (err: any, res: any) => { + if (err) { + // console.log(err) + return + } + }); + } + } + + public getDocument(id: string, fn: (res: any) => void) { + var result: JSON; + if (this.db) { + let collection = this.db.collection('documents'); + collection.findOne({ _id: id }, (err: any, res: any) => { + result = res + if (!result) { + fn(undefined) + } + fn(result) + }) + }; + } + + public getDocuments(ids: string[], fn: (res: any) => void) { + if (this.db) { + let collection = this.db.collection('documents'); + let cursor = collection.find({ _id: { "$in": ids } }) + cursor.toArray((err, docs) => { + fn(docs); + }) + }; + } + + public print() { + console.log("db says hi!") + } +} diff --git a/src/server/index.ts b/src/server/index.ts new file mode 100644 index 000000000..56881e254 --- /dev/null +++ b/src/server/index.ts @@ -0,0 +1,155 @@ +import * as express from 'express' +const app = express() +import * as webpack from 'webpack' +import * as wdm from 'webpack-dev-middleware'; +import * as whm from 'webpack-hot-middleware'; +import * as path from 'path' +import * as passport from 'passport'; +import { MessageStore, Message, SetFieldArgs, GetFieldArgs, Transferable } from "./Message"; +import { Client } from './Client'; +import { Socket } from 'socket.io'; +import { Utils } from '../Utils'; +import { ObservableMap } from 'mobx'; +import { FieldId, Field } from '../fields/Field'; +import { Database } from './database'; +import { ServerUtils } from './ServerUtil'; +import { ObjectID } from 'mongodb'; +import { Document } from '../fields/Document'; +import * as io from 'socket.io' +import * as passportConfig from './authentication/config/passport'; +import { getLogin, postLogin, getSignup, postSignup } from './authentication/controllers/user'; +const config = require('../../webpack.config'); +const compiler = webpack(config); +const port = 1050; // default port to listen +const serverPort = 1234; +import * as expressValidator from 'express-validator'; +import expressFlash = require('express-flash'); +import * as bodyParser from 'body-parser'; +import * as session from 'express-session'; +import c = require("crypto"); +const MongoStore = require('connect-mongo')(session); +const mongoose = require('mongoose'); +const bluebird = require('bluebird'); +import { performance } from 'perf_hooks' +import * as fs from 'fs'; +import * as request from 'request' + +const download = (url: string, dest: fs.PathLike) => { + request.get(url).pipe(fs.createWriteStream(dest)); +} + +const mongoUrl = 'mongodb://localhost:27017/Dash'; +// mongoose.Promise = bluebird; +mongoose.connect(mongoUrl)//.then( +// () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ }, +// ).catch((err: any) => { +// console.log("MongoDB connection error. Please make sure MongoDB is running. " + err); +// process.exit(); +// }); +mongoose.connection.on('connected', function () { + console.log("connected"); +}) + +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: true })); +app.use(expressValidator()); +app.use(expressFlash()); +app.use(require('express-session')({ + secret: `${c.randomBytes(64)}`, + resave: true, + saveUninitialized: true, + store: new MongoStore({ + url: 'mongodb://localhost:27017/Dash' + }) +})); +app.use(passport.initialize()); +app.use(passport.session()); +app.use((req, res, next) => { + res.locals.user = req.user; + next(); +}); + +app.get("/signup", getSignup); +app.post("/signup", postSignup); +app.get("/login", getLogin); +app.post("/login", postLogin); + +let FieldStore: ObservableMap<FieldId, Field> = new ObservableMap(); + +// define a route handler for the default home page +app.get("/", (req, res) => { + res.sendFile(path.join(__dirname, '../../deploy/index.html')); +}); + +app.get("/hello", (req, res) => { + res.send("<p>Hello</p>"); +}) + +app.get("/delete", (req, res) => { + deleteAll(); + res.redirect("/"); +}); + +app.use(wdm(compiler, { + publicPath: config.output.publicPath +})) + +app.use(whm(compiler)) + +// start the Express server +app.listen(port, () => { + console.log(`server started at http://localhost:${port}`); +}) + +const server = io(); +interface Map { + [key: string]: Client; +} +let clients: Map = {} + +server.on("connection", function (socket: Socket) { + console.log("a user has connected") + + Utils.Emit(socket, MessageStore.Foo, "handshooken") + + Utils.AddServerHandler(socket, MessageStore.Bar, barReceived) + Utils.AddServerHandler(socket, MessageStore.SetField, (args) => setField(socket, args)) + Utils.AddServerHandlerCallback(socket, MessageStore.GetField, getField) + Utils.AddServerHandlerCallback(socket, MessageStore.GetFields, getFields) + Utils.AddServerHandler(socket, MessageStore.DeleteAll, deleteAll) +}) + +function deleteAll() { + Database.Instance.deleteAll(); +} + +function barReceived(guid: String) { + clients[guid.toString()] = new Client(guid.toString()); +} + +function addDocument(document: Document) { + +} + +function getField([id, callback]: [string, (result: any) => void]) { + Database.Instance.getDocument(id, (result: any) => { + if (result) { + callback(result) + } + else { + callback(undefined) + } + }) +} + +function getFields([ids, callback]: [string[], (result: any) => void]) { + Database.Instance.getDocuments(ids, callback); +} + +function setField(socket: Socket, newValue: Transferable) { + Database.Instance.update(newValue._id, newValue) + socket.broadcast.emit(MessageStore.SetField.Message, newValue) +} + +server.listen(serverPort); +console.log(`listening on port ${serverPort}`);
\ No newline at end of file |