front/index.js

/* ============================================================================ *\
|| ########################################################################## ||
|| # Auction Software Marketplace          Release: 0.6   Build 0.7         # ||
|| # ---------------------------------------------------------------------- # ||
|| # License # 35YAHCNR9344X6O666C123AB                                     # ||
|| # ---------------------------------------------------------------------- # ||
|| # Copyright ©2014–2021 Develop Scripts LLC. All Rights Reserved          # ||
|| # This file may not be redistributed in whole or significant part.       # ||
|| # ------------- AUCTION SOFTWARE IS NOT FREE SOFTWARE ------------------ # ||
|| # http://www.auctionsoftwaremarketplace.com|support@auctionsoftware.com  # ||
|| # ---------------------------------------------------------------------- # ||
|| ########################################################################## ||
\* ============================================================================ */

const express = require('express')
const config = require('config').get('JwtToken')
const fs = require('fs')
const morgan = require('morgan')
const path = require('path')
const jwt = require('jsonwebtoken')
const user = require('./routes/user')
const product = require('./routes/product')
const bid = require('./routes/bid')
const common = require('./routes/common')
const cart = require('./routes/cart')
const returnProd = require('./routes/return')
const refund = require('./routes/refund')
const payment = require('./routes/payment')
const auction = require('./routes/auction')
const userModule = require('./modules/user').default

// const { CustomStatusError } = require('../../middleware/custom_error')
// const checkIPValidation = require('../../middleware/ip_whitelist');
const { accessLogStream, jsonResponse } = require('./controllers/logger')
// const checkip = new checkIPValidation();
const app = express.Router()

app.use(
    morgan(':remote-addr - :remote-user [:date[web]] ":method :url HTTP/:http-version" :reqbody', {
        immediate: true,
        stream: accessLogStream,
    }),
)
app.use(
    morgan(':status :res[content-length] - :response-time ms"', {
        immediate: false,
        stream: accessLogStream,
    }),
)
app.use(
    morgan(
        ':remote-addr - :remote-user [:date[web]] ":method :url HTTP/:http-version" :status :res[header] :req[header] - :response-time ms ":referrer" ":user-agent" :reqbody',
        {
            stream: fs.createWriteStream(
                path.join(__dirname, '../../../../public/logs/api/error/access.log'),
                { flags: 'a' },
            ),
            skip(req, res) {
                return res.statusCode < 400
            },
        },
    ),
)

const NotAuthenticated = async (req, res, next) => {
    const bearerHeader = req.headers.authorization
    if (typeof bearerHeader !== 'undefined') {
        const bearer = bearerHeader.split(' ')
        const bearerToken = bearer[1]
        try {
            const decoded = await jwt.verify(bearerToken, config.get('secret'))
            req.token = bearerToken
            const [results] = await Promise.all([userModule.userDetails(decoded.id)])
            const [userValue] = results
            req.user = userValue
            return next()
        } catch (err) {
            jsonResponse(res, 'error', {
                responseType: 403,
                message: 'Session timed out!',
            })
            return false
        }
        // finally {
        // let ipvalidated = checkip.checkIpValidation(req);
        // if(ipvalidated[0]){
        //     next();
        // } else {
        //     throw new CustomStatusError('IP '+ipvalidated[1]+' is not whitelisted', 403);
        // }
        // }
    } else {
        return next()
    }
}

const Authenticated = async (req, res, next) => {
    const bearerHeader = req.headers.authorization
    if (typeof bearerHeader !== 'undefined') {
        const bearer = bearerHeader.split(' ')
        const bearerToken = bearer[1]
        try {
            const decoded = await jwt.verify(bearerToken, config.get('secret'))
            req.token = bearerToken
            const [results] = await Promise.all([userModule.userDetails(decoded.id)])
            const [userValue] = results
            req.user = userValue
            return next()
        } catch (err) {
            jsonResponse(res, 'error', {
                responseType: 403,
                message: 'Session timed out!',
            })
            return false
        }
        // finally {
        // let ipvalidated = checkip.checkIpValidation(req);
        // if(ipvalidated[0]){
        //     next();
        // } else {
        //     throw new CustomStatusError('IP '+ipvalidated[1]+' is not whitelisted', 403);
        // }
        // }
    } else if (
        req.originalUrl === '/api/user/checkValidation' ||
        req.originalUrl === '/api/user/login' ||
        req.originalUrl === '/api/user/register' ||
        req.originalUrl === '/api/user/forgotPassword' ||
        req.originalUrl === '/api/user/resetPassword' ||
        req.originalUrl === '/api/user/sendPhoneVerifyCode' ||
        req.originalUrl === '/api/user/reSendPhoneVerifyCode' ||
        req.originalUrl === '/api/user/verifyPhoneVerifyCode' ||
        req.originalUrl === '/api/common/getDefault' ||
        req.originalUrl === '/api/auction/search' ||
        req.originalUrl === '/api/common/getStaticPage' ||
        req.originalUrl === '/api/user/verifyEmail'
    ) {
        return next()
    } else {
        jsonResponse(res, 'error', {
            responseType: 403,
            message: 'No Bearer Token Available!',
        })
        return false
    }
}

/**
 * Operations for Frontend.
 *
 * @namespace frontend
 */

app.use('/user', Authenticated, user)
app.use('/product', NotAuthenticated, product)
app.use('/bid', Authenticated, bid)
app.use('/common', Authenticated, common)
app.use('/cart', Authenticated, cart)
app.use('/return', Authenticated, returnProd)
app.use('/refund', Authenticated, refund)
app.use('/payment', Authenticated, payment)
app.use('/auction', Authenticated, auction)

module.exports = app