From e53741754d6f6039bc335a82e40af633e8a9762e Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Wed, 7 Mar 2018 13:33:01 +0000 Subject: Add documentation for some files --- src/app.ts | 46 +++++++++++++++++++++++++-- src/auth.ts | 83 +++++++++++++++++++++++++++++++++++++++---------- src/errors/errorware.ts | 63 ++++++++++++++++++++++++++++++++++++- 3 files changed, 171 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index bedffa4..bcb29ca 100644 --- a/src/app.ts +++ b/src/app.ts @@ -13,10 +13,31 @@ import { default as File } from './db/model/File'; import { default as Project } from './db/model/Project'; import { default as User } from './db/model/User'; +/** + * Configuration of the Express server app, including installation of + * various middleware functions. + */ + +/** + * The Class used to configure the Express app used in the server instance. + */ class App { + /** + * The Express app used throught the server. + */ public express: ex.Express; + + /** + * Whether or not logging is enabled on the server. + */ private readonly logEnabled: boolean = true; + /** + * Constructs an instance of the app, by loading middleware. + * + * @param enableLog Whether or not logging should be enabled on the + * server. + */ public constructor(enableLog: boolean) { this.logEnabled = enableLog; this.express = ex(); @@ -35,11 +56,13 @@ class App { this.errorware(); } - // Configure Express middleware. + /** + * Configures regular Express middleware. + */ private middleware(): void { this.express.use(expressJwt({secret: 'Mr Secret'}) .unless({path: [ - '/cs3099group-be-4/login', + '/cs3099group-be-4/oauth/token', '/cs3099group-be-4/_supported_protocols_' ] }) ); @@ -51,7 +74,9 @@ class App { this.express.use(bodyParser.urlencoded({ extended: false })); } - // Configure API endpoints. + /** + * Adds the Router routes to the Express app. + */ private mountRoutes(): void { const defRouter: ex.Router = ex.Router(); defRouter.get('/', (req: ex.Request, res: ex.Response): void => { @@ -75,11 +100,22 @@ class App { this.express.use('/', defRouter); } + /** + * Adds error-handling (4-arity) middleware to the Express app. + */ private errorware(): void { this.express.use(unauthorisedErr); this.express.use(errorHandler); } + /** + * Introduces variable-preconditioning middleware to the Express app. + * + * These middleware functions pre-process Express' matching variables + * in routes (e.g. `:project_name`). + * If an entity cannot be found in the database, the corresponding + * value is set to `null` instead. + */ private precondition(): void { // Fetch a user from their name: this.express.param( @@ -197,6 +233,10 @@ class App { } export default new App(true).express; + +/** + * A version of the app used only for testing. + */ export function TestApp() { return new App(false).express; } diff --git a/src/auth.ts b/src/auth.ts index 5a1707c..37f2f4c 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,5 +1,3 @@ -/* tslint:disable:prefer-function-over-method */ - import { RequestError } from './errors/errorware'; import { NextFunction, Request, Response, Router } from 'express'; import * as jwt from 'jsonwebtoken'; @@ -11,22 +9,41 @@ import { default as Project } from './db/model/Project'; import { Errorware } from './errors/errorware'; +/** + * The module for system authentication. + */ + +/** + * A class used to configure the authentication of the server. + */ export class AuthRouter { + /** + * The Express Router this authenticator is built on. + */ public router: Router; + /** + * A simple constructor that initialises the authenticator. + */ public constructor() { this.router = Router(); this.init(); } - // Middleware which generates token and sends it as response + /** + * A middleware function that generates an OAuth-like token, used for + * authentication in future interactions with the client. + * + * @param req The Express http request. + * @param res The Express http response. + */ public async genToken(req: Request, res: Response): Promise { const user: User | null = await User.findOne({ where: { username: req.body.username }, include: [ UserGroup, Project] - }); + }); if (user === null) { // Whoa, what an error! @@ -47,6 +64,13 @@ export class AuthRouter { }); } + /** + * Middleware used to authenticate the user, using previously-obtained + * OAuth-like tokens. + * + * @param req The Express http request. + * @param res The Express http response. + */ private authenticate(req: Request, res: Response, next: NextFunction): void { passport.authenticate( 'local', @@ -65,7 +89,13 @@ export class AuthRouter { next(); } - // Checks for errors within request before authentication + /** + * Middleware that checks the incoming request for missing or + * inaccurate properties, before the authentication process. + * + * @param req The Express http request. + * @param res The Express http response. + */ public checkErr(req: Request, res: Response, next: NextFunction): void { if (!req.body.grant_type || !req.body.username || !req.body.password) { next(new RequestError(400, 'invalid_request', 'Missing parameters')); @@ -79,8 +109,10 @@ export class AuthRouter { next(); } - - // Configure local strategy to use with passport-js. + + /** + * Used to configure Passport to use the custom authentication strategy. + */ private configStrategy(): void { // tslint:disable-next-line:typedef passport.use(new Strategy( async(username, password, done) => { @@ -93,11 +125,14 @@ export class AuthRouter { if (!user || user.password !== password) { return done(null, false); - } + } return done(null, user); })); } + /** + * Function used by the constructor to initialise the authenticator. + */ public init(): void { this.configStrategy(); @@ -109,7 +144,17 @@ export class AuthRouter { } } -// Handle error if user is unauthorised +/** + * Error-handling middleware used to handle authentication errors. + * + * The error is transformed into one that can be handled by later + * error-handling middleware functions. + * + * @param err The Error to handle/transform. + * @param req The Express http request. + * @param res The Express http response. + * @param next The next Express middleware function. + */ export const unauthorisedErr: Errorware = (err: Error, req: Request, res: Response, next: NextFunction): void => { console.log('fffff'); @@ -123,11 +168,18 @@ export const unauthorisedErr: Errorware = next(err); }; -// Middleware to check privileges - admin -export const isAdmin: any = -(req: Request, res: Response, next: NextFunction): void => { +/** + * A middleware to check whether or not the currently-authenticated User is + * an admin. + * + * @param req The Express http request. + * @param res The Express http response. + * @param next The next Express middleware function. + */ +export const isAdmin: any = +(req: Request, res: Response, next: NextFunction): void => { var isAdmin: boolean = req.user.object.userGroups.some((x: UserGroup): boolean => x.name === 'admin'); - + if (!isAdmin) { next(new RequestError( 401, 'not_authorised', @@ -138,10 +190,7 @@ export const isAdmin: any = next(); } -const authRoutes: AuthRouter = new AuthRouter(); -authRoutes.init(); - -export default authRoutes.router; +export default new AuthRouter().router; /////////////////////////////////////////////////// /* diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts index b01f83b..e28e6ae 100644 --- a/src/errors/errorware.ts +++ b/src/errors/errorware.ts @@ -1,5 +1,12 @@ import { NextFunction, Request, Response } from 'express'; +/** + * General error and error-handling logic for the middleware stack. + */ + +/** + * The body of the response to a client on errors. + */ export interface ErrorResponseBlock { status: string; error: string; @@ -9,7 +16,18 @@ export interface ErrorResponseBlock { error_data?: any; } +/** + * The custom-made Error format, containing enough information to send in + * response to a client. + */ export class RequestError extends Error { + /** + * Used to check that an object is specifically a RequestError. + * + * @param test The object to test. + * @returns `true` if the object is a [[RequestError]]; `false` + * otherwise. + */ public static is(test: Object): test is RequestError { const err: RequestError = test as RequestError; return err.code !== undefined @@ -17,11 +35,36 @@ export class RequestError extends Error { && err.responseBlock !== undefined; } + /** + * The http response code associated with the error. + */ public code: number; + + /** + * The user-friendly message that describes the error. + */ public userMessage?: string; + + /** + * Miscellaneous data associated with the error. + */ // tslint:disable-next-line:no-any public errorData?: any; + /** + * Constructs a [[RequestError]] using information intended to be sent + * to the client. + * + * @param errCode The http error-code. + * @param errName The descriptive name of the problem, for further + * detail from the error-code. + * @param errDescription A more verbose description based on the error + * name. + * @param errUserMessage A user-friendly version of the description, to + * possibly be displayed to the user. + * @param errData Miscellaneous data related to the error; probably + * used more during development. + */ public constructor( errCode: number = 500, errName: string = 'internal_server_error', @@ -48,11 +91,29 @@ export class RequestError extends Error { } } +/** + * The outside shell of an Express error-handling (_4-arity_) function. + * + * @param err The Error to act on. + * @param req The Express http request. + * @param res The Express http response. + * @param next The next Express middleware function to use; probably another + * [[Errorware]]. + */ export type Errorware = (err: Error, req: Request, res: Response, next: NextFunction) => void; +/** + * A terminal [[Errorware]] for sending errors to the user. + * Has special functionality for handling [[RequestError]]s, but can handle + * regular Errors too. + * + * @param err The Error to act on. + * @param req The Express http request. + * @param res The Express http response. + */ export const errorHandler: Errorware = - (err: Error, req: Request, res: Response, next: NextFunction): void => { + (err: Error, req: Request, res: Response): void => { if (RequestError.is(err)) { res.status(err.code) .json(err.responseBlock()); -- cgit v1.2.1