Advertisement
Guest User

Untitled

a guest
Jan 17th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.17 KB | None | 0 0
  1. /*****************************************************************************
  2. * Import package *
  3. *****************************************************************************/
  4. import cryptoJS = require ('crypto-js');
  5. import express = require ('express');
  6. import { Request, Response } from 'express';
  7. import session = require ('express-session');
  8. import mysql = require ('mysql');
  9. import { Connection, MysqlError } from 'mysql';
  10. import { Configuration } from '../config/config';
  11. import { Rights } from '../model/rights';
  12. import { User } from '../model/user';
  13.  
  14. import ProjectRoutes from './project_routes';
  15.  
  16. /*****************************************************************************
  17. * Define app and database connection *
  18. *****************************************************************************/
  19. const app = express();
  20. const database: Connection = mysql.createConnection(Configuration.mysqlOptions);
  21.  
  22. /*****************************************************************************
  23. * Configure web-app *
  24. *****************************************************************************/
  25. app.use(express.json());
  26. app.use(session(Configuration.sessionOptions));
  27.  
  28. // register custom project routes
  29. ProjectRoutes(app, database);
  30.  
  31. /*****************************************************************************
  32. * Start server and connect to database *
  33. *****************************************************************************/
  34. app.listen(8080, () => {
  35. console.log('Server started: http://localhost:8080');
  36. // Start up database connection
  37. database.connect((err: MysqlError) => {
  38. if (err) {
  39. console.log('Database connection failed: ', err);
  40. } else {
  41. console.log('Database is connected');
  42. }
  43. });
  44. });
  45.  
  46. /*****************************************************************************
  47. * STATIC ROUTES *
  48. *****************************************************************************/
  49. app.use('/', express.static(__dirname + '/../../client/views'));
  50. app.use('/css', express.static(__dirname + '/../../client/css'));
  51. app.use('/src', express.static(__dirname + '/../../client/src'));
  52. app.use('/jquery', express.static(__dirname + '/../../client/node_modules/jquery/dist'));
  53. app.use('/popperjs', express.static(__dirname + '/../../client/node_modules/popper.js/dist'));
  54. app.use('/bootstrap', express.static(__dirname + '/../../client/node_modules/bootstrap/dist'));
  55. app.use('/font-awesome', express.static(__dirname + '/../../client/node_modules/font-awesome'));
  56.  
  57.  
  58. /** app.post('/register',(req:Request,res: Response) => {
  59. // Read data from request
  60. const firstName: string = req.body.firstName;
  61. const lastName: string = req.body.lastName;
  62. const email: string = req.body.email;
  63. const phone: string = req.body.phone;
  64. const birthday: string = req.body.birthday;
  65. const password: string = cryptoJS.SHA512(req.body.password).toString();
  66. const company_name: string = req.body.companyName;
  67. const company_register_no: string = req.body.companyRegisterNo;
  68.  
  69. // Check that all arguments are given
  70. if (firstName && lastName && email && password && birthday && company_name && company_register_no) {
  71. // Create database query and data
  72. const data: any = [
  73. email, firstName, lastName, password, phone, birthday, company_name, company_register_no
  74. ];
  75. const selectQuery: string = 'SELECT * FROM nutzer (email,company_registration_no) \' +\n' +
  76. ' \'VALUES (?, ?);\';';
  77. database.query(selectQuery, data, (err: MysqlError, result: any) => {
  78. if (!result) {
  79. // Query could not been executed
  80. res.status(200).send({
  81. message: 'user does not exist: ' + err,
  82. });
  83. } else {
  84. // The user already exists
  85. res.status(500).send({
  86. userId: result.insertId,
  87. message: 'user already exists',
  88. });
  89. }
  90. });
  91. const insertQuery: string = 'INSERT INTO nutzer (email, first_name, last_name, password, phone, birthday, company_name, company_registration_no) ' +
  92. 'VALUES (?, ?, ?, ?, ?, ?, ?, ?);';
  93. // Execute database query
  94. database.query(insertQuery, data, (err: MysqlError, result: any) => {
  95. if (err) {
  96. // Query could not been executed
  97. res.status(500).send({
  98. message: 'Database request failed: ' + err,
  99. });
  100. } else {
  101. // The user was created
  102. res.status(200).send({
  103. userId: result.insertId,
  104. message: 'Successfully created new user',
  105. });
  106. }
  107. });
  108. } else {
  109. res.status(400).send({
  110. message: 'Not all mandatory fields are filled in',
  111. });
  112. }
  113. }); **/
  114. /*****************************************************************************
  115. * Middleware routes for session management (login and authentication) *
  116. *****************************************************************************/
  117. /**
  118. * @apiDefine SessionExpired
  119. *
  120. * @apiError (Client Error) {401} SessionNotFound The session of the user is expired or was not set
  121. *
  122. * @apiErrorExample SessionNotFound:
  123. * HTTP/1.1 401 Unauthorized
  124. * {
  125. * "message":"Session expired, please log in again."
  126. * }
  127. */
  128. function isLoggedIn() {
  129. // Abstract middleware route for checking login state of the user
  130. return (req: Request, res: Response, next) => {
  131. if (req.session.user) {
  132. // User has an active session and is logged in, continue with route
  133. next();
  134. } else {
  135. // User is not logged in
  136. res.status(401).send({
  137. message: 'Session expired, please log in again',
  138. });
  139. }
  140. };
  141. }
  142.  
  143. /*****************************************************************************
  144. * HTTP ROUTES: LOGIN *
  145. *****************************************************************************/
  146. /**
  147. * @api {get} /login Request login state
  148. * @apiName GetLogin
  149. * @apiGroup Login
  150. * @apiVersion 2.0.0
  151. *
  152. * @apiSuccess {User} user The user object
  153. * @apiSuccess {string} message Message stating that the user is still logged in
  154. *
  155. * @apiSuccessExample Success-Response:
  156. * HTTP/1.1 200 OK
  157. * {
  158. * "user":{
  159. * "id":1,
  160. * "username":"admin",
  161. * "firstName":"Peter",
  162. * "lastName":"Kneisel",
  163. * "creationDate":"2017-11-12T09:33:25.000Z",
  164. * "rights":"2"
  165. * },
  166. * "message":"User still logged in"
  167. * }
  168. *
  169. * @apiError (Client Error) {401} SessionNotFound The session of the user is expired or was not set
  170. *
  171. * @apiErrorExample SessionNotFound:
  172. * HTTP/1.1 401 Unauthorized
  173. * {
  174. * "message":"Session expired, please log in again."
  175. * }
  176. */
  177. app.get('/login', isLoggedIn(), (req: Request, res: Response) => {
  178. res.status(200).send({
  179. message: 'User still logged in',
  180. user: req.session.user, // Send user object to client for greeting message
  181. });
  182. });
  183.  
  184. /**
  185. * @api {post} /login Send login request
  186. * @apiName PostLogin
  187. * @apiGroup Login
  188. * @apiVersion 2.0.0
  189. *
  190. * @apiParam {string} username Username of the user to log in
  191. * @apiParam {string} password Password of the user to log in
  192. *
  193. * @apiSuccess {User} user The user object
  194. * @apiSuccess {string} message Message stating the user logged in successfully
  195. *
  196. * @apiSuccessExample Success-Response:
  197. * HTTP/1.1 200 OK
  198. * {
  199. * "user":{
  200. * "id":1,
  201. * "username":"admin",
  202. * "firstName":"Peter",
  203. * "lastName":"Kneisel",
  204. * "creationDate":"2017-11-12T09:33:25.000Z",
  205. * "rights":"2"
  206. * },
  207. * "message":"Successfully logged in"
  208. * }
  209. *
  210. * @apiError (Client Error) {401} LoginIncorrect The login data provided is not correct.
  211. * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed.
  212. *
  213. * @apiErrorExample LoginIncorrect:
  214. * HTTP/1.1 401 Unauthorized
  215. * {
  216. * "message":"Username or password is incorrect."
  217. * }
  218. *
  219. *
  220. * @apiErrorExample DatabaseRequestFailed:
  221. * HTTP/1.1 500 Internal Server Errror
  222. * {
  223. * "message":"Database request failed: ..."
  224. * }
  225. */
  226. app.post('/login', (req: Request, res: Response) => {
  227. // Read data from request
  228. const username: string = req.body.username;
  229. const password: string = req.body.password;
  230.  
  231. // Create database query and data
  232. const data: [string, string] = [username, cryptoJS.SHA512(password).toString()];
  233. const query: string = 'SELECT * FROM nutzer WHERE email = ? AND password = ?;';
  234.  
  235. // request user from database
  236. database.query(query, data, (err: MysqlError, rows: any) => {
  237. if (err) {
  238. // Login data is incorrect, user is not logged in
  239. res.status(500).send({
  240. message: 'Database request failed: ' + err,
  241. });
  242. } else {
  243. // Check if database response contains exactly one entry
  244. if (rows.length === 1) {
  245. // Login data is correct, user is logged in
  246. const user: User = new User(
  247. rows[0].id,
  248. rows[0].email,
  249. rows[0].first_name,
  250. rows[0].last_name,
  251. rows[0].password,
  252. rows[0].phone,
  253. new Date(rows[0].birthday),
  254. rows[0].company_name,
  255. rows[0].company_registration_no
  256. );
  257. req.session.user = user; // Store user object in session for authentication
  258. res.status(200).send({
  259. message: 'Successfully logged in',
  260. user, // Send user object to client for greeting message
  261. });
  262. } else {
  263. // Login data is incorrect, user is not logged in
  264. res.status(401).send({
  265. message: 'Username or password is incorrect.',
  266. });
  267. }
  268. }
  269. });
  270. });
  271.  
  272. /**
  273. * @api {post} /logout Logout user
  274. * @apiName PostLogout
  275. * @apiGroup Logout
  276. * @apiVersion 2.0.0
  277. *
  278. * @apiSuccess {string} message Message stating that the user is logged out
  279. *
  280. * @apiSuccessExample Success-Response:
  281. * HTTP/1.1 200 OK
  282. * {
  283. * message: "Successfully logged out"
  284. * }
  285. */
  286. app.post('/logout', (req: Request, res: Response) => {
  287. // Log out user
  288. delete req.session.user; // Delete user from session
  289. res.status(200).send({
  290. message: 'Successfully logged out',
  291. });
  292. });
  293.  
  294. function isAdmin(req, res, next) {
  295. /* TODO: check if user really has the "admin" group */
  296. next();
  297. }
  298.  
  299. /*****************************************************************************
  300. * HTTP ROUTES: USER *
  301. *****************************************************************************/
  302. /**
  303. * @api {post} /user Create a new user
  304. * @apiName PostUser
  305. * @apiGroup User
  306. * @apiVersion 2.0.0
  307. *
  308. * @apiUse SessionExpired
  309. * @apiUse NotAuthorized
  310. *
  311. * @apiParam {string} firstName First name of the user
  312. * @apiParam {string} lastName Last name of the user
  313. * @apiParam {string} username Username of the user
  314. * @apiParam {string} password Password of the user
  315. *
  316. * @apiSuccess {string} message Message stating the new user has been created successfully
  317. *
  318. * @apiSuccessExample Success-Response:
  319. * HTTP/1.1 200 OK
  320. * {
  321. * "userId": 0,
  322. * "message":"Successfully created new user"
  323. * }
  324. *
  325. * @apiError (Client Error) {400} NotAllMandatoryFields The request did not contain all mandatory fields
  326. * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed.
  327. *
  328. * @apiErrorExample NotAllMandatoryFields:
  329. * HTTP/1.1 400 Bad Request
  330. * {
  331. * "message":"Not all mandatory fields are filled in"
  332. * }
  333. *
  334. * @apiErrorExample DatabaseRequestFailed:
  335. * HTTP/1.1 500 Internal Server Error
  336. * {
  337. * "message":"Database request failed: ..."
  338. * }
  339. */
  340. app.post('/user', isLoggedIn(), isAdmin, (req: Request, res: Response) => {
  341. // Read data from request
  342. const firstName: string = req.body.firstName;
  343. const lastName: string = req.body.lastName;
  344. const email: string = req.body.email;
  345. const phone: string = req.body.phone;
  346. const birthday: string = req.body.birthday;
  347. const password: string = cryptoJS.SHA512(req.body.password).toString();
  348. const company_name: string = req.body.companyName;
  349. const company_register_no: string = req.body.companyRegisterNo;
  350.  
  351. // Check that all arguments are given
  352. if (firstName && lastName && email && password) {
  353. // Create database query and data
  354. const data: any = [
  355. email, firstName, lastName, password, phone, birthday, company_name, company_register_no
  356. ];
  357. const query: string = 'INSERT INTO nutzer (email, first_name, last_name, password, phone, birthday, company_name, company_registration_no) ' +
  358. 'VALUES (?, ?, ?, ?, ?, ?, ?, ?);';
  359. // Execute database query
  360. database.query(query, data, (err: MysqlError, result: any) => {
  361. if (err) {
  362. // Query could not been executed
  363. res.status(500).send({
  364. message: 'Database request failed: ' + err,
  365. });
  366. } else {
  367. // The user was created
  368. res.status(200).send({
  369. userId: result.insertId,
  370. message: 'Successfully created new user',
  371. });
  372. }
  373. });
  374. } else {
  375. res.status(400).send({
  376. message: 'Not all mandatory fields are filled in',
  377. });
  378. }
  379. });
  380.  
  381.  
  382.  
  383. /**
  384. * @api {get} /user:userId Get user with given id
  385. * @apiName GetUser
  386. * @apiGroup User
  387. * @apiVersion 2.0.0
  388. *
  389. * @apiUse SessionExpired
  390. *
  391. * @apiParam {number} userId The id of the requested user
  392. *
  393. * @apiSuccess {User} user The requested user object
  394. * @apiSuccess {string} message Message stating the user has been found
  395. *
  396. * @apiSuccessExample Success-Response:
  397. * HTTP/1.1 200 OK
  398. * {
  399. * "user":{
  400. * "id":1,
  401. * "firstName":"Peter",
  402. * "lastName":"Kneisel",
  403. * "username":"admin",
  404. * "creationDate":"2018-10-21 14:19:12",
  405. * "rights":2
  406. * },
  407. * "message":"Successfully got user"
  408. * }
  409. *
  410. * @apiError (Client Error) {404} NotFound The requested user can not be found
  411. * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
  412. *
  413. * @apiErrorExample NotFound:
  414. * HTTP/1.1 404 Not Found
  415. * {
  416. * "message":"The requested user can not be found."
  417. * }
  418. *
  419. * @apiErrorExample DatabaseRequestFailed:
  420. * HTTP/1.1 500 Internal Server Error
  421. * {
  422. * "message":"Database request failed: ..."
  423. * }
  424. */
  425. app.get('/user/:userId', isLoggedIn(), (req: Request, res: Response) => {
  426. // Read data from request and create database query and data
  427. const data: number = Number(req.params.userId);
  428. const query: string = 'SELECT * FROM nutzer WHERE id = ?;';
  429.  
  430. // request user from database
  431. database.query(query, data, (err: MysqlError, rows: any) => {
  432. if (err) {
  433. // Database operation has failed
  434. res.status(500).send({
  435. message: 'Database request failed: ' + err,
  436. });
  437. } else {
  438. // Check if database response contains exactly one entry
  439. if (rows.length === 1) {
  440. const user: User = new User(
  441. rows[0].id,
  442. rows[0].email,
  443. rows[0].first_name,
  444. rows[0].last_name,
  445. rows[0].password,
  446. rows[0].phone,
  447. new Date(rows[0].birthday),
  448. rows[0].company_name,
  449. rows[0].company_registration_no
  450. );
  451. res.status(200).send({
  452. message: 'Successfully got user',
  453. user: user
  454. });
  455. } else {
  456. // Login data is incorrect, user is not logged in
  457. res.status(404).send({
  458. message: 'The requested user can not be found.',
  459. });
  460. }
  461. }
  462. });
  463. });
  464.  
  465. /**
  466. * @api {put} /user/:userId Update user with given id
  467. * @apiName PutUser
  468. * @apiGroup User
  469. * @apiVersion 2.0.0
  470. *
  471. * @apiUse SessionExpired
  472. * @apiUse NotAuthorized
  473. *
  474. * @apiParam {number} userId The id of the requested user
  475. * @apiParam {string} firstName The (new) first name of the user
  476. * @apiParam {string} lastName The (new) last name of the user
  477. * @apiParam {string} password Optional: The (new) password of the user
  478. *
  479. * @apiSuccess {string} message Message stating the user has been updated
  480. *
  481. * @apiSuccessExample Success-Response:
  482. * HTTP/1.1 200 OK
  483. * {
  484. * "message":"Successfully updated user ..."
  485. * }
  486. *
  487. * @apiError (Client Error) {400} NotAllMandatoryFields The request did not contain all mandatory fields
  488. * @apiError (Client Error) {404} NotFound The requested user can not be found
  489. * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
  490. *
  491. * @apiErrorExample NotAllMandatoryFields:
  492. * HTTP/1.1 400 Bad Request
  493. * {
  494. * "message":"Not all mandatory fields are filled in"
  495. * }
  496. *
  497. * @apiErrorExample NotFound:
  498. * HTTP/1.1 404 Not Found
  499. * {
  500. * "message":"The user can not be found"
  501. * }
  502. *
  503. * @apiErrorExample DatabaseRequestFailed:
  504. * HTTP/1.1 500 Internal Server Error
  505. * {
  506. * "message":"Database request failed: ..."
  507. * }
  508. */
  509. app.put('/user/:userId', isLoggedIn(), isAdmin, (req: Request, res: Response) => {
  510. // Read data from request
  511. const userId: number = Number(req.params.userId);
  512. const firstName: string = req.body.firstName;
  513. const lastName: string = req.body.lastName;
  514. const password: string = req.body.password;
  515.  
  516. // Define data for database query
  517. let data: any;
  518. let query: string;
  519.  
  520. // Check that all arguments are given
  521. if (firstName && lastName) {
  522. // check if password was provided
  523. if (password) {
  524. // Create database query and data
  525. data = [firstName, lastName, cryptoJS.SHA512(password), userId];
  526. query = 'UPDATE nutzer SET firstName = ?, lastName = ?, password = ? WHERE id = ?;';
  527. } else {
  528. // Create database query and data
  529. data = [firstName, lastName, userId];
  530. query = 'UPDATE nutzer SET firstName = ?, lastName = ? WHERE id = ?;';
  531. }
  532. // Execute database query
  533. database.query(query, data, (err: MysqlError, result: any) => {
  534. if (err) {
  535. // Query could not been executed
  536. res.status(500).send({
  537. message: 'Database request failed: ' + err,
  538. });
  539. } else {
  540. if (result.affectedRows === 1) {
  541. // The user was updated
  542. res.status(200).send({
  543. message: 'Successfully updated user ' + userId,
  544. });
  545. } else {
  546. // The user can not be found
  547. res.status(404).send({
  548. message: 'The user can not be found',
  549. });
  550. }
  551. }
  552. });
  553. } else {
  554. res.status(400).send({
  555. message: 'Not all mandatory fields are filled in',
  556. });
  557. }
  558. });
  559.  
  560. /**
  561. * @api {delete} /user/:userId Delete user with given id
  562. * @apiName DeleteUser
  563. * @apiGroup User
  564. * @apiVersion 2.0.0
  565. *
  566. * @apiUse SessionExpired
  567. * @apiUse NotAuthorized
  568. *
  569. * @apiParam {number} userId The id of the requested user
  570. *
  571. * @apiSuccess {string} message Message stating the user has been updated
  572. *
  573. * @apiSuccessExample Success-Response:
  574. * HTTP/1.1 200 OK
  575. * {
  576. * "message":"Successfully deleted user ..."
  577. * }
  578. *
  579. * @apiError (Client Error) {404} NotFound The requested user can not be found
  580. * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
  581. *
  582. * @apiErrorExample NotFound:
  583. * HTTP/1.1 404 Not Found
  584. * {
  585. * "message":"The requested user can not be deleted"
  586. * }
  587. *
  588. * @apiErrorExample DatabaseRequestFailed:
  589. * HTTP/1.1 500 Internal Server Error
  590. * {
  591. * "message":"Database request failed: ..."
  592. * }
  593. */
  594. app.delete('/user/:userId', isLoggedIn(), isAdmin, (req: Request, res: Response) => {
  595. // Read data from request
  596. const userId: number = Number(req.params.userId);
  597. // Create database query and data
  598. const data: number = userId;
  599. const query: string = 'DELETE FROM nutzer WHERE id = ?;';
  600.  
  601. // request user from database
  602. database.query(query, data, (err: MysqlError, result: any) => {
  603. if (err) {
  604. // Database operation has failed
  605. res.status(500).send({
  606. message: 'Database request failed: ' + err,
  607. });
  608. } else {
  609. // Check if database response contains at least one entry
  610. if (result.affectedRows === 1) {
  611. res.status(200).send({
  612. message: 'Successfully deleted user ' + userId,
  613. });
  614. } else {
  615. // No user found to delete
  616. res.status(404).send({
  617. message: 'The requested user can not be deleted.',
  618. });
  619. }
  620. }
  621. });
  622. });
  623.  
  624. /*****************************************************************************
  625. * HTTP ROUTES: USERS *
  626. *****************************************************************************/
  627. /**
  628. * @api {get} /users Get all users
  629. * @apiName GetUsers
  630. * @apiGroup Users
  631. * @apiVersion 2.0.0
  632. *
  633. * @apiUse SessionExpired
  634. *
  635. * @apiSuccess {User[]} userList The list of all users
  636. * @apiSuccess {string} message Message stating the users have been found
  637. *
  638. * @apiSuccessExample Success-Response:
  639. * HTTP/1.1 200 OK
  640. * {
  641. * "user":{
  642. * "id":1,
  643. * "firstName":"Peter",
  644. * "lastName":"Kneisel",
  645. * "username":"admin",
  646. * "creationDate":"2018-10-21 14:19:12",
  647. * "rights":2
  648. * },
  649. * "message":"Successfully got user"
  650. * }
  651. *
  652. * @apiError (Server Error) {500} DatabaseRequestFailed The request to the database failed
  653. *
  654. * @apiErrorExample DatabaseRequestFailed:
  655. * HTTP/1.1 500 Internal Server Error
  656. * {
  657. * "message":"Database request failed: ..."
  658. * }
  659. */
  660. app.get('/users', isLoggedIn(), (req: Request, res: Response) => {
  661. // Create database query and data
  662. const query: string = 'SELECT * FROM nutzer;';
  663.  
  664. // request user from database
  665. database.query(query, (err: MysqlError, rows: any) => {
  666. if (err) {
  667. // Database operation has failed
  668. res.status(500).send({
  669. message: 'Database request failed: ' + err,
  670. });
  671. } else {
  672. // Create local user list to parse users from database
  673. const userList: User[] = [];
  674. // Parse every entry
  675. for (const row of rows) {
  676. const user: User = new User(
  677. row.id,
  678. row.email,
  679. row.first_name,
  680. row.last_name,
  681. row.password,
  682. row.phone,
  683. new Date(row.birthday),
  684. row.company_name,
  685. row.company_registration_no
  686. );
  687. userList.push(user);
  688. }
  689. // Send user list to client
  690. res.status(200).send({
  691. message: 'Successfully requested user list',
  692. userList,
  693. });
  694. }
  695. });
  696. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement