How to use the forest-express-sequelize.ensureAuthenticated function in forest-express-sequelize

To help you get started, we’ve selected a few forest-express-sequelize examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github opencollective / opencollective-api / server / lib / forest.js View on Github external
export default app => {
  if (!process.env.FOREST_ENV_SECRET || !process.env.FOREST_AUTH_SECRET) {
    return;
  }

  app.use(init());

  app.post('/forest/actions/activate-subscription', Liana.ensureAuthenticated, (req, res) => {
    const data = req.body.data;
    const id = data.attributes.ids[0];
    models.Subscription.findOne({ where: { id } })
      .then(subscription => subscription.activate())
      .then(() => {
        res.status(200).send({ success: 'The subscription was successfully activated.' });
      })
      .catch(e => {
        res.status(400).send({ error: e.message });
      });
  });

  app.post('/forest/actions/cancel-subscription', Liana.ensureAuthenticated, (req, res) => {
    const data = req.body.data;
    const id = data.attributes.ids[0];
    models.Subscription.findOne({ where: { id } })
github opencollective / opencollective-api / server / lib / forest.js View on Github external
const msg = 'The user and its dependencies were successfully deleted.';
      res.status(200).send({
        html: `<p>${msg}</p>
               <p><a href="../../../">Click here to continue</a>.</p>`,
      });
    } catch (e) {
      const msg = e.message;
      res.status(400).send({
        error: `There was an error while processing your request.\n
          "${msg}"\n
          Maybe you want to proceed manually?`,
      });
    }
  });

  app.post('/forest/actions/delete-user-and-merge', Liana.ensureAuthenticated, async (req, res) =&gt; {
    const data = req.body.data;
    console.log(data);
    const id = data.attributes.ids[0];
    const mergeIntoUserId = data.attributes.values['User ID'];
    try {
      const user = await models.User.findOne({ where: { id } });
      const userCollective = await models.Collective.findOne({
        where: { id: user.CollectiveId },
      });
      if (!user || !userCollective) {
        throw Error('Can not fetch origin user.');
      }
      const mergeIntoUser = await models.User.findOne({
        where: { id: mergeIntoUserId },
      });
      const mergeIntoUserCollective = await models.Collective.findOne({
github ForestAdmin / forest-live-demo-lumber / routes / dashboard.js View on Github external
repartition.push({ key: country, value: 1 }); 
        } else {
          entry.value++;
        }
      });
    })
    .then(() => {
      let json = new Liana.StatSerializer({ 
        value: repartition 
      }).perform();

      res.send(json);
    });
});

router.post('/stats/charges-per-day', Liana.ensureAuthenticated, (req, res) => {
  let values = [];

  let from = moment.utc('2018-03-01').unix();
  let to = moment.utc('2018-03-31').unix();

  return stripe.charges
    .list({ 
      created: { gte: from, lte: to }
    })
    .then((response) => {
      return P.each(response.data, (charge) => {
        let date = moment.unix(charge.created).startOf('day').format('LLL');

        let entry = _.find(values, { label: date });
        if (!entry) {
          values.push({ label: date, values: { value: 1 } });
github ForestAdmin / forest-live-demo-lumber / routes / customers.js View on Github external
const express = require('express');
const router = express.Router();
const Liana = require('forest-express-sequelize');
const models = require('../models');
const jwt = require('jsonwebtoken');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

router.post('/actions/generate-invoice', Liana.ensureAuthenticated, (req, res) => {
  let options = {
    root: __dirname + '/../public/',
    dotfiles: 'deny',
    headers: {
      'Access-Control-Expose-Headers': 'Content-Disposition',
      'Content-Disposition': 'attachment; filename="invoice-2342.pdf"'
    }
  };

  let fileName = 'invoice-2342.pdf';
  res.sendFile(fileName, options, (error) => {
    if (error) { next(error); }
  });
});

router.post('/actions/charge-credit-card', Liana.ensureAuthenticated, (req, res) => {
github ForestAdmin / forest-live-demo-lumber / routes / products.js View on Github external
return models.products.create({
							label: row[0],
							price: price,
							picture: row[1].replace('//i5.walmartimages.com/asr/', '//s3-eu-west-1.amazonaws.com/forestadmin-test/livedemo/')
						});
					})
					.then(() => {
						res.send({ success: 'Data successfuly imported!' });
					});
			}
		});
  });

router.get('/products/:product_id/relationships/buyers', 
  Liana.ensureAuthenticated, (req, res, next) => {
    let limit = parseInt(req.query.page.size) || 10;
    let offset = (parseInt(req.query.page.number) - 1) * limit;

    let queryType = models.sequelize.QueryTypes.SELECT;

    let countQuery = `
      SELECT COUNT(*)
      FROM customers
      JOIN orders ON orders.customer_id = customers.id
      JOIN products ON orders.product_id = products.id
      WHERE product_id = ${req.params.product_id};
    `;

    let dataQuery = `
      SELECT customers.*
      FROM customers
github ForestAdmin / forest-live-demo-lumber / routes / customers.js View on Github external
let options = {
    root: __dirname + '/../public/',
    dotfiles: 'deny',
    headers: {
      'Access-Control-Expose-Headers': 'Content-Disposition',
      'Content-Disposition': 'attachment; filename="invoice-2342.pdf"'
    }
  };

  let fileName = 'invoice-2342.pdf';
  res.sendFile(fileName, options, (error) => {
    if (error) { next(error); }
  });
});

router.post('/actions/charge-credit-card', Liana.ensureAuthenticated, (req, res) => {
  let customerId = req.body.data.attributes.ids[0];
  let amount = req.body.data.attributes.values.amount * 100;
  let description = req.body.data.attributes.values.description;

  return models.customers
    .findById(customerId)
    .then((customer) => {
      return stripe.charges.create({
        amount: amount,
        currency: 'usd',
        customer: customer.stripe_id,
        description: description
      });
    })
    .then((response) => {
      res.send({
github ForestAdmin / forest-live-demo-lumber / routes / products.js View on Github external
const P = require('bluebird');
const express = require('express');
const router = express.Router();
const Liana = require('forest-express-sequelize');
const faker = require('faker');
const parseDataUri = require('parse-data-uri');
const csv = require('csv');
const models = require('../models');

router.post('/products/actions/import-data', Liana.ensureAuthenticated,
  (req, res) => {
		let parsed = parseDataUri(req.body.data.attributes.values['CSV file']);

		csv.parse(parsed.data, { delimiter: ';' }, function (err, rows) {
			if (err) {
				res.status(400).send({ 
					error: `Cannot import data: ${err.message}` });
			} else {
				return P
					.each(rows, (row) => {
						let price = 0;
						switch (req.body.data.attributes.values['Type']) {
							case 'phone':
								price = faker.commerce.price(300, 1000) * 100;
								break;
							case 'dress':
github ForestAdmin / forest-live-demo-lumber / routes / dashboard.js View on Github external
const _ = require('lodash');
const P = require('bluebird');
const express = require('express');
const router = express.Router();
const Liana = require('forest-express-sequelize');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const moment = require('moment');

router.post('/stats/mrr', Liana.ensureAuthenticated, (req, res) => {
  let mrr = 0;

  let from = moment.utc('2018-03-01').unix();
  let to = moment.utc('2018-03-31').unix();

  return stripe.charges
    .list({ 
      created: { gte: from, lte: to }
    })
    .then((response) => {
      return P.each(response.data, (charge) => {
        mrr += charge.amount;
      });
    })
    .then(() => {
      let json = new Liana.StatSerializer({