diff options
31 files changed, 2722 insertions, 451 deletions
diff --git a/Report/report.tex b/Report/report.tex index fb5e066..dae5b11 100644 --- a/Report/report.tex +++ b/Report/report.tex @@ -2,6 +2,10 @@ \usepackage[margin=1in]{geometry} \usepackage{graphicx} \usepackage{a4wide} +\usepackage{float} +\usepackage{listings} + +\graphicspath{graphics} \begin{document} \title{Report --- Juniour Honours Project Submission 1} @@ -10,6 +14,8 @@ \maketitle +\tableofcontents + \section{Requirements Overview} For our Junior Honours project, we are to design and create a database for a system which will be used primarily for the sharing and viewing @@ -25,7 +31,7 @@ Our database is to be: provide a user with a desirable output filetype. \item[Substitutable] The system should follow standardised communication protocols, to participate in a framework of modularised - systems created by the other Junior Honours groups. + systems created in conjunction with other Junior Honours groups. \end{description} \section{Using Scrum} @@ -38,7 +44,7 @@ required to address the frequent design changes. Throughout the project a Scrum board has been used to keep track of current tasks and further items to implement. A whiteboard in the John Honey main computer lab was used throughout this process. Examples of the board in use can be found in -Appendix A. +Appendix \ref{app:board}. The Scrum board made visualizing tasks and progression straightforward. Using it in meetings helped with determining how much was still to be done. @@ -55,14 +61,27 @@ Initially, we divided our total available time with the number of available task but over time experience from previous work and from previous meetings was helpful in refining the expected duration of the future tasks. This, combined with -the late reveal of the specification meant that work wqs done over holidays, greatly -warping the duration of several Sprints to be longer than anticipated. This is -evident in the burnout graphs provided for the period over December% -\footnote{The burnout graph we generated is available in Appendix B.}. +the late reveal of the specification meant that work was done over holidays, greatly +warping the duration of several Sprints to be longer than anticipated. + +\begin{figure}[H] +\centering + \includegraphics[width=\linewidth]{graphics/chart.png} + \caption{A Burn Down chart graphically representing average completion time of tasks} + \label{fig:burndown} +\end{figure} \subsection{Meetings} -... -\footnote{The minutes for formal meetings are available in Appendix C.} +Meetings were held every 1-3 weeks with the entire team. +They were carried out in person or, during the holidays, using +voice chat clients. + +Meetings helped members of the team understand what was being done by +other members of the team, particularly in areas were only one person +was working. They also helped the team decide on what was important to +attempt in the next Sprint. + +The minutes for formal meetings are available in Appendix \ref{app:meet}. \subsection{Paired Programming/Teamwork} Paired Programming was used extensively throughout implementation of basic server @@ -86,12 +105,94 @@ accommodate them, instead of persisting to the next Sprint. \section{Design Decisions} \subsection{Database} +\subsubsection{Security} Passwords in the database are currently stored totally unencrypted. Initially, -the focus of the team's work was on routing traffic, and for this purpose salting +the focus of work was on routing traffic, and for this purpose salting passwords is unnecessary. Once the server is past development phase, passwords will be encrypted in some secure fashion. +\subsubsection{File Representation} +File paths are stored in the database, represented as one-to-many parent-folder-to-file +mappings. This decision was made since all files will already have entries in the +database (such as metadata and their UUID), and adding the remainder of necessary +information for a file would be simple. + +While file paths are stored in the database, the file content itself will not be. +It has been specified that the system should be capable of storing large files, +and databases may struggle with the difficulties of storing variable-size Binary +Large Objects when said objects are of this scale. In addition, the breakdown and +caching of large images into image pyramids both increases the quantity of binary +data that will need to be stored, and greatly increases the number of reads and +writes carried out by the server on binary data. File systems, on the other hand, +are optimised for jobs of this kind. + +The resulting setup is a virtual filesystem that resembles a regular filesystem, +and a very flat physical filesystem: a root folder containing a folder for each +project, which in turn contain all non-folder files belonging to that particular project. +Keeping the files separated by folders named after their projects allows for simple +deletion of an entire project. + +All files in the database are given a UUID, which serves a number of functions: +\begin{enumerate} + \item It is the name of the file in the physical file system on disk, + \item It can be used to uniquely identify a file irrespective of its position + in the virtual file system, + \item It can be used to keep a reference to a file even if it is moved + (or even if it is deleted). +\end{enumerate} + +Examples of SQL queries using the structure described can be found in Appendix +\ref{app:sql}. + \subsection{Server Framework} +This practical requires a variety of utilities, and should be easy to document and +to understand from an outside perspective. Additionally, it was decided that for a +large project a language and platform that all members of the team were comfortable +with was a high priority. Finally, the system would need to be scalable, in the sense +that additional features should be easy to implement and plug in to the +already-functioning system. + +For these reasons, NodeJS and Typescript were chosen as the framework and language +for the project. + +\subsubsection{NodeJS} +NodeJS has a huge library (or \emph{package}) repository, providing teams with a wide variety of options on how to implement projects. Its ease of deployment on both *nix and Windows systems, +and its common IDE support make it ideal for team development. + +\subsubsection{Typescript} +While not every team member had previously used Typescript, all had used and are comfortable +with Javascript, and were willing to take on the slight increase in complexity for static +type checking. Typescript's compile-time checks and IDE integration remove the ambiguity of +Javascript from large projects, improving their scalability and maintainability as the project +increases in size. + +\subsubsection{ExpressJS} +A core package used by the project for client-server communication is the middleware handler +ExpressJS. This package allows for easy insertion and use of any number of middlewares, both created in-house +and imported from other packages. Uses for this multi-layer structure include authentication, user +permission checking, and wrapping responses with statuses. + +ExpressJS also handles client-server communication through a RESTful API. + +\begin{figure}[H] + \centering + \includegraphics[width=1.5in]{graphics/be-layer-structure.pdf} + \caption{Structure of Layers in a Server Instance} + \label{fig:layer} +\end{figure} + +\subsubsection{Sequelize (and Sequelize-Typescript)} +Sequelize was chosen as the ORM package to use to connect to the database server. It was chosen over other +similar packages for its variety of powerful features (such as eager loading) and its large user-base. +It can connect to a variety of SQL-dialect databases, and hides the low-level table interactions to create +a simple abstraction to Javascript objects. +Furthermore, it also has comprehensive and clear documentation, providing better access to these features. + +In addition to Sequelize is the add-on package Sequelize-Typescript: this improves Sequelize syntax to +accept ES6 classes with Typescript types as ORM model definitions, amongst other smaller improvements +made possible by Typescript's experimental annotation support. + +\subsubsection{Token-Based Authentication (Passport/JWT)} The protocol designed by the entire year uses a token-based authentication service similar to and inspired by OAuth2. Using token-based authentication removes the need for sessions or for cookies while still providing a smooth and secure user experience, @@ -100,16 +201,238 @@ It was decided that implementing OAuth2 in its entirety would be superfluous. OA relies on the acquisition of tokens from third parties, which would be unsuitable for a simple system such as this. +The Javascript package Passport was used for handling authentication through this protocol. +Passport's support for custom authentication services in addition to its synergy with ExpressJS middleware +support made it an obvious choice. + +For generating authentication "bearer" tokens, JWT was used. + \subsection{Testing Framework} -... +Testing was extensive and concurrent to the implementation in each Sprint. This was to ensure minimal time was spent debugging which then prevented the team from missing the Sprint deadlines. Unit testing was one of the primary methods of testing individual functionality. This was very useful for a modularised task as each module could be debugged without affecting other modules which were functioning as expected. Producing unit tests concurrently with the implementation of certain functionality gave the advantage of designing the functionality around the possible input or validation errors that may occur. MochaJS and ChaiJS were the JavaScript frameworks used for unit testing. These were chosen due to their simplicity of use and strong compatibility with TypeScript and Express.js. They both also allowed automation which increased efficiency and productivity. An example of tests that were performed include matching the response object for all routes to what is expected as defined by the protocols. + +Unit test were convenient for implementation, however, to be thorough further tests were applied whilst the server was actually running in order to ensure that different components work as expected as a larger unit. These particular tests were applied during the end of each implementation iteration as all components are needed. The process began by starting the server on a host machine and specific port. Then tools such as cURL and Postman helped act as the client, in order to send appropriate requests to the server. A set of requests were sent and the responses given were compared to the responses that were actually expected. Some stages resulted in server errors which described bugs in the system where previously we would not have foreseen. + +As well as testing the individual functionality of components, testing was also carried out on data types to ensure certain programming errors will be detected and reported. This was also completed using MochaJS and ChaiJS. + +Further testing is still in progress however this requires additional components to be added to the system in upcoming Sprints. One portion of testing includes producing a mock user interface in order to test integration further on with other sections of the system which are completed by other teams. A client-side SDK for each request is generated by SwaggerHub, which prevents any focus being applied to user interaction and keeps the back-end server as the main task. \section{Looking Ahead} \subsection{File Agnosticity} +It is the goal of a backend server to be able to support any file type possible as part of a project. These may be miscellaneous files that a user would like to store in the project, or it may also be a temporary file created by an HCI or ML service which is proprietary to the work they are carrying out. In the average case where a file is one of the Users’ complex image formats, or an excel spreadsheet perhaps - the server should be capable of converting this into a standardised file format that anything should be able to read. In particular, if a ‘Leica’ file is uploaded in ‘.scn’, our server should be capable of converting this into whatever resolution of sub pictures in PNG format so that we can ensure interoperability between components and clients. The server may still hold on to the original file and, in-fact would be expected to do so, but should only ever hand out standard formats from endpoints. In the case of Excel files (.xlsx), the server should be capable of transforming these sheets into ‘.csv’, to be read from another service, whilst maintaining the ability for clients to still download the original proprietary format. For example, if an ‘HCI’ client is connecting through a mobile phone, the client shouldn’t care which format an image was uploaded to a project in, as it should always send out a standard (PNG for images) format to remain type-agnostic. \subsection{Advanced Telemetry} +As part of professional development, an end goal was set to enable the server to be particularly self-aware through advanced telemetry monitoring. There are many benefits to this, mainly improved system performance to reduce bottlenecks, as well as being resilient to errors that may crop up with user interaction. +Some forms of telemetry considered were continually monitoring the kinds of requests that are coming in and check to see if they access similar locations. Then UUIDs could be cached with meta information such as hit count, and related files so that the sever could learn about the kinds of operations being carried out on it, and report back to some kind of systems admin. We could also start to preemptively carry out certain tasks such as unpacking and converting spatially adjacent images for files that are currently being browsed to reduce latency on further “panning” of the file for example. Statistics about this kind of operation could be gathered, such as time taken to complete and the time difference that was saved by doing so. These kinds of results would then be used to make an internal decision if some of the files should be “permanently” stored in some converted format. + +With regards to the scalability potential of running multiple instances, there is a plethora of further telemetry that can be gathered about connections made between instances, both with reference to the content in the database and the ACID/atomic properties which would need to be upheld, as well as with regards to the physical file distribution across multiple geographical nodes. +There could then be all kinds of algorithms to determine if files should be “invisibly” shuffled around behind the scenes to provide a more seamless experience for the end-user. \subsection{ACID Distribution} +\begin{figure} + \centering + \includegraphics[width=3in]{graphics/acid-echo.pdf} + \caption{A Server Instance Connected to an Echo Server as Part of a Distributed Network} + \label{fig:acid} +\end{figure} -\end{document} +Building on the atomic nature of a database transaction, and given the Users deployment scenario (multiple research facilities potentially across multiple geographically diverse locations), we thought it would be critical to allow the database to have multiple instances operating concurrently. Approximately how this would look, is that clients talk to the backend server they are physically closest to on the network for the lowest possible latency. However, since there can be multiple nodes to serve clients in different locations, the servers would need to make a "best attempt" to synchronise in an atomic manner. This would make the system far more scalable in the future, and may have potential applications for things such as a "live" backup server - since medical data is all fairly critical. +On top of the transactions to the Database being atomic and synchronised across all instances of the server, the physical distribution of file storage would additionally need to be considered. + +Since we made the design decision to store all of the actual files, outside of the database, then keeping atomic communication to each instance server does not necessarily solve the issue of file replication.For example, if a member of a group is working on a node other than the "root" node where that project was created and all of the data happens to be stored for it, then we will need to include some kind of notion of a "server reference" for each file known about by the database. +Then, if a client made a request for data not locally stored, it could either be re-directed by the server to the other node, or the server forwards the request then pipes it back to the client. + +Alternatively, as a further specialisation of this functionality, the server could intelligently detect related data to the "foreign" request being made, and pre-emptively load in the data from the alternate server, so it is ready to serve future data locally. This data could be cached locally and used, then re-synchronised if changes were made back to the original, or dropped if it was just for reading. It is likely however that most of these interactions will be reads, so activities such as carrying out a machine learning session on some data would only require the (potentially) smaller file containing the results to be synchronised back, which is a much easier task as it would likely just be new file upload to the remote server. +As part of professional development, an end goal was set to enable the server to be incredibly self aware through advanced telemetry monitoring. There are many benefits to this, mainly improved system performance to reduce bottlenecks, as well as being resilient to errors that may crop up with user interaction. +Some forms of telemetry considered were continually monitoring the kinds of requests that are coming in and check to see if they access similar locations. Then UUIDs could be cached with meta information such as hit count, and related files so that the sever could learn about the kinds of operations being carried out on it, and report back to some kind of systems admin. We could also start to preemptively carry out certain tasks such as unpacking and converting spatially adjacent images for files that are currently being browsed to reduce latency on further “panning” of the file for example. Statistics about this kind of operation could be gathered, such as time taken to complete and the time difference that was saved by doing so. These kinds of results would then be used to make an internal decision if some of the files should be “permanently” stored in some converted format. + +With regards the scalability potential of running multiple instances, there is a plethora of further telemetry that can be gathered about connections made between instances, both with reference to the content in the database and the acid/atomic properties which would need to be upheld, as well as with regards the physical file distribution across multiple geographical nodes. +There could then be all kinds of algorithms to determine if files should be “invisibly” shuffled around behind the scenes to provide a more seamless experience for the end-user +\appendix +\section{Scrum Board Images} \label{app:board} + +{ +\centering +\includegraphics[width=\textwidth]{graphics/4-12-17.jpg} +\includegraphics[width=\textwidth]{graphics/4-12-17-2.jpg} +\includegraphics[width=\textwidth]{graphics/8-1-18.jpg} +\includegraphics[width=\textwidth]{graphics/29-1-18.jpg} +\includegraphics[width=\textwidth]{graphics/5-2-18.jpg} +} + +\section{Scrum Meeting Minutes} \label{app:meet} +\begin{lstlisting} +Project Meeting minutes +Group project meeting 1 +Date: 10/11/17 +Topics: +Code type +User initial tasks and roles + + +Outcomes: + + +* Scrum +* Scrum master: Tom +* Product owner: Calum +* Code: + * Language: typescript + * Framework: NodeJS +* File conversion: + * On-the-fly - only keep original and convert when necessary +* OpenCdragon lib +* Networking: + * Express.js +* Storage: + * Database + * Storing json format for metadata + * Filepath for files +* Users, groups: + * Tokens - libraries? + * oauth -> which version? + * stored in tables - encryption +* Security: + * Per-file encryption + * Hash passwords + * not needed? +* Other: + * ask IT services for more user space + * Use teamspeak over christmas +* Deadline 5 days after we come back +* Next_Tasks: + * Tom: setup basic Node Server + * Get data from user on friday + * Design API + * Johannes: test file conversion libraries + * Calum: think about database format + * Make ER diagram and Schema + + +Group project meeting 2 pre sprint +Date: 4/12/17 +Topics: +Database type and design +Authorisation +Protocol +Set up first set of user stories +Setting up server + + +Outcomes: +* Database +* Postgres +* Talk about design +* Set up ER diagram +* Authentication and security +* Passport +* oauth tokens +* User stories- +* Setting up stubs for conforming to database +* Setting up database from ER diagram + + +Group project meeting 3 post sprint +Date: 8/12/17 +Topics: +Burnout chart +Evaluation of sprint +Setting next time for sprint +Change of scrum master and project + + +Outcomes: +* Change of roles +* Scrum master: Johannes +* Project Owner: Hafeez + + +Group project meeting 4 +Date: 8/1/18 +Topics +Storing files +Setting up mock HCI +Dealing with file types +Thinking About File type conversions + +Change of roles + +Outcomes +* Change of roles +* Scrum master: Calum +* Project Owner: Josh + + +Group project meeting 5 +Date: 28/1/18 +Topics: +Discuss previous sprint +Catching up on research Over Holidays +Planning How to Acheive First Deliverable + +Outcomes: +* Continuing on the Scrum board with realistic +goals of tasks that can be completed by the deadline +* Redistribution of work between members so that +everyone has an even share of the work + +Group project meeting 6 +Date: 3/2/18 +Topics: +User stories for sprint before first hand in. +What tasks we are leaving until next hand in + + +Outcomes: +* File conversions saving for future hand in +* Have a working demo for following hand in +* User stories +* Is the Epic User Story achievable by the end of the year? + +Discuss previous sprint +Discuss how to present hand in + + +Outcomes: +* Responsibilities +\end{lstlisting} + +\section{Example SQL Queries on File System} \label{app:sql} +\subsection{Example 1} +To locate an image called image1 at folder1/folder2/folder3/image1 to find it you would use the queries: +\begin{lstlisting}[language=SQL] +SELECT * FROM dirent + NATURAL JOIN folder WHERE + folder_name = 'folder1' AND + super_folder is null AND + project_name = 'project 1'; +SELECT * FROM dirent WHERE + super_folder = '77dea3b7-523e-463a-aff1-3d8b92259fbb'; +SELECT * FROM dirent WHERE + super_folder = '12596fe5-2838-4cc0-8d2f-4745e91738f5'; +SELECT * FROM dirent + NATURAL JOIN image WHERE + super_folder = '22b94214-6942-40dd-b8af-deb1371fa298'; +\end{lstlisting} + +From this directory, if you wanted to find dirents contained within folder 2 you could use the +queries: +\begin{lstlisting}[language=SQL] +SELECT * FROM dirent WHERE + id = '22b94214-6942-40dd-b8af-deb1371fa298'; +SELECT * FROM dirent + WHERE super_folder = '12596fe5-2838-4cc0-8d2f-4745e91738f5'; +\end{lstlisting} + +\subsection{Example 2} +Using: +\begin{lstlisting}[language=SQL] +INSERT INTO + project ("project_name", "owner") + VALUES ('project 1', 'josh') +\end{lstlisting} + +Would give all permissions to josh in project 1. + +\end{document} diff --git a/getmepostgres.sh b/getmepostgres.sh index 50976f8..035b300 100755 --- a/getmepostgres.sh +++ b/getmepostgres.sh @@ -1,26 +1,27 @@ #!/bin/bash -echo "> Checking for postgres at ~/pg"; -if [ -d "~/pg" ]; then +PGDIR=${1-"$HOME/pg"} + +echo "> Checking for postgres at $PGDIR"; +if [ -d "$PGDIR" ]; then echo "Postgres Directory exists, nevermind..."; exit 1; fi -echo " "; -echo " "; -echo " "; +echo; +echo; +echo; echo "This installation process takes ~3:50 minutes to complete."; -echo " "; -echo " "; -echo " "; -sleep 3; +echo; +echo; +echo; -echo "> Making postgres directory at ~/pg"; -mkdir ~/pg; +echo "> Making postgres directory at $PGDIR"; +mkdir -p "$PGDIR"; currentDir=$(pwd); -echo "> Chaning dir to ~/pg"; -cd ~/pg; +echo "> Changing dir to $PGDIR"; +cd "$PGDIR"; echo "> Cloning Repo"; git clone https://github.com/postgres/postgres.git; @@ -30,34 +31,34 @@ cd ./postgres; git reset --hard REL_10_1; echo "> Configuring"; -./configure --prefix=$HOME/pg/postgres/ --with-python PYTHON=/usr/bin/python2.7; +./configure --prefix="$PWD" --with-python PYTHON="/usr/bin/python2.7"; echo "> Building Postgres"; -make -j 5; +make; echo "> Installing Postgres"; make install; echo "> Initialise the Database"; -~/pg/postgres/bin/initdb -D ~/pg/postgres/data/; -echo " "; -echo " "; -echo " "; -echo " "; +"$PGDIR/postgres/bin/initdb" -D "$PGDIR/postgres/data/"; +echo; +echo; +echo; +echo; echo "> Starting the postgres server"; -~/pg/postgres/bin/pg_ctl -D ~/pg/postgres/data/ -l POSTGRES_logfile start; +"$PGDIR/postgres/bin/pg_ctl" -D "$PGDIR/postgres/data/" -l POSTGRES_logfile start; echo "> Create the Database"; -~/pg/postgres/bin/createdb be4; +"$PGDIR/postgres/bin/createdb" be4; echo "> Creating Admin user"; -~/pg/postgres/bin/psql -U ${USER} postgres -c "CREATE USER admin WITH PASSWORD 'eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af';"; +"$PGDIR/postgres/bin/psql" -U ${USER} postgres -c "CREATE USER admin;"; echo "> Granting Admin Permissions"; -~/pg/postgres/bin/psql -U ${USER} postgres -c "ALTER DATABASE be4 OWNER TO admin;"; +"$PGDIR/postgres/bin/psql" -U ${USER} postgres -c "ALTER DATABASE be4 OWNER TO admin;"; -echo " "; -echo " "; -echo " "; -echo " "; -echo " "; +echo; +echo; +echo; +echo; +echo; echo "> Completed the installation of Postgres."; cd $currentDir; diff --git a/package.json b/package.json index 4a072d6..8359cf3 100644 --- a/package.json +++ b/package.json @@ -4,9 +4,7 @@ "main": "index.ts", "license": "UNLICENSED", "scripts": { - "test": "mocha --reporter spec -r ts-node/register './test/**/*.test.ts'", - "test:routes": "mocha --reporter spec -r ts-node/register './test/**/*.routes.test.ts'", - "test:unit": "mocha --reporter spec -r ts-node/register './test/**/*.unit.test.ts'", + "test": "mocha --reporter spec -r ts-node/register './**/*.test.ts'", "docs": "typedoc --out 'docs' --readme 'README.md' --name 'St Andrews Junior Honours 2017/18 - Team BE4' --module commonjs --target ES5 --exclude '*.test.ts' --includeDeclarations --excludeExternals 'src'", "start": "ts-node src/index.ts", "lint": "tslint --fix --force -p './tsconfig.json'", @@ -29,6 +27,7 @@ "@types/chai-http": "0.0.29", "@types/debug": "0.0.29", "@types/mocha": "^2.2.32", + "@types/mocha-each": "^1.1.0", "chai": "^3.5.0", "chai-http": "^3.0.0", "mocha": "^3.1.2", @@ -39,13 +38,22 @@ "dependencies": { "@types/body-parser": "0.0.33", "@types/express": "^4.0.33", + "@types/express-jwt": "^0.0.38", + "@types/jsonwebtoken": "^7.2.5", "@types/morgan": "^1.7.32", "@types/node": "^6.0.46", + "@types/passport": "^0.4.2", + "@types/passport-local": "^1.0.32", "@types/sequelize": "^4.27.5", + "@types/uuid": "^3.4.3", "body-parser": "^1.18.2", "express": "^4.16.2", + "express-jwt": "^5.3.0", + "jsonwebtoken": "^8.1.1", "mocha-each": "^1.1.0", "morgan": "^1.9.0", + "passport": "^0.4.0", + "passport-local": "^1.0.0", "pg": "^7.4.1", "pg-hstore": "^2.3.2", "reflect-metadata": "^0.1.12", @@ -53,6 +61,7 @@ "sequelize-typescript": "^0.6.2", "ts-node": "^3.3.0", "typescript": "^2.7.1", + "uuid": "^3.2.1", "xlsx": "^0.11.19" } } diff --git a/package_old.json b/package_old.json new file mode 100644 index 0000000..35f0f7f --- /dev/null +++ b/package_old.json @@ -0,0 +1,68 @@ +{ + "name": "cs3099jhbe4", + "description": "2017 Junior Honours Project - Backend Group 4", + "main": "index.ts", + "license": "UNLICENSED", + "scripts": { + "test": "mocha --reporter spec -r ts-node/register './test/**/*.test.ts'", + "test:routes": "mocha --reporter spec -r ts-node/register './test/**/*.routes.test.ts'", + "test:unit": "mocha --reporter spec -r ts-node/register './test/**/*.unit.test.ts'", + "docs": "typedoc --out 'docs' --readme 'README.md' --name 'St Andrews Junior Honours 2017/18 - Team BE4' --module commonjs --target ES5 --exclude '*.test.ts' --includeDeclarations --excludeExternals 'src'", + "start": "ts-node src/index.ts", + "lint": "tslint --fix --force -p './tsconfig.json'", + "_gl-lint": "tslint -p './tsconfig.json'" + }, + "repository": { + "type": "git", + "url": "https://gitlab.cs.st-andrews.ac.uk/cs3099group-be-4/project-code.git" + }, + "keywords": [ + "backend", + "database", + "university", + "honours", + "project" + ], + "author": "2017 Junior Honours Backend Group 4", + "devDependencies": { + "@types/chai": "^3.4.34", + "@types/chai-http": "0.0.29", + "@types/debug": "0.0.29", + "@types/mocha": "^2.2.32", + "@types/mocha-each": "^1.1.0", + "chai": "^3.5.0", + "chai-http": "^3.0.0", + "mocha": "^5.0.1", + "nodemon": "^1.14.10", + "tslint": "^5.9.1", + "typedoc": "^0.10.0" + }, + "dependencies": { + "@types/body-parser": "0.0.33", + "@types/express": "^4.0.33", + "@types/express-jwt": "^0.0.38", + "@types/jsonwebtoken": "^7.2.5", + "@types/morgan": "^1.7.32", + "@types/node": "^6.0.46", + "@types/passport": "^0.4.2", + "@types/passport-local": "^1.0.32", + "@types/sequelize": "^4.27.5", + "body-parser": "^1.18.2", + "express": "^4.16.2", + "express-jwt": "^5.3.0", + "jsonwebtoken": "^8.1.1", + "mocha-each": "^1.1.0", + "morgan": "^1.9.0", + "passport": "^0.4.0", + "passport-local": "^1.0.0", + "pg": "^7.4.1", + "pg-hstore": "^2.3.2", + "reflect-metadata": "^0.1.12", + "sequelize": "^4.32.7", + "sequelize-typescript": "^0.6.2", + "supertest": "^3.0.0", + "ts-node": "^5.0.0", + "typescript": "^2.7.1", + "xlsx": "^0.11.19" + } +} diff --git a/runmepostgres.sh b/runmepostgres.sh index 632ea66..dfa5764 100755 --- a/runmepostgres.sh +++ b/runmepostgres.sh @@ -1,8 +1,10 @@ #!/bin/bash +PGDIR=${1-"$HOME/pg"} + read -p "Press [Enter] key to start Postgres (will already be running if you just got it) use ctl+c to cancel"; echo "> Starting Server"; -~/pg/postgres/bin/pg_ctl -D ~/pg/postgres/data/ -l POSTGRES_logfile start; +"$PGDIR/postgres/bin/pg_ctl" -D "$PGDIR/postgres/data/" -l POSTGRES_logfile start; -#echo "> Conecting as admin user: " + ${USER}; -#~/pg/postgres/bin/psql -U ${USER} postgres; +echo "> Conecting as admin user: " + ${USER}; +"$PGDIR/postgres/bin/psql" -U ${USER} postgres; diff --git a/src/FileRouter.ts b/src/FileRouter.ts index 7d3d549..8d13401 100644 --- a/src/FileRouter.ts +++ b/src/FileRouter.ts @@ -1,6 +1,20 @@ +import { ContributorGroupFullInfo, default as ContributorGroup + } from './db/model/ContributorGroup'; +import { default as File } from './db/model/File'; +import { ProjectFullInfo, default as Project } from './db/model/Project'; +import { UserFullInfo, default as User } from './db/model/User'; +import { default as UserGroup } from './db/model/UserGroup'; + import { NextFunction, Request, Response, Router } from 'express'; -import { Property, default as serverConfig, - propertyExists } from './serverConfig'; + +import { RequestError } from './errors/errorware'; +import { files } from './files'; +import { logger } from './logger'; +import { Property, default as serverConfig } from './serverConfig'; +import { uuid } from './uuid'; + +// TODO: figure this out +const BASE_FILE_STORAGE: string = 'TODO: figure this out'; /** * The type of an Express middleware callback. @@ -8,415 +22,502 @@ import { Property, default as serverConfig, type Middleware = (req: Request, res: Response, next: NextFunction) => void; -/* +/** * Returns the supported Protocols * * The server's unwrapped response MUST match: - - exactly({ - "supported": array(string), - "required": array(string) - }) + * + * exactly({ + * "supported": array(string), + * "required": array(string) + * }) */ const getProtocols: Middleware = (req: Request, res: Response, next: NextFunction): void => { - const returnValue: { - supported: string[]; - required: string[]; - } = { - supported: [ - 'BE50' - ], + res.locals.data = { + supported: [], required: [ 'BE01' ] }; - res.send(JSON.stringify(returnValue)); + next(); }; -/* +/** * Logging Endpoint for all components: * * with a request matching - - array({ - "component": string, - "level": alternative([ - "info", "security", "warning", "error", "critical" - ]), - "value": anything - }) + * + * array({ + * "component": string, + * "level": alternative([ + * "info", + * "security", + * "warning", + * "error", + * "critical" + * ]), + * "value": anything + * }) */ const postLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(501) - .send({error: 'logging_not_enabled'}); + if (!req.user.hasPrivilege('logging')) { + next(new RequestError(400, 'invalid_privilege')); + return; + } else if (!logger.isEnabled()) { + next(new RequestError(501, 'logging_not_enabled')); + return; + } + for (const item of req.body) { + logger.log(item.level, item.value, { + component: item.component, + user: req.user.username, + external: true + }); + } + next(); }; -/* +/** * Clients authorised as a user with the admin privilege can access * * http://backend.endpoint/log?before=<datetime>&after=<datetime>&level=<level> * * the server response should match - - array({ - "component": string, - "level": alternative( - ["info", "security", "warning", "error", "critical" - ]), - "value": anything, - "username": string, - "timestamp": string - }) + * + * array({ + * "component": string, + * "level": alternative([ + * "info", + * "security", + * "warning", + * "error", + * "critical" + * ]), + * "value": anything, + * "username": string, + * "timestamp": string + * }) */ const getLog: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(501) - .send({error: 'logging_not_enabled'}); + if (!req.user.hasPrivilege('admin')) { + next(new RequestError(400, 'invalid_privilege')); + } + res.locals.data = logger.fetch( + req.params.level, { + before: new Date(req.params.before), + after: new Date(req.params.after) + } + ); + next(); }; -/* +/** * Any authenticated client can access * * http://backend.endpoint/properties * * the server SHOULD respond with a list of properties, * with the unwrapped response matching - - array({ - "id": string, - "display": optional({ - "category": string, - "group": string, - "display_name": string, - "description": string - }), - "read_only": boolean, - "type": alternative(["string", "integer", "boolean"]), - "value": alternative([string, integer, boolean]) - }) + * + * array({ + * "id": string, + * "display": optional({ + * "category": string, + * "group": string, + * "display_name": string, + * "description": string + * }), + * "read_only": boolean, + * "type": alternative(["string", "integer", "boolean"]), + * "value": alternative([string, integer, boolean]) + * }) */ const getProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.send(serverConfig); + res.locals.data = serverConfig; + next(); }; -/* +/** * To update properties the client POSTs to * * http://backend.endpoint/properties?action=update * * with body - - array({ - "id": string, - "value": alternative([string, integer, boolean]) - }) + * + * array({ + * "id": string, + * "value": alternative([string, integer, boolean]) + * }) */ const postProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { - let success: boolean = true; - - // For each property to update - let prop: Property; - for (prop of req.body) { - - // Check that the property has an ID and a value - if (!prop.hasOwnProperty('id') || !prop.hasOwnProperty('value')) { - res.status(400) - .send({ - error: 'invalid_request', - error_description: 'A supplied property is missing an id or value' - }); - success = false; - break; + for (const newProp of req.body) { + const prop: Property | undefined = serverConfig.find( + (p: Property): boolean => p.id === newProp.id + ); + if (prop === undefined) { + next(new RequestError(400, 'invalid_property', undefined, newProp.id)); + return; + } else if (prop.readOnly) { + next(new RequestError(400, 'invalid_property', undefined, newProp.id)); + return; } - - // Find out if the property exists in the config and if so, at which index - const index: number = propertyExists(prop.id); - - // Check some of the properties values to ensure that it can be updated - if (index === -1 || serverConfig[index].readOnly) { - /* TODO Implement an or, using Tom's type checker to ensure - * the value is "valid" based on the type of the property */ - const description: string = - index === -1 - ? 'Property not found' - : 'Property is Read_Only'; - res.status(400) - .send({ - error: 'invalid_property', - error_data: prop.id, - error_description: description - }); - success = false; - break; + try { + prop.value = newProp.value; + } catch (err) { + // FIXME: Assuming it's a value-type error, but it might not be! + next(new RequestError(400, 'invalid_property_value', undefined, newProp.id)); + return; } - - // Make the update to the property - serverConfig[index].value = prop.value; - } - - // Tell the client that everything was okay; - if (success) { - res.status(200) - .send(); } + next(); }; -/* +/** * Listing available privileges * * And the server's response, unwrapped, must match - - array({ - "privilege": string, - "description": string, - "internal": boolean - }) + * + * array({ + * "privilege": string, + * "description": string, + * "internal": boolean + * }) */ -const getUserPriveleges: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); +const getUserPrivileges: Middleware = + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + const usergroups: UserGroup[] = await UserGroup.findAll(); + res.locals.data = usergroups.map( + (ug: UserGroup) => ug.getPrivilege() + ); + next(); }; -/* +/** * Listing users * * If the client is authorised as a user with the admin privilege * the server MUST respond with a list of users, * with the unwrapped response matching - - array({ - "username": string, - "privileges": array(string), - "projects": array({ - "project_name": string, - "access_level": string - }), - "public_user_metadata": metadata, - "private_user_metadata": metadata, - "public_admin_metadata": metadata, - "private_admin_metadata": metadata - }) + * + * array({ + * "username": string, + * "privileges": array(string), + * "projects": array({ + * "project_name": string, + * "access_level": string + * }), + * "public_user_metadata": metadata, + * "private_user_metadata": metadata, + * "public_admin_metadata": metadata, + * "private_admin_metadata": metadata + * }) */ const getUsers: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); - + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + const users: User[] = await User.findAll({ + include: [ + UserGroup, + Project + ] + }); + res.locals.data = users.map<UserFullInfo>( + (u: User) => { + const info: UserFullInfo = u.fullInfo; + if (!req.user.hasPrivilege('admin')) { + delete info.private_user_metadata; + delete info.private_admin_metadata; + } + return info; + } + ); + next(); }; -/* - * expose additional configuration options for individual users - * - * +/** + * Expose additional configuration options for individual users */ const getUserProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + res.locals.data = res.locals.user.properties; + next(); }; -/* +/** * Listing a particular User * * If the client is authorised as a user with the admin privilege - * the server MUST respond with details of the particular user - * if they exist (unwrapped response): - - { - "username": string, - "privileges": array(string), - "projects": array({ - "project_name": string, - "access_level": string - }), - "public_user_metadata": metadata, - "private_user_metadata": metadata, - "public_admin_metadata": metadata, - "private_admin_metadata": metadata - } + * the server MUST respond with details of the particular user if they exist + * (unwrapped response): + * + * { + * "username": string, + * "privileges": array(string), + * "projects": array({ + * "project_name": string, + * "access_level": string + * }), + * "public_user_metadata": metadata, + * "private_user_metadata": metadata, + * "public_admin_metadata": metadata, + * "private_admin_metadata": metadata + * } */ -const getUsername: - (req: Request, res: Response, next: NextFunction, user?: string) => void = - (req: Request, res: Response, next: NextFunction, user?: string): void => { - res.status(500) - .send(); +const getUsername: Middleware = + (req: Request, res: Response, next: NextFunction): void => { + if (res.locals.user === null) { + next(new RequestError(404, 'user_not_found')); + return; + } + res.locals.data = res.locals.user.fullInfo; + next(); }; const getCurUser: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); - const curUser: string = ''; - getUsername(req, res, next, curUser); + res.locals.data = req.user.fullInfo; + next(); }; -/* +/** * Updating the current user * * http://backend.endpoint/current_user?action=update * * with body matching - - { - "password": optional({ - "old": string, - "new": string - }), - "public_user_metadata": optional(metadata), - "private_user_metadata": optional(metadata), - "public_admin_metadata": not_present, - "private_admin_metadata": not_present - } -*/ + * + * { + * "password": optional({ + * "old": string, + * "new": string + * }), + * "public_user_metadata": optional(metadata), + * "private_user_metadata": optional(metadata), + * "public_admin_metadata": not_present, + * "private_admin_metadata": not_present + * } + */ const postCurUser: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + try { + await req.user.updateInfo(req.body); + await req.user.save(); + } catch (err) { + next(err); + return; + } + next(); }; -/* +/** * Creating a User/updating a user * * http://backend.endpoint/users/<username>?action=create * * with body matching - - { - "privileges": array(string), - "password": string, - "public_user_metadata": optional(metadata), - "private_user_metadata": optional(metadata), - "public_admin_metadata": optional(metadata), - "private_admin_metadata": optional(metadata) - } + * + * { + * "privileges": array(string), + * "password": string, + * "public_user_metadata": optional(metadata), + * "private_user_metadata": optional(metadata), + * "public_admin_metadata": optional(metadata), + * "private_admin_metadata": optional(metadata) + * } */ const postUsername: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + let user: User | null | undefined = res.locals.user; + if (user == null) { + user = new User({ + username: req.params.username, + password: req.params.password + }); + } else { + user.password = req.params.password; + } + user.metadata = req.body; + next(); }; -/* +/** * Listing available Roles * * The servers response, unwrapped, must match - - array({ - "role": string, - "description": string, - "internal": boolean - }) + * + * array({ + * "role": string, + * "description": string, + * "internal": boolean + * }) */ const getProjectRoles: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + const roles: ContributorGroup[] = await ContributorGroup.findAll(); + res.locals.data = roles.filter( + (cg: ContributorGroup): boolean => !cg.isInternal + ).map( + (cg: ContributorGroup): ContributorGroupFullInfo => cg.fullInfo + ); + next(); }; -/* +/** * Listing Projects * * The server MUST respond with a list of projects, * with the unwrapped response matching - - array({ - "project_name": string, - "users": array({ - "username": string, - "access_level": string - }), - "public_metadata": metadata, - "private_metadata": optional(metadata), - "admin_metadata": optional(metadata) - }) + * + * array({ + * "project_name": string, + * "users": array({ + * "username": string, + * "access_level": string + * }), + * "public_metadata": metadata, + * "private_metadata": optional(metadata), + * "admin_metadata": optional(metadata) + * }) */ const getProjects: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + const projects: Project[] = await Project.findAll({ + include: [ + User + ] + }); + res.locals.data = projects.map( + (p: Project): ProjectFullInfo => p.fullInfo + ); + next(); }; -/* +/** * Listing a specific Project * * The server MUST respond with details of the particular project * if it exists (unwrapped response): - - { - "project_name": string, - "users": array({ - "username": string, - "access_level": string - }), - "public_metadata": metadata, - "private_metadata": metadata, - "admin_metadata": optional(metadata) - } + * + * { + * "project_name": string, + * "users": array({ + * "username": string, + * "access_level": string + * }), + * "public_metadata": metadata, + * "private_metadata": metadata, + * "admin_metadata": optional(metadata) + * } */ const getProjectName: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + const project: Project | null = res.locals.project; + if (project === null) { + next(new RequestError(404, 'project_not_found')); + } else { + res.locals.data = project.fullInfo; + next(); + } }; -/* +/** * Creating a Project / updating a project / deleting / Project grants * * http://backend.endpoint/projects/<project_name>?action=create * * with body matching - - { - "public_metadata": optional(metadata), - "private_metadata": optional(metadata), - "admin_metadata": optional(metadata) - } + * + * { + * "public_metadata": optional(metadata), + * "private_metadata": optional(metadata), + * "admin_metadata": optional(metadata) + * } */ const postProjectName: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + let project: Project | null = res.locals.project; + let promise: PromiseLike<File> | null = null; + if (project === null) { + const file: File = new File({ + mimetype: 'inode/directory' + }); + promise = file.save(); + project = new Project({ + uuid: uuid.generate(), + name: req.params.project_name, + rootFolder: file + }); + } + project.metadata = req.body; + // tslint:disable-next-line:await-promise + await promise; + await project.save(); + next(); }; -/* +/** * additional configuration options for individual projects */ const getProjectProperties: Middleware = (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + if (res.locals.project == null) { + next(new RequestError(404, 'project_not_found')); + } else { + res.locals.data = res.locals.project.properties; + next(); + } }; /** * GET a File. */ const getFilePath: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + async(req: Request, res: Response, next: NextFunction): Promise<void> => { + const file: File | null = res.locals.file; + if (file === null) { + next(new RequestError(404, 'file_not_found')); + return; + } + res.locals.function = res.sendFile; + res.locals.data = + `${BASE_FILE_STORAGE}/${res.locals.project.name}/${file.uuid}`; + next(); }; /** * GET a File. */ const getFileId: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + (req: Request, res: Response, next: NextFunction): void => { + const file: File | null = res.locals.file; + if (file === null) { + next(new RequestError(404, 'file_not_found')); + return; + } + res.locals.function = res.sendFile; + res.locals.data = files.path(req.params.id, res.locals.project.name); + next(); }; /** * Post a File. / delete / move / etc */ const postFilePath: Middleware = - (req: Request, res: Response, next: NextFunction): void => { - res.status(500) - .send(); + (req: Request, res: Response, next: NextFunction): void => { + if (res.locals.file != null) { + next(new RequestError(400, 'file_exists')); + } + const file: File = new File({ + uuid: uuid.generate(), + name: res.locals.filename, + parentFolder: res.locals.parentFolder + }); + req.pipe(files.writableStream(file.uuid, res.locals.project.name)); + next(); }; export class FileRouter { @@ -436,13 +537,13 @@ export class FileRouter { */ public init(): void { // General - this.router.get ('/_supported_protocols_', getProtocols); + this.router.get ('/_supported_protocols_', getProtocols); this.router.get ('/log', getLog); this.router.post('/log', postLog); this.router.get ('/properties', getProperties); this.router.post('/properties', postProperties); // Users - this.router.get ('/user_privileges', getUserPriveleges); + this.router.get ('/user_privileges', getUserPrivileges); this.router.get ('/users', getUsers); this.router.get ('/users/:username', getUsername); this.router.post('/users/:username', postUsername); @@ -1,23 +1,50 @@ import * as bodyParser from 'body-parser'; import * as ex from 'express'; -import FileRouter from './FileRouter'; +import * as expressJwt from 'express-jwt'; import * as logger from 'morgan'; +import * as passport from 'passport'; + +import { default as authRouter } from './auth'; + +import { RequestError, errorHandler } from './errors/errorware'; +import FileRouter from './FileRouter'; + +import { default as File } from './db/model/File'; +import { default as Project } from './db/model/Project'; +import { default as User } from './db/model/User'; class App { public express: ex.Express; - private logEnabled: boolean; + private logEnabled: boolean = true; public constructor(enableLog: boolean) { + this.logEnabled = enableLog; this.express = ex(); + this.precondition(); this.middleware(); this.mountRoutes(); - this.logEnabled = enableLog; + this.express.use( + async(req: ex.Request, res: ex.Response, next: ex.NextFunction): + Promise<void> => { + res.json({ + status: 'success', + data: await res.locals.data + }); + } + ); + this.errorware(); } // Configure Express middleware. private middleware(): void { + this.express.use(expressJwt({secret: 'Mr Secret'}) + .unless({path: [ + '/cs3099group-be-4/login', + '/cs3099group-be-4/_supported_protocols_' + ] }) + ); + this.express.use(passport.initialize()); if (this.logEnabled) { - console.log("log enabled") this.express.use(logger('combined')); } this.express.use(bodyParser.json()); @@ -30,7 +57,7 @@ class App { defRouter.get('/', (req: ex.Request, res: ex.Response): void => { res.json({ message: 'Welcome to the CS3099 BE4 server!', - important : 'Endpoints start from /cs3099group-be-4/' + important: 'Endpoints start from /cs3099group-be-4/' }); }); defRouter.get('/*', (req: ex.Request, res: ex.Response): void => { @@ -44,11 +71,132 @@ class App { }); }) this.express.use('/cs3099group-be-4', FileRouter); + this.express.use('/cs3099group-be-4', authRouter); this.express.use('/', defRouter); } + + private errorware(): void { + // TODO: this.express.use(authRouter.unauthorisedErr); + this.express.use(errorHandler); + } + + private precondition(): void { + // Fetch a user from their name: + this.express.param( + 'username', + async( + req: ex.Request, res: ex.Response, next: ex.NextFunction, + name: string + ): Promise<void> => { + const user: User | null = await User.findOne({ + where: { + username: name + } + }); + if (user === null) { + next(new RequestError(404, 'user_not_found')); + return; + } else { + res.locals.user = user; + } + next(); + } + ); + + // Fetch a project from its name: + this.express.param( + 'project_name', + async( + req: ex.Request, res: ex.Response, next: ex.NextFunction, + project: string + ): Promise<void> => { + res.locals.project = await Project.findOne({ + where: { + name: project + } + }); + next(); + } + ); + + // Fetch a file from its path: + this.express.param( + 'file', + async( + req: ex.Request, res: ex.Response, next: ex.NextFunction, + filename: string + ): Promise<void> => { + const fileNames: string[] = req.params.path.split('/'); + const project: Project | null = res.locals.project; + if (project === null) { + next(new RequestError(404, 'project_not_found')); + return; + } + let file: File = project.rootFolder; + // TODO Rewrite using sub-queries instead of repeated queries. + while (fileNames.length > 2) { + const fileOrNull: File | null = await File.findOne({ + where: { + name: fileNames[0], + parentFolder: file + } + }); + if (fileOrNull === null) { + next(); + return; + } else { + file = fileOrNull; + } + fileNames.splice(0, 1); + } + const parentFolder: File | null = await File.findOne({ + include: [ + { model: File, as: 'containedFiles' } + ], + where: { + parentFolder: file, + name: fileNames[0] + } + }); + if (parentFolder === null) { + next(); + return; + } + res.locals.parentFolder = parentFolder; + const tFile: File | undefined = parentFolder.containedFiles.find( + (f: File): boolean => f.name === fileNames[1] + ); + res.locals.file = tFile; + res.locals.filename = fileNames[1]; + next(); + } + ); + + // Fetch a file from its UUID: + this.express.param( + 'id', + async( + req: ex.Request, res: ex.Response, next: ex.NextFunction, + fileId: string + ): Promise<void> => { + const file: File | null = await File.findOne({ + where: { + uuid: fileId + } + }); + if (file === null) { + next(new RequestError(404, 'file_not_found')); + return; + } else { + res.locals.file = file; + } + next(); + } + ); + } } export default new App(true).express; export function TestApp(){ return new App(false).express; -} +} diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..b40cddb --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,142 @@ +/* tslint:disable:prefer-function-over-method */ + +import { RequestError } from './errors/errorware'; +import { NextFunction, Request, Response, Router } from 'express'; +import * as jwt from 'jsonwebtoken'; +import * as passport from 'passport'; +import { Strategy } from 'passport-local'; +import { default as User } from './db/model/User'; + +export class AuthRouter { + public router: Router; + + public constructor() { + this.router = Router(); + this.init(); + } + + // 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 + } + }); + + if (user === null) { + // Whoa, what an error! + return; + } + + const token: string = jwt.sign( + { id: user.username }, + 'Mr Secret', + { expiresIn: 21600 } + ); + + res.json({ + token_type: 'bearer', + access_token: token, + refresh_token: token, + expires_in: 21600 + }); + } + + 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): void { + if (!req.body.grant_type || !req.body.username || !req.body.password) { + next(new RequestError(400, 'invalid_request', 'Missing parameters')); + } + + if (req.body.grant_type !== 'refresh_token' + && req.body.grant_type !== 'password') { + next(new RequestError(400, 'unsupported_grant_type', 'invalid grant type')); + } + + next(); + } + + // Handle error if user is unauthorised + public unauthorisedErr( + err: Error, req: Request, res: Response, next: NextFunction + ): void { + if (err.name === 'UnauthorizedError') { + next(new RequestError( + 401, 'not_authorised', + 'user does not have correct authorisation for task' + )); + } + next(); + } + + // 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(): 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) { + return done(null, false); + } + return done(null, user); + })); + } + + public init(): void { + this.configStrategy(); + + this.router.post('/login', this.checkErr, this.authenticate, this.genToken); + this.router.get( + '/logout', + (req: Request, res: Response): void => { req.logout(); } + ); + } +} + +const authRoutes: AuthRouter = new AuthRouter(); +authRoutes.init(); + +export default authRoutes.router; +/////////////////////////////////////////////////// + +/* + * tasks left: + * refreshing tokens + * connect to db + * revoke tokens/checking validity + * logging out + */ diff --git a/src/db/model/ContributorGroup.ts b/src/db/model/ContributorGroup.ts new file mode 100644 index 0000000..d3a5867 --- /dev/null +++ b/src/db/model/ContributorGroup.ts @@ -0,0 +1,54 @@ +import { AllowNull, Column, DataType, HasMany, Model, Table + } from 'sequelize-typescript'; +import { default as UserJoinsProject } from './UserJoinsProject'; + +@Table +export default class ContributorGroup extends Model<ContributorGroup> { + @AllowNull + @Column(DataType.TEXT) + public name!: string | null; + + /* "Error: Foreign key for "ContributorGroup" + * is missing on "UserJoinsProject"." */ + @HasMany(() => UserJoinsProject, 'contributorGroupId') + public uses?: UserJoinsProject[]; + + @Column + public canCreateFiles!: boolean; + + @Column + public canDeleteFiles!: boolean; + + @Column + public canViewFiles!: boolean; + + @Column + public canAddUsers!: boolean; + + @Column + public canRemoveUsers!: boolean; + + @Column + public canEditUserPermissions!: boolean; + + @AllowNull + @Column(DataType.TEXT) + public description!: string | null; + + @Column + public isInternal!: boolean; + + public get fullInfo(): ContributorGroupFullInfo { + return { + role: `${this.name}`, + description: `${this.description}`, + internal: this.isInternal + }; + } +} + +export interface ContributorGroupFullInfo { + role: string; + description: string; + internal: boolean; +} diff --git a/src/db/model/File.ts b/src/db/model/File.ts new file mode 100644 index 0000000..50c8e74 --- /dev/null +++ b/src/db/model/File.ts @@ -0,0 +1,59 @@ +import { default as Project } from './Project'; +import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, HasMany, + HasOne, Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript'; +import { default as User } from './User'; + +@Table +export default class File extends Model<File> { + @AllowNull + @Column + public name!: string; + + @PrimaryKey + @Column + public uuid!: string; + + @Column + public mimetype!: string; + + @ForeignKey(() => File) + @AllowNull + @Column(DataType.TEXT) + public parentFolderId!: string | null; + + @BelongsTo(() => File) + public parentFolder?: File; + + @HasMany(() => File) + public containedFilesInternal?: File[]; + + @ForeignKey(() => User) + @AllowNull + @Column(DataType.TEXT) + public creatorName!: string | null; + + @BelongsTo(() => User) + public creator?: User; + + @HasOne(() => Project) + public rootFolderOf?: Project; + + @CreatedAt + @Column + public uploadDate!: Date; + + @UpdatedAt + @Column + public modifyDate!: Date; + + public get containedFiles(): File[] { + if (this.containedFilesInternal === undefined) { + throw new Error('containedFiles is undefined'); + } + return this.containedFilesInternal; + } + + public set containedFiles(files: File[]) { + this.containedFilesInternal = files; + } +} diff --git a/src/db/model/Project.ts b/src/db/model/Project.ts new file mode 100644 index 0000000..388c5e5 --- /dev/null +++ b/src/db/model/Project.ts @@ -0,0 +1,136 @@ +import { default as ContributorGroup } from './ContributorGroup'; +import { default as File } from './File'; +import { BelongsTo, BelongsToMany, Column, CreatedAt, ForeignKey, + Model, PrimaryKey, Table, UpdatedAt } from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as UserJoinsProject } from './UserJoinsProject'; + +@Table +export default class Project extends Model<Project> { + @PrimaryKey + @Column + public name!: string; + + @BelongsToMany(() => User, () => UserJoinsProject) + public contributors?: User[]; + + @ForeignKey(() => File) + @Column + public rootFolderId!: string; + + @BelongsTo(() => File) + private readonly rootFolderInternal?: File; + + @CreatedAt + @Column + public creationDate!: Date; + + @UpdatedAt + @Column + public lastActivity!: Date; + + public get rootFolder(): File { + if (this.rootFolderInternal === undefined) { + throw new Error('rootFolderInternal is undefined'); + } + return this.rootFolderInternal; + } + + public get metadata(): { + public_metadata?: Metadata; + private_metadata?: Metadata; + admin_metadata?: Metadata; + } { + return { + public_metadata: this.publicMetadata, + private_metadata: this.privateMetadata, + admin_metadata: this.adminMetadata + }; + } + + public set metadata(newMetadata: { + public_metadata?: Metadata; + private_metadata?: Metadata; + admin_metadata?: Metadata; + }) { + if (newMetadata.public_metadata) { + this.publicMetadata = newMetadata.public_metadata; + } + if (newMetadata.private_metadata) { + this.privateMetadata = newMetadata.private_metadata; + } + if (newMetadata.admin_metadata) { + this.adminMetadata = newMetadata.admin_metadata; + } + } + + public get publicMetadata(): Metadata { + return {}; + } + + public set publicMetadata(newMetadata: Metadata) { + return; + } + + public get privateMetadata(): Metadata { + return {}; + } + + public set privateMetadata(newMetadata: Metadata) { + return; + } + + public get adminMetadata(): Metadata { + return {}; + } + + public set adminMetadata(newMetadata: Metadata) { + return; + } + + public getAccessLevel(user: User): ContributorGroup { + throw new Error(`unimplemented, ${this}`); + } + + public getUserInfo(user: User): UserInfo { + return { + username: user.username, + access_level: this.getAccessLevel(user) + .toString() + }; + } + + public get fullInfo(): ProjectFullInfo { + if (this.contributors === undefined) { + throw new Error('contributors undefined'); + } + return { + project_name: this.name, + users: this.contributors + .map<UserInfo>( + (u: User) => this.getUserInfo(u) + ), + public_metadata: { + creation_date: this.creationDate + }, + // TODO: Check if we have anything to use these for yet? + private_metadata: {}, + admin_metadata: {} + }; + } +} + +interface Metadata {} + +interface UserInfo { + username: string; + access_level: string; +} + +export interface ProjectFullInfo { + project_name: string; + users: UserInfo[]; + public_metadata: Metadata; + private_metadata?: Metadata; + admin_metadata?: Metadata; +} diff --git a/src/db/model/User.ts b/src/db/model/User.ts new file mode 100644 index 0000000..d290fd9 --- /dev/null +++ b/src/db/model/User.ts @@ -0,0 +1,197 @@ +import { default as File } from './File'; +import { default as Project } from './Project'; +import { BelongsToMany, Column, CreatedAt, HasMany, + Model, PrimaryKey, Table } from 'sequelize-typescript'; +import { default as UserGroup } from './UserGroup'; +import { default as UserHasPrivilege } from './UserHasPrivilege'; +import { default as UserJoinsProject } from './UserJoinsProject'; + +@Table +export default class User extends Model<User> { + @PrimaryKey + @Column + public username!: string; + + @Column + private readonly passwordInternal!: string; + + @BelongsToMany(() => UserGroup, () => UserHasPrivilege) + public userGroups?: UserGroup[]; + + @BelongsToMany(() => Project, () => UserJoinsProject) + public projects?: Project[]; + + @HasMany(() => File) + public createdFiles?: File[]; + + @CreatedAt + @Column + public creationDate!: Date; + + // TODO: Implement + public get properties(): UserProperty[] { + return []; + } + + // TODO: Implement + public set properties(newProps: UserProperty[]) { + return; + } + + public get metadata(): { + public_user_metadata?: Metadata; + private_user_metadata?: Metadata; + public_admin_metadata?: Metadata; + private_admin_metadata?: Metadata; + } { + return { + public_user_metadata: this.publicUserMetadata, + private_user_metadata: this.privateUserMetadata, + public_admin_metadata: this.publicAdminMetadata, + private_admin_metadata: this.privateAdminMetadata + }; + } + + public set metadata(newMetadata: { + public_user_metadata?: Metadata; + private_user_metadata?: Metadata; + public_admin_metadata?: Metadata; + private_admin_metadata?: Metadata; + }) { + if (newMetadata.public_user_metadata) { + this.publicUserMetadata = newMetadata.public_user_metadata; + } + if (newMetadata.private_user_metadata) { + this.privateUserMetadata = newMetadata.private_user_metadata; + } + if (newMetadata.public_admin_metadata) { + this.publicAdminMetadata = newMetadata.public_admin_metadata; + } + if (newMetadata.private_admin_metadata) { + this.privateAdminMetadata = newMetadata.private_admin_metadata; + } + } + + public get publicUserMetadata(): Metadata { + return {}; + } + + public set publicUserMetadata(newMetadata: Metadata) { + return; + } + + public get privateUserMetadata(): Metadata { + return {}; + } + + public set privateUserMetadata(newMetadata: Metadata) { + return; + } + + public get publicAdminMetadata(): Metadata { + return {}; + } + + public set publicAdminMetadata(newMetadata: Metadata) { + return; + } + + public get privateAdminMetadata(): Metadata { + return {}; + } + + public set privateAdminMetadata(newMetadata: Metadata) { + return; + } + + // TODO implement + public getAccessLevel(project: Project): string { + throw new Error(`unimplemented, ${this}`); + } + + public hasPrivilege(privilege: string): boolean { + // FIXME: Fetch these things if they aren't already present + if (this.userGroups === undefined) { + throw new Error('usergroups undefined'); + } + return this.userGroups.some( + (ug: UserGroup): boolean => ug.name === privilege + ); + } + + public getProjectInfo(project: Project): ProjectInfo { + return { + project_name: project.name, + access_level: this.getAccessLevel(project) + }; + } + + public get fullInfo(): UserFullInfo { + // FIXME: Fetch these things if they aren't already present + if (this.userGroups === undefined) { + throw new Error('userGroups undefined'); + } else if (this.projects === undefined) { + throw new Error('projects undefined'); + } + return { + username : this.username, + privileges: this.userGroups + .filter((ug: UserGroup): boolean => ug.name !== null) + .map((ug: UserGroup): string => ug.name as string), + projects : this.projects.map( + (p: Project): ProjectInfo => this.getProjectInfo(p) + ), + // TODO: Check if we have anything to use these for yet? + public_user_metadata: {}, + private_user_metadata: {}, + public_admin_metadata: {}, + private_admin_metadata: {} + }; + } + + public updateInfo(newInfo: { + password?: { old: string; new: string }; + public_user_metadata?: Metadata; + private_user_metadata?: Metadata; + }): void { + if (newInfo.password !== undefined) { + if (this.authenticate(newInfo.password.old)) { + this.password = newInfo.password.new; + } + } + } + + public authenticate(password: string): boolean { + // TODO use salting (and maybe even constant-time comparison?) + return password === this.password; + } + + public get password(): string { + return this.passwordInternal; + } + + public set password(newPassword: string) { + // TODO use salting + this.password = newPassword; + } +} + +// TODO MAKE PRETTY below +interface Metadata {} + +interface ProjectInfo { + project_name: string; + access_level: string; +} + +export interface UserFullInfo { + username: string; + privileges: string[]; + projects: ProjectInfo[]; + public_user_metadata: Metadata; + private_user_metadata: Metadata; + public_admin_metadata: Metadata; + private_admin_metadata: Metadata; +} + +export interface UserProperty {} diff --git a/src/db/model/UserGroup.ts b/src/db/model/UserGroup.ts new file mode 100644 index 0000000..7d42425 --- /dev/null +++ b/src/db/model/UserGroup.ts @@ -0,0 +1,54 @@ +import { AllowNull, BelongsToMany, Column, DataType, Model, Table, + Unique } from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as UserHasPrivilege } from './UserHasPrivilege'; + +interface UserPrivilege { + privilege: string; + description: string; + internal: boolean; +} + +@Table +export default class UserGroup extends Model<UserGroup> { + @AllowNull + @Unique + @Column(DataType.TEXT) + public name!: string | null; + + @BelongsToMany(() => User, () => UserHasPrivilege) + public users?: User[]; + + @Column + public canCreateUsers!: boolean; + + @Column + public canDeleteUsers!: boolean; + + @Column + public canEditUsers!: boolean; + + @Column + public canCreateProjects!: boolean; + + @Column + public canDeleteProjects!: boolean; + + @Column + public canEditProjects!: boolean; + + @Column + public isInternal!: boolean; + + @AllowNull + @Column(DataType.TEXT) + public description!: string | null; + + public getPrivilege(): UserPrivilege { + return { + privilege : `${this.name}`, + description : `${this.description}`, + internal : this.isInternal + }; + } +} diff --git a/src/db/model/UserHasPrivilege.ts b/src/db/model/UserHasPrivilege.ts new file mode 100644 index 0000000..17105c0 --- /dev/null +++ b/src/db/model/UserHasPrivilege.ts @@ -0,0 +1,14 @@ +import { Column, ForeignKey, Model, Table } from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as Privilege } from './UserGroup'; + +@Table +export default class UserHasPrivilege extends Model<UserHasPrivilege> { + @ForeignKey(() => User) + @Column + public username!: string; + + @ForeignKey(() => Privilege) + @Column + public privilegeId!: number; +} diff --git a/src/db/model/UserJoinsProject.ts b/src/db/model/UserJoinsProject.ts new file mode 100644 index 0000000..2bf7ea0 --- /dev/null +++ b/src/db/model/UserJoinsProject.ts @@ -0,0 +1,27 @@ +import { default as Project } from './Project'; +import { BelongsTo, Column, CreatedAt, ForeignKey, Model, Table + } from 'sequelize-typescript'; +import { default as User } from './User'; +import { default as ContributorGroup } from './UserGroup'; + +@Table +export default class UserJoinsProject extends Model<UserJoinsProject> { + @ForeignKey(() => User) + @Column + public username!: string; + + @ForeignKey(() => Project) + @Column + public projectName!: string; + + @CreatedAt + @Column + public joinDate!: Date; + + @ForeignKey(() => ContributorGroup) + @Column + public contributorGroupId!: number; + + @BelongsTo(() => ContributorGroup) + public contributorGroup?: ContributorGroup; +} diff --git a/src/db/orm.ts b/src/db/orm.ts new file mode 100644 index 0000000..01d8037 --- /dev/null +++ b/src/db/orm.ts @@ -0,0 +1,12 @@ +import { Sequelize } from 'sequelize-typescript'; + +const seq: Sequelize = new Sequelize({ + database: 'be4', + dialect: 'postgres', + username: 'admin', + password: '', + operatorsAliases: false, + modelPaths: [`${__dirname}/model`] +}); + +export default seq; diff --git a/src/errors/errorware.test.ts b/src/errors/errorware.test.ts new file mode 100644 index 0000000..eb85cc6 --- /dev/null +++ b/src/errors/errorware.test.ts @@ -0,0 +1,35 @@ +/* tslint:disable:no-unused-expression */ +// Disabled to allow chai-style assertions. + +import * as chai from 'chai'; +chai.should(); + +import { ErrorResponseBlock, RequestError } from './errorware'; + +describe('RequestError', () => { + describe('constructor', () => { + it('constructs simple errors', () => { + const err: RequestError = new RequestError( + 404, 'user_not_found' + ); + err.code.should.equal(404); + err.name.should.equal('user_not_found'); + }); + it('constructs with sensible defaults', () => { + const err: RequestError = new RequestError(); + err.code.should.not.be.undefined; + err.name.should.not.be.undefined; + }); + }); + describe('response generation', () => { + it('generates responses', () => { + const err: RequestError = new RequestError( + 500, 'internal_server_error' + ); + const response: ErrorResponseBlock = + err.responseBlock(); + response.status.should.equal('error'); + response.error.should.equal('internal_server_error'); + }); + }); +}); diff --git a/src/errors/errorware.ts b/src/errors/errorware.ts new file mode 100644 index 0000000..45a76b3 --- /dev/null +++ b/src/errors/errorware.ts @@ -0,0 +1,56 @@ +import { NextFunction, Request, Response } from 'express'; + +export interface ErrorResponseBlock { + status: string; + error: string; + error_description?: string; + user_message?: string; + // tslint:disable-next-line:no-any + error_data?: any; +} + +export class RequestError extends Error { + public code: number; + public userMessage?: string; + // tslint:disable-next-line:no-any + public errorData?: any; + + public constructor( + errCode: number = 500, + errName: string = 'internal_server_error', + errDescription?: string, + errUserMessage?: string, + // tslint:disable-next-line:no-any + errData?: any + ) { + super(errDescription); + this.code = errCode; + this.name = errName; + this.userMessage = errUserMessage; + this.errorData = errData; + } + + public responseBlock(): ErrorResponseBlock { + return { + status: 'error', + error: this.name, + error_description: this.message, + user_message: this.userMessage, + error_data: this.errorData + }; + } +} + +type Errorware = + (err: Error, req: Request, res: Response, next: NextFunction) => void; + +export const errorHandler: Errorware = + (err: Error, req: Request, res: Response, next: NextFunction): void => { + if ((err as RequestError).responseBlock) { + const rerr: RequestError = err as RequestError; + res.status(rerr.code) + .json(rerr.responseBlock()); + } else { + res.send(err); + } +}; diff --git a/src/files.ts b/src/files.ts new file mode 100644 index 0000000..daab817 --- /dev/null +++ b/src/files.ts @@ -0,0 +1,22 @@ +import * as fs from 'fs'; + +const CONTENT_BASE_DIRECTORY: string = './files'; + +const path: (filename: string, projectName: string) => string + = (filename: string, projectName: string): string => { + return `${CONTENT_BASE_DIRECTORY}/${projectName}/${filename}`; +}; + +const writableStream: + (filename: string, projectName: string) => fs.WriteStream = + (filename: string, projectName: string): fs.WriteStream => { + return fs.createWriteStream(path(filename, projectName)); +}; + +export const files: { + path: (f: string, p: string) => string; + writableStream: (f: string, p: string) => fs.WriteStream; +} = { + path, + writableStream +}; diff --git a/src/index.ts b/src/index.ts index 54ff848..c6adf32 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,13 @@ /* tslint:disable:no-console * This only goes here until we have a logging system */ -import app from './app'; +console.log('begin import'); +import { default as app } from './app'; +import { default as seq } from './db/orm'; +console.log('end import'); -console.log('Welcome to the CS3099 Server thingy!'); +import { default as User } from './db/model/User'; +import { default as UserGroup } from './db/model/UserGroup'; const DEFAULT_PORT: number = 3000; @@ -12,10 +16,49 @@ const port: number = process.env.PORT ? process.env.PORT : DEFAULT_PORT; -app.listen(port, (err: Error): void => { - if (err) { - return console.log(err); - } +// tslint:disable:no-floating-promises +(async(): Promise<void> => { + console.log('Booting PSQL database'); - return console.log(`server is listening on port ${port}`); -}); + await seq.authenticate(); + + console.log('Resetting Database'); + + await seq.sync({ + force: true + }); + + const admin: UserGroup = new UserGroup({ + name: 'admin', + canCreateUsers: true, + canDeleteUsers: true, + canEditUsers: true, + canCreateProjects: true, + canDeleteProjects: true, + canEditProjects: true, + isInternal: false, + description: 'Systems admin' + }); + + await admin.save(); + + console.log(admin.id); + + const root: User = new User({ + username: 'hafeez', + password: 'pass', + userGroup: admin + }); + + root.save(); + + console.log('Booting ExpressJS server'); + + app.listen(port, (err: Error) => { + if (err) { + return console.log(err); + } else { + return console.log(`server is listening on port ${port}`); + } + }); +})(); diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000..70c6455 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,26 @@ +/* tslint:disable:no-any */ + +interface Metadata { + [key: string]: any; +} + +export const logger: { + log: ( + level: string, + value: any, + meta: Metadata + ) => void; + fetch: ( + level: string, + meta: Metadata + ) => any[]; + isEnabled: () => boolean; +} = { + log: (level: string, value: any, meta: Metadata): void => { + return; + }, + fetch: (level: string, meta: Metadata): any[] => { + return []; + }, + isEnabled: (): boolean => false +}; diff --git a/src/matcher/options.test.ts b/src/matcher/options.test.ts new file mode 100644 index 0000000..ff5763e --- /dev/null +++ b/src/matcher/options.test.ts @@ -0,0 +1,163 @@ +/* tslint:disable:typedef */ +// Disabled to allow quick template creation. + +/* tslint:disable:newline-per-chained-call */ +// Disabled to allow Chai- and Mocha-style test formatting. + +/* tslint:disable:no-unused-expression */ +// Disabled to allow `...to.be.true`. + +import * as chai from 'chai'; +chai.should(); + +import * as options from './options'; +import { default as types } from './types'; + +// tslint:disable-next-line:no-require-imports + +describe('Matching:', () => { + describe('Rough Matching', () => { + context('for literals', () => { + context('accepts matching', () => { + it('strings', () => { + options.match('a', 'a').should.be.true; + }); + it('numbers', () => { + options.match(3, 3).should.be.true; + }); + it('boolean values', () => { + options.match(true, true).should.be.true; + }); + it('null to null', () => { + options.match(null, null).should.be.true; + }); + }); + context('rejects', () => { + it('different strings', () => { + options.match('x', 'y').should.be.false; + }); + it('different numbers', () => { + options.match(20, 42).should.be.false; + }); + it('different boolean values', () => { + options.match(true, false).should.be.false; + }); + it('different types', () => { + options.match('55', 55).should.be.false; + }); + it('null matched with non-null values', () => { + options.match(null, false).should.be.false; + }); + it('non-null values matched with null', () => { + options.match(0, null).should.be.false; + }); + }); + }); + context('for checker functions', () => { + context('accepts', () => { + it('values that succeed the checker function', () => { + options.match(types.number, 9).should.be.true; + }); + }); + context('rejects', () => { + it('values that do not succeed the checker function', () => { + options.match(types.boolean, 'true').should.be.false; + }); + }); + }); + it('accepts basic things', () => { + const template = { + a: types.string + }; + const matchee = { + a: 'yes' + }; + options.match(template, matchee).should.be.true; + }); + it('accepts objects with superfluous properties', () => { + const template = { + a: types.number + }; + const matchee = { + a: 40, + b: 20 + }; + options.match(template, matchee).should.be.true; + }); + it('rejects objects missing some properties', () => { + const template = { + a: types.boolean, + b: types.number, + c: types.number + }; + const matchee = { + b: 5 + }; + options.match(template, matchee).should.be.false; + }); + it('accepts objects that omit not_present properties', () => { + const template = { + a: types.number, + b: types.not_present, + c: types.not_present + }; + const matchee = { + a: 4 + }; + options.match(template, matchee).should.be.true; + }); + it('rejects empty objects for non-empty templates', () => { + const template = { + a: types.boolean + }; + const matchee = { + }; + options.match(template, matchee).should.be.false; + }); + it('accepts empty objects for empty templates', () => { + const template = { + }; + const matchee = { + }; + options.match(template, matchee).should.be.true; + }); + it('accepts nested objects that match', () => { + const template = { + a: types.number, + b: { + ba: types.string, + bb: types.string + }, + c: types.boolean + }; + const matchee = { + a: 432, + b: { + ba: 'baracus', + bb: 'ATEAM' + }, + c: true, + x: false + }; + options.match(template, matchee).should.be.true; + }); + it('accepts literal matches', () => { + const template = { + a: 'literal' + }; + const matchee = { + a: 'literal' + }; + options.match(template, matchee).should.be.true; + }); + it('rejects incorrect literal matches', () => { + const template = { + g: 99 + }; + const matchee = { + g: 80 + }; + options.match(template, matchee).should.be.false; + }); + }); +}); diff --git a/src/matcher/options.ts b/src/matcher/options.ts new file mode 100644 index 0000000..62e4985 --- /dev/null +++ b/src/matcher/options.ts @@ -0,0 +1,99 @@ +import { Atom, default as types } from './types'; + +type Checker = ((value: Value | undefined) => boolean); + +export type TemplateValue = + Atom | Template | Checker; + +export interface Template { + [key: string]: TemplateValue | undefined; +} + +export type Value = + { [key: string]: Value | undefined } | Atom; + +const matchNoCurry: + (template: TemplateValue, value: Value | undefined) => boolean = + (template: TemplateValue, value: Value | undefined): boolean => { + if (types.atom(template)) { + return template === value; + } else if (types.function(template)) { + return template(value); + } else if (types.atom(value) || value === undefined) { + return false; + } else if (types.object(template)) { + return Object.keys(template) + .every((key: string): boolean => { + const v: Value | undefined = value[key]; + return matchNoCurry(template[key] as TemplateValue, v); + }); + } else { + throw new Error(`Unknown template value: ${template}`); + } +}; + +// tslint:disable-next-line:typedef +export const match = (template: TemplateValue, value?: Value) => { + if (value === undefined) { + return matchNoCurry.bind(null, template); + } + return matchNoCurry(template, value); +}; + +// tslint:disable-next-line:typedef +export const exact = (template: Template, value?: Value) => { + if (value === undefined) { + return exact.bind(null, template); + } + if (!match(template, value)) { + return false; + } + if (!types.atom(value)) { + const k1: string[] = Object.keys(template); + const k2: string[] = Object.keys(value); + return k2.every((x: string) => k1.indexOf(x) < 0); + } else { + return true; + } +}; + +// tslint:disable-next-line:typedef +export const optional = (template: TemplateValue, value?: Value) => { + if (value === undefined) { + return optional.bind(null, template); + } + return types.undefined(value) || match(template, value); +}; + +// tslint:disable-next-line:typedef +export const alternative = (templates: TemplateValue[], value?: Value) => { + if (value === undefined) { + return alternative.bind(null, templates); + } + if (templates.length === 0) { + return false; + } else { + return templates.some((t: TemplateValue): boolean => match(t, value)); + } +}; + +// tslint:disable-next-line:typedef +export const array = (template: TemplateValue, values?: Value[]) => { + if (values === undefined) { + return array.bind(null, template); + } + const m: Checker = types.function(template) + ? template + : match.bind(null, template); + return values.every(m); +}; + +// tslint:disable-next-line:typedef +const options = { + match, + exact, + optional, + alternative, + array +}; +export default options; diff --git a/src/matcher/types.test.ts b/src/matcher/types.test.ts new file mode 100644 index 0000000..398064c --- /dev/null +++ b/src/matcher/types.test.ts @@ -0,0 +1,178 @@ +/* tslint:disable:no-unused-expression */ +// Disabled to allow `...to.be.true`. + +import * as chai from 'chai'; +chai.should(); + +import { default as types } from './types'; + +describe('Type Checking:', () => { + for (const x of [ + { name: 'Object', func: types.object }, + { name: 'Number', func: types.number }, + { name: 'Integer', func: types.integer }, + { name: 'String', func: types.string }, + { name: 'Boolean', func: types.boolean }, + { name: 'Array', func: types.array } + ]) { + describe(`${x.name} Checking`, () => { + it('rejects null', () => { + x.func(null).should.be.false; + }); + it('rejects undefined', () => { + x.func(undefined).should.be.false; + }); + }); + } + + describe('Presence Checking', () => { + it('accepts non-undefined values', () => { + types.anything(1).should.be.true; + types.anything('string').should.be.true; + types.anything(false).should.be.true; + }); + it('accepts null', () => { + types.anything(null).should.be.true; + }); + it('rejects undefined', () => { + types.anything(undefined).should.be.false; + }); + it('rejects objects without the named property', () => { + const x: { [key: string]: number } = {}; + /* There's no way to pick a key that definitely won't be + /* on the object */ + types.anything(x["hopefully this isn't a property"]) + .should.be.false; + }); + }); + + describe('Absence Checking', () => { + it('accepts undefined', () => { + types.not_present(undefined).should.be.true; + }); + }); + + describe('Number Checking', () => { + it('accepts positive integers', () => { + types.number(4).should.be.true; + }); + it('accepts negative integers', () => { + types.number(-10).should.be.true; + }); + it('accepts floats', () => { + types.number(3.14).should.be.true; + }); + it('accepts zero', () => { + types.number(0).should.be.true; + }); + it('accepts boxed numbers', () => { + // tslint:disable-next-line:no-construct + types.number(new Number(20)).should.be.true; + }); + it('rejects strings', () => { + types.number('haha').should.be.false; + }); + it('rejects objects', () => { + types.number(new Object()).should.be.false; + }); + it('rejects arrays', () => { + types.number([1, 2, 3]).should.be.false; + }); + it('rejects things that look like numbers', () => { + types.number('1234').should.be.false; + types.number('-3.14').should.be.false; + }); + it('accepts NaN', () => { + types.number(NaN).should.be.true; + }); + it('accepts Infinity', () => { + types.number(Infinity).should.be.true; + }); + }); + + describe('Integer Checking', () => { + it('rejects non-integer numbers', () => { + types.integer(3.14).should.be.false; + }); + it('rejects NaN', () => { + types.integer(NaN).should.be.false; + }); + it('rejects Infinity', () => { + types.integer(Infinity).should.be.false; + }); + }); + + describe('String Checking', () => { + it('accepts basic primitive strings', () => { + types.string('string!').should.be.true; + }); + it('accepts strings of numbers', () => { + types.string('1234').should.be.true; + }); + it('accepts the empty string', () => { + types.string('').should.be.true; + }); + it('accepts non-primitive string objects', () => { + // tslint:disable-next-line:no-construct + types.string(new String('String!')).should.be.true; + }); + it('rejects numbers', () => { + types.string(5).should.be.false; + // tslint:disable-next-line:no-construct + types.string(new Number(28)).should.be.false; + }); + it('rejects objects', () => { + types.string(new Object()).should.be.false; + }); + it('rejects arrays', () => { + types.string(['ah', 'ha']).should.be.false; + }); + }); + + describe('Boolean Checking', () => { + it('accepts true and false', () => { + types.boolean(true).should.be.true; + types.boolean(false).should.be.true; + }); + it('rejects numbers', () => { + types.boolean(2).should.be.false; + }); + it('rejects strings', () => { + types.boolean('not boolean').should.be.false; + }); + it('rejects strings of boolean values', () => { + types.boolean('true').should.be.false; + }); + it('rejects objects', () => { + types.boolean(new Object()).should.be.false; + }); + it('rejects arrays', () => { + types.boolean([true, true, false]).should.be.false; + }); + it('rejects falsy values', () => { + types.boolean(0).should.be.false; + }); + }); + + describe('Array Checking', () => { + it('accepts arrays', () => { + types.array([1, 'two', false]).should.be.true; + }); + it('accepts empty arrays', () => { + types.array([]).should.be.true; + types.array(new Array()).should.be.true; + }); + it('rejects strings', () => { + types.array('not an array').should.be.false; + }); + it('rejects strings that look like arrays', () => { + types.array('[1, 2, false]').should.be.false; + }); + it('rejects numbers', () => { + types.array(8).should.be.false; + }); + it('rejects objects', () => { + types.array(new Object()).should.be.false; + }); + }); +}); diff --git a/src/matcher/types.ts b/src/matcher/types.ts new file mode 100644 index 0000000..aad1e9f --- /dev/null +++ b/src/matcher/types.ts @@ -0,0 +1,79 @@ +/* tslint:disable:no-any */ + +type Checker<T = any> = (v: any) => v is T; + +export type Atom = Number | String | Boolean | null; + +const typeCheckerGenerator: <T>(test: T) => Checker<T> = + <T>(test: T): Checker<T> => { + const f: Checker<T> = (value: any): value is T => + value != null && value.constructor === test.constructor; + return f; +}; + +export const isObject: Checker<Object> = + typeCheckerGenerator<Object>({}); + +export const isNumber: Checker<Number> = + typeCheckerGenerator<Number>(0); + +export const isString: Checker<String> = + typeCheckerGenerator<String>(''); + +export const isBoolean: Checker<Boolean> = + typeCheckerGenerator<Boolean>(true); + +export const isArray: Checker<any[]> = + typeCheckerGenerator<any[]>([]); + +export const isFunction: Checker<Function> = + typeCheckerGenerator<Function>(new Function()); + +export const isNull: Checker<null> = + (v: any): v is null => v === null; + +export const isUndefined: Checker<undefined> = + (v: any): v is undefined => v === undefined; + +export const isPresent: (v: any) => boolean = + (v: any): boolean => !isUndefined(v); + +export const isInteger: Checker<Number> = + (v: any): v is Number => isNumber(v) && Number.isInteger(v as number); + +export const isAtom: Checker<Atom> = + (v: any): v is Atom => + isNull(v) || isNumber(v) || isString(v) || isBoolean(v); + +const types: { + object: Checker<Object>; + number: Checker<Number>; + string: Checker<String>; + boolean: Checker<Boolean>; + array: Checker<any[]>; + function: Checker<Function>; + integer: Checker<Number>; + null: Checker<null>; + present: (v: any) => boolean; + is_present: (v: any) => boolean; + not_present: Checker<undefined>; + undefined: Checker<undefined>; + anything: (v: any) => boolean; + atom: Checker<Atom>; +} = { + object: isObject, + number: isNumber, + string: isString, + boolean: isBoolean, + array: isArray, + function: isFunction, + integer: isInteger, + null: isNull, + present: isPresent, + is_present: isPresent, + not_present: isUndefined, + undefined: isUndefined, + anything: isPresent, + atom: isAtom +}; +export default types; diff --git a/src/serverConfig.ts b/src/serverConfig.ts index ea7b195..136995a 100644 --- a/src/serverConfig.ts +++ b/src/serverConfig.ts @@ -1,64 +1,54 @@ +import { default as types } from './matcher/types'; + +type Value = string | number | boolean; +type ValueString = 'string' | 'number' | 'integer' | 'boolean'; + const serverConfig: Property[] = []; /** * A way to display user-configurable properties. */ -class PropertyDisplay { +interface PropertyDisplay { /** * The category the property belongs to. */ - public category: string; + category: string; /** * The group the property belongs to. */ - public group: string; + group: string; /** * The name for the property to display to a user. */ - public displayName: string; + displayName: string; /** * The description of the property. */ - public description: string; - - /** - * Constructs a [[PropertyDisplay]] using its properties. - * - * @param cat The property's category. - * @param grp The property's group. - * @param dn The property's displayable name. - * @param desc A description of the property. - */ - public constructor(cat: string, grp: string, dn: string, desc: string) { - this.category = cat; - this.group = grp; - this.displayName = dn; - this.description = desc; - } + description: string; } /** * A server property that infuences the running of the server. * Loaded from configs at launch, and possibly editable during run-time. */ -export interface Property { +export class Property { /** * The property's unique ID. */ - id: string; + public id: string; /** * How to display the property to the user. */ - display?: PropertyDisplay; + public display?: PropertyDisplay; /** * Is the property read-only, or can it be edited at run-time? */ - readOnly: boolean; + public readOnly: boolean; /** * The variable type of the property. @@ -66,71 +56,81 @@ export interface Property { * These strings represent Javascript types directly, * except `"integer"`, which is a `number` in logic. */ - type: 'string' | 'number' | 'integer' | 'boolean'; + public type: ValueString; /** * The value of the property. */ - value: string | number | boolean; + private valueInternal!: Value; + + public constructor( + id: string, + type: ValueString, + value: Value, + readOnly: boolean = true, + display?: PropertyDisplay + ) { + this.id = id; + this.display = display; + this.readOnly = readOnly; + this.type = type; + this.valueInternal = value; + } + + public get value(): Value { + return this.valueInternal; + } + + public set value(value: Value) { + if (!this.readOnly) { + throw new Error('this property is read-only'); + } else if (!types[this.type](value)) { + throw new Error(`value ${value} is not of type ${this.type}`); + } + this.valueInternal = value; + } } // Logging -let propertyDisplay: PropertyDisplay = new PropertyDisplay( - 'Logging', - 'BE4', - 'Is logging enabled?', - 'This property defines if logging is currently enabled on this backend server.' -); - -serverConfig.push({ - id: 'Server_Log', - display: propertyDisplay, - readOnly: false, - type: 'boolean', - value: false -}); +let propertyDisplay: PropertyDisplay = { + category: 'logging', + group: 'BE4', + displayName: 'Is logging enabled?', + description: + 'This property defines if logging is enabled on this backend server.' +}; + +serverConfig.push(new Property( + 'Server_Log', + 'boolean', + false, + false, + propertyDisplay +)); // Caching Settings (global) -serverConfig.push({ - id: 'Global_Cache_Limit', - readOnly: true, - type: 'integer', - value: 1 -}); +serverConfig.push(new Property( + 'Global_Cache_Limit', + 'integer', + 1, + true +)); // Caching Settings (project level) -propertyDisplay = new PropertyDisplay( - 'Caching', - 'BE4', - 'Caching Type', - 'This property defines the current caching style for this project.' -); - -serverConfig.push({ - id: 'project_example', - display: propertyDisplay, - readOnly: false, - type: 'integer', - value: 1 -}); - -/** - * Checks if a property exists in the server's property list. - * - * @param propKey The property unique ID to search for. - * @returns The index of the property in the server's property list, - * or `-1` if the property is not present. - */ -export const propertyExists: (propKey: string) => number = - (propKey: string): number => { - let found: number = -1; - for (const prop in serverConfig) { - if (serverConfig[prop].id === propKey) { - found = parseInt(prop, 10); - break; - } - } - return found; +propertyDisplay = { + category: 'Caching', + group: 'BE4', + displayName: 'Caching Type', + description: + 'This property defines the current caching style for this project.' }; +serverConfig.push(new Property( + 'project_example', + 'integer', + 1, + false, + propertyDisplay +)); + export default serverConfig; diff --git a/src/uuid.ts b/src/uuid.ts new file mode 100644 index 0000000..983a92d --- /dev/null +++ b/src/uuid.ts @@ -0,0 +1,7 @@ +import { v4 } from 'uuid'; + +export const uuid: { + generate: () => string; +} = { + generate: v4 +}; diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts index 9c51e23..808fe50 100644 --- a/test/integration/protocol.routes.test.ts +++ b/test/integration/protocol.routes.test.ts @@ -2,29 +2,18 @@ import * as mocha from 'mocha'; import * as chai from 'chai'; const expect: Chai.ExpectStatic = chai.expect; -// Chai-http must be imported this way: -// tslint:disable-next-line:no-var-requires no-require-imports chai.use(require('chai-http')); - -// Mocha must be imported as a side-effect library: -// tslint:disable-next-line:no-import-side-effect import 'mocha'; - -// Mocha-each must be imported using a require call: -// tslint:disable-next-line:no-require-imports import forEach = require('mocha-each'); +import request = require('supertest'); import { Template, alternative, array, exact, match, optional } from '../../src/matcher/options'; import { default as types } from '../../src/matcher/types'; - import * as App from '../../src/app'; let app = App.TestApp(); - -//chai.use(chaiHttp); -//const expect = chai.expect; - +// The error response template according to protocol const errorResponseTemplate: Template = { status: 'error', error: types.string, @@ -33,14 +22,32 @@ const errorResponseTemplate: Template = { error_data: optional(types.anything) }; -type MochaForEachInput = [ string, string, Template ]; +type MochaForEachInput = [ string, string, Template, number ]; + +const userCredentials = { + email: 'sponge@bob.com', + password: 'garyTheSnail' +} + +//now let's login the user before we run any tests +let authenticatedUser = request.agent(app); + +before(function(done){ + authenticatedUser + .post('/login') + .send(userCredentials) + .end(function(err, response){ + expect(response.statusCode).to.equal(200); + done(); + }); +}); describe('routes : errors', () => { describe('GET invalid routes', function(){ it('should have response code 404', () => { return chai.request(app).get('/invalid/route') - .catch(function (res) { - expect(res.status).to.equal(404); + .catch(function (err: any) { + expect(err.status).to.equal(404); }); }); it('should conform to the error protocol', function(){ @@ -55,11 +62,13 @@ describe('routes : errors', () => { describe('routes : protocol', () => { const base: string = '/cs3099group-be-4'; + // format: + // <method> <route> <json-response-template> <response-code> const completeProtocol: MochaForEachInput[] = [ ['get', '/_supported_protocols_', exact({ supported: array(types.string), required: array(types.string) - })], + }), 200], ['get', '/log', types.array({ component: types.string, level: alternative([ @@ -72,8 +81,8 @@ describe('routes : protocol', () => { value: types.anything, username: types.string, timestamp: types.string - })], - ['post', '/log', null], + }), 500], + ['post', '/log', null, 500], ['get', '/properties', types.array({ id: types.string, display: optional(match({ @@ -93,13 +102,13 @@ describe('routes : protocol', () => { types.integer, types.boolean ]) - })], - ['post', '/properties', null], + }), 200], + ['post', '/properties', null, 200], ['get', '/user_privileges', array({ privilege: types.string, description: types.string, internal: types.boolean - })], + }), 200], ['get', '/users', array({ username: types.string, privileges: array(types.string), @@ -111,8 +120,8 @@ describe('routes : protocol', () => { private_user_metadata: types.anything, public_admin_metadata: types.anything, private_admin_metadata: types.anything - })], - // TODO types.metadata + }), 401], + // todo types.metadata ['get', '/users/:username', { username: types.string, privileges: array(types.string), @@ -124,11 +133,11 @@ describe('routes : protocol', () => { private_user_metadata: types.anything, public_admin_metadata: types.anything, private_admin_metadata: types.anything - }], - ['post', '/users/:username', null], + }, 401], + ['post', '/users/:username', null, 401], ['get', '/users/:username/properties', { data: optional(types.anything) - }], + }, 401], ['get', '/current_user', { username: types.string, privileges: array(types.string), @@ -140,13 +149,13 @@ describe('routes : protocol', () => { private_user_metadata: types.anything, public_admin_metadata: types.anything, private_admin_metadata: types.anything - }], - ['post', '/current_user', null], + }, 200], + ['post', '/current_user', null, 200], ['get', '/project_roles', array({ role: types.string, description: types.string, internal: types.boolean - })], + }), 200], ['get', '/projects', array({ project_name: types.string, users: array({ @@ -156,7 +165,7 @@ describe('routes : protocol', () => { public_metadata: types.anything, private_metadata: optional(types.anything), admin_metadata: optional(types.anything) - })], + }), 200], ['get', '/projects/:project_name', { project_name: types.string, users: array({ @@ -166,20 +175,20 @@ describe('routes : protocol', () => { public_metadata: types.anything, private_metadata: types.anything, admin_metadata: optional(types.anything) - }], - ['post', '/projects/:project_name', null], + }, 200], + ['post', '/projects/:project_name', null, 200], ['get', '/projects/:project_name/properties', { data: optional(types.anything) - }], - ['get', '/projects/:project_name/files/:path', null], - ['post', '/projects/:project_name/files/:id', null], - ['get', '/projects/:project_name/files_by_id/:id', null] + }, 200], + ['get', '/projects/:project_name/files/:path', null, 200], + ['post', '/projects/:project_name/files/:id', null, 200], + ['get', '/projects/:project_name/files_by_id/:id', null, 200] ]; describe('GET/POST all valid routes', () => { forEach(completeProtocol).it( '%s %s should be json', - (method: string, path: string, temp: Template) => { + (method: string, path: string, temp: Template, res_code: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); @@ -190,20 +199,20 @@ describe('routes : protocol', () => { });; }); forEach(completeProtocol).it( - '%s %s should have a status 200', - (method: string, path: string, temp: Template) => { + '%s %s should have a status %d', + (method: string, path: string, temp: Template, res_code: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); return request.then((res: ChaiHttp.Response) => { - expect(res).to.have.status(200); + expect(res).to.have.status(res_code); }).catch(function (err: any) { match(errorResponseTemplate)(err.response.body).should.be.true; });; }); forEach(completeProtocol).it( '%s %s should conform to the standard response protocol', - (method: string, path: string, temp: Template) => { + (method: string, path: string, temp: Template, res_code: number) => { const request: ChaiHttp.Request = method === 'get' ? chai.request(app).get(base + path) : chai.request(app).post(base + path); @@ -215,7 +224,7 @@ describe('routes : protocol', () => { }); forEach(completeProtocol).it( 'the response for %s %s should conform to its specific response protocol', - (method: string, path: string, temp: Template) => { + (method: string, path: string, temp: Template, res_code: number) => { if (method === 'get' && temp != null) { return chai.request(app).get(base + path) .then((res: ChaiHttp.Response) => { diff --git a/tsconfig.json b/tsconfig.json index 142540b..cde030b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,7 +6,9 @@ "module": "commonjs", /* Where to output .js files */ "outDir": "dist", - "strict": true + "strict": true, + "experimentalDecorators": true, + "emitDecoratorMetadata": true }, /* Where to look for .ts files */ "include": [ @@ -15,7 +17,5 @@ /* Exclude directory */ "exclude": [ "node_modules" - ], - "experimentalDecorators": true, - "emitDecoratorMetadata": true + ] } diff --git a/tslint.json b/tslint.json index cb318c8..5cf11a4 100644 --- a/tslint.json +++ b/tslint.json @@ -69,7 +69,10 @@ ], "unified-signatures": true, - "await-promise": true, + "await-promise": [ + true, + "Bluebird" + ], "ban-comma-operator": true, "ban": [ false ], "curly": true, @@ -88,9 +91,15 @@ "no-dynamic-delete": true, "no-empty": true, "no-eval": true, - "no-floating-promises": true, + "no-floating-promises":[ + true, + "Bluebird" + ], "no-for-in-array": false, - "no-implicit-dependencies": true, + "no-implicit-dependencies": [ + true, + "dev" + ], "no-inferred-empty-object-type": true, "no-invalid-template-strings": true, "no-invalid-this": true, @@ -215,7 +224,7 @@ ], "match-default-export-name": false, "newline-before-return": false, - "newline-per-chained-call": true, + "newline-per-chained-call": false, "new-parens": true, "no-angle-bracket-type-assertion": true, "no-boolean-literal-compare": true, @@ -52,6 +52,13 @@ version "1.1.0" resolved "https://registry.yarnpkg.com/@types/events/-/events-1.1.0.tgz#93b1be91f63c184450385272c47b6496fd028e02" +"@types/express-jwt@^0.0.38": + version "0.0.38" + resolved "https://registry.yarnpkg.com/@types/express-jwt/-/express-jwt-0.0.38.tgz#64b90b917299d99d3558d15e912ed22af0b48e6d" + dependencies: + "@types/express" "*" + "@types/express-unless" "*" + "@types/express-serve-static-core@*": version "4.11.1" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.11.1.tgz#f6f7212382d59b19d696677bcaa48a37280f5d45" @@ -59,6 +66,12 @@ "@types/events" "*" "@types/node" "*" +"@types/express-unless@*": + version "0.0.32" + resolved "https://registry.yarnpkg.com/@types/express-unless/-/express-unless-0.0.32.tgz#783f3cc1fa5e67cc2ed30000f3e1f22501f75d50" + dependencies: + "@types/express" "*" + "@types/express@*", "@types/express@^4.0.33": version "4.11.1" resolved "https://registry.yarnpkg.com/@types/express/-/express-4.11.1.tgz#f99663b3ab32d04cb11db612ef5dd7933f75465b" @@ -93,6 +106,12 @@ version "9.12.2" resolved "https://registry.yarnpkg.com/@types/highlight.js/-/highlight.js-9.12.2.tgz#6ee7cd395effe5ec80b515d3ff1699068cd0cd1d" +"@types/jsonwebtoken@^7.2.5": + version "7.2.5" + resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-7.2.5.tgz#413159d570ec45fc3e7da7ea3f7bca6fb9300e72" + dependencies: + "@types/node" "*" + "@types/lodash@*": version "4.14.102" resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.102.tgz#586a3e22385fc79b07cef9c5a1c8a5387986fbc8" @@ -113,7 +132,13 @@ version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" -"@types/mocha@^2.2.32": +"@types/mocha-each@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@types/mocha-each/-/mocha-each-1.1.0.tgz#0def5f984f8d59a905b8c4a2a9e5f6b083632717" + dependencies: + "@types/mocha" "*" + +"@types/mocha@*", "@types/mocha@^2.2.32": version "2.2.48" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-2.2.48.tgz#3523b126a0b049482e1c3c11877460f76622ffab" @@ -135,6 +160,27 @@ version "6.0.100" resolved "https://registry.yarnpkg.com/@types/node/-/node-6.0.100.tgz#26e5599c65f96efa0f100915144eb92cddaa95df" +"@types/passport-local@^1.0.32": + version "1.0.32" + resolved "https://registry.yarnpkg.com/@types/passport-local/-/passport-local-1.0.32.tgz#0856e3772c46ab8ac89aacf5535fa001a2ce5a13" + dependencies: + "@types/express" "*" + "@types/passport" "*" + "@types/passport-strategy" "*" + +"@types/passport-strategy@*": + version "0.2.32" + resolved "https://registry.yarnpkg.com/@types/passport-strategy/-/passport-strategy-0.2.32.tgz#0c1fb2e3b83621c8faf68c92f37898453ef60f71" + dependencies: + "@types/express" "*" + "@types/passport" "*" + +"@types/passport@*", "@types/passport@^0.4.2": + version "0.4.2" + resolved "https://registry.yarnpkg.com/@types/passport/-/passport-0.4.2.tgz#0374b3fb69834437ad5657442e5d9be16d9a8e82" + dependencies: + "@types/express" "*" + "@types/reflect-metadata@0.0.4": version "0.0.4" resolved "https://registry.yarnpkg.com/@types/reflect-metadata/-/reflect-metadata-0.0.4.tgz#b6477ca9a97e5265f2ac67f9ea704eae5e0eaf4d" @@ -171,6 +217,12 @@ "@types/glob" "*" "@types/node" "*" +"@types/uuid@^3.4.3": + version "3.4.3" + resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.3.tgz#121ace265f5569ce40f4f6d0ff78a338c732a754" + dependencies: + "@types/node" "*" + "@types/validator@*": version "6.3.0" resolved "https://registry.yarnpkg.com/@types/validator/-/validator-6.3.0.tgz#d7454bd67c6a933a9dbe939ae16edbf0f6894e70" @@ -308,7 +360,7 @@ async-each@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.1.tgz#19d386a1d9edc6e7c1c85d388aedbcc56d33602d" -async@^1.4.0, async@^1.5.2: +async@^1.4.0, async@^1.5.0, async@^1.5.2: version "1.5.2" resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" @@ -340,6 +392,10 @@ balanced-match@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" +base64url@2.0.0, base64url@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/base64url/-/base64url-2.0.0.tgz#eac16e03ea1438eff9423d69baa36262ed1f70bb" + base@^0.11.1: version "0.11.2" resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f" @@ -438,6 +494,10 @@ browser-stdout@1.3.0: version "1.3.0" resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.0.tgz#f351d32969d32fa5d7a5567154263d928ae3bd1f" +buffer-equal-constant-time@1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819" + buffer-writer@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/buffer-writer/-/buffer-writer-1.0.1.tgz#22a936901e3029afcd7547eb4487ceb697a3bf08" @@ -829,6 +889,13 @@ ecc-jsbn@~0.1.1: dependencies: jsbn "~0.1.0" +ecdsa-sig-formatter@1.0.9: + version "1.0.9" + resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.9.tgz#4bc926274ec3b5abb5016e7e1d60921ac262b2a1" + dependencies: + base64url "^2.0.0" + safe-buffer "^5.0.1" + ee-first@1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" @@ -901,6 +968,19 @@ expand-brackets@^2.1.4: snapdragon "^0.8.1" to-regex "^3.0.1" +express-jwt@^5.3.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/express-jwt/-/express-jwt-5.3.0.tgz#3d90cd65802e6336252f19e6a3df3e149e0c5ea0" + dependencies: + async "^1.5.0" + express-unless "^0.3.0" + jsonwebtoken "^7.3.0" + lodash.set "^4.0.0" + +express-unless@^0.3.0: + version "0.3.1" + resolved "https://registry.yarnpkg.com/express-unless/-/express-unless-0.3.1.tgz#2557c146e75beb903e2d247f9b5ba01452696e20" + express@^4.16.2: version "4.16.2" resolved "https://registry.yarnpkg.com/express/-/express-4.16.2.tgz#e35c6dfe2d64b7dca0a5cd4f21781be3299e076c" @@ -1489,6 +1569,10 @@ isarray@1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" +isemail@1.x.x: + version "1.2.0" + resolved "https://registry.yarnpkg.com/isemail/-/isemail-1.2.0.tgz#be03df8cc3e29de4d2c5df6501263f1fa4595e9a" + isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" @@ -1507,6 +1591,15 @@ isstream@~0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" +joi@^6.10.1: + version "6.10.1" + resolved "https://registry.yarnpkg.com/joi/-/joi-6.10.1.tgz#4d50c318079122000fe5f16af1ff8e1917b77e06" + dependencies: + hoek "2.x.x" + isemail "1.x.x" + moment "2.x.x" + topo "1.x.x" + js-string-escape@1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/js-string-escape/-/js-string-escape-1.0.1.tgz#e2625badbc0d67c7533e9edc1068c587ae4137ef" @@ -1554,6 +1647,31 @@ jsonify@~0.0.0: version "0.0.0" resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" +jsonwebtoken@^7.3.0: + version "7.4.3" + resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-7.4.3.tgz#77f5021de058b605a1783fa1283e99812e645638" + dependencies: + joi "^6.10.1" + jws "^3.1.4" + lodash.once "^4.0.0" + ms "^2.0.0" + xtend "^4.0.1" + +jsonwebtoken@^8.1.1: + version "8.1.1" + resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.1.1.tgz#b04d8bb2ad847bc93238c3c92170ffdbdd1cb2ea" + dependencies: + jws "^3.1.4" + lodash.includes "^4.3.0" + lodash.isboolean "^3.0.3" + lodash.isinteger "^4.0.4" + lodash.isnumber "^3.0.3" + lodash.isplainobject "^4.0.6" + lodash.isstring "^4.0.1" + lodash.once "^4.0.0" + ms "^2.1.1" + xtend "^4.0.1" + jsprim@^1.2.2: version "1.4.1" resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" @@ -1563,6 +1681,23 @@ jsprim@^1.2.2: json-schema "0.2.3" verror "1.10.0" +jwa@^1.1.4: + version "1.1.5" + resolved "https://registry.yarnpkg.com/jwa/-/jwa-1.1.5.tgz#a0552ce0220742cd52e153774a32905c30e756e5" + dependencies: + base64url "2.0.0" + buffer-equal-constant-time "1.0.1" + ecdsa-sig-formatter "1.0.9" + safe-buffer "^5.0.1" + +jws@^3.1.4: + version "3.1.4" + resolved "https://registry.yarnpkg.com/jws/-/jws-3.1.4.tgz#f9e8b9338e8a847277d6444b1464f61880e050a2" + dependencies: + base64url "^2.0.0" + jwa "^1.1.4" + safe-buffer "^5.0.1" + kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: version "3.2.2" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" @@ -1630,6 +1765,10 @@ lodash.create@3.1.1: lodash._basecreate "^3.0.0" lodash._isiterateecall "^3.0.0" +lodash.includes@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/lodash.includes/-/lodash.includes-4.3.0.tgz#60bb98a87cb923c68ca1e51325483314849f553f" + lodash.isarguments@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a" @@ -1638,6 +1777,26 @@ lodash.isarray@^3.0.0: version "3.0.4" resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55" +lodash.isboolean@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz#6c2e171db2a257cd96802fd43b01b20d5f5870f6" + +lodash.isinteger@^4.0.4: + version "4.0.4" + resolved "https://registry.yarnpkg.com/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz#619c0af3d03f8b04c31f5882840b77b11cd68343" + +lodash.isnumber@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz#3ce76810c5928d03352301ac287317f11c0b1ffc" + +lodash.isplainobject@^4.0.6: + version "4.0.6" + resolved "https://registry.yarnpkg.com/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz#7c526a52d89b45c45cc690b88163be0497f550cb" + +lodash.isstring@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz#d527dfb5456eca7cc9bb95d5daeaf88ba54a5451" + lodash.keys@^3.0.0: version "3.1.2" resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a" @@ -1646,6 +1805,14 @@ lodash.keys@^3.0.0: lodash.isarguments "^3.0.0" lodash.isarray "^3.0.0" +lodash.once@^4.0.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac" + +lodash.set@^4.0.0: + version "4.3.2" + resolved "https://registry.yarnpkg.com/lodash.set/-/lodash.set-4.3.2.tgz#d8757b1da807dde24816b0d6a84bea1a76230b23" + lodash@3.x: version "3.10.1" resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" @@ -1805,7 +1972,7 @@ moment-timezone@^0.5.14: dependencies: moment ">= 2.9.0" -"moment@>= 2.9.0", moment@^2.20.0: +moment@2.x.x, "moment@>= 2.9.0", moment@^2.20.0: version "2.20.1" resolved "https://registry.yarnpkg.com/moment/-/moment-2.20.1.tgz#d6eb1a46cbcc14a2b2f9434112c1ff8907f313fd" @@ -1823,6 +1990,10 @@ ms@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" +ms@^2.0.0, ms@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a" + nan@^2.3.0: version "2.8.0" resolved "https://registry.yarnpkg.com/nan/-/nan-2.8.0.tgz#ed715f3fe9de02b57a5e6252d90a96675e1f085a" @@ -2010,6 +2181,23 @@ pascalcase@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14" +passport-local@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/passport-local/-/passport-local-1.0.0.tgz#1fe63268c92e75606626437e3b906662c15ba6ee" + dependencies: + passport-strategy "1.x.x" + +passport-strategy@1.x.x: + version "1.0.0" + resolved "https://registry.yarnpkg.com/passport-strategy/-/passport-strategy-1.0.0.tgz#b5539aa8fc225a3d1ad179476ddf236b440f52e4" + +passport@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/passport/-/passport-0.4.0.tgz#c5095691347bd5ad3b5e180238c3914d16f05811" + dependencies: + passport-strategy "1.x.x" + pause "0.0.1" + path-dirname@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz#cc33d24d525e099a5388c0336c6e32b9160609e0" @@ -2040,6 +2228,10 @@ pause-stream@0.0.11: dependencies: through "~2.3" +pause@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/pause/-/pause-0.0.1.tgz#1d408b3fdb76923b9543d96fb4c9dfd535d9cb5d" + performance-now@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-0.2.0.tgz#33ef30c5c77d4ea21c5a53869d91b56d8f2555e5" @@ -2725,6 +2917,12 @@ to-regex@^3.0.1: extend-shallow "^2.0.1" regex-not "^1.0.0" +topo@1.x.x: + version "1.1.0" + resolved "https://registry.yarnpkg.com/topo/-/topo-1.1.0.tgz#e9d751615d1bb87dc865db182fa1ca0a5ef536d5" + dependencies: + hoek "2.x.x" + toposort-class@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/toposort-class/-/toposort-class-1.0.1.tgz#7ffd1f78c8be28c3ba45cd4e1a3f5ee193bd9988" @@ -3051,7 +3249,7 @@ xlsx@^0.11.19: exit-on-epipe "~1.0.1" ssf "~0.10.1" -xtend@^4.0.0: +xtend@^4.0.0, xtend@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af" |
