2016-03-26 18:19:10 +08:00
|
|
|
///<reference path="ExtendedRequest.d.ts"/>
|
|
|
|
///<reference path="../../typings/main.d.ts"/>
|
|
|
|
|
2016-03-20 00:31:42 +08:00
|
|
|
|
|
|
|
import {UserManager} from "../model/UserManager";
|
|
|
|
import {NextFunction, Request, Response} from "express";
|
|
|
|
import {Error, ErrorCodes} from "../../common/entities/Error";
|
|
|
|
import {UserRoles} from "../../common/entities/User";
|
|
|
|
|
2016-03-26 18:19:10 +08:00
|
|
|
export class AuthenticationMWs {
|
2016-03-20 00:31:42 +08:00
|
|
|
|
|
|
|
|
2016-03-27 02:24:12 +08:00
|
|
|
public static authenticate(req:Request, res:Response, next:NextFunction){
|
|
|
|
/* if (typeof req.session.user === 'undefined') {
|
2016-03-26 18:19:10 +08:00
|
|
|
return next(new Error(ErrorCodes.NOT_AUTHENTICATED));
|
2016-03-27 02:24:12 +08:00
|
|
|
}*/
|
2016-04-10 00:06:29 +08:00
|
|
|
//TODO: uncomment
|
2016-03-20 00:31:42 +08:00
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static authorise(role:UserRoles){
|
|
|
|
return (req:Request, res:Response, next:NextFunction) => {
|
|
|
|
if (req.session.user.role < role) {
|
2016-03-26 18:19:10 +08:00
|
|
|
return next(new Error(ErrorCodes.NOT_AUTHORISED));
|
2016-03-20 00:31:42 +08:00
|
|
|
}
|
|
|
|
return next();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
public static inverseAuthenticate(req:Request, res:Response, next:NextFunction){
|
|
|
|
if (typeof req.session.user !== 'undefined') {
|
2016-03-26 18:19:10 +08:00
|
|
|
return next(new Error(ErrorCodes.ALREADY_AUTHENTICATED));
|
2016-03-20 00:31:42 +08:00
|
|
|
}
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static login(req:Request, res:Response, next:NextFunction){
|
|
|
|
//not enough parameter
|
2016-03-20 23:54:30 +08:00
|
|
|
if ((typeof req.body === 'undefined') || (typeof req.body.loginCredential === 'undefined') || (typeof req.body.loginCredential.username === 'undefined') ||
|
|
|
|
(typeof req.body.loginCredential.password === 'undefined')) {
|
2016-03-20 00:31:42 +08:00
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
|
|
|
//lets find the user
|
|
|
|
UserManager.findOne({
|
2016-03-20 23:54:30 +08:00
|
|
|
username: req.body.loginCredential.username,
|
|
|
|
password: req.body.loginCredential.password
|
2016-03-20 00:31:42 +08:00
|
|
|
}, (err, result) => {
|
|
|
|
if ((err) || (!result)) {
|
2016-03-26 18:19:10 +08:00
|
|
|
return next(new Error(ErrorCodes.CREDENTIAL_NOT_FOUND));
|
2016-03-20 00:31:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
req.session.user = result;
|
|
|
|
|
|
|
|
return next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|