Example #1
0
  return new Promise(function(resolve, reject) {
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');

    // uncomment after placing your favicon in /public
    app.use(favicon(__dirname + '/public/ECG_favicon.png'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    require("node-jsx").install();
    var key = new stormpath.ApiKey(process.env.STORMPATH_API_KEY_ID, process.env.STORMPATH_API_KEY_SECRET);
    var client = new stormpath.Client({apiKey: key});
    var strategy = new StormpathStrategy();

    passport.use(strategy);
    passport.serializeUser(strategy.serializeUser);
    passport.deserializeUser(strategy.deserializeUser);
    app.use(session({ secret: "adsgfjaklajkl;46j;kl6bkjlgkjl;gkl;jadfbh", key: 'sid', cookie: {secure: false} }));
    app.use(passport.initialize());
    app.use(passport.session());

    client.getApplications({name: "Empty Clip Gaming"}, function(err, applications) {
      if (err) return reject(err);

      app.use(function(req, res, next) {
        req.stormpath = applications.items[0];
        next();
      });

      return resolve();
    });
  });
/**
 * Initialize the Stormpath client.
 *
 * @method
 * @private
 *
 * @param {Object} app - The express application.
 * @param {object} opts - A JSON hash of user supplied options.
 *
 * @return {Function} A function which accepts a callback.
 */
function initClient(app, opts) {
  var userAgent = 'stormpath-express/' + version + ' ' + 'express/' + expressVersion;
  opts.userAgent = userAgent;

  // If the options aren't valid for any reason, we'll throw a nice
  // human-readable error so the developer can quickly fix the configuration
  // issue(s) that may be present.

  var client = new stormpath.Client(opts);

  if (!app.get('stormpathLogger')) {
    app.set('stormpathLogger', new winston.Logger({
      transports: [
        new winston.transports.Console({
          colorize: true,
          level: opts.debug ? 'info' : 'error'
        })
      ]
    }));
  }

  client.on('ready', function() {
    new ExpressStormpathConfig(client.config).validate(function(err) {
      if (err) {
        throw err;
      }
    });
    app.set('stormpathClient', client);
    app.set('stormpathConfig', client.config);
  });

  return client;
}
  before(function (done) {
    client = new stormpath.Client({
      skipRemoteConfig: true,
      client: {
        apiKey: {
          id: 'abc',
          secret: 'def'
        }
      }
    });

    testStrategy = new EnrichIntegrationFromRemoteConfigStrategy(function () {
      return client;
    });

    client.on('error', function (err) {
      throw err;
    });

    client.on('ready', function () {
      sinon.stub(client, 'getDirectory')
        .yields(null, mockDirectory);
      done();
    });
  });
stormpath.loadApiKey(apiKeyFilePath, function (err, apiKey) {
  if (err) throw err;

  client = new stormpath.Client({apiKey: apiKey});
  client.getCurrentTenant(function (err, tenant) {
    if (err) throw err;
    onTenantReady(tenant);
  });
});
Example #5
0
stormpath.loadApiKey(apiKeyFilePath, function apiKeyFileLoaded(err, apiKey) {
  if (err){ throw err; }

  var client = new stormpath.Client({apiKey: apiKey});

  client.getApplication('https://api.stormpath.com/v1/applications/1h72PFWoGxHKhysKjYIkir',function(err,app){
    if (err){ throw err; }
    stormpathApplication = app;
    http.createServer(server).listen(3000);
  });
});
Example #6
0
stormpath.loadApiKey(apiKeyFilePath, function apiKeyFileLoaded(err, apiKey) {
  console.log({ apiKey: apiKey });
  var apiKey = { apiKey: apiKey };
  var client = new stormpath.Client(apiKey);
  console.log('Client Created');

  //Get Application
  client.getApplication(appHref, function(err, RMFapp) {
    console.log(RMFapp);
  });
});
Example #7
0
router.post('/register', function(req, res) {

  var username = req.body.username;
  var password = req.body.password;

  // Grab user fields.
  if (!username || !password) {
    return res.render('register', { title: 'Register', error: 'Email and password required.' });
  }

  // Initialize our Stormpath client.
  var apiKey = new stormpath.ApiKey(
    process.env['STORMPATH_API_KEY_ID'],
    process.env['STORMPATH_API_KEY_SECRET']
  );
  var spClient = new stormpath.Client({ apiKey: apiKey });

  // Grab our app, then attempt to create this user's account.
  var app = spClient.getApplication(process.env['STORMPATH_APP_HREF'], function(err, app) {
    if (err) throw err;

    app.createAccount({
      givenName: 'John',
      surname: 'Smith',
      username: username,
      email: username,
      password: password,
    }, function (err, createdAccount) {
      if (err) {
        return res.render('register', {'title': 'Register', error: err.userMessage });
      } else {
        passport.authenticate('stormpath')(req, res, function () {
          var userModel = new model_user.model({ email: req.user.email, 
                                                 counter_owner: 0, 
                                                 counter_public: 0});
          userModel.save(function (err, item) {
            if (err) {
                console.log("error:" + err);
                return res.render('register', {'title': 'Register', error: err });
            }
            return res.redirect('/dashboard');
          });
          
        });
      }
    });

  });

});
Example #8
0
app.get('/', function(req, res){
  if(req.sp && req.sp.accountHref){
    client.getAccount(req.sp.accountHref,function(err,account){
      if(err){
        res.render('error',{
          errorText: String(err)
        });
      }else{
        res.render('index',{
          lastJwt: req.lastJwt.value ? JSON.stringify(req.lastJwt.value,null,2) : null,
          account: account,
          accountJson: JSON.stringify(account,null,2),
          cb_uri: CB_URI,
          idSiteBaseUrl: req.idSiteBaseUrl.value
        });
      }
    });
  }else{

    res.render('index',{
      lastJwt: req.lastJwt.value ? JSON.stringify(req.lastJwt.value,null,2) : null,
      account: null,
      cb_uri: CB_URI,
      idSiteBaseUrl: req.idSiteBaseUrl.value
    });

  }
});
module.exports.getTenantsForUser = function(user){
  var defer = Q.defer();
  client.getAccount(user.href, function(err, account) {
    account.getGroups({name: 'tenant_*'}, function (err, groups) {
      defer.resolve(groups);
    });
  });
  return defer.promise;
};
module.exports.getUsersForGroup = function(group){
  var defer = Q.defer();
  client.getGroup(group.href, function(err, group){
    group.getAccounts(function(err, accounts){
      defer.resolve(accounts.items);
    })
  });
  return defer.promise;
};
Example #11
0
function getApplication(then){
  client.getApplication(client.config.application.href,function(err,a){
    if (err){
      throw err;
    }
    application = a;
    console.log('Using Application "' + application.name + '" (' + application.href + ')')
    then();
  });
}
getApplication = function(){
  if(!applicationPromise){
    var defer = Q.defer();
    applicationPromise = defer.promise;
    client.getApplication(applicationURL, function(err, application){
      if (err) throw err;
      defer.resolve(application);
    });
  }
  return applicationPromise;
};
Example #13
0
// ==================================================
// Step 2 - Register an application with Stormpath
// ==================================================
function createApplication() {

  var app = {
    name: unique('My Awesome Application'),
    description: ('No, Srsly. It\'s Awesome')
  };

  return client.createApplication(app, {createDirectory: true}, function(err, app) {
    if (err) throw err;
    application = app;
    console.log('Created application:');
    console.log(application);
    return createAccount(); //next quickstart step
  });
}
Example #14
0
module.exports.handler = function(event, context, cb) {
  const apiKey = new stormpath.ApiKey(
      event.stormpathClientApiKeyId,
      event.stormpathClientApiKeySecret
  );
  const client = new stormpath.Client({ apiKey: apiKey });

  console.log('Send to ' + 'https://api.stormpath.com/v1/applications/' + event.stormpathApplicationKey);
  console.log('remaining time =', context.getRemainingTimeInMillis());
  client.getApplication('https://api.stormpath.com/v1/applications/' + event.stormpathApplicationKey, function(err, app) {
    if (err) return cb(err, null);
    console.log('remaining time =', context.getRemainingTimeInMillis());

    return stormpathHelper.authenticateAccountByToken(app, event.access_token, function(err, account) {
      console.log('remaining time =', context.getRemainingTimeInMillis());

      console.log('found account: ');
      console.log(account);
      cb(null, account);
    });
  });


};
Example #15
0
router.post('/register', function(req, res) {

  var username = req.body.username;
  var password = req.body.password;
  var fullname = req.body.fullname;
  var firstname,lastname = '';
  var nameRegex = /^([A-Za-z\u00C0-\u017F]*)\s(.*)/;

  if (fullname) {

    var match = nameRegex.exec(fullname);
    if (match && match.length > 2) {
      firstname = match[1];
      lastname = match[2];
    }
   
  }
  


  // Grab user fields.
  if (!firstname || !lastname) {
    req.flash('error','Firstname and lastname required.');
    req.flash('title','Sign Up');
    return res.redirect('/');
  }

  if (!username || !password) {
    req.flash('error','Email and password required.');
    req.flash('title','Sign Up');
    return res.redirect('/');
  }

  // Initialize our Stormpath client.
  var apiKey = new stormpath.ApiKey(
    process.env['STORMPATH_API_KEY_ID'],
    process.env['STORMPATH_API_KEY_SECRET']
  );
  var spClient = new stormpath.Client({ apiKey: apiKey });

  // Grab our app, then attempt to create this user's account.
  var app = spClient.getApplication(process.env['STORMPATH_APP_HREF'], function(err, app) {
    if (err) throw err;

    app.createAccount({
      givenName: firstname,
      surname: lastname,
      username: username,
      email: username,
      password: password,
    }, function (err, createdAccount) {
      if (err) {
        req.flash('error',err.userMessage);
        req.flash('title','Sign Up');
        return res.redirect('/');
      } else {
        passport.authenticate('stormpath')(req, res, function () {
          return res.redirect('/dashboard');
        });
      }
    });
  });

});
Example #16
0
var stormpath = require('stormpath');

//helper function to prevent any data collisions in the tenant while running the quickstart:
function unique(aString) {
  return aString + '-' + require('uuid').v4().toString();
}

//populated during the quickstart steps
var client, application, account, group = null;

var accountEmail = unique('jlpicard') + '@mailinator.com';

// ==================================================
// Step 1 - Create a client and wait for it to ready
// ==================================================
var client = new stormpath.Client();

client.on('ready', createApplication);

// ==================================================
// Step 2 - Register an application with Stormpath
// ==================================================
function createApplication() {

  var app = {
    name: unique('My Awesome Application'),
    description: ('No, Srsly. It\'s Awesome')
  };

  return client.createApplication(app, {createDirectory: true}, function(err, app) {
    if (err) throw err;
 app: new Promise((resolve,reject) => {
   client.getApplication(applicationHref, (err, application) => {
     if (err) reject(err)
     else resolve(application)
   })
 }),
Example #18
0
var apiKey = {
	id: process.env.STORMPATH_ID,
	secret: process.env.STORMPATH_SECRET
};
var appId = process.env.STORMPATH_APPID;

if(!apiKey.id || !apiKey.secret) {
	apiKey.id = 'NF0P0OR4JZ0BYI1MMHFCH9Z4X';
  apiKey.secret = 'jjpXpjDjBF8o21VzltHygmYhAkbEozbk7NPsyAPogfQ';
	appId = '2dOFY5UnOtoCGznZKlA5ax';

	//console.warn('Stormpath API key and secret are required');
//	process.exit();
}

var client = new stormpath.Client({ apiKey: apiKey });

var application = null;
client.getApplication('https://api.stormpath.com/v1/applications/' + appId, function(err, resource) {
	if(err) console.log('Could not retrieve stormpath application', appId);
	application = resource;
});

controller.spawn({ token: token }).startRTM(function (err, bot, payload) {
  if (err) throw new Error('Error connecting to Slack: ', err);
  console.log('Connected to Slack');
});

controller.hears(['hi'], ['direct_message', 'direct_mention'], function (bot, message) {
  startRegistrationConversation(bot, message);
});
 it ('should retrieve our application', (done) => {
   client.getApplication(applicationHref, (err, result) => {
     application = result
     done()
   })
 })
Example #20
0
var nJwt = require('njwt');
var sessions = require('client-sessions');
var stormpath = require('stormpath');
var request = require('request');
var url = require('url');

var IS_PRODUCTION = process.env.NODE_ENV==='production';
var PORT = process.env.PORT || 8001;
var DOMAIN = process.env.DOMAIN || 'stormpath.localhost';
var ID_SITE_PATH = process.env.ID_SITE_PATH || '';
var CB_URI = process.env.CB_URI || ('http://' + DOMAIN + ':' + PORT + '/idSiteCallback' );

var app = express();
var application;
var client = new stormpath.Client({
  baseUrl: process.env.STORMPATH_APPLICATION_HREF.match(/.+v1/)[0]
});

app.set('views', './views');
app.set('view engine', 'jade');


var spCookieInterface = sessions({
  cookieName: 'sp', // cookie name dictates the key name added to the request object
  secret: 'will be set after client initialization', // should be a large unguessable string
  duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
  activeDuration: 1000 * 60 * 5 // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
});

var lastJwtCookieInterface = sessions({
  cookieName: 'lastJwt', // cookie name dictates the key name added to the request object