mardi 5 mai 2015

How to set up environment variables for MEAN stack?

I just followed a MEAN stack tutorial to build a demo app. A hard-coded JWT secret 'SECRET' was used for authentication and the tutorial notes you should implement this as an environment variable instead of hard-coding it (makes sense). How does one do this?

The relevant portions of code are in models/Users.js:

var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');

var UserSchema = new mongoose.Schema({
  username: {type: String, lowercase: true, unique: true},
  hash: String,
  salt: String
});

// ...

UserSchema.methods.generateJWT = function() {
    var today = new Date();
    var exp = new Date(today);
    exp.setDate(today.getDate() + 60);
    return jwt.sign({
        _id: this._id,
        username: this.username,
        exp: parseInt(exp.getTime() / 1000)
    }, 'SECRET');  // <----
};

mongoose.model('User', UserSchema);

And in routes/index.js:

var express = require('express');
var router = express.Router();
var passport = require('passport');

var jwt = require('express-jwt');
var auth = jwt({secret: 'SECRET', userProperty: 'payload'}); // <----

var mongoose = require('mongoose');
var User = mongoose.model('User');

// ...

How to make 'SECRET' an environment variable?

Thanks in advance.

2 commentaires: