How to make API call using API token in Node.js using express, passport-local

时光怂恿深爱的人放手 提交于 2020-01-14 05:59:50

问题


I'm a newbie in Node.js and trying to use API token to access Grafana. And I created one API token by following instruction from Grafana page.

However, I don't know how to make API calls from my code of node.js to access my local server of grafana page. Also, I have a local login-page by using mongoDB to manage users.

How can I make Node.js API calls to access my local server of grafana page?

Please help me out here.. I'm having hard time on this.. If you want me to show code, I can edit here..

EDIT: This is my whole code for app.js

var io = require('socket.io');
var express = require('express');
var app = express();
var redis = require('redis');
var sys = require('util');
var fs = require('fs');
//Added for connecting login session
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//Adding grafana
var request = require('request');

//Connecting Database (MongoDB)
mongoose.connect("my mongoDB private address");
var db = mongoose.connection;
db.once("open",function () {
  console.log("DB connected!");
});
db.on("error",function (err) {
  console.log("DB ERROR :", err);
});

//Setting bcrypt for password.
var bcrypt = require("bcrypt-nodejs");

//Setting userSchema for MongoDB.
var userSchema = mongoose.Schema({
  email: {type:String, required:true, unique:true},
  password: {type:String, required:true},
  createdAt: {type:Date, default:Date.now}
});
userSchema.pre("save", function (next){
  var user = this;
  if(!user.isModified("password")){
    return next();
  } else {
    user.password = bcrypt.hashSync(user.password);
    return next();
  }
});

//setting bcrypt for password.
userSchema.methods.authenticate = function (password) {
  var user = this;
  return bcrypt.compareSync(password,user.password);
};

//Setting User as userSchema.
var User = mongoose.model('user',userSchema);

io = io.listen(server);

//Setting middleware for login format.
app.set("view engine", 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(flash());

app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());

//Initializing passport.
passport.serializeUser(function(user, done) {
  //console.log('serializeUser()', user);
  done(null, user.id);
});
passport.deserializeUser(function(id, done) {
  //console.log('deserializeUser()', user);
  User.findById(id, function(err, user) {
    done(err, user);
  });
});
var username_tmp = '';
var global_username = '';         //Global variable for username to put in the address
var pass = '';
//Initializing passport-local strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
  new LocalStrategy({
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true
    },
    function(req, email, password, done) {
      User.findOne({ 'email' :  email }, function(err, user) {
        if (err) return done(err);
        if (!user){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'No user found.'));
        }
        if (!user.authenticate(password)){
            req.flash("email", req.body.email);
            return done(null, false, req.flash('loginError', 'Password does not Match.'));
        }
        var email_address = req.body.email;
        username_tmp = email_address;
        var username = email_address.substring(0, email_address.lastIndexOf("@"));
        global_username = username;
        pass = req.body.password;
        return done(null, user);
      });
    }
  )
);

//Check whether it is logged in or not.
//If it is not logged in(Session is out), it goes to login page
//If it is logged in(Session is still on), it goes directly to status.html

app.get('/', loggedInCheck);

app.get('/login', function (req, res) {
  res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
});

//Accessing to MongoDB to check to login or not
app.post('/login',
  function (req,res,next){
    next();
  }, passport.authenticate('local-login', {
    successRedirect : '/status',
    failureRedirect : '/login',
    failureFlash : true
  })
);

//Creating new account
app.get('/users/new', function(req,res){
  res.render('users/new', {
                            formData: req.flash('formData')[0],
                            emailError: req.flash('emailError')[0],
                            passwordError: req.flash('passwordError')[0]
                          }
  );
});


//Calling status.html
app.get('/status', isLoggedIn, function(req, res){
  var user_temp = {user: ''};
  user_temp.user = global_username;
  res.render('status/status', user_temp);
  //res.redirect('/status.html?channel=' + global_username);
});

app.get('/grafana', isLoggedIn, function(req, res){
  console.log('Accessing to grafana');
  res.redirect('http://localhost:8080');
 });

request.get('http://localhost:8080',{
  auth: {
    bearer: 'TOKEN HERE'
  }
});


server.listen(4000);

Edited more

app.get('/grafana', isLoggedIn, function(req, res){
  console.log('Accessing to grafana');
  var url = 'http://localhost:8080/api/dashboards/db/test';
  request.get(url,{
    auth: {
      bearer: 'API token from Grafana page'
    }
  });
  res.redirect(url);
 });

Thank you..


回答1:


The API calls are made with HTTP requests. You can use the request package from npm.

From the docs:

You use the token in all requests in the Authorization header, like this: GET http://your.grafana.com/api/dashboards/db/mydash HTTP/1.1 Accept: application/json Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk

Example (I'm using request-promise but you can use whatever you want):

let request = require('request-promise');
let url = `http://your.grafana.com/api/dashboards/db/mydash`;
//Obviously replace this with your token
let myToken = `eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk`;
request.get(url).auth(null, null, true, myToken).then(res=> { ... });
// or
request.get(url, {
  auth: {
    bearer: myToken
  }
}).then(res=> { ... });


来源:https://stackoverflow.com/questions/42545857/how-to-make-api-call-using-api-token-in-node-js-using-express-passport-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!