1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2025-01-14 14:43:17 +08:00

refactoring middleware rendering methods

This commit is contained in:
Braun Patrik 2016-03-26 11:19:10 +01:00
parent 7d246dc909
commit 9ceac016aa
17 changed files with 167 additions and 98 deletions

View File

@ -1,17 +1,18 @@
///<reference path="ExtendedRequest.d.ts"/>
///<reference path="../../typings/main.d.ts"/>
import {UserManager} from "../model/UserManager";
import {NextFunction, Request, Response} from "express";
import {BaseMWs} from "./BaseMWs";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {UserRoles} from "../../common/entities/User";
import {Utils} from "../../common/Utils";
export class AuthenticationMWs extends BaseMWs{
export class AuthenticationMWs {
public static authenticate(req:Request, res:Response, next:NextFunction){
public static authenticate(req:Request, res:Response, next:NextFunction){
if (typeof req.session.user === 'undefined') {
return super.renderError(res,new Error(ErrorCodes.NOT_AUTHENTICATED));
return next(new Error(ErrorCodes.NOT_AUTHENTICATED));
}
return next();
}
@ -19,7 +20,7 @@ export class AuthenticationMWs extends BaseMWs{
public static authorise(role:UserRoles){
return (req:Request, res:Response, next:NextFunction) => {
if (req.session.user.role < role) {
return super.renderError(res, new Error(ErrorCodes.NOT_AUTHORISED));
return next(new Error(ErrorCodes.NOT_AUTHORISED));
}
return next();
};
@ -27,7 +28,7 @@ export class AuthenticationMWs extends BaseMWs{
public static inverseAuthenticate(req:Request, res:Response, next:NextFunction){
if (typeof req.session.user !== 'undefined') {
return super.renderError(res,new Error(ErrorCodes.ALREADY_AUTHENTICATED));
return next(new Error(ErrorCodes.ALREADY_AUTHENTICATED));
}
return next();
}
@ -45,7 +46,7 @@ export class AuthenticationMWs extends BaseMWs{
password: req.body.loginCredential.password
}, (err, result) => {
if ((err) || (!result)) {
return super.renderError(res,new Error(ErrorCodes.CREDENTIAL_NOT_FOUND));
return next(new Error(ErrorCodes.CREDENTIAL_NOT_FOUND));
}
@ -57,15 +58,6 @@ export class AuthenticationMWs extends BaseMWs{
public static renderUser(req:Request, res:Response, next:NextFunction){
if(!(req.session.user)){
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
}
let user = Utils.clone(req.session.user);
delete user.password;
super.renderMessage(res,user);
}
}

View File

@ -1,21 +0,0 @@
import {NextFunction, Request, Response} from "express";
import {Message} from "../../common/entities/Message";
import {Error} from "../../common/entities/Error";
export class BaseMWs {
protected static renderMessage<T>(res:Response, content:T){
let message = new Message<T> (null,content);
res.json(message);
}
protected static renderError(res:Response, error:Error){
let message = new Message<any> (error,null);
res.json(message);
}
public static renderOK(req:Request, res:Response, next:NextFunction){
let message = new Message<string> (null,"ok");
res.json(message);
}
}

View File

@ -0,0 +1,14 @@
declare module Express {
export interface Request{
resultPipe?:any
body?:{
loginCredential
}
}
export interface Session {
user?;
}
}

View File

@ -1,10 +0,0 @@
declare namespace Express {
export interface Request {
}
export interface Session {
user?;
}
}

View File

@ -2,15 +2,14 @@
import * as path from 'path';
import * as fs from 'fs';
import {NextFunction, Request, Response} from "express";
import {BaseMWs} from "./BaseMWs";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {GalleryManager} from "../model/GalleryManager";
import {Directory} from "../../common/entities/Directory";
export class GalleryMWs extends BaseMWs{
export class GalleryMWs {
public static listDirectory(req:Request, res:Response, next:NextFunction){
public static listDirectory(req:Request, res:Response, next:NextFunction){
let directoryName = "/";
if(req.params.directory){
directoryName = req.params.directory;
@ -23,15 +22,15 @@ export class GalleryMWs extends BaseMWs{
GalleryManager.listDirectory(directoryName,(err,directory:Directory) => {
if(err || !directory){
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR,err));
return next(new Error(ErrorCodes.GENERAL_ERROR,err));
}
return super.renderMessage(res,directory);
req.resultPipe = directory;
return next();
});
}
public static renderImage(req:Request, res:Response, next:NextFunction){
public static loadImage(req:Request, res:Response, next:NextFunction){
let directoryName = "/";
if(req.params.directory){
directoryName = req.params.directory;
@ -44,23 +43,24 @@ export class GalleryMWs extends BaseMWs{
if(fs.statSync(fullImagePath).isDirectory()){
return next();
}
return res.sendFile(fullImagePath);
req.resultPipe = fullImagePath;
return next();
}
public static renderThumbnail(req:Request, res:Response, next:NextFunction){
public static loadThumbnail(req:Request, res:Response, next:NextFunction){
//TODO: implement
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
public static search(req:Request, res:Response, next:NextFunction){
//TODO: implement
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
public static autocomplete(req:Request, res:Response, next:NextFunction){
//TODO: implement
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}

View File

@ -0,0 +1,54 @@
import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {Utils} from "../../common/Utils";
import {Message} from "../../common/entities/Message";
export class RenderingMWs {
public static renderResult(req:Request, res:Response, next:NextFunction){
if(!req.resultPipe)
return next();
return RenderingMWs.renderMessage(res,req.resultPipe);
}
public static renderSessionUser(req:Request, res:Response, next:NextFunction){
if(!(req.session.user)){
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
let user = Utils.clone(req.session.user);
delete user.password;
RenderingMWs.renderMessage(res,user);
}
public static renderFile(req:Request, res:Response, next:NextFunction){
if(!req.resultPipe)
return next();
return res.sendFile(req.resultPipe);
}
public static renderOK(req:Request, res:Response, next:NextFunction){
let message = new Message<string> (null,"ok");
res.json(message);
}
public static renderError(err:any, req:Request, res:Response, next:NextFunction):any{
if(err instanceof Error) {
let message = new Message<any> (err,null);
return res.json(message);
}
return next(err);
}
protected static renderMessage<T>(res:Response, content:T){
let message = new Message<T> (null,content);
res.json(message);
}
}

View File

@ -1,10 +1,9 @@
import {UserManager} from "../model/UserManager";
import {NextFunction, Request, Response} from "express";
import {BaseMWs} from "./BaseMWs";
import {Error, ErrorCodes} from "../../common/entities/Error";
export class UserMWs extends BaseMWs{
export class UserMWs {
public static changePassword(req:Request, res:Response, next:NextFunction){
if ((typeof req.body === 'undefined') || (typeof req.body.userModReq === 'undefined')
@ -16,7 +15,7 @@ export class UserMWs extends BaseMWs{
UserManager.changePassword(req.body.userModReq, (err, result) =>{
if ((err) || (!result)) {
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
return next();
@ -31,7 +30,7 @@ export class UserMWs extends BaseMWs{
UserManager.createUser(req.body.newUser, (err, result) =>{
if ((err) || (!result)) {
return super.renderError(res,new Error(ErrorCodes.USER_CREATION_ERROR));
return next(new Error(ErrorCodes.USER_CREATION_ERROR));
}
@ -48,7 +47,7 @@ export class UserMWs extends BaseMWs{
UserManager.deleteUser(req.body.userModReq.id, (err, result) =>{
if ((err) || (!result)) {
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
@ -66,7 +65,7 @@ export class UserMWs extends BaseMWs{
UserManager.changeRole(req.body.userModReq, (err, result) =>{
if ((err) || (!result)) {
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
return next();
@ -77,11 +76,11 @@ export class UserMWs extends BaseMWs{
public static listUsers(req:Request, res:Response, next:NextFunction){
UserManager.find({}, (err, result) =>{
if ((err) || (!result)) {
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
super.renderMessage(res,result);
req.resultPipe = result;
return next();
});
}

View File

@ -1,11 +1,10 @@
import {UserManager} from "../model/UserManager";
import {NextFunction, Request, Response} from "express";
import {BaseMWs} from "./BaseMWs";
import {Error, ErrorCodes} from "../../common/entities/Error";
import {UserRoles} from "../../common/entities/User";
export class UserRequestConstrainsMWs extends BaseMWs{
export class UserRequestConstrainsMWs {
public static forceSelfRequest(req:Request, res:Response, next:NextFunction){
@ -13,7 +12,7 @@ export class UserRequestConstrainsMWs extends BaseMWs{
return next();
}
if(req.session.user.id !== req.params.id){
return super.renderError(res,new Error(ErrorCodes.NOT_AUTHORISED));
return next(new Error(ErrorCodes.NOT_AUTHORISED));
}
return next();
@ -26,7 +25,7 @@ export class UserRequestConstrainsMWs extends BaseMWs{
}
if(req.session.user.id === req.params.id){
return super.renderError(res,new Error(ErrorCodes.NOT_AUTHORISED));
return next(new Error(ErrorCodes.NOT_AUTHORISED));
}
return next();
@ -43,10 +42,10 @@ export class UserRequestConstrainsMWs extends BaseMWs{
UserManager.find({minRole:UserRoles.Admin}, (err, result) =>{
if ((err) || (!result)) {
return super.renderError(res,new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
if(result.length <= 1) {
return super.renderError(res, new Error(ErrorCodes.GENERAL_ERROR));
return next(new Error(ErrorCodes.GENERAL_ERROR));
}
});

View File

@ -0,0 +1,21 @@
///<reference path="../../typings/main.d.ts"/>
import {RenderingMWs} from "../middlewares/RenderingMWs";
export class ErrorRouter{
constructor(private app) {
this.addError();
}
private addError() {
this.app.use("/api/*",
RenderingMWs.renderError
);
};
}

View File

@ -2,6 +2,7 @@
import {AuthenticationMWs} from "../middlewares/AuthenticationMWs";
import {GalleryMWs} from "../middlewares/GalleryMWs";
import {RenderingMWs} from "../middlewares/RenderingMWs";
export class GalleryRouter{
constructor(private app){
@ -17,7 +18,8 @@ export class GalleryRouter{
private addDirectoryList() {
this.app.get(["/api/gallery/:directory","/api/gallery/"],
AuthenticationMWs.authenticate,
GalleryMWs.listDirectory
GalleryMWs.listDirectory,
RenderingMWs.renderResult
);
};
@ -25,28 +27,32 @@ export class GalleryRouter{
private addGetImage() {
this.app.get(["/api/gallery/:directory/:image","/api/gallery/:image"],
AuthenticationMWs.authenticate,
GalleryMWs.renderImage
GalleryMWs.loadImage,
RenderingMWs.renderFile
);
};
private addGetImageThumbnail() {
this.app.get("/api/gallery/:directory/:image/thumbnail",
AuthenticationMWs.authenticate,
GalleryMWs.renderThumbnail
GalleryMWs.loadThumbnail,
RenderingMWs.renderFile
);
};
private addSearch() {
this.app.get("/api/gallery/search",
AuthenticationMWs.authenticate,
GalleryMWs.search
GalleryMWs.search,
RenderingMWs.renderResult
);
};
private addAutoComplete() {
this.app.get("/api/gallery/autocomplete",
AuthenticationMWs.authenticate,
GalleryMWs.autocomplete
GalleryMWs.autocomplete,
RenderingMWs.renderResult
);
};

View File

@ -3,7 +3,7 @@
import {AuthenticationMWs} from "../middlewares/AuthenticationMWs";
import {UserRoles} from "../../common/entities/User";
export class AdminRouter{
export class SharingRouter{
constructor(private app) {
this.addGetSharing();

View File

@ -4,6 +4,7 @@ import {UserMWs} from "../middlewares/UserMWs";
import {UserRoles} from "../../common/entities/User";
import {AuthenticationMWs} from "../middlewares/AuthenticationMWs";
import {UserRequestConstrainsMWs} from "../middlewares/UserRequestConstrainsMWs";
import {RenderingMWs} from "../middlewares/RenderingMWs";
export class UserRouter{
constructor(private app){
@ -22,14 +23,14 @@ export class UserRouter{
this.app.post("/api/user/login",
AuthenticationMWs.inverseAuthenticate,
AuthenticationMWs.login,
AuthenticationMWs.renderUser
RenderingMWs.renderSessionUser
);
};
private addGetSessionUser() {
this.app.get("/api/user/login",
AuthenticationMWs.authenticate,
AuthenticationMWs.renderUser
RenderingMWs.renderSessionUser
);
};
@ -39,7 +40,7 @@ export class UserRouter{
AuthenticationMWs.authenticate,
UserRequestConstrainsMWs.forceSelfRequest,
UserMWs.changePassword,
UserMWs.renderOK
RenderingMWs.renderOK
);
};
@ -49,7 +50,7 @@ export class UserRouter{
AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin),
UserMWs.createUser,
UserMWs.renderOK
RenderingMWs.renderOK
);
};
@ -59,7 +60,7 @@ export class UserRouter{
AuthenticationMWs.authorise(UserRoles.Admin),
UserRequestConstrainsMWs.notSelfRequest,
UserMWs.deleteUser,
UserMWs.renderOK
RenderingMWs.renderOK
);
};
@ -68,7 +69,8 @@ export class UserRouter{
this.app.post("/api/user/list",
AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin),
UserMWs.listUsers
UserMWs.listUsers,
RenderingMWs.renderResult
);
};
@ -78,7 +80,7 @@ export class UserRouter{
AuthenticationMWs.authorise(UserRoles.Admin),
UserRequestConstrainsMWs.notSelfRequestOr2Admins,
UserMWs.changeRole,
UserMWs.renderOK
RenderingMWs.renderOK
);
};

View File

@ -9,6 +9,10 @@ import {PublicRouter} from "./routes/PublicRouter";
import {UserRouter} from "./routes/UserRouter";
import {GalleryRouter} from "./routes/GalleryRouter";
import {AdminRouter} from "./routes/AdminRouter";
import {Error} from "../common/entities/Error";
import {json} from "body-parser";
import {ErrorRouter} from "./routes/ErrorRouter";
import {SharingRouter} from "./routes/SharingRouter";
export class Server {
@ -47,11 +51,16 @@ export class Server {
*/
// for parsing application/json
this.app.use(_bodyParser.json());
new PublicRouter(this.app);
new UserRouter(this.app);
new GalleryRouter(this.app);
new SharingRouter(this.app);
new AdminRouter(this.app);
new ErrorRouter(this.app);
@ -103,7 +112,7 @@ export class Server {
? 'Pipe ' + this.port
: 'Port ' + this.port;
// handle specific listen errors with friendly messages
// handle specific listen error with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');

View File

@ -1,5 +1,10 @@
import {Error} from "./Error";
export class Message<T>{
constructor(public errors:Error,public result:T){}
public error:Error = null;
public result:T = null;
constructor(error:Error, result:T){
this.error = error;
this.result = result;
}
}

View File

@ -14,7 +14,6 @@ import {GalleryService} from "./gallery/gallery.service";
@Component({
selector: 'pi-gallery2-app',
template: `<router-outlet></router-outlet>`,

View File

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

View File

@ -27,8 +27,8 @@ export class AuthenticationService{
private getSessionUser(){
this._userService.getSessionUser().then( (message:Message<User>) =>{
console.log(message);
if(message.errors){
console.log(message.errors);
if(message.error){
console.log(message.error);
}else{
this._user = message.result;
this.OnAuthenticated.trigger(this._user);
@ -39,8 +39,8 @@ export class AuthenticationService{
public login(credential:LoginCredential){
this._userService.login(credential).then( (message:Message<User>) =>{
console.log(message);
if(message.errors){
console.log(message.errors);
if(message.error){
console.log(message.error);
}else{
this._user = message.result;
this.OnAuthenticated.trigger(this._user);