Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*****************************************************************************
- * Import package *
- *****************************************************************************/
- import cryptoJS = require ('crypto-js');
- import express = require ('express');
- import { Request, Response } from 'express';
- import session = require ('express-session');
- import mysql = require ('mysql');
- import { Connection, MysqlError } from 'mysql';
- import { Configuration } from '../config/config';
- import { Rights } from '../model/rights';
- import { User } from '../model/user';
- import ProjectRoutes from './project_routes';
- /*****************************************************************************
- * Define app and database connection *
- *****************************************************************************/
- const app = express();
- const database: Connection = mysql.createConnection(Configuration.mysqlOptions);
- /*****************************************************************************
- * Configure web-app *
- *****************************************************************************/
- app.use(express.json());
- app.use(session(Configuration.sessionOptions));
- // register custom project routes
- ProjectRoutes(app, database);
- /*****************************************************************************
- * Start server and connect to database *
- *****************************************************************************/
- app.listen(8080, () => {
- console.log('Server started: http://localhost:8080');
- // Start up database connection
- database.connect((err: MysqlError) => {
- if (err) {
- console.log('Database connection failed: ', err);
- } else {
- console.log('Database is connected');
- }
- });
- });
- /*****************************************************************************
- * STATIC ROUTES *
- *****************************************************************************/
- app.use('/', express.static(__dirname + '/../../client/views'));
- app.use('/css', express.static(__dirname + '/../../client/css'));
- app.use('/src', express.static(__dirname + '/../../client/src'));
- app.use('/jquery', express.static(__dirname + '/../../client/node_modules/jquery/dist'));
- app.use('/popperjs', express.static(__dirname + '/../../client/node_modules/popper.js/dist'));
- app.use('/bootstrap', express.static(__dirname + '/../../client/node_modules/bootstrap/dist'));
- app.use('/font-awesome', express.static(__dirname + '/../../client/node_modules/font-awesome'));
- /** app.post('/register',(req:Request,res: Response) => {
- // Read data from request
- const firstName: string = req.body.firstName;
- const lastName: string = req.body.lastName;
- const email: string = req.body.email;
- const phone: string = req.body.phone;
- const birthday: string = req.body.birthday;
- const password: string = cryptoJS.SHA512(req.body.password).toString();
- const company_name: string = req.body.companyName;
- const company_register_no: string = req.body.companyRegisterNo;
- // Check that all arguments are given
- if (firstName && lastName && email && password && birthday && company_name && company_register_no) {
- // Create database query and data
- const data: any = [
- email, firstName, lastName, password, phone, birthday, company_name, company_register_no
- ];
- const selectQuery: string = 'SELECT * FROM nutzer (email,company_registration_no) \' +\n' +
- ' \'VALUES (?, ?);\';';
- database.query(selectQuery, data, (err: MysqlError, result: any) => {
- if (!result) {
- // Query could not been executed
- res.status(200).send({
- message: 'user does not exist: ' + err,
- });
- } else {
- // The user already exists
- res.status(500).send({
- userId: result.insertId,
- message: 'user already exists',
- });
- }
- });
- const insertQuery: string = 'INSERT INTO nutzer (email, first_name, last_name, password, phone, birthday, company_name, company_registration_no) ' +
- 'VALUES (?, ?, ?, ?, ?, ?, ?, ?);';
- // Execute database query
- database.query(insertQuery, data, (err: MysqlError, result: any) => {
- if (err) {
- // Query could not been executed
- res.status(500).send({
- message: 'Database request failed: ' + err,
- });
- } else {
- // The user was created
- res.status(200).send({
- userId: result.insertId,
- message: 'Successfully created new user',
- });
- }
- });
- } else {
- res.status(400).send({
- message: 'Not all mandatory fields are filled in',
- });
- }
- }); **/
- /*****************************************************************************
- * Middleware routes for session management (login and authentication) *
- *****************************************************************************/
- /**
- * @apiDefine SessionExpired
- *
- * @apiError (Client Error) {401} SessionNotFound The session of the user is expired or was not set
- *
- * @apiErrorExample SessionNotFound:
- * HTTP/1.1 401 Unauthorized
- * {
- * "message":"Session expired, please log in again."
- * }
- */
- function isLoggedIn() {
- // Abstract middleware route for checking login state of the user
- return (req: Request, res: Response, next) => {
- if (req.session.user) {
- // User has an active session and is logged in, continue with route
- next();
- } else {
- // User is not logged in
- res.status(401).send({
- message: 'Session expired, please log in again',
- });
- }
- };
- }
- /*****************************************************************************
- * HTTP ROUTES: LOGIN *
- *****************************************************************************/
- /**
- * @api {get} /login Request login state
- * @apiName GetLogin
- * @apiGroup Login
- * @apiVersion 2.0.0
- *
- * @apiSuccess {User} user The user object
- * @apiSuccess {string} message Message stating that the user is still logged in
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "user":{
- * "id":1,
- * "username":"admin",
- * "firstName":"Peter",
- * "lastName":"Kneisel",
- * "creationDate":"2017-11-12T09:33:25.000Z",
- * "rights":"2"
- * },
- * "message":"User still logged in"
- * }
- *
- * @apiError (Client Error) {401} SessionNotFound The session of the user is expired or was not set
- *
- * @apiErrorExample SessionNotFound:
- * HTTP/1.1 401 Unauthorized
- * {
- * "message":"Session expired, please log in again."
- * }
- */
- app.get('/login', isLoggedIn(), (req: Request, res: Response) => {
- res.status(200).send({
- message: 'User still logged in',
- user: req.session.user, // Send user object to client for greeting message
- });
- });
- /**
- * @api {post} /login Send login request
- * @apiName PostLogin
- * @apiGroup Login
- * @apiVersion 2.0.0
- *
- * @apiParam {string} username Username of the user to log in
- * @apiParam {string} password Password of the user to log in
- *
- * @apiSuccess {User} user The user object
- * @apiSuccess {string} message Message stating the user logged in successfully
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "user":{
- * "id":1,
- * "username":"admin",
- * "firstName":"Peter",
- * "lastName":"Kneisel",
- * "creationDate":"2017-11-12T09:33:25.000Z",
- * "rights":"2"
- * },
- * "message":"Successfully logged in"
- * }
- *
- * @apiError (Client Error) {401} LoginIncorrect The login data provided is not correct.
- * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed.
- *
- * @apiErrorExample LoginIncorrect:
- * HTTP/1.1 401 Unauthorized
- * {
- * "message":"Username or password is incorrect."
- * }
- *
- *
- * @apiErrorExample DatabaseRequestFailed:
- * HTTP/1.1 500 Internal Server Errror
- * {
- * "message":"Database request failed: ..."
- * }
- */
- app.post('/login', (req: Request, res: Response) => {
- // Read data from request
- const username: string = req.body.username;
- const password: string = req.body.password;
- // Create database query and data
- const data: [string, string] = [username, cryptoJS.SHA512(password).toString()];
- const query: string = 'SELECT * FROM nutzer WHERE email = ? AND password = ?;';
- // request user from database
- database.query(query, data, (err: MysqlError, rows: any) => {
- if (err) {
- // Login data is incorrect, user is not logged in
- res.status(500).send({
- message: 'Database request failed: ' + err,
- });
- } else {
- // Check if database response contains exactly one entry
- if (rows.length === 1) {
- // Login data is correct, user is logged in
- const user: User = new User(
- rows[0].id,
- rows[0].email,
- rows[0].first_name,
- rows[0].last_name,
- rows[0].password,
- rows[0].phone,
- new Date(rows[0].birthday),
- rows[0].company_name,
- rows[0].company_registration_no
- );
- req.session.user = user; // Store user object in session for authentication
- res.status(200).send({
- message: 'Successfully logged in',
- user, // Send user object to client for greeting message
- });
- } else {
- // Login data is incorrect, user is not logged in
- res.status(401).send({
- message: 'Username or password is incorrect.',
- });
- }
- }
- });
- });
- /**
- * @api {post} /logout Logout user
- * @apiName PostLogout
- * @apiGroup Logout
- * @apiVersion 2.0.0
- *
- * @apiSuccess {string} message Message stating that the user is logged out
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * message: "Successfully logged out"
- * }
- */
- app.post('/logout', (req: Request, res: Response) => {
- // Log out user
- delete req.session.user; // Delete user from session
- res.status(200).send({
- message: 'Successfully logged out',
- });
- });
- function isAdmin(req, res, next) {
- /* TODO: check if user really has the "admin" group */
- next();
- }
- /*****************************************************************************
- * HTTP ROUTES: USER *
- *****************************************************************************/
- /**
- * @api {post} /user Create a new user
- * @apiName PostUser
- * @apiGroup User
- * @apiVersion 2.0.0
- *
- * @apiUse SessionExpired
- * @apiUse NotAuthorized
- *
- * @apiParam {string} firstName First name of the user
- * @apiParam {string} lastName Last name of the user
- * @apiParam {string} username Username of the user
- * @apiParam {string} password Password of the user
- *
- * @apiSuccess {string} message Message stating the new user has been created successfully
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "userId": 0,
- * "message":"Successfully created new user"
- * }
- *
- * @apiError (Client Error) {400} NotAllMandatoryFields The request did not contain all mandatory fields
- * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed.
- *
- * @apiErrorExample NotAllMandatoryFields:
- * HTTP/1.1 400 Bad Request
- * {
- * "message":"Not all mandatory fields are filled in"
- * }
- *
- * @apiErrorExample DatabaseRequestFailed:
- * HTTP/1.1 500 Internal Server Error
- * {
- * "message":"Database request failed: ..."
- * }
- */
- app.post('/user', isLoggedIn(), isAdmin, (req: Request, res: Response) => {
- // Read data from request
- const firstName: string = req.body.firstName;
- const lastName: string = req.body.lastName;
- const email: string = req.body.email;
- const phone: string = req.body.phone;
- const birthday: string = req.body.birthday;
- const password: string = cryptoJS.SHA512(req.body.password).toString();
- const company_name: string = req.body.companyName;
- const company_register_no: string = req.body.companyRegisterNo;
- // Check that all arguments are given
- if (firstName && lastName && email && password) {
- // Create database query and data
- const data: any = [
- email, firstName, lastName, password, phone, birthday, company_name, company_register_no
- ];
- const query: string = 'INSERT INTO nutzer (email, first_name, last_name, password, phone, birthday, company_name, company_registration_no) ' +
- 'VALUES (?, ?, ?, ?, ?, ?, ?, ?);';
- // Execute database query
- database.query(query, data, (err: MysqlError, result: any) => {
- if (err) {
- // Query could not been executed
- res.status(500).send({
- message: 'Database request failed: ' + err,
- });
- } else {
- // The user was created
- res.status(200).send({
- userId: result.insertId,
- message: 'Successfully created new user',
- });
- }
- });
- } else {
- res.status(400).send({
- message: 'Not all mandatory fields are filled in',
- });
- }
- });
- /**
- * @api {get} /user:userId Get user with given id
- * @apiName GetUser
- * @apiGroup User
- * @apiVersion 2.0.0
- *
- * @apiUse SessionExpired
- *
- * @apiParam {number} userId The id of the requested user
- *
- * @apiSuccess {User} user The requested user object
- * @apiSuccess {string} message Message stating the user has been found
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "user":{
- * "id":1,
- * "firstName":"Peter",
- * "lastName":"Kneisel",
- * "username":"admin",
- * "creationDate":"2018-10-21 14:19:12",
- * "rights":2
- * },
- * "message":"Successfully got user"
- * }
- *
- * @apiError (Client Error) {404} NotFound The requested user can not be found
- * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
- *
- * @apiErrorExample NotFound:
- * HTTP/1.1 404 Not Found
- * {
- * "message":"The requested user can not be found."
- * }
- *
- * @apiErrorExample DatabaseRequestFailed:
- * HTTP/1.1 500 Internal Server Error
- * {
- * "message":"Database request failed: ..."
- * }
- */
- app.get('/user/:userId', isLoggedIn(), (req: Request, res: Response) => {
- // Read data from request and create database query and data
- const data: number = Number(req.params.userId);
- const query: string = 'SELECT * FROM nutzer WHERE id = ?;';
- // request user from database
- database.query(query, data, (err: MysqlError, rows: any) => {
- if (err) {
- // Database operation has failed
- res.status(500).send({
- message: 'Database request failed: ' + err,
- });
- } else {
- // Check if database response contains exactly one entry
- if (rows.length === 1) {
- const user: User = new User(
- rows[0].id,
- rows[0].email,
- rows[0].first_name,
- rows[0].last_name,
- rows[0].password,
- rows[0].phone,
- new Date(rows[0].birthday),
- rows[0].company_name,
- rows[0].company_registration_no
- );
- res.status(200).send({
- message: 'Successfully got user',
- user: user
- });
- } else {
- // Login data is incorrect, user is not logged in
- res.status(404).send({
- message: 'The requested user can not be found.',
- });
- }
- }
- });
- });
- /**
- * @api {put} /user/:userId Update user with given id
- * @apiName PutUser
- * @apiGroup User
- * @apiVersion 2.0.0
- *
- * @apiUse SessionExpired
- * @apiUse NotAuthorized
- *
- * @apiParam {number} userId The id of the requested user
- * @apiParam {string} firstName The (new) first name of the user
- * @apiParam {string} lastName The (new) last name of the user
- * @apiParam {string} password Optional: The (new) password of the user
- *
- * @apiSuccess {string} message Message stating the user has been updated
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "message":"Successfully updated user ..."
- * }
- *
- * @apiError (Client Error) {400} NotAllMandatoryFields The request did not contain all mandatory fields
- * @apiError (Client Error) {404} NotFound The requested user can not be found
- * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
- *
- * @apiErrorExample NotAllMandatoryFields:
- * HTTP/1.1 400 Bad Request
- * {
- * "message":"Not all mandatory fields are filled in"
- * }
- *
- * @apiErrorExample NotFound:
- * HTTP/1.1 404 Not Found
- * {
- * "message":"The user can not be found"
- * }
- *
- * @apiErrorExample DatabaseRequestFailed:
- * HTTP/1.1 500 Internal Server Error
- * {
- * "message":"Database request failed: ..."
- * }
- */
- app.put('/user/:userId', isLoggedIn(), isAdmin, (req: Request, res: Response) => {
- // Read data from request
- const userId: number = Number(req.params.userId);
- const firstName: string = req.body.firstName;
- const lastName: string = req.body.lastName;
- const password: string = req.body.password;
- // Define data for database query
- let data: any;
- let query: string;
- // Check that all arguments are given
- if (firstName && lastName) {
- // check if password was provided
- if (password) {
- // Create database query and data
- data = [firstName, lastName, cryptoJS.SHA512(password), userId];
- query = 'UPDATE nutzer SET firstName = ?, lastName = ?, password = ? WHERE id = ?;';
- } else {
- // Create database query and data
- data = [firstName, lastName, userId];
- query = 'UPDATE nutzer SET firstName = ?, lastName = ? WHERE id = ?;';
- }
- // Execute database query
- database.query(query, data, (err: MysqlError, result: any) => {
- if (err) {
- // Query could not been executed
- res.status(500).send({
- message: 'Database request failed: ' + err,
- });
- } else {
- if (result.affectedRows === 1) {
- // The user was updated
- res.status(200).send({
- message: 'Successfully updated user ' + userId,
- });
- } else {
- // The user can not be found
- res.status(404).send({
- message: 'The user can not be found',
- });
- }
- }
- });
- } else {
- res.status(400).send({
- message: 'Not all mandatory fields are filled in',
- });
- }
- });
- /**
- * @api {delete} /user/:userId Delete user with given id
- * @apiName DeleteUser
- * @apiGroup User
- * @apiVersion 2.0.0
- *
- * @apiUse SessionExpired
- * @apiUse NotAuthorized
- *
- * @apiParam {number} userId The id of the requested user
- *
- * @apiSuccess {string} message Message stating the user has been updated
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "message":"Successfully deleted user ..."
- * }
- *
- * @apiError (Client Error) {404} NotFound The requested user can not be found
- * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
- *
- * @apiErrorExample NotFound:
- * HTTP/1.1 404 Not Found
- * {
- * "message":"The requested user can not be deleted"
- * }
- *
- * @apiErrorExample DatabaseRequestFailed:
- * HTTP/1.1 500 Internal Server Error
- * {
- * "message":"Database request failed: ..."
- * }
- */
- app.delete('/user/:userId', isLoggedIn(), isAdmin, (req: Request, res: Response) => {
- // Read data from request
- const userId: number = Number(req.params.userId);
- // Create database query and data
- const data: number = userId;
- const query: string = 'DELETE FROM nutzer WHERE id = ?;';
- // request user from database
- database.query(query, data, (err: MysqlError, result: any) => {
- if (err) {
- // Database operation has failed
- res.status(500).send({
- message: 'Database request failed: ' + err,
- });
- } else {
- // Check if database response contains at least one entry
- if (result.affectedRows === 1) {
- res.status(200).send({
- message: 'Successfully deleted user ' + userId,
- });
- } else {
- // No user found to delete
- res.status(404).send({
- message: 'The requested user can not be deleted.',
- });
- }
- }
- });
- });
- /*****************************************************************************
- * HTTP ROUTES: USERS *
- *****************************************************************************/
- /**
- * @api {get} /users Get all users
- * @apiName GetUsers
- * @apiGroup Users
- * @apiVersion 2.0.0
- *
- * @apiUse SessionExpired
- *
- * @apiSuccess {User[]} userList The list of all users
- * @apiSuccess {string} message Message stating the users have been found
- *
- * @apiSuccessExample Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "user":{
- * "id":1,
- * "firstName":"Peter",
- * "lastName":"Kneisel",
- * "username":"admin",
- * "creationDate":"2018-10-21 14:19:12",
- * "rights":2
- * },
- * "message":"Successfully got user"
- * }
- *
- * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
- *
- * @apiErrorExample DatabaseRequestFailed:
- * HTTP/1.1 500 Internal Server Error
- * {
- * "message":"Database request failed: ..."
- * }
- */
- app.get('/users', isLoggedIn(), (req: Request, res: Response) => {
- // Create database query and data
- const query: string = 'SELECT * FROM nutzer;';
- // request user from database
- database.query(query, (err: MysqlError, rows: any) => {
- if (err) {
- // Database operation has failed
- res.status(500).send({
- message: 'Database request failed: ' + err,
- });
- } else {
- // Create local user list to parse users from database
- const userList: User[] = [];
- // Parse every entry
- for (const row of rows) {
- const user: User = new User(
- row.id,
- row.email,
- row.first_name,
- row.last_name,
- row.password,
- row.phone,
- new Date(row.birthday),
- row.company_name,
- row.company_registration_no
- );
- userList.push(user);
- }
- // Send user list to client
- res.status(200).send({
- message: 'Successfully requested user list',
- userList,
- });
- }
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement