aboutsummaryrefslogtreecommitdiff
path: root/src/server/authentication
diff options
context:
space:
mode:
Diffstat (limited to 'src/server/authentication')
-rw-r--r--src/server/authentication/config/passport.ts22
-rw-r--r--src/server/authentication/controllers/user_controller.ts40
-rw-r--r--src/server/authentication/models/current_user_utils.ts48
-rw-r--r--src/server/authentication/models/user_model.ts18
4 files changed, 57 insertions, 71 deletions
diff --git a/src/server/authentication/config/passport.ts b/src/server/authentication/config/passport.ts
index 8915a4abf..286209b20 100644
--- a/src/server/authentication/config/passport.ts
+++ b/src/server/authentication/config/passport.ts
@@ -1,9 +1,6 @@
import * as passport from 'passport';
import * as passportLocal from 'passport-local';
-import _ from "lodash";
import { default as User } from '../models/user_model';
-import { Request, Response, NextFunction } from "express";
-import { RouteStore } from '../../RouteStore';
const LocalStrategy = passportLocal.Strategy;
@@ -29,21 +26,4 @@ passport.use(new LocalStrategy({ usernameField: 'email', passReqToCallback: true
return done(undefined, user);
});
});
-}));
-
-export let isAuthenticated = (req: Request, res: Response, next: NextFunction) => {
- if (req.isAuthenticated()) {
- return next();
- }
- return res.redirect(RouteStore.login);
-};
-
-export let isAuthorized = (req: Request, res: Response, next: NextFunction) => {
- const provider = req.path.split("/").slice(-1)[0];
-
- if (_.find((req.user as any).tokens, { kind: provider })) {
- next();
- } else {
- res.redirect(`/auth/${provider}`);
- }
-}; \ No newline at end of file
+})); \ No newline at end of file
diff --git a/src/server/authentication/controllers/user_controller.ts b/src/server/authentication/controllers/user_controller.ts
index f5c6e1610..f0086d4ea 100644
--- a/src/server/authentication/controllers/user_controller.ts
+++ b/src/server/authentication/controllers/user_controller.ts
@@ -3,17 +3,11 @@ 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";
import flash = require("express-flash");
-import * as session from "express-session";
-import * as pug from 'pug';
import * as async from 'async';
import * as nodemailer from 'nodemailer';
import c = require("crypto");
-import { RouteStore } from "../../RouteStore";
import { Utils } from "../../../Utils";
-import { Schema } from "mongoose";
-import { Opt } from "../../../new_fields/Doc";
import { MailOptions } from "nodemailer/lib/stream-transport";
/**
@@ -23,8 +17,7 @@ import { MailOptions } from "nodemailer/lib/stream-transport";
*/
export let getSignup = (req: Request, res: Response) => {
if (req.user) {
- let user = req.user;
- return res.redirect(RouteStore.home);
+ return res.redirect("/home");
}
res.render("signup.pug", {
title: "Sign Up",
@@ -45,7 +38,7 @@ export let postSignup = (req: Request, res: Response, next: NextFunction) => {
const errors = req.validationErrors();
if (errors) {
- return res.redirect(RouteStore.signup);
+ return res.redirect("/signup");
}
const email = req.body.email as String;
@@ -62,7 +55,7 @@ export let postSignup = (req: Request, res: Response, next: NextFunction) => {
User.findOne({ email }, (err, existingUser) => {
if (err) { return next(err); }
if (existingUser) {
- return res.redirect(RouteStore.login);
+ return res.redirect("/login");
}
user.save((err: any) => {
if (err) { return next(err); }
@@ -75,13 +68,13 @@ export let postSignup = (req: Request, res: Response, next: NextFunction) => {
};
-let tryRedirectToTarget = (req: Request, res: Response) => {
+const tryRedirectToTarget = (req: Request, res: Response) => {
if (req.session && req.session.target) {
- let target = req.session.target;
+ const target = req.session.target;
req.session.target = undefined;
res.redirect(target);
} else {
- res.redirect(RouteStore.home);
+ res.redirect("/home");
}
};
@@ -93,7 +86,7 @@ let tryRedirectToTarget = (req: Request, res: Response) => {
export let getLogin = (req: Request, res: Response) => {
if (req.user) {
req.session!.target = undefined;
- return res.redirect(RouteStore.home);
+ return res.redirect("/home");
}
res.render("login.pug", {
title: "Log In",
@@ -115,13 +108,13 @@ export let postLogin = (req: Request, res: Response, next: NextFunction) => {
if (errors) {
req.flash("errors", "Unable to login at this time. Please try again.");
- return res.redirect(RouteStore.signup);
+ return res.redirect("/signup");
}
passport.authenticate("local", (err: Error, user: DashUserModel, info: IVerifyOptions) => {
if (err) { next(err); return; }
if (!user) {
- return res.redirect(RouteStore.signup);
+ return res.redirect("/signup");
}
req.logIn(user, (err) => {
if (err) { next(err); return; }
@@ -141,7 +134,7 @@ export let getLogout = (req: Request, res: Response) => {
if (sess) {
sess.destroy((err) => { if (err) { console.log(err); } });
}
- res.redirect(RouteStore.login);
+ res.redirect("/login");
};
export let getForgot = function (req: Request, res: Response) {
@@ -155,7 +148,6 @@ export let postForgot = function (req: Request, res: Response, next: NextFunctio
const email = req.body.email;
async.waterfall([
function (done: any) {
- let token: string;
c.randomBytes(20, function (err: any, buffer: Buffer) {
if (err) {
done(null);
@@ -168,7 +160,7 @@ export let postForgot = function (req: Request, res: Response, next: NextFunctio
User.findOne({ email }, function (err, user: DashUserModel) {
if (!user) {
// NO ACCOUNT WITH SUBMITTED EMAIL
- res.redirect(RouteStore.forgot);
+ res.redirect("/forgotPassword");
return;
}
user.passwordResetToken = token;
@@ -192,7 +184,7 @@ export let postForgot = function (req: Request, res: Response, next: NextFunctio
subject: 'Dash Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
- 'http://' + req.headers.host + '/reset/' + token + '\n\n' +
+ 'http://' + req.headers.host + '/resetPassword/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
} as MailOptions;
smtpTransport.sendMail(mailOptions, function (err: Error | null) {
@@ -202,14 +194,14 @@ export let postForgot = function (req: Request, res: Response, next: NextFunctio
}
], function (err) {
if (err) return next(err);
- res.redirect(RouteStore.forgot);
+ res.redirect("/forgotPassword");
});
};
export let getReset = function (req: Request, res: Response) {
User.findOne({ passwordResetToken: req.params.token, passwordResetExpires: { $gt: Date.now() } }, function (err, user: DashUserModel) {
if (!user || err) {
- return res.redirect(RouteStore.forgot);
+ return res.redirect("/forgotPassword");
}
res.render("reset.pug", {
title: "Reset Password",
@@ -239,7 +231,7 @@ export let postReset = function (req: Request, res: Response) {
user.save(function (err) {
if (err) {
- res.redirect(RouteStore.login);
+ res.redirect("/login");
return;
}
req.logIn(user, function (err) {
@@ -271,6 +263,6 @@ export let postReset = function (req: Request, res: Response) {
});
}
], function (err) {
- res.redirect(RouteStore.login);
+ res.redirect("/login");
});
}; \ No newline at end of file
diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts
index 5b9bba47d..220c37e2b 100644
--- a/src/server/authentication/models/current_user_utils.ts
+++ b/src/server/authentication/models/current_user_utils.ts
@@ -1,4 +1,4 @@
-import { action, computed, observable, reaction, runInAction } from "mobx";
+import { action, computed, observable, reaction } from "mobx";
import * as rp from 'request-promise';
import { DocServer } from "../../../client/DocServer";
import { Docs } from "../../../client/documents/Documents";
@@ -9,12 +9,11 @@ import { Doc, DocListCast } from "../../../new_fields/Doc";
import { List } from "../../../new_fields/List";
import { listSpec } from "../../../new_fields/Schema";
import { ScriptField, ComputedField } from "../../../new_fields/ScriptField";
-import { Cast, PromiseValue } from "../../../new_fields/Types";
+import { Cast, PromiseValue, StrCast } from "../../../new_fields/Types";
import { Utils } from "../../../Utils";
-import { RouteStore } from "../../RouteStore";
-import { InkingControl } from "../../../client/views/InkingControl";
-import { DragManager } from "../../../client/util/DragManager";
import { nullAudio } from "../../../new_fields/URLField";
+import { DragManager } from "../../../client/util/DragManager";
+import { InkingControl } from "../../../client/views/InkingControl";
export class CurrentUserUtils {
private static curr_id: string;
@@ -42,12 +41,13 @@ export class CurrentUserUtils {
}
// setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools
- static setupCreatorButtons(doc: Doc) {
- let notes = CurrentUserUtils.setupNoteTypes(doc);
+ static setupCreatorButtons(doc: Doc, buttons?: string[]) {
+ const notes = CurrentUserUtils.setupNoteTypes(doc);
doc.noteTypes = Docs.Create.TreeDocument(notes, { title: "Note Types", height: 75 });
doc.activePen = doc;
- let docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [
+ const docProtoData: { title: string, icon: string, drag?: string, ignoreClick?: boolean, click?: string, ischecked?: string, activePen?: Doc, backgroundColor?: string, dragFactory?: Doc }[] = [
{ title: "collection", icon: "folder", ignoreClick: true, drag: 'Docs.Create.FreeformDocument([], { nativeWidth: undefined, nativeHeight: undefined, width: 150, height: 100, title: "freeform" })' },
+ { title: "preview", icon: "expand", ignoreClick: true, drag: 'Docs.Create.DocumentDocument(ComputedField.MakeFunction("selectedDocs(this,true,[_last_])?.[0]"), { width: 250, height: 250, title: "container" })' },
{ title: "todo item", icon: "check", ignoreClick: true, drag: 'getCopy(this.dragFactory, true)', dragFactory: notes[notes.length - 1] },
{ title: "web page", icon: "globe-asia", ignoreClick: true, drag: 'Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", { width: 300, height: 300, title: "New Webpage" })' },
{ title: "cat image", icon: "cat", ignoreClick: true, drag: 'Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { width: 200, title: "an image of a cat" })' },
@@ -61,7 +61,7 @@ export class CurrentUserUtils {
{ title: "use scrubber", icon: "eraser", click: 'activateScrubber(this.activePen.pen = sameDocs(this.activePen.pen, this) ? undefined : this);', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "green", activePen: doc },
{ title: "use drag", icon: "mouse-pointer", click: 'deactivateInk();this.activePen.pen = this;', ischecked: `sameDocs(this.activePen.pen, this)`, backgroundColor: "white", activePen: doc },
];
- return docProtoData.map(data => Docs.Create.FontIconDocument({
+ return docProtoData.filter(d => !buttons || !buttons.includes(d.title)).map(data => Docs.Create.FontIconDocument({
nativeWidth: 100, nativeHeight: 100, width: 100, height: 100, dropAction: data.click ? "copy" : undefined, title: data.title, icon: data.icon, ignoreClick: data.ignoreClick,
onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined, onClick: data.click ? ScriptField.MakeScript(data.click) : undefined,
ischecked: data.ischecked ? ComputedField.MakeFunction(data.ischecked) : undefined, activePen: data.activePen,
@@ -69,6 +69,27 @@ export class CurrentUserUtils {
}));
}
+ static async updateCreatorButtons(doc: Doc) {
+ const toolsBtn = await Cast(doc.ToolsBtn, Doc);
+ if (toolsBtn) {
+ const stackingDoc = await Cast(toolsBtn.sourcePanel, Doc);
+ if (stackingDoc) {
+ const stackdocs = await Cast(stackingDoc.data, listSpec(Doc));
+ if (stackdocs) {
+ const dragset = await Cast(stackdocs[0], Doc);
+ if (dragset) {
+ const dragdocs = await Cast(dragset.data, listSpec(Doc));
+ if (dragdocs) {
+ const dragDocs = await Promise.all(dragdocs);
+ const newButtons = this.setupCreatorButtons(doc, dragDocs.map(d => StrCast(d.title)));
+ newButtons.map(nb => Doc.AddDocToList(dragset, "data", nb));
+ }
+ }
+ }
+ }
+ }
+ }
+
// setup the Creator button which will display the creator panel. This panel will include the drag creators and the color picker. when clicked, this panel will be displayed in the target container (ie, sidebarContainer)
static setupToolsPanel(sidebarContainer: Doc, doc: Doc) {
// setup a masonry view of all he creators
@@ -203,11 +224,12 @@ export class CurrentUserUtils {
doc.undoBtn && reaction(() => UndoManager.undoStack.slice(), () => Doc.GetProto(doc.undoBtn as Doc).opacity = UndoManager.CanUndo() ? 1 : 0.4, { fireImmediately: true });
doc.redoBtn && reaction(() => UndoManager.redoStack.slice(), () => Doc.GetProto(doc.redoBtn as Doc).opacity = UndoManager.CanRedo() ? 1 : 0.4, { fireImmediately: true });
+ this.updateCreatorButtons(doc);
return doc;
}
- public static loadCurrentUser() {
- return rp.get(Utils.prepend(RouteStore.getCurrUser)).then(response => {
+ public static async loadCurrentUser() {
+ return rp.get(Utils.prepend("/getCurrentUser")).then(response => {
if (response) {
const result: { id: string, email: string } = JSON.parse(response);
return result;
@@ -220,7 +242,7 @@ export class CurrentUserUtils {
public static async loadUserDocument({ id, email }: { id: string, email: string }) {
this.curr_id = id;
Doc.CurrentUserEmail = email;
- await rp.get(Utils.prepend(RouteStore.getUserDocumentId)).then(id => {
+ await rp.get(Utils.prepend("/getUserDocumentId")).then(id => {
if (id && id !== "guest") {
return DocServer.GetRefField(id).then(async field =>
Doc.SetUserDoc(await this.updateUserDocument(field instanceof Doc ? field : new Doc(id, true))));
@@ -279,7 +301,7 @@ export class CurrentUserUtils {
if (this._northstarCatalog && CurrentUserUtils._northstarSchemas) {
this._northstarCatalog.schemas!.push(schema);
CurrentUserUtils._northstarSchemas.push(schemaDoc);
- let schemas = Cast(CurrentUserUtils.UserDocument.DBSchemas, listSpec("string"), []);
+ const schemas = Cast(CurrentUserUtils.UserDocument.DBSchemas, listSpec("string"), []);
schemas.push(schema.displayName!);
CurrentUserUtils.UserDocument.DBSchemas = new List<string>(schemas);
}
diff --git a/src/server/authentication/models/user_model.ts b/src/server/authentication/models/user_model.ts
index 45fbf23b1..78e39dbc1 100644
--- a/src/server/authentication/models/user_model.ts
+++ b/src/server/authentication/models/user_model.ts
@@ -1,20 +1,8 @@
//@ts-ignore
import * as bcrypt from "bcrypt-nodejs";
//@ts-ignore
-import * as mongoose from "mongoose";
-var url = 'mongodb://localhost:27017/Dash';
+import * as mongoose from 'mongoose';
-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 DashUserModel = mongoose.Document & {
email: String,
password: string,
@@ -85,7 +73,11 @@ userSchema.pre("save", function save(next) {
});
const comparePassword: comparePasswordFunction = function (this: DashUserModel, candidatePassword, cb) {
+ // Choose one of the following bodies for authentication logic.
+ // secure
bcrypt.compare(candidatePassword, this.password, cb);
+ // bypass password
+ // cb(undefined, true);
};
userSchema.methods.comparePassword = comparePassword;