Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import _ from 'lodash';
- import logger from '../lib/logger';
- import nonce from 'nonce';
- import * as config from '../lib/config';
- import * as models from './models';
- import * as date from '../lib/date';
- import * as crypto from '../lib/crypto';
- import * as mail from '../lib/mailer';
- import { passportInstance } from '../lib/passport';
- import { bookshelf } from '../lib/dbmanager';
- import { Organization } from '../organizations/models';
- import { Role } from './rolemodels';
- import InvalidTokenError from '../lib/errors/InvalidTokenError';
- import UserNotFoundError from '../lib/errors/UserNotFoundError';
- import * as cropper from './handleImageSave';
- let numberGenerator = nonce();
- // Helper function
- function generateRandomId() {
- return numberGenerator();
- }
- function authenticate(req, res, next, func) {
- passportInstance.authenticate(func, (err, user, info) => {
- if (err) {
- return next(err);
- }
- if (!user) {
- if (info && info.message) {
- return (res.status(401).send(info.message));
- }
- return (res.status(401).send('Unknown error'));
- } else {
- return res.status(200).send('Registered');
- }
- })(req, res, next);
- }
- // Regular login
- export function login(req, res, next) {
- passportInstance.authenticate('local', (err, user, info) => {
- if (err) {
- return next(err);
- }
- if (user) {
- req.logIn(user, (error) => {
- if (error) {
- return next(error);
- }
- return res.send(user);
- });
- } else {
- if (info && info.message) {
- return (res.status(401).send(info.message));
- }
- return (res.status(401).send('Unknown error'));
- }
- })(req, res, next);
- }
- export function currentUser(req, res) {
- res.status(200).send({
- id: req.user.attributes.id
- });
- }
- export function logout(req, res) {
- req.logout();
- res.sendStatus(200);
- }
- export function signup (req, res, next) {
- var errors = req.validationErrors();
- if (errors) {
- res.status(400).send(errors);
- } else {
- authenticate(req, res, next, 'signup');
- }
- }
- export function confirmUser (req, res, next) {
- if (req.params.token) {
- models.User
- .where({
- userConfirmationToken: req.params.token
- })
- .fetch()
- .then((user) => {
- if (user) {
- user.set('isConfirmed', true);
- return user.save();
- } else {
- throw new UserNotFoundError('user_not_found', new Error('User not found'));
- }
- })
- .then(() => {
- res.json({
- success: true,
- loginUrl: config.loginUrl
- });
- })
- .catch((err) => {
- if (err.name === 'UserNotFoundError') {
- res.status(400).send({
- error: err.message
- });
- } else {
- next(err);
- }
- });
- } else {
- res.status(400).send({
- error: 'Invalid token'
- });
- }
- }
- export function sendResetAccountEmail(req, res, next) {
- let resetToken = generateRandomId();
- if (req.query.email) {
- models.User
- .where({
- username: req.query.email
- })
- .fetch()
- .then((user) => {
- if (user) {
- user.set('resetToken', resetToken);
- let expirationDate = date.todayPlusDays(1);
- user.set('resetTokenExpiration', expirationDate);
- return user.save();
- } else {
- throw new UserNotFoundError('user_not_found', new Error('User not found'));
- }
- })
- .then((user) => {
- return mail.sendResetLink(user.get('username'), resetToken);
- })
- .then(() => {
- res.json({
- success: true
- });
- })
- .catch((err) => {
- if (err.name === 'UserNotFoundError') {
- res.status(400).send({
- error: err.message
- });
- } else {
- next(err);
- }
- });
- } else {
- res.status(400).send({
- error: 'Invalid email'
- });
- }
- }
- export function sendAffiliate(req, res, next) {
- if (typeof req.body.affiliateLink !== 'undefined') {
- mail.sendAffiliateMail(req.body.email, req.body.affiliateLink)
- .then(() => {
- res.status(200).send({message: 'SUCCESS'});
- })
- .catch((err) => {
- next(err);
- })
- .done();
- } else {
- res.status(500).send({errror: 'Can not send email'});
- }
- }
- export function resetAccount(req, res, next) {
- if (req.body.newpassword && req.body.token) {
- models.User
- .where({
- resetToken: req.body.token
- })
- .fetch()
- .then((user) => {
- if (user) {
- let now = new Date();
- let expDate = new Date(user.get('resetTokenExpiration'));
- if (now < expDate) {
- user.set('resetToken', null);
- user.set('resetTokenExpiration', null);
- let hashedPass = crypto.hashSync(req.body.newpassword.trim());
- user.set('password', hashedPass);
- user.save();
- return user.save();
- } else {
- throw new InvalidTokenError('invalid_reset_token', new Error('Account Reset invitation has expired.'));
- }
- } else {
- throw new UserNotFoundError('user_not_found', new Error('User not found'));
- }
- })
- .then((user) => {
- res.json({
- success: true,
- userFirstName: user.attributes.firstname
- });
- })
- .catch((err) => {
- if (err.name === 'UserNotFoundError' || err.name === 'InvalidTokenError') {
- res.status(400).send({
- error: err.message
- });
- } else {
- next(err);
- }
- });
- } else {
- res.status(400).send({
- error: 'Invalid reset token or password data'
- });
- }
- }
- //All users with related organizations
- export function listUsers(req, res, next) {
- models.User.fetchAll({
- columns: ['id', 'name', 'username', 'providerName']
- })
- .then(function(data) {
- res.json(data);
- })
- .catch(function(err) {
- next(err);
- });
- }
- export function updateUserInfo(req, res) {
- cropper.saveImage(req.body.image, req.body.croppedRect, false)
- .then((image) => {
- return bookshelf.knex('users')
- .where('id', req.user.attributes.id)
- .update({
- name: req.body.name,
- username: req.body.email,
- image: image
- });
- })
- .then(() => {
- return models.User
- .query({where: {id: req.user.attributes.id}})
- .fetch({columns: ['id', 'name', 'username', 'providerName', 'image']});
- })
- .then((user)=> {
- res.status(200).send(user);
- })
- .catch((err) => {
- logger.log(err);
- res.status(500).send({error: 'Unable to update user info!'});
- })
- .done();
- }
- //Fetch all organizations for current user
- export function getCurrentUserOrganizations(req, res, next) {
- // If trying to access admin page while logged in in POS/mobile
- if (req.user.loginType === 'm') {
- return res.status(403).end();
- }
- //Get userId from session
- var userId = req.user.attributes.id;
- models.User
- .query({where: {id: userId}})
- .fetch({
- columns: ['users.id', 'users.name', 'users.username', 'users.providerName', 'image'],
- withRelated: [
- {
- 'organizations': function(qb) {
- qb.select('organizations.*');
- qb.join('roles', 'roleId', '=', 'roles.id');
- qb.select('roles.rolename');
- }
- },
- {
- 'organizations.events': function(qb) {
- qb.join('users_organizations', 'events.organizationId', '=', 'users_organizations.organizationId');
- qb.where('users_organizations.userId', '=', userId);
- qb.join('roles', 'users_organizations.roleId', '=', 'roles.id');
- qb.select('events.*');
- qb.select('roles.rolename');
- }
- }
- ]}).
- then(function(data) {
- res.json(data);
- })
- .catch(function(err) {
- next(err);
- });
- }
- // Get user by ID
- export function userById(req, res, next) {
- if (req.params.id == null) {
- return res.status(500).end();
- }
- models.User
- .query({where: {id: req.params.id}})
- .fetch({columns: ['id', 'firstname', 'lastname', 'username', 'providerName']})
- .then(function(data) {
- res.json(data);
- })
- .catch(function(err) {
- next(err);
- });
- }
- export function inviteUser(req, res) {
- let userId = req.user.attributes.id;
- let invitationToken = generateRandomId();
- models.User
- .query({where: {id: userId}})
- .fetch({
- columns: ['name']
- }).then((user)=> {
- let name = `${_.capitalize(user.attributes.name)}`;
- bookshelf.knex.insert({
- email: req.body.userData.invitedUserEmail,
- inviteToken: invitationToken,
- organizationId: req.body.currentOrganizationId
- }, 'email')
- .into('invited_users')
- .then((invitedUserEmail) => {
- return mail.sendInvitationForNonRegistered(name, req.body.userData.invitedUserEmail, req.body.currentOrganizationName, invitationToken);
- })
- .then(() => {
- res.json({
- invitedUserEmail: req.body.userData.invitedUserEmail
- });
- })
- .catch((err) => {
- res.status(400).send({
- error: err.message
- });
- })
- .done();
- });
- }
- export function setUserRole(req, res) {
- let data = {};
- let previousRoleId = null;
- let newRoleId = req.body.roleId;
- models.UsersOrganizations.forge({userId: req.params.id})
- .fetch({require: true})
- .then(function(userOrganization) {
- previousRoleId = userOrganization.toJSON().roleId;
- return bookshelf.knex('users_organizations').where({userId: req.params.id}).update({roleId: newRoleId});
- })
- .then(function() {
- return models.User
- .query({where: {id: req.params.id}})
- .fetch({
- columns: ['name']
- });
- })
- .then(function(usr) {
- data.user = usr;
- return Role.query({where: {id: previousRoleId}}).fetch({columns: ['rolename']});
- })
- .then(function(previousRole) {
- data.previousRole = previousRole;
- })
- .then(function() {
- return Role.query({where: {id: newRoleId}}).fetch({columns: ['rolename']});
- })
- .then(function(newRole) {
- data.newRole = newRole;
- })
- .then(function() {
- res.json({
- error: false,
- data: data
- });
- })
- .catch(function (err) {
- res.status(500).json({error: true, data: {message: err.message}});
- })
- .done();
- }
- export function payout(req, res) {
- bookshelf.knex('event_currencies').where({sign: req.body.payoutCurrencySign}).select('id')
- .then((updatedRowsIdArray) => {
- return bookshelf.knex('payouts').insert({payoutAmount: req.body.payoutAmount, userId: req.user.attributes.id, currencyId: updatedRowsIdArray[0].id, companyId: req.body.orgId});
- })
- .then((payoutId) => {
- return bookshelf.knex('payouts')
- .select('payoutAmount','sign as currencySign', 'name as currencyName', 'payoutStatus', 'companyId', 'created_at')
- .where({'payouts.id': payoutId[0]})
- .innerJoin('event_currencies', 'payouts.currencyId', 'event_currencies.id')
- })
- .then((data) => {
- res.json(data[0]);
- })
- .catch(function (err) {
- res.sendStatus(500);
- })
- .done();
- }
- export function removeUserFromOrganization(req, res) {
- let data = {};
- models.UsersOrganizations.forge({userId: req.params.id, organizationId: req.params.orgId})
- .fetch({require: true})
- .then(function(userOrganization) {
- userOrganization.destroy();
- return userOrganization.toJSON();
- })
- .then(function(userOrganization) {
- return models.User.query({where: {id: userOrganization.userId}})
- .fetch({columns: ['name']});
- })
- .then(function(user) {
- data.user = user;
- return Organization
- .query({where: {id: req.params.orgId}})
- .fetch({
- columns: ['name']
- });
- })
- .then(function(organization) {
- data.organization = organization;
- res.json({
- error: false,
- data: data
- });
- })
- .catch(function (err) {
- res.status(500).json({error: true, data: {message: err.message}});
- })
- .done();
- }
- export function activateInvitation(req, res, next) {
- let token = req.body.token;
- bookshelf.knex('invited_users')
- .where('inviteToken', token)
- .update({
- active: 1
- })
- .then(() => {
- res.sendStatus(200);
- })
- .catch((err) => {
- next(err);
- })
- .done();
- }
- export function userInviteVerification(req, res) {
- let token = req.body.token;
- let inviteData = [];
- let userData = [];
- let userExist = false;
- models.UserInvites
- .query({where: {inviteToken: token}})
- .fetch()
- .then((data) => {
- inviteData = data.toJSON();
- return models.User.query({where: {username: inviteData.email}}).fetch();
- })
- .then((result) => {
- if (result) {
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement