1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2024-11-24 08:42:24 +02:00

improving routing. injecting user information to client side to prevent false routing

This commit is contained in:
Braun Patrik 2016-04-09 18:06:29 +02:00
parent 0cfa60143a
commit 65d88fe061
12 changed files with 83 additions and 29 deletions

View File

@ -14,6 +14,7 @@ export class AuthenticationMWs {
/* if (typeof req.session.user === 'undefined') { /* if (typeof req.session.user === 'undefined') {
return next(new Error(ErrorCodes.NOT_AUTHENTICATED)); return next(new Error(ErrorCodes.NOT_AUTHENTICATED));
}*/ }*/
//TODO: uncomment
return next(); return next();
} }

View File

@ -5,8 +5,12 @@ declare module Express {
body?:{ body?:{
loginCredential loginCredential
} }
} }
export interface Response{
tpl?:any
}
export interface Session { export interface Session {
user?; user?;
} }

View File

@ -5,15 +5,24 @@ import {RenderingMWs} from "../middlewares/RenderingMWs";
export class ErrorRouter{ export class ErrorRouter{
constructor(private app) { constructor(private app) {
this.addError(); this.addApiErrorHandler();
} }
private addError() { private addApiErrorHandler() {
this.app.use("/api/*", this.app.use("/api/*",
RenderingMWs.renderError 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);
});
}

View File

@ -4,15 +4,34 @@
import * as _express from 'express'; import * as _express from 'express';
import * as _path from 'path'; import * as _path from 'path';
import {Utils} from "../../common/Utils";
import {NextFunction, Request, Response} from "express";
export class PublicRouter{ export class PublicRouter{
constructor(private app){ 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(_express.static(_path.resolve(__dirname, './../../frontend')));
this.app.use('/node_modules',_express.static(_path.resolve(__dirname, './../../node_modules'))); this.app.use('/node_modules',_express.static(_path.resolve(__dirname, './../../node_modules')));
var renderIndex = (req: _express.Request, res: _express.Response) => { var renderIndex = (req: Request, res: Response) => {
res.sendFile(_path.resolve(__dirname, './../../frontend/index.html')); res.render(_path.resolve(__dirname, './../../frontend/index.ejs'),res.tpl);
}; };
this.app.get(['/login',"/gallery*"], renderIndex);
this.app.get(['/','/login',"/gallery*"], renderIndex);
} }

View File

@ -27,6 +27,8 @@ export class Server {
this.debug = _debug("PiGallery2:server"); this.debug = _debug("PiGallery2:server");
this.app = _express(); this.app = _express();
this.app.set('view engine', 'ejs');
if(process.env.DEBUG) { if(process.env.DEBUG) {
var _morgan = require('morgan'); var _morgan = require('morgan');
this.app.use(_morgan('dev')); this.app.use(_morgan('dev'));
@ -51,6 +53,8 @@ export class Server {
*/ */
// for parsing application/json // for parsing application/json
this.app.use(_bodyParser.json()); this.app.use(_bodyParser.json());

View File

@ -28,6 +28,10 @@ import {GeneratedUrl} from "angular2/src/router/rules/route_paths/route_path";
] ]
}) })
@RouteConfig([ @RouteConfig([
{
path: '/',
redirectTo: ["Login"]
},
{ {
path: '/login', path: '/login',
name: 'Login', name: 'Login',
@ -36,17 +40,13 @@ import {GeneratedUrl} from "angular2/src/router/rules/route_paths/route_path";
}, },
{ {
path: '/gallery', path: '/gallery',
name: 'GalleryBase', redirectTo: ["Gallery",{directory:""}]
},
{
path: '/gallery/:directory',
name: 'Gallery',
component: GalleryComponent component: GalleryComponent
}, },
{
regex: 'gallery/([\w]*)',
name: 'Gallery',
serializer: (params): GeneratedUrl => {
return new GeneratedUrl(`gallery/${params['directory']}`, {})
},
component: GalleryComponent
}
]) ])
export class AppComponent implements OnInit{ export class AppComponent implements OnInit{
@ -55,10 +55,11 @@ export class AppComponent implements OnInit{
} }
ngOnInit() { ngOnInit() {
this._authenticationService.OnAuthenticated.on((user:User) => this._authenticationService.OnAuthenticated.on((user:User) => {
{ if (this._router.isRouteActive(this._router.generate(['Login']))) {
// this._location.replaceState('/'); // clears browser history so they can't navigate with back button console.log("routing");
this._router.navigate(["GalleryBase"]); this._router.navigate(["Gallery",{directory:""}]);
}
}); });
} }

View File

@ -1 +1 @@
<a [routerLink]="['/Gallery',{directory: getDirectoryPath()}]">{{directory.name}}</a> <a [routerLink]="['Gallery',{directory: getDirectoryPath()}]">{{directory.name}}</a>

View File

@ -34,7 +34,9 @@ export class GalleryComponent implements OnInit{
return; return;
} }
let directoryName = this._params.get('directory'); let directoryName = this._params.get('directory');
console.log(this._params);
console.log(directoryName);
directoryName = directoryName ? directoryName : ""; directoryName = directoryName ? directoryName : "";
this._galleryService.getDirectory(directoryName).then(( message:Message<Directory>) => { this._galleryService.getDirectory(directoryName).then(( message:Message<Directory>) => {
if(message.error){ if(message.error){

View File

@ -8,6 +8,10 @@ import {LoginCredential} from "../../../common/entities/LoginCredential";
import {Message} from "../../../common/entities/Message"; import {Message} from "../../../common/entities/Message";
import { Cookie } from 'ng2-cookies/ng2-cookies'; import { Cookie } from 'ng2-cookies/ng2-cookies';
declare module ServerInject{
export var user;
}
@Injectable() @Injectable()
export class AuthenticationService{ export class AuthenticationService{
@ -19,14 +23,17 @@ export class AuthenticationService{
//picking up session.. //picking up session..
if(this.isAuthenticated() == false && Cookie.getCookie('pigallery2-session') != null){ 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(); this.getSessionUser();
} }
} }
private getSessionUser(){ private getSessionUser(){
this._userService.getSessionUser().then( (message:Message<User>) =>{ this._userService.getSessionUser().then( (message:Message<User>) =>{
console.log(message);
if(message.error){ if(message.error){
console.log(message.error); console.log(message.error);
}else{ }else{
@ -38,15 +45,18 @@ export class AuthenticationService{
public login(credential:LoginCredential){ public login(credential:LoginCredential){
this._userService.login(credential).then( (message:Message<User>) =>{ this._userService.login(credential).then( (message:Message<User>) =>{
console.log(message);
if(message.error){ if(message.error){
console.log(message.error); console.log(message.error);
}else{ }else{
this._user = message.result; this.setUser(message.result);
this.OnAuthenticated.trigger(this._user);
} }
}); });
} }
private setUser(user:User){
this._user = user;
this.OnAuthenticated.trigger(this._user);
}
public isAuthenticated():boolean{ public isAuthenticated():boolean{
return (this._user && this._user != null) ? true : false; return (this._user && this._user != null) ? true : false;

View File

@ -8,6 +8,9 @@
<body> <body>
<pi-gallery2-app>Loading...</pi-gallery2-app> <pi-gallery2-app>Loading...</pi-gallery2-app>
</body> </body>
<script>
var ServerInject = {user: <%- JSON.stringify(user)%>}
</script>
<script src="https://code.angularjs.org/2.0.0-beta.12/angular2-polyfills.js"></script> <script src="https://code.angularjs.org/2.0.0-beta.12/angular2-polyfills.js"></script>
<script src="dist/app-bundle.js"></script> <script src="dist/app-bundle.js"></script>
</html> </html>

View File

@ -25,6 +25,7 @@
"body-parser": "^1.15.0", "body-parser": "^1.15.0",
"core-js": "^2.2.2", "core-js": "^2.2.2",
"debug": "^2.2.0", "debug": "^2.2.0",
"ejs": "^2.4.1",
"express": "^4.13.4", "express": "^4.13.4",
"express-session": "^1.13.0", "express-session": "^1.13.0",
"image-size": "^0.5.0", "image-size": "^0.5.0",

View File

@ -42,9 +42,9 @@ module.exports = {
}, },
exclude: [ /\.e2e\.ts$/ ] exclude: [ /\.e2e\.ts$/ ]
}, },
{ test: /\.json$/, loader: 'json-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.html') ] }, { test: /\.html$/, loader: 'raw-loader', exclude: [ root('frontend/index.ejs') ] },
{ test: /\.css$/, loader: 'raw-loader', exclude: [ root('frontend/index.html') ] } { test: /\.css$/, loader: 'raw-loader', exclude: [ root('frontend/index.ejs') ] }
], ],
postLoaders: [ postLoaders: [
// instrument only testing sources with Istanbul // instrument only testing sources with Istanbul