aboutsummaryrefslogtreecommitdiff
path: root/src/auth.ts
diff options
context:
space:
mode:
authorcjd242018-03-04 18:15:30 +0000
committercjd242018-03-04 18:15:30 +0000
commit955da66072042089cf457ab6406bfd7c97c4286f (patch)
tree379e4c4ea0bc008b3004b87b75bba8fc0348b18d /src/auth.ts
parentPlaying around trying to get a list of base tiles we may be interested in for... (diff)
parentImplement handling of unauthorised requests (diff)
downloadmedicine-955da66072042089cf457ab6406bfd7c97c4286f.tar.gz
medicine-955da66072042089cf457ab6406bfd7c97c4286f.zip

Merge branch ‘trh/payload-checker’ into cjd24/conversion

Diffstat (limited to 'src/auth.ts')
-rw-r--r--src/auth.ts167
1 files changed, 88 insertions, 79 deletions
diff --git a/src/auth.ts b/src/auth.ts
index a59e417..083357e 100644
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -1,41 +1,37 @@
+/* tslint:disable:prefer-function-over-method */
+
+import { RequestError } from './errors/errorware';
import { NextFunction, Request, Response, Router } from 'express';
-import * as expressJwt from 'express-jwt';
import * as jwt from 'jsonwebtoken';
import * as passport from 'passport';
import { Strategy } from 'passport-local';
import { default as User } from './db/model/User';
+import { Errorware } from './errors/errorware';
+
export class AuthRouter {
- public localStrategy: Strategy;
public router: Router;
public constructor() {
- this.localStrategy = Strategy();
- this.router();
+ this.router = Router();
this.init();
}
- // Used by passport-js to locate a user object from the database by username
- public findByUsername(username: string): User {
- if (username === user.username) {
- return user;
- }
- return false;
- }
+ // Middleware which generates token and sends it as response
+ public async genToken(req: Request, res: Response): Promise<void> {
+ const user: User | null = await User.findOne({
+ where: {
+ username: req.body.username
+ }
+ });
- // Find user object from database by user ID
- public findUserByID(id): User {
- if (id === user.id) {
- return user;
+ if (user === null) {
+ // Whoa, what an error!
+ return;
}
- return false;
- }
- // Middleware which generates token and sends it as response
- public genToken(req: Request, res: Response) {
- const userid = findUserByID(req.body.username);
- const token = jwt.sign(
- { id: userid },
+ const token: string = jwt.sign(
+ { id: user.username },
'Mr Secret',
{ expiresIn: 21600 }
);
@@ -48,89 +44,102 @@ export class AuthRouter {
});
}
+ private authenticate(req: Request, res: Response, next: NextFunction): void {
+ passport.authenticate(
+ 'local',
+ { session: false },
+ (err: Error, user: User) => {
+ // TODO: Implement
+ if (err) { throw err; }
+
+ if (!user) {
+ next(new RequestError(
+ 400, 'invalid_grant', 'Incorrect authentication details'
+ ));
+ }
+ }
+ );
+ next();
+ }
+
// Checks for errors within request before authentication
- public checkErr(req: Request, res: Response, next: NextFunction) {
+ public checkErr(req: Request, res: Response, next: NextFunction): void {
if (!req.body.grant_type || !req.body.username || !req.body.password) {
- res.status(400)
- .json({
- error: 'invalid_request',
- error_description: 'Missing parameters'
- });
- res.end();
+ next(new RequestError(400, 'invalid_request', 'Missing parameters'));
}
if (req.body.grant_type !== 'refresh_token'
&& req.body.grant_type !== 'password') {
- res.status(400)
- .json({
- error: 'unsupported_grant_type',
- error_description: 'invalid grant type'
- });
- res.end();
+ next(new RequestError(400, 'unsupported_grant_type', 'invalid grant type'));
}
next();
}
- // Handle error if user is unauthorised
- public unauthorisedErr(err, req: Request, res: Response, next: NextFunction) {
- if (err.name === 'UnauthorizedError') {
- res.status(401).json({
- status: 'error',
- error: 'not_authorised',
- error_description:
- 'user does not have correct authorisation to complete task'
- });
+ // Middleware to check privileges - admin
+ public isAdmin(req: Request, res: Response, next: NextFunction): void {
+ if (!req.user.admin) {
+ next(new RequestError(
+ 401, 'not_authorised',
+ 'user is not authorised to perform task'
+ ));
+ return;
}
next();
}
// Configure local strategy to use with passport-js.
- private configStrategy() {
- passport.use(new localStrategy( (username, password, done) => {
- const user = findByUsername(username);
+ private configStrategy(): void {
+ // tslint:disable-next-line:typedef
+ passport.use(new Strategy( async(username, password, done) => {
+ const user: User | null = await User.findOne({
+ where: {
+ username
+ }
+ });
- if (!user || user.password != password) {
+ if (!user || user.password !== password) {
return done(null, false);
}
return done(null, user);
}));
}
-}
-///////////////////////////////////////////////////
-
-const app = express();
-const ensureAuth = expressJwt({secret: 'Mr Secret'}); //protect routes
-app.use(passport.initialize());
-app.use(unauthorisedErr); //currently does not handle userdefined error
+ public init(): void {
+ this.configStrategy();
-app.post('/login', checkErr, function(req, res, next) {
- passport.authenticate('local', { session: false }, function(err, user) {
- if (err) { console.log(err); }
+ this.router.post('/login', this.checkErr, this.authenticate, this.genToken);
+ this.router.get(
+ '/logout',
+ (req: Request, res: Response): void => { req.logout(); }
+ );
+ }
+}
- if (!user) {
- res.status(400).json({
- error: 'invalid_grant',
- error_description: 'Incorrect authentication details'
- });
- }
- });
- next();
-}, genToken);
+// Handle error if user is unauthorised
+export const unauthorisedErr: Errorware =
+ (err: Error, req: Request, res: Response, next: NextFunction): void => {
+ console.log('fffff');
+ if (err.name === 'UnauthorizedError') {
+ console.log('efewfwf');
+ return next(new RequestError(
+ 401, 'not_authorised',
+ 'user does not have correct authorisation for task'
+ ));
+ }
+ next(err);
+};
-app.get('/logout', function(req, res) {
- req.logout();
-});
+const authRoutes: AuthRouter = new AuthRouter();
+authRoutes.init();
-app.get('/test', ensureAuth, function(req, res) {
- res.send('you are authenticated!');
-});
+export default authRoutes.router;
+///////////////////////////////////////////////////
/*
-tasks left:
- refreshing tokens
- connect to db
- revoke tokens/checking validity
- logging out
-*/
+ * tasks left:
+ * refreshing tokens
+ * connect to db
+ * revoke tokens/checking validity
+ * logging out
+ */