Skip to content
Snippets Groups Projects
Select Git revision
  • f4ed114bbd21f1ca202b0a5030f5edc7672bce5c
  • main default protected
  • jw_sonar
  • v6.0.0 protected
  • interactive-mode-preference
  • bedran_exercise-list
  • add_route_user
  • Jw_sonar_backup
  • exercise_list_filter
  • assignment_filter
  • add_route_assignments
  • move-to-esm-only
  • 6.0.0-dev
  • Pre-alpha
  • 5.0.0
  • Latest
  • 4.2.0
  • 4.1.1
  • 4.1.0
  • 4.0.1
  • 4.0.0
  • 3.5.0
  • 3.4.2
  • 3.4.1
  • 3.3.0
  • 3.2.3
  • 3.2.2
  • 3.2.0
  • 3.1.2
  • 3.1.1
  • 3.1.0
  • 3.0.1
32 results

Config.ts

Blame
  • server.js 9.35 KiB
    /*
    Page: server.js
    Author: Dylan Wacker
    Description: manager the server application
     */
    var jwt = require('jsonwebtoken');
    const express = require('express'); // framework for node.js
    const bodyParser = require('body-parser'); //  get args and parameter in http request
    const exp = require('constants');
    const games = require('./modules/games');
    const jwtUtils = require('./modules/jwtUtils');
    const { checkUserExist, database } = require('./modules/persist');
    
    
    let token = undefined;
    
    // init server
    let server = express();
    
    // body parser config - parse incoming request bodies
    server.use(bodyParser.json()); // look request where Content-Type: application/json header is present and  the text-based JSON input into JS-accessible variables 
    server.use(bodyParser.urlencoded({ extended: false })); // Same for URL-encoded requests (extend : false -> only string)
    server.use(express.static('../frontend')); // for load static files
    
    const PORT_NUMBER = 8080;
    
    /*
     * API Documentation
     */
    server.get('/api/v1', function(request, response) {
        response.setHeader('Content-Type', 'text/plain');
        response.send(`
        API REST CRUD by Search Game in the backend with root /api/v1/
        
        | HTTP verb  | Endpoint                     | Data                   | Description                                    |
        |:-----------|:-----------------------------|:-----------------------|:-----------------------------------------------|
        |: POST      |: games/                      |: username\*, gameId\*  |:Add a favorite game for a specified user       |
        |: DELETE    |: games/                      |: username\*, gameId\*  |:Remove a favorite game for a specified user    |
        |: POST      |: login/                      |: username\*, password\*|:Login user with JWT                            |
        |: POST      |: logout/                     |: username\*, password\*|:Logout a user                                  |
        |: GET       |: games/*:username*/*:limit   |                        |:Return all the favorite games of a user        |
        * needed
          `);
    });
    
    /*
     * Add a favorite game for a specified user
     * body, args are not in the url
     * params username* username of the user
     * params gameId* game id to add
     */
    server.post('/api/v1/games', function(request, response) {
        if (request.body.gameId !== undefined && request.body.username !== undefined) {
            if (database[request.body.username]) {
                if (database[request.body.username].token != undefined) {
                    // test the if it's the right token, in the payload of the token we have the username
                    if (jwt.decode(database[request.body.username].token).username == request.body.username) {
                        let result = games.addFavoriteGameFor(request.body.gameId, request.body.username);
                        if (result) {
                            console.log('add a favorite game ', request.body);
                            return response.status(201).json({
                                'Sucess': 'Added',
                                'gameid': request.body.gameId,
                                'userid': request.body.username
                            }); // 201: Created
                        } else {
                            return response.status(400).json({ 'error': 'game id [' + request.body.gameId + '] already exist in ' + request.body.username });
                        }
                    } else {
                        return response.status(400).json({ 'error': 'not the good token gived' });
                    }
                } else {
                    console.log('error: you\'re not logged!');
                    return response.status(400).json({ 'error': 'you\'re not logged' });
                }
            } else {
                console.log('error: user incorrect!');
                return response.status(400).json({ 'error': 'user incorrect!' });
            }
        }
    
        return response.status(400).json({
            'error': 'Bad request'
        });
    });
    
    /*
     * Delete a favorite game for a specified user
     * body, args are not in the url
     * params username* username of the user
     * params gameId* game id to add
     */
    server.delete('/api/v1/games', function(request, response) {
        if (request.body.gameId !== undefined && request.body.username !== undefined) {
            if (database[request.body.username]) {
                if (database[request.body.username].token != undefined) {
                    // test the if it's the right token, in the payload of the token we have the username
                    if (jwt.decode(database[request.body.username].token).username == request.body.username) {
                        let result = games.removeFavoriteGameFor(request.body.gameId, request.body.username);
                        if (result) {
                            console.log('Delete a favorite game ', request.body);
                            return response.status(201).json({
                                'Sucess': 'Removed',
                                'gameid': request.body.gameId,
                                'userid': request.body.username
                            }); // 201: Removed
                        } else {
                            return response.status(400).json({ 'error': 'game id [' + request.body.gameId + '] not exist in ' + request.body.username });
                        }
                    } else {
                        console.log('not the good token gived!');
                        return response.status(400).json({ 'error': 'not the good token gived' });
                    }
                } else {
                    console.log('error: you\'re not logged!');
                    return response.status(400).json({ 'error': 'you\'re not logged' });
                }
            } else {
                console.log('error: user incorrect!');
                return response.status(400).json({ 'error': 'user incorrect!' });
            }
        }
    
        return response.status(400).json({
            'error': 'Bad request'
        });
    });
    
    /*
     * Login a user
     * body, args are not in the url
     * params username* username of the user
     * params password* password of the user
     */
    server.post('/api/v1/login', function(request, response) {
        if (request.body.username !== undefined && request.body.password !== undefined) {
            if (checkUserExist(request.body.username, request.body.password)) {
                database[request.body.username].token = jwtUtils.generateTokenForUser(request.body.username);
                console.log('logged as', request.body.username);
                console.log(database);
                return response.status(201).json({
                    'username': request.body.username,
                    'token': database[request.body.username].token
                }); // 201: login
            } else {
                console.log('error: username or password incorrect!');
                return response.status(400).json({ 'error': 'username or password incorrect!' });
            }
        }
        return response.status(400).json({
            'error': 'Bad request'
        });
    });
    
    /*
     * logout a user
     * body, args are not in the url
     */
    server.post('/api/v1/logout', function(request, response) {
        // can't logout if nobody is logged
        if (request.body.username !== undefined) {
            if (database[request.body.username]) {
                if (database[request.body.username].token != undefined) {
                    database[request.body.username].token = undefined;
                    console.log('logout');
                    console.log(database);
                    return response.status(201).json({
                        'Success': 'Logout!'
                    }); // 201: logout
                } else {
                    console.log('error: nobody is logged');
                    return response.status(400).json({ 'error': 'nobody is logged!' });
                }
            } else {
                console.log('error: user incorrect!');
                return response.status(400).json({ 'error': 'user incorrect!' });
            }
        }
        return response.status(400).json({
            'error': 'Bad request'
        });
    });
    
    /*
     * Favorite games of specific user
     * parmas args is in the url
     * params username* username of the user
     * params limit the number of games returned
     */
    server.get('/api/v1/games/:username/:limit?', function(request, response) {
        if (request.params.username !== undefined) {
            // test the if it's the right token, in the payload of the token we have the username
            console.log(database[request.params.username].token);
    
            if (database[request.params.username].token != undefined) {
                if (jwt.decode(database[request.params.username].token).username == request.params.username) {
    
                    // test the if it's the right token, in the payload of the token we have the username
                    if (jwt.decode(database[request.params.username].token).username == request.params.username) {
                        return response.status(201).json(games.getFavoriteGamesOfUser(request.params.username, request.params.limit));
                    } else {
                        return response.status(400).json({ 'error': 'not the good token gived' });
                    }
    
                } else {
                    console.log('error: not the good token gived!');
                    return response.status(400).json({ 'error': 'not the good token gived' });
                }
            } else {
                console.log('error: user not connected!');
                return response.status(400).json({ 'error': 'user not connected!' });
    
            }
        }
        return response.status(400).json({
            'error': 'Bad request'
        });
    
    });
    
    
    server.listen(PORT_NUMBER);
    console.log('Server started on port: ' + PORT_NUMBER);