Skip to content
Snippets Groups Projects
server.ts 16.2 KiB
Newer Older
„Sophia's avatar
„Sophia committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
/*****************************************************************************
 * Import package                                                            *
 *****************************************************************************/
import express, {Express, NextFunction, Request, Response} from 'express';
import {Connection, createConnection, ResultSetHeader, RowDataPacket} from "mysql2/promise";
import session from "express-session";
import crypto from "crypto"
import * as path from "node:path";

/*****************************************************************************
 * Database Connection                                                       *
 *****************************************************************************/
let database: Connection;
async function connectDatabase() {
  try {
    database = await createConnection({
      host: "localhost",
      user: "root",
      password: "toortoor",
      database: "userman"
    });
    await database.connect();
    console.log("Database is connected");
  } catch (error) {
    console.log(`Database connection failed: ${error}`);
  }
}
connectDatabase();

/*****************************************************************************
 * Define and start web-app server, define json-Parser                       *
 *****************************************************************************/
const app: Express = express();
app.listen(8080, () => {
  console.log('Server started: http://localhost:8080');
});
app.use(express.json());

/*****************************************************************************
 * session management configuration                                          *
 *****************************************************************************/
app.use(session({
  // save session even if not modified
  resave: true,
  // save session even if not used
  saveUninitialized: true,
  // forces cookie set on every response needed to set expiration (maxAge)
  rolling: true,
  // encrypt session-id in cookie using "secret" as modifier
  secret: "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  // set some cookie-attributes. Here expiration-date (offset in ms)
  cookie: { maxAge: 1000 * 60 * 60 } // 1h
}));

declare module 'express-session' {
  interface SessionData {
    user?: User
  }
}

/*****************************************************************************
 * Datastructure                                                             *
 *****************************************************************************/
export interface User {
  id: number;
  givenName: string;
  familyName: string;
  creationTime: string;
}

/**
 * @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(req: Request, res: Response, next: NextFunction) {
  // Abstract middleware route for checking login state of the user
  if (req.session.user != null) {
    // 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
 *
 * @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",
 *         "givenName":"Peter",
 *         "familyName":"Kneisel",
 *         "creationTime":"2017-11-12T09:33:25.000Z"
 *      },
 *      "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): void => {
  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
 *
 * @apiBody {string} username Username of the user to log in
 * @apiBody {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",
 *         "givenName":"Peter",
 *         "familyName":"Kneisel",
 *         "creationTime":"2017-11-12T09:33:25.000Z"
 *     },
 *     "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', async (req: Request, res: Response): Promise<void> => {
  // 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,
    crypto.createHash("sha512").update(password).digest('hex')
  ];
  const query: string = 'SELECT * FROM userlist WHERE username = ? AND password = ?;';

  try {
    const [rows] = await database.query<RowDataPacket[]>(query, data);
    // Check if database response contains exactly one entry
    if (rows.length === 1) {
      // Login data is correct, user is logged in
      const user: User = {
        id: rows[0].id,
        givenName: rows[0].givenName,
        familyName: rows[0].familyName,
        creationTime: rows[0].time
      };
      req.session.user = user; // Store user object in session for authentication
      res.status(200).send({
        message: 'Successfully logged in',
        user: 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.',
      });
    }
  } catch (error: unknown) {
    // Unknown error
    res.status(500).send({
      message: 'Database request failed: ' + error,
    });
  }
});

/**
 * @api {post} /logout Logout user
 * @apiName PostLogout
 * @apiGroup Logout
 *
 * @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): void => {
  // Log out user
  req.session.user = undefined; // Delete user from session
  res.status(200).send({
    message: 'Successfully logged out',
  });
});

/*****************************************************************************
 * HTTP ROUTES: USER, USERS                                                  *
 *****************************************************************************/
/**
 * @api {post} /user Create a new user
 * @apiName postUser
 * @apiGroup User
 *
 * @apiBody {string} givenName First name of the user
 * @apiBody {string} familyName Last name of the user
 *
 * @apiSuccess {string} message Message stating the new user has been created successfully
 *
 * @apiSuccessExample Success-Response:
 * HTTP/1.1 200 OK
 * {
 *     "message":"Successfully created new user"
 * }
 *
 * @apiError (Client Error) {400} NotAllMandatoryFields The request did not contain all mandatory fields
 *
 * @apiErrorExample NotAllMandatoryFields:
 * HTTP/1.1 400 Bad Request
 * {
 *     "message":"Not all mandatory fields are filled in"
 * }
 */
app.post('/user', isLoggedIn, async (req: Request, res: Response): Promise<void> => {
  // Read data from request body
  const username: string = req.body.username;
  const password: string = req.body.password;
  const givenName: string = req.body.givenName;
  const familyName: string = req.body.familyName;
  // add a new user if first- and familyName exist
  if (username && password && givenName && familyName) {
    const data: [string, string, string, string, string] = [
      username,
      crypto.createHash("sha512").update(password).digest('hex'),
      givenName,
      familyName,
      new Date().toLocaleString()
    ];
    const query: string = 'INSERT INTO userlist (username, password, givenName, familyName, creationTime) VALUES (?, ?, ?, ?, ?);';
    // Execute database query
    try {
      const [result] = await database.query<ResultSetHeader>(query, data);
      res.status(201).send({
        message: `Successfully created new user. ID: ${result.insertId}`,
      });
    } catch (error) {
      // Send response
      res.status(500).send({
        message: 'Database request failed: ' + error,
      });
    }
  } 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
 *
 * @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,
 *         "givenName":"Peter",
 *         "familyName":"Kneisel",
 *         "creationTime":"2018-10-21 14:19:12"
 *     },
 *     "message":"Successfully got user"
 * }
 *
 *  @apiError (Client Error) {404} NotFound The requested user can not be found
 *
 * @apiErrorExample NotFound:
 * HTTP/1.1 404 Not Found
 * {
 *     "message":"The requested user can not be found."
 * }
 */
app.get('/user/:userId', isLoggedIn, async (req: Request, res: Response): Promise<void> => {
  // Read data from request parameters
  const data: [number] = [
    parseInt(req.params.userId)
  ];
  // Search user in database
  const query: string = 'SELECT * FROM userlist WHERE id = ?;';

  try {
    const [rows] = await database.query<RowDataPacket[]>(query, data);
    if (rows.length === 1) {
      const user: User = {
        id: rows[0].id,
        givenName: rows[0].givenName,
        familyName: rows[0].familyName,
        creationTime: rows[0].time
      };

      // Send user list to client
      res.status(200).send({
        user: user,
        message: 'Successfully got user',
      });
    } else {
      res.status(404).send({
        message: 'The requested user can not be found.',
      });
    }
  } catch (error) {
    // Database operation has failed
    res.status(500).send({
      message: 'Database request failed: ' + error
    });
  }
});

/**
 * @api {put} /user/:userId Update user with given id
 * @apiName putUser
 * @apiGroup User
 *
 * @apiParam {number} userId The id of the requested user
 * @apiBody {string} givenName The (new) first name of the user
 * @apiBody {string} familyName The (new) last name 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
 *
 * @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 to update could not be found"
 * }
 */
app.put('/user/:userId', isLoggedIn, async (req: Request, res: Response): Promise<void> => {
  // Read data from request
  const userId: number = parseInt(req.params.userId);
  const givenName: string = req.body.givenName;
  const familyName: string = req.body.familyName;
  // Check that all arguments are given
  if (givenName && familyName) {
    // Create database query and data
    const data: [string, string, number] = [
      givenName,
      familyName,
      userId
    ];
    const query: string = 'UPDATE userlist SET givenName = ?, familyName = ? WHERE id = ?;';

    // Execute database query
    try {
      const [result] = await database.query<ResultSetHeader>(query, data);

      if (result.affectedRows != 1) {
        res.status(404).send({
          message: 'The user to update could not be found',
        });
      } else {
        res.status(200).send({
          message: `Successfully updated user ${givenName} ${familyName}`,
        });
      }
    } catch (error) {
      res.status(500).send({
        message: 'Database request failed: ' + error
      });
    }
  } 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
 *
 * @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 ..."
 * }
 */
app.delete('/user/:userId', isLoggedIn, async (req: Request, res: Response): Promise<void> => {
  // Read data from request
  const userId: number = parseInt(req.params.userId);
  // Delete user
  const query: string = 'DELETE FROM userlist WHERE id = ?;';
  try {
    const [result] = await database.query<ResultSetHeader>(query, userId);
    if (result.affectedRows === 1) {
      res.status(200).send({
        message: `Successfully deleted user `,
      });
    } else {
      res.status(404).send({
        message: 'The user to be deleted could not be found',
      });
    }
  } catch (error) {
    // Database operation has failed
    res.status(500).send({
      message: 'Database request failed: ' + error
    });
  }
});

/**
 * @api {get} /users Get all users
 * @apiName getUsers
 * @apiGroup Users
 *
 * @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
 * {
 *    "userList": [
 *      {
 *        "givenName": "Hans",
 *        "familyName": "Mustermann",
 *        "creationTime": "2018-11-04T13:02:44.791Z",
 *        "id": 1
 *     },
 *      {
 *        "givenName": "Bruce",
 *        "familyName": "Wayne",
 *        "creationTime": "2018-11-04T13:03:18.477Z",
 *        "id": 2
 *      }
 *    ]
 *    "message":"Successfully requested user list"
 * }
 */
app.get('/users', isLoggedIn, async (req: Request, res: Response): Promise<void> => {
  // Send user list to client
  const query: string = 'SELECT * FROM userlist;';

  try {
    const [rows] = await database.query<RowDataPacket[]>(query);
    // Create local user list to parse users from database
    const userList: User[] = [];
    // Parse every entry
    for (const row of rows) {
      const user: User = {
        id: row.id,
        givenName: row.givenName,
        familyName: row.familyName,
        creationTime: row.creationTime
      };
      userList.push(user);
    }

    // Send user list to client
    res.status(200).send({
      userList: userList,
      message: 'Successfully requested user list'
    });
  } catch (error) {
    // Database operation has failed
    res.status(500).send({
      message: 'Database request failed: ' + error
    });
  }
});

/*****************************************************************************
 * STATIC ROUTES                                                             *
 *****************************************************************************/
app.use(express.static(path.join(__dirname, "..", "..", "client")));