From 65d88fe061a0679831b7ce7748b44a950245b1d2 Mon Sep 17 00:00:00 2001 From: Braun Patrik Date: Sat, 9 Apr 2016 18:06:29 +0200 Subject: [PATCH] improving routing. injecting user information to client side to prevent false routing --- backend/middlewares/AuthenticationMWs.ts | 1 + backend/middlewares/ExtendedRequest.d.ts | 6 ++++- backend/routes/ErrorRouter.ts | 13 +++++++-- backend/routes/PublicRouter.ts | 25 ++++++++++++++--- backend/server.ts | 4 +++ frontend/app/app.component.ts | 27 ++++++++++--------- .../directory.gallery.component.html | 2 +- frontend/app/gallery/gallery.component.ts | 4 ++- frontend/app/model/authentication.service.ts | 20 ++++++++++---- frontend/{index.html => index.ejs} | 3 +++ package.json | 1 + test/webpack.test.config.js | 6 ++--- 12 files changed, 83 insertions(+), 29 deletions(-) rename frontend/{index.html => index.ejs} (83%) diff --git a/backend/middlewares/AuthenticationMWs.ts b/backend/middlewares/AuthenticationMWs.ts index 656bfb41..ae6a7e49 100644 --- a/backend/middlewares/AuthenticationMWs.ts +++ b/backend/middlewares/AuthenticationMWs.ts @@ -14,6 +14,7 @@ export class AuthenticationMWs { /* if (typeof req.session.user === 'undefined') { return next(new Error(ErrorCodes.NOT_AUTHENTICATED)); }*/ + //TODO: uncomment return next(); } diff --git a/backend/middlewares/ExtendedRequest.d.ts b/backend/middlewares/ExtendedRequest.d.ts index bc40fbdc..b2c3601b 100644 --- a/backend/middlewares/ExtendedRequest.d.ts +++ b/backend/middlewares/ExtendedRequest.d.ts @@ -5,8 +5,12 @@ declare module Express { body?:{ loginCredential } - } + } + export interface Response{ + tpl?:any + } + export interface Session { user?; } diff --git a/backend/routes/ErrorRouter.ts b/backend/routes/ErrorRouter.ts index 39bf71ee..f7c6b9a9 100644 --- a/backend/routes/ErrorRouter.ts +++ b/backend/routes/ErrorRouter.ts @@ -5,15 +5,24 @@ import {RenderingMWs} from "../middlewares/RenderingMWs"; export class ErrorRouter{ constructor(private app) { - this.addError(); + this.addApiErrorHandler(); } - private addError() { + private addApiErrorHandler() { this.app.use("/api/*", RenderingMWs.renderError ); }; + private addGenericHandler() { + this.app.use((err, req, res, next) => { + res.status(500).send('Houston, we have a problem!'); + + //Flush out the stack to the console + console.error(err.stack); + }); + + } diff --git a/backend/routes/PublicRouter.ts b/backend/routes/PublicRouter.ts index d01625c4..59a1c274 100644 --- a/backend/routes/PublicRouter.ts +++ b/backend/routes/PublicRouter.ts @@ -4,15 +4,34 @@ import * as _express from 'express'; import * as _path from 'path'; + +import {Utils} from "../../common/Utils"; + +import {NextFunction, Request, Response} from "express"; + export class PublicRouter{ constructor(private app){ + this.app.use((req:Request, res:Response, next:NextFunction) => { + res.tpl = {}; + + res.tpl.user = null; + if(req.session.user) { + let user = Utils.clone(req.session.user); + delete user.password; + res.tpl.user = user; + } + + return next(); + }); + this.app.use(_express.static(_path.resolve(__dirname, './../../frontend'))); this.app.use('/node_modules',_express.static(_path.resolve(__dirname, './../../node_modules'))); - var renderIndex = (req: _express.Request, res: _express.Response) => { - res.sendFile(_path.resolve(__dirname, './../../frontend/index.html')); + var renderIndex = (req: Request, res: Response) => { + res.render(_path.resolve(__dirname, './../../frontend/index.ejs'),res.tpl); }; - this.app.get(['/login',"/gallery*"], renderIndex); + + this.app.get(['/','/login',"/gallery*"], renderIndex); } diff --git a/backend/server.ts b/backend/server.ts index baa16453..b5f4f334 100644 --- a/backend/server.ts +++ b/backend/server.ts @@ -27,6 +27,8 @@ export class Server { this.debug = _debug("PiGallery2:server"); this.app = _express(); + this.app.set('view engine', 'ejs'); + if(process.env.DEBUG) { var _morgan = require('morgan'); this.app.use(_morgan('dev')); @@ -51,6 +53,8 @@ export class Server { */ // for parsing application/json this.app.use(_bodyParser.json()); + + diff --git a/frontend/app/app.component.ts b/frontend/app/app.component.ts index ed8f3717..7f98e7a4 100644 --- a/frontend/app/app.component.ts +++ b/frontend/app/app.component.ts @@ -28,6 +28,10 @@ import {GeneratedUrl} from "angular2/src/router/rules/route_paths/route_path"; ] }) @RouteConfig([ + { + path: '/', + redirectTo: ["Login"] + }, { path: '/login', name: 'Login', @@ -36,17 +40,13 @@ import {GeneratedUrl} from "angular2/src/router/rules/route_paths/route_path"; }, { path: '/gallery', - name: 'GalleryBase', + redirectTo: ["Gallery",{directory:""}] + }, + { + path: '/gallery/:directory', + name: 'Gallery', component: GalleryComponent }, - { - regex: 'gallery/([\w]*)', - name: 'Gallery', - serializer: (params): GeneratedUrl => { - return new GeneratedUrl(`gallery/${params['directory']}`, {}) - }, - component: GalleryComponent - } ]) export class AppComponent implements OnInit{ @@ -55,10 +55,11 @@ export class AppComponent implements OnInit{ } ngOnInit() { - this._authenticationService.OnAuthenticated.on((user:User) => - { - // this._location.replaceState('/'); // clears browser history so they can't navigate with back button - this._router.navigate(["GalleryBase"]); + this._authenticationService.OnAuthenticated.on((user:User) => { + if (this._router.isRouteActive(this._router.generate(['Login']))) { + console.log("routing"); + this._router.navigate(["Gallery",{directory:""}]); + } }); } diff --git a/frontend/app/gallery/directory/directory.gallery.component.html b/frontend/app/gallery/directory/directory.gallery.component.html index 9c159103..69fa3efa 100644 --- a/frontend/app/gallery/directory/directory.gallery.component.html +++ b/frontend/app/gallery/directory/directory.gallery.component.html @@ -1 +1 @@ -{{directory.name}} \ No newline at end of file +{{directory.name}} \ No newline at end of file diff --git a/frontend/app/gallery/gallery.component.ts b/frontend/app/gallery/gallery.component.ts index c336090c..a459e1e3 100644 --- a/frontend/app/gallery/gallery.component.ts +++ b/frontend/app/gallery/gallery.component.ts @@ -34,7 +34,9 @@ export class GalleryComponent implements OnInit{ return; } - let directoryName = this._params.get('directory'); + let directoryName = this._params.get('directory'); + console.log(this._params); + console.log(directoryName); directoryName = directoryName ? directoryName : ""; this._galleryService.getDirectory(directoryName).then(( message:Message) => { if(message.error){ diff --git a/frontend/app/model/authentication.service.ts b/frontend/app/model/authentication.service.ts index 0e5e3e59..4f24a6bc 100644 --- a/frontend/app/model/authentication.service.ts +++ b/frontend/app/model/authentication.service.ts @@ -8,6 +8,10 @@ import {LoginCredential} from "../../../common/entities/LoginCredential"; import {Message} from "../../../common/entities/Message"; import { Cookie } from 'ng2-cookies/ng2-cookies'; +declare module ServerInject{ + export var user; +} + @Injectable() export class AuthenticationService{ @@ -19,14 +23,17 @@ export class AuthenticationService{ //picking up session.. if(this.isAuthenticated() == false && Cookie.getCookie('pigallery2-session') != null){ + if(typeof ServerInject !== "undefined" && typeof ServerInject.user !== "undefined"){ + console.log("user found"); + this.setUser(ServerInject.user); + } this.getSessionUser(); } } private getSessionUser(){ - this._userService.getSessionUser().then( (message:Message) =>{ - console.log(message); + this._userService.getSessionUser().then( (message:Message) =>{ if(message.error){ console.log(message.error); }else{ @@ -38,15 +45,18 @@ export class AuthenticationService{ public login(credential:LoginCredential){ this._userService.login(credential).then( (message:Message) =>{ - console.log(message); if(message.error){ console.log(message.error); }else{ - this._user = message.result; - this.OnAuthenticated.trigger(this._user); + this.setUser(message.result); } }); } + + private setUser(user:User){ + this._user = user; + this.OnAuthenticated.trigger(this._user); + } public isAuthenticated():boolean{ return (this._user && this._user != null) ? true : false; diff --git a/frontend/index.html b/frontend/index.ejs similarity index 83% rename from frontend/index.html rename to frontend/index.ejs index 9d745f0e..724367e3 100644 --- a/frontend/index.html +++ b/frontend/index.ejs @@ -8,6 +8,9 @@ Loading... + \ No newline at end of file diff --git a/package.json b/package.json index 2f7f7dba..0df98e13 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "body-parser": "^1.15.0", "core-js": "^2.2.2", "debug": "^2.2.0", + "ejs": "^2.4.1", "express": "^4.13.4", "express-session": "^1.13.0", "image-size": "^0.5.0", diff --git a/test/webpack.test.config.js b/test/webpack.test.config.js index 49c36b99..eeb73cd8 100644 --- a/test/webpack.test.config.js +++ b/test/webpack.test.config.js @@ -42,9 +42,9 @@ module.exports = { }, exclude: [ /\.e2e\.ts$/ ] }, - { test: /\.json$/, loader: 'json-loader', exclude: [ root('frontend/index.html') ] }, - { test: /\.html$/, loader: 'raw-loader', exclude: [ root('frontend/index.html') ] }, - { test: /\.css$/, loader: 'raw-loader', exclude: [ root('frontend/index.html') ] } + { test: /\.json$/, loader: 'json-loader', exclude: [ root('frontend/index.ejs') ] }, + { test: /\.html$/, loader: 'raw-loader', exclude: [ root('frontend/index.ejs') ] }, + { test: /\.css$/, loader: 'raw-loader', exclude: [ root('frontend/index.ejs') ] } ], postLoaders: [ // instrument only testing sources with Istanbul