1

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..

paulc1111
  • 631
  • 3
  • 14
  • 32

1 Answers1

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=> { ... });
Muli Yulzary
  • 2,559
  • 3
  • 21
  • 39
  • Thank you for the answer! I have few questions about your answer. Can I use just 'request' package instead of 'request-promise'? And what should be inside of .then(res=>{...});? – paulc1111 Mar 02 '17 at 03:01
  • If you use `request` instead of `request-promise` you will have to use the node-style callback instead of the `.then()` promise syntax. check request's repo. Inside the curly braces is the code you want to run after getting the results from the API. – Muli Yulzary Mar 02 '17 at 03:20
  • ah ha I see, I have one more question. what is 'let'? Shouldn't it be 'var' instead of 'let'? – paulc1111 Mar 02 '17 at 03:55
  • 1
    @paulc1111 - [see here](http://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable)... javascript enclosures are complicated, but not when you get the hang of them. – wahwahwah Mar 02 '17 at 05:34
  • @MuliYulzary I'm getting {message: "Unauthorized"} Can you see my "edited more" from the post? :'( – paulc1111 Mar 02 '17 at 06:06
  • You've used it incorrectly. do you wish to **redirect** your user to the graphana interface or **present** some useful data from their API? – Muli Yulzary Mar 02 '17 at 14:40