diff --git a/api_v1/server.js b/api_v1/server.js index b6c983e..12f0e0b 100644 --- a/api_v1/server.js +++ b/api_v1/server.js @@ -1,190 +1,115 @@ -/** - * Require necessary libraries - */ -const fs = require('fs') -const bodyParser = require('body-parser') -const jsonServer = require('json-server') -const jwt = require('jsonwebtoken') -const bcrypt = require('bcrypt') +const fs = require('fs'); +const bodyParser = require('body-parser'); +const jsonServer = require('json-server'); +const jwt = require('jsonwebtoken'); +const bcrypt = require('bcrypt'); const path = require('path'); -const scanPhoto = require('./scanphoto.js') +const scanPhoto = require('./scanphoto.js'); +const SECRET_KEY = '123456789'; +const expiresIn = '1h'; -// JWT confing data -const SECRET_KEY = '123456789' -const expiresIn = '1h' +const server = jsonServer.create(); -// Create server -var server = jsonServer.create() +// Serve static files +server.use(jsonServer.defaults({ + static: path.join(__dirname, '../public') +})); -// Create router -if(fs.existsSync('./api_v1/db.json')){ - var router = jsonServer.router('./api_v1/db.json') +// Router +let router; +if (fs.existsSync('./api_v1/db.json')) { + router = jsonServer.router('./api_v1/db.json'); } else { - const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8'); - // to update (sync) current database (db.json) file - fs.writeFileSync('api_v1/db.json', initialData); - var router = jsonServer.router('./api_v1/db.json') + const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8'); + fs.writeFileSync('api_v1/db.json', initialData); + router = jsonServer.router('./api_v1/db.json'); } -// Create router -var router = jsonServer.router('./api_v1/db.json') +// Users DB +const userdb = JSON.parse(fs.readFileSync('./api_v1/users.json', 'UTF-8')); -// Users database -const userdb = JSON.parse(fs.readFileSync('./api_v1/users.json', 'UTF-8')) +server.use(bodyParser.urlencoded({ extended: true })); +server.use(bodyParser.json()); -// Default middlewares -server.use(bodyParser.urlencoded({ extended: true })) -server.use(bodyParser.json()) - -// Create a token from a payload function createToken(payload) { - return jwt.sign(payload, SECRET_KEY, { expiresIn }) + return jwt.sign(payload, SECRET_KEY, { expiresIn }); } -// Verify the token function verifyToken(token) { - return jwt.verify( - token, - SECRET_KEY, - (err, decode) => (decode !== undefined ? decode : err) - ) + return jwt.verify(token, SECRET_KEY, (err, decode) => decode || err); } -// Check if the user exists in database function isAuthenticated({ email, password }) { - return ( - userdb.users.findIndex( - user => - user.email === email && bcrypt.compareSync(password, user.password) - ) !== -1 - ) + return userdb.users.findIndex( + user => user.email === email && bcrypt.compareSync(password, user.password) + ) !== -1; } -function azz(){ - const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8'); - // to update (sync) current database (db.json) file - fs.writeFileSync('api_v1/db.json', initialData); - router.db.setState(JSON.parse(initialData)); - console.log('DB resettato'); +function azz() { + const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8'); + fs.writeFileSync('api_v1/db.json', initialData); + router.db.setState(JSON.parse(initialData)); + console.log('DB resettato'); } - -// con 192.168.1.3:7771/ apre http:192.168.1.3:7771/public.index.html +// Home → public/index.html server.get('/', (req, res) => { - //console.log(req.query) - res.sendFile(path.resolve("public/index.html")) -}) + res.sendFile(path.resolve("public/index.html")); +}); -// scansiona le foto +// Scan photos server.get('/scan', async (req, res) => { azz(); - await scanPhoto('./public/photos/original') - console.log("Ricaricato") - res.send({status: 'Ricaricato'}) -}) + await scanPhoto('./public/photos/original'); + console.log("Ricaricato"); + res.send({ status: 'Ricaricato' }); +}); - -// esempio http:192.168.1.3:7771/files?file=mio.txt +// Serve files server.get('/files', (req, res) => { - console.log(req.query) - res.sendFile(path.resolve("public/"+req.query.file)) -}) - -server.get('/initDB1',(req, res, next) => { - const Data = { photos: []}; - // to update (sync) current database (db.json) file - fs.writeFileSync('api_v1/db.json', JSON.stringify(Data)); - router.db.setState(Data); - res.send({status: 'DB resettato'}); - //res.sendStatus(200); + res.sendFile(path.resolve("public/" + req.query.file)); }); -server.get('/initDB',(req, res, next) => { - const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8'); - // to update (sync) current database (db.json) file - fs.writeFileSync('api_v1/db.json', initialData); - router.db.setState(JSON.parse(initialData)); - //router = jsonServer.router('./api_v1/db.json') - res.send({status: 'DB resettato'}); - //res.sendStatus(200); +// Reset DB +server.get('/initDB', (req, res) => { + const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8'); + fs.writeFileSync('api_v1/db.json', initialData); + router.db.setState(JSON.parse(initialData)); + res.send({ status: 'DB resettato' }); }); -server.get('/log', (req, res) => { - console.log(server) -}) -/* -server.use((req, res, next) => { - console.log(req.headers); - console.log(req.method); - console.log(req.path); - var a = req.path.split("/"); - if (req.method === 'GET' && a[1] == 'pub' && a.length > 2) { - //console.log(req.headers.host); - //console.log(a.slice(2).join("/")); - res.status(200).sendFile(path.resolve("public/"+a.slice(2).join("/"))); - //res.sendStatus(200); - } else { - next(); - } -}) -*/ -server.use((req, res, next) => { - console.log(req.headers); - console.log(req.method); - console.log(req.path); - var a = req.path.split("/"); - if (req.method === 'GET' && a[1] == 'pub' && a.length > 2) { - //console.log(req.headers.host); - //console.log(a.slice(2).join("/")); - res.status(200).sendFile(path.resolve("public/"+req.path)); - //res.sendStatus(200); - } else { - next(); - } -}) - -/** - * Method: POST - * Endpoint: /auth/login - */ +// Login server.post('/auth/login', (req, res) => { - const { email, password } = req.body - if (isAuthenticated({ email, password }) === false) { - const status = 401 - const message = 'Incorrect email or password' - res.status(status).json({ status, message }) - return - } - const token = createToken({ email, password }) - res.status(200).json({ token }) -}) + const { email, password } = req.body; -/** - * Middleware: Check authorization - */ + if (!isAuthenticated({ email, password })) { + return res.status(401).json({ status: 401, message: 'Incorrect email or password' }); + } + + const token = createToken({ email, password }); + res.status(200).json({ token }); +}); + +// Auth middleware server.use(/^(?!\/auth).*$/, (req, res, next) => { - if ( - req.headers.authorization === undefined || - req.headers.authorization.split(' ')[0] !== 'Bearer' - ) { - const status = 401 - const message = 'Bad authorization header' - res.status(status).json({ status, message }) - return + if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== 'Bearer') { + return res.status(401).json({ status: 401, message: 'Bad authorization header' }); } - try { - verifyToken(req.headers.authorization.split(' ')[1]) - next() - } catch (err) { - const status = 401 - const message = 'Error: access_token is not valid' - res.status(status).json({ status, message }) - } -}) -// Server mount -server.use(router) -server.listen(3000, () => { - console.log('Auth API server runing on port 3000 ...') -}) + try { + verifyToken(req.headers.authorization.split(' ')[1]); + next(); + } catch (err) { + res.status(401).json({ status: 401, message: 'Error: access_token is not valid' }); + } +}); + +// Mount router +server.use(router); + +// Start server on 4000 +server.listen(4000, () => { + console.log('Auth API server running on port 4000 ...'); +}); +