How can I redirect my user to another screen by passing a HEADER with Nodejs

Asked

Viewed 58 times

1

I’m doing the authentication/authorization part of my application, and I need to pass through my screens always passing the TOKEN through the HEADER, but I can’t redirect my user passing the TOKEN through the HEADER in any way

What can I do? How can I redirect my user by passing the token through the header?

Grateful from now on

Authcontroller.js

require('dotenv/config');
var axios = require('axios');

const User = require('../Models/User');
const bcrypt = require('bcrypt');

const Meli = require('./../../lib/Meli');
const MeliObject = new Meli.Meli();

const UserRepository = require('./../repositories/UserRepository');
const authService = require('./../services/auth-service');

module.exports = {
    async login(req, res) {
        const { email, password } = req.body;
        try {
            const user = await UserRepository.authenticate({
                email,
                password
            });

            const token = await authService.generateToken({
                id: user._id,
                email: user.email,
                nickname: user.nickname,
                roles: user.roles
            });

            if (!user) {
                res.status(404).send({
                    message: 'Usuário ou senha inválidos'
                });
                return;
            } else {
                res.header('x-access-token', token);
                res.redirect("/");
                /*
                res.status(201).send({
                    token: token,
                    data: {
                        id: user._id,
                        email: user.email,
                        nickname: user.nickname,
                        roles: user.roles,
                    }
                });*/
            }

        } catch (e) {
            console.log(e);
            res.status(500).send({
                message: 'Falha ao processar sua requisição'
            });
        }
    },
}

auth-service.js (Middlewere verifying authentication)

'use strict';

const jwt = require('jsonwebtoken');

require('dotenv/config');

exports.generateToken = async(data) => {
    return jwt.sign(data, process.env.SALT_KEY, { expiresIn: '1d' });
}

exports.decodeToken = async(token) => {
    var data = await jwt.verify(token, process.env.SALT_KEY);
    return data;
}

exports.authorize = function(req, res, next) {
    console.log("RES: " + req.headers['x-access-token']);

    var token = req.body.token || req.query.token || req.headers['x-access-token'];
    console.log("TOKEN: " + token);
    if (!token) {
        res.status(401).json({
            message: 'Acesso restrito'
        });
    } else {
        jwt.verify(token, process.env.SALT_KEY, function(err, decoded) {
            if (err) {
                res.status(401).json({
                    message: 'Token Inválido'
                });
            } else {
                next();
            }
        })
    }
}

exports.isAdmin = function(req, res, next) {
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    if (!token) {
        res.status(401).json({
            message: 'Token Inválido'
        });
    } else {
        jwt.verify(token, process.env.SALT_KEY, function(err, decoded) {
            if (err) {
                res.status(401).json({
                    message: 'Token Inválido'
                });
            } else {
                if (decoded.roles.includes('admin')) {
                    next();
                } else {
                    res.status(401).json({
                        message: 'Only admins'
                    });
                }

            }
        })
    }
}

Routes.js

const express = require('express');

const routes = express.Router();
const authServer = require('./src/services/auth-service');


//Controllers
const UserController = require('./src/Controllers/UserController');
const AuthController = require('./src/Controllers/AuthController');
const NotificationController = require('./src/Controllers/NotificationController');
const ProductsController = require('./src/Controllers/ProductsController');
const _Controller = require('./src/Controllers/_Controller');

//Rotas

routes.get('/', authServer.authorize, _Controller.index);


//routes.get('/user', UserController.index);
routes.get('/register', UserController.getRegister);
routes.post('/register', UserController.create);



routes.put('/user', authServer.isAdmin, UserController.update);
routes.delete('/user', UserController.delete);

/*
routes.post('/user/digital-product', UserController.add_digital_product);
routes.delete('/user/digital-product', UserController.remove_digital_product);
routes.put('/user/digital-product', UserController.edit_digital_product);
*/
routes.post('/auth', AuthController.login);
routes.get('/auth/mercadolivre/code', AuthController.getCode);
routes.get('/auth/mercadolivre/token', AuthController.getToken);

routes.get('/teste', AuthController.teste);
routes.get('/login', AuthController.getLogin);
routes.post('/login', AuthController.login);
routes.post('/refresh-token', authServer.authorize, AuthController.refreshToken);

routes.get('/email', NotificationController.email);
routes.post('/notification/receive', NotificationController.receive);
routes.get('/notification/history', NotificationController.history);

routes.get('/products/register', authServer.authorize, ProductsController.getRegister);
routes.post('/products/register', authServer.authorize, ProductsController.create);

routes.get('/auth/mercadolivre/token', AuthController.getToken);

module.exports = routes;
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.