admin/controllers/admin/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 md5 = require('md5')
const jwt = require('jsonwebtoken')
let config = require('config')
const adminModule = require('../../modules/admin').default
const cryptosFunction = require('../../../common/cryptos')
const commonFunction = require('../../../common/function').default
const sendgridModule = require('../../../common/thirdparty/sendgrid').default
const schemaModule = require('./schema').default

config = config.get('JwtToken')

const { jsonResponse } = require('../logger')

const updateProfileFunction = async (req) => {
    await Promise.all([adminModule.updateProfile(req, req.body)])
    if (global.configColumns.custom_employees.enabled) {
        console.log('custom user', req.body)
        await Promise.all([adminModule.updateCustomUsersProfile(req, req.body)])
    }
    return true
}

module.exports = {
    /**
     * Login Admin User
     *
     * @memberOf adminside.admin
     * @param {adminModule.updateLastLogin} modules
     * @param {adminModule.userViews} modules
     */
    loginUser: async (req, res) => {
        try {
            await schemaModule.login().validateSync(req.body)
            const processObject = async (row) => {
                if (row.length > 0) {
                    if (row[0].emp_status === 'moderate') {
                        jsonResponse(res, 'error', {
                            responseType: 2,
                            message: 'Account has not been approved by admin yet',
                        })
                    } else if (row[0].emp_status === 'deleted') {
                        jsonResponse(res, 'error', {
                            responseType: 2,
                            message: 'Account has been suspended',
                        })
                    } else if (row[0].emp_status === 'deactivate') {
                        jsonResponse(res, 'error', {
                            responseType: 2,
                            message: 'Account has been suspended',
                        })
                    } else {
                        await Promise.all([
                            adminModule.updateLastLogin(row[0].id),
                            adminModule.userViews(req, row[0].id),
                        ])
                        const obj = {
                            admin_id: row[0].id,
                        }
                        const token = jwt.sign(obj, config.get('secret'), {
                            expiresIn: '168h',
                        })
                        if (row[0].isemp === '1') {
                            jsonResponse(res, 'success', {
                                responseType: 6,
                                token,
                                message: 'Logged in successfully',
                            })
                        } else {
                            jsonResponse(res, 'success', {
                                responseType: 3,
                                token,
                                message: 'Logged in successfully',
                            })
                        }
                    }
                } else {
                    jsonResponse(res, 'error', {
                        responseType: 2,
                        message: 'Invalid Email/Password',
                    })
                }
            }
            adminModule.process(req, processObject)
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Login Admin User
     *
     * @memberOf adminside.admin
     * @param {adminModule.adminDetails} modules
     */
    checkTokenUser: async (req, res) => {
        try {
            const results = await Promise.all([adminModule.adminDetails(req.user.admin_id)])
            if (results[0].length > 0) {
                results[0][0].admin_id = results[0][0].id
                delete results[0][0].id
                jsonResponse(res, 'success', {
                    responseType: 1,
                    message: 'Details successfully retrieved!',
                    responseData: results[0][0],
                })
            } else {
                jsonResponse(res, 'error', {
                    responseType: 2,
                    message: 'User details not available!',
                })
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Check Validation
     *
     * @memberOf adminside.admin
     * @param {adminModule.checkEmailExisting} modules
     */
    checkValidation: async (req, res) => {
        try {
            await schemaModule.checkValidation().validateSync(req.body)

            if (req.body.type === 'email') {
                req.body.text = req.body.text.toLowerCase()
                const resultuser = await Promise.all([
                    adminModule.checkEmailExisting(req.body.text),
                ])
                if (resultuser[0].length > 0) {
                    jsonResponse(res, 'error', {
                        responseType: 2,
                        message: 'Email Already Exists!',
                    })
                } else {
                    jsonResponse(res, 'success', {
                        responseType: 1,
                        message: 'Email available!',
                    })
                }
            } else {
                jsonResponse(res, 'error', {
                    responseType: 4,
                    message: 'Unknown type!',
                })
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Check Validation
     *
     * @memberOf adminside.admin
     * @param {adminModule.adminDetails} modules
     * @param {adminModule.updateProfile} modules
     */
    updateProfile: async (req, res) => {
        try {
            if (req.body.change_password) {
                const results = await Promise.all([adminModule.adminDetails(req.user.admin_id)])
                if (results[0].length > 0) {
                    const currentUserPasswordSalt = results[0][0].password_salt
                    const encryptCurrentUserOldPassword = results[0][0].password_hash
                    req.body.password_hash = md5(
                        md5(req.body.new_password) + currentUserPasswordSalt,
                    )
                    const encryptOldPasswordFromRequest = md5(
                        md5(req.body.current_password) + currentUserPasswordSalt,
                    )
                    if (encryptOldPasswordFromRequest !== encryptCurrentUserOldPassword) {
                        jsonResponse(res, 'error', {
                            responseType: 2,
                            message: 'Current password not match!',
                        })
                    } else {
                        await Promise.all([updateProfileFunction(req)])
                        jsonResponse(res, 'success', {
                            responseType: 1,
                            message: 'Password changed successfully',
                        })
                    }
                } else {
                    jsonResponse(res, 'error', {
                        responseType: 2,
                        message: 'User details not available!',
                    })
                }
            } else {
                const [resultuser] = await Promise.all([
                    adminModule.checkEmailExisting(req.body.email),
                ])
                if (resultuser.length && resultuser[0].id !== req.user.id) {
                    jsonResponse(res, 'error', {
                        responseType: 2,
                        message: 'Email Already Exists',
                    })
                    return false
                }

                // update profile
                await Promise.all([updateProfileFunction(req)])

                jsonResponse(res, 'success', {
                    responseType: 1,
                    message: 'Profile updated successfully',
                })
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Check Validation
     *
     * @memberOf adminside.admin
     * @param {adminModule.checkForgotUserExists} modules
     * @param {adminModule.inserUserToken} modules
     */
    forgotPassword: async (req, res) => {
        try {
            const emailID = req.body.email
            const [userExist] = await Promise.all([adminModule.checkForgotUserExists(emailID)])
            if (userExist.length > 0) {
                const hw = cryptosFunction.encrypt(req.body.email.toLowerCase())
                console.log('hw', hw)
                req.body.token = hw
                const verifyurl = `${global.url}/login/forgot_password?id=${hw}`
                const [results2] = await Promise.all([
                    commonFunction.mailtemps('forgot_password'),
                    adminModule.inserUserToken(userExist[0], req.body.token),
                ])
                console.log('results2[0]', results2[0])
                if (results2[0]) {
                    let { template, subject } = results2[0][0]
                    template = template.replace(/{{event.siteurl}}/g, global.url)
                    template = template.replace(
                        '{{event.user}}',
                        `${req.user.first_name} ${req.user.last_name}`,
                    )
                    template = template.replace(/{{event.verifyurl}}/g, verifyurl)
                    sendgridModule.sendEmail(subject, req.body.email, template, 1)
                    jsonResponse(res, 'success', {
                        responseType: 1,
                        message: 'Email sent out successfully',
                    })
                } else {
                    jsonResponse(res, 'error', {
                        responseType: 3,
                        message: 'Email Template does not exist',
                    })
                }
            } else {
                jsonResponse(res, 'error', {
                    responseType: 3,
                    message: 'Email did not match with record',
                })
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Check Validation
     *
     * @memberOf adminside.admin
     * @param {adminModule.getForgotUserToken} modules
     */
    resetPassword: async (req, res) => {
        try {
            await schemaModule.resetPassword().validateSync(req.body)
            req.body.email = cryptosFunction.decrypt(req.body.user_token)
            const [userExist] = await Promise.all([
                adminModule.getForgotUserToken(req.body.email, req.body.user_token),
            ])
            if (userExist.length > 0) {
                const userId = userExist[0][0].id
                const currentUserPasswordSalt = userExist[0][0].password_salt
                req.body.password_hash = md5(md5(req.body.password) + currentUserPasswordSalt)
                console.log('<=====change-password=====>')
                const [results2] = await Promise.all([commonFunction.mailtemps('password_changed')])

                let { template } = results2[0][0]
                const { subject } = results2[0][0]
                template = template.replace('{{event.fname}}', userExist[0][0].first_name)
                template = template.replace('{{event.tname}}', userExist[0][0].last_name)
                template = template.replace('{{event.email}}', req.body.email)
                sendgridModule.sendEmail(subject, req.body.email, template, 1)
                jsonResponse(res, 'success', {
                    responseType: 1,
                    message: 'Password changed successfully.',
                })
            } else {
                jsonResponse(res, 'success', {
                    responseType: 1,
                    message: 'Not a valid request!',
                })
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Get Admin Main Dashboard Data, active, draft, sold listing count
     * @memberOf adminside.admin
     */
    getMainDashboardData: async (req, res) => {
        try {
            const mainDashboardData = await adminModule.getMainDashboardData()
            jsonResponse(res, 'success', {
                responseType: 1,
                status: 'success',
                message: 'Details successfully retrieved!',
                mainDashboardData: mainDashboardData[0],
            })
        } catch (e) {
            jsonResponse(res, 'error', {
                responseType: 3,
                status: 'error',
                message: 'Internal Server error!',
            })
        }
    },

    getMainDashboardDataMore: async (req, res) => {
        try { 
            let query = ''
            await commonFunction.asyncForEach(req.body.additionalData, (data,index)=>{
                if (index !== 0) query += ','
                query += ` (select count(${data.variable}) from ${data.table} where ${data.condition}) as ${data.alias} `
            })
            const mainDashboardData = await adminModule.getMainDashboardDataMore(query)
            jsonResponse(res, 'success', {
                responseType: 1,
                status: 'success',
                message: 'Details successfully retrieved!',
                mainDashboardData: mainDashboardData[0],
            })
        } catch (e) {
            jsonResponse(res, 'error', {
                responseType: 3,
                status: 'error',
                message: 'Internal Server error!',
            })
        }
    },
}