Advertisement
Guest User

Untitled

a guest
Oct 11th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.67 KB | None | 0 0
  1. import _ from 'lodash';
  2. import logger from '../lib/logger';
  3. import nonce from 'nonce';
  4.  
  5. import * as config from '../lib/config';
  6. import * as models from './models';
  7. import * as date from '../lib/date';
  8. import * as crypto from '../lib/crypto';
  9. import * as mail from '../lib/mailer';
  10. import { passportInstance } from '../lib/passport';
  11. import { bookshelf } from '../lib/dbmanager';
  12. import { Organization } from '../organizations/models';
  13. import { Role } from './rolemodels';
  14. import InvalidTokenError from '../lib/errors/InvalidTokenError';
  15. import UserNotFoundError from '../lib/errors/UserNotFoundError';
  16. import * as cropper from './handleImageSave';
  17.  
  18. let numberGenerator = nonce();
  19. // Helper function
  20. function generateRandomId() {
  21. return numberGenerator();
  22. }
  23.  
  24. function authenticate(req, res, next, func) {
  25. passportInstance.authenticate(func, (err, user, info) => {
  26. if (err) {
  27. return next(err);
  28. }
  29. if (!user) {
  30. if (info && info.message) {
  31. return (res.status(401).send(info.message));
  32. }
  33. return (res.status(401).send('Unknown error'));
  34. } else {
  35. return res.status(200).send('Registered');
  36. }
  37. })(req, res, next);
  38. }
  39.  
  40. // Regular login
  41. export function login(req, res, next) {
  42. passportInstance.authenticate('local', (err, user, info) => {
  43. if (err) {
  44. return next(err);
  45. }
  46. if (user) {
  47. req.logIn(user, (error) => {
  48. if (error) {
  49. return next(error);
  50. }
  51. return res.send(user);
  52. });
  53. } else {
  54. if (info && info.message) {
  55. return (res.status(401).send(info.message));
  56. }
  57. return (res.status(401).send('Unknown error'));
  58. }
  59. })(req, res, next);
  60. }
  61.  
  62. export function currentUser(req, res) {
  63. res.status(200).send({
  64. id: req.user.attributes.id
  65. });
  66. }
  67.  
  68. export function logout(req, res) {
  69. req.logout();
  70. res.sendStatus(200);
  71. }
  72.  
  73. export function signup (req, res, next) {
  74. var errors = req.validationErrors();
  75. if (errors) {
  76. res.status(400).send(errors);
  77. } else {
  78. authenticate(req, res, next, 'signup');
  79. }
  80. }
  81.  
  82. export function confirmUser (req, res, next) {
  83. if (req.params.token) {
  84. models.User
  85. .where({
  86. userConfirmationToken: req.params.token
  87. })
  88. .fetch()
  89. .then((user) => {
  90. if (user) {
  91. user.set('isConfirmed', true);
  92. return user.save();
  93. } else {
  94. throw new UserNotFoundError('user_not_found', new Error('User not found'));
  95. }
  96. })
  97. .then(() => {
  98. res.json({
  99. success: true,
  100. loginUrl: config.loginUrl
  101. });
  102. })
  103. .catch((err) => {
  104. if (err.name === 'UserNotFoundError') {
  105. res.status(400).send({
  106. error: err.message
  107. });
  108. } else {
  109. next(err);
  110. }
  111. });
  112. } else {
  113. res.status(400).send({
  114. error: 'Invalid token'
  115. });
  116. }
  117. }
  118.  
  119. export function sendResetAccountEmail(req, res, next) {
  120. let resetToken = generateRandomId();
  121. if (req.query.email) {
  122. models.User
  123. .where({
  124. username: req.query.email
  125. })
  126. .fetch()
  127. .then((user) => {
  128. if (user) {
  129. user.set('resetToken', resetToken);
  130. let expirationDate = date.todayPlusDays(1);
  131. user.set('resetTokenExpiration', expirationDate);
  132. return user.save();
  133. } else {
  134. throw new UserNotFoundError('user_not_found', new Error('User not found'));
  135. }
  136. })
  137. .then((user) => {
  138. return mail.sendResetLink(user.get('username'), resetToken);
  139. })
  140. .then(() => {
  141. res.json({
  142. success: true
  143. });
  144. })
  145. .catch((err) => {
  146. if (err.name === 'UserNotFoundError') {
  147. res.status(400).send({
  148. error: err.message
  149. });
  150. } else {
  151. next(err);
  152. }
  153. });
  154. } else {
  155. res.status(400).send({
  156. error: 'Invalid email'
  157. });
  158. }
  159. }
  160.  
  161. export function sendAffiliate(req, res, next) {
  162. if (typeof req.body.affiliateLink !== 'undefined') {
  163. mail.sendAffiliateMail(req.body.email, req.body.affiliateLink)
  164. .then(() => {
  165. res.status(200).send({message: 'SUCCESS'});
  166. })
  167. .catch((err) => {
  168. next(err);
  169. })
  170. .done();
  171. } else {
  172. res.status(500).send({errror: 'Can not send email'});
  173. }
  174. }
  175.  
  176. export function resetAccount(req, res, next) {
  177. if (req.body.newpassword && req.body.token) {
  178. models.User
  179. .where({
  180. resetToken: req.body.token
  181. })
  182. .fetch()
  183. .then((user) => {
  184. if (user) {
  185. let now = new Date();
  186. let expDate = new Date(user.get('resetTokenExpiration'));
  187. if (now < expDate) {
  188. user.set('resetToken', null);
  189. user.set('resetTokenExpiration', null);
  190. let hashedPass = crypto.hashSync(req.body.newpassword.trim());
  191. user.set('password', hashedPass);
  192. user.save();
  193. return user.save();
  194. } else {
  195. throw new InvalidTokenError('invalid_reset_token', new Error('Account Reset invitation has expired.'));
  196. }
  197. } else {
  198. throw new UserNotFoundError('user_not_found', new Error('User not found'));
  199. }
  200. })
  201. .then((user) => {
  202. res.json({
  203. success: true,
  204. userFirstName: user.attributes.firstname
  205. });
  206. })
  207. .catch((err) => {
  208. if (err.name === 'UserNotFoundError' || err.name === 'InvalidTokenError') {
  209. res.status(400).send({
  210. error: err.message
  211. });
  212. } else {
  213. next(err);
  214. }
  215. });
  216. } else {
  217. res.status(400).send({
  218. error: 'Invalid reset token or password data'
  219. });
  220. }
  221. }
  222.  
  223.  
  224. //All users with related organizations
  225. export function listUsers(req, res, next) {
  226. models.User.fetchAll({
  227. columns: ['id', 'name', 'username', 'providerName']
  228. })
  229. .then(function(data) {
  230. res.json(data);
  231. })
  232. .catch(function(err) {
  233. next(err);
  234. });
  235. }
  236.  
  237. export function updateUserInfo(req, res) {
  238. cropper.saveImage(req.body.image, req.body.croppedRect, false)
  239. .then((image) => {
  240. return bookshelf.knex('users')
  241. .where('id', req.user.attributes.id)
  242. .update({
  243. name: req.body.name,
  244. username: req.body.email,
  245. image: image
  246. });
  247. })
  248. .then(() => {
  249. return models.User
  250. .query({where: {id: req.user.attributes.id}})
  251. .fetch({columns: ['id', 'name', 'username', 'providerName', 'image']});
  252. })
  253. .then((user)=> {
  254. res.status(200).send(user);
  255. })
  256. .catch((err) => {
  257. logger.log(err);
  258. res.status(500).send({error: 'Unable to update user info!'});
  259. })
  260. .done();
  261. }
  262.  
  263. //Fetch all organizations for current user
  264. export function getCurrentUserOrganizations(req, res, next) {
  265. // If trying to access admin page while logged in in POS/mobile
  266. if (req.user.loginType === 'm') {
  267. return res.status(403).end();
  268. }
  269. //Get userId from session
  270. var userId = req.user.attributes.id;
  271. models.User
  272. .query({where: {id: userId}})
  273. .fetch({
  274. columns: ['users.id', 'users.name', 'users.username', 'users.providerName', 'image'],
  275. withRelated: [
  276. {
  277. 'organizations': function(qb) {
  278. qb.select('organizations.*');
  279. qb.join('roles', 'roleId', '=', 'roles.id');
  280. qb.select('roles.rolename');
  281. }
  282. },
  283. {
  284. 'organizations.events': function(qb) {
  285. qb.join('users_organizations', 'events.organizationId', '=', 'users_organizations.organizationId');
  286. qb.where('users_organizations.userId', '=', userId);
  287. qb.join('roles', 'users_organizations.roleId', '=', 'roles.id');
  288. qb.select('events.*');
  289. qb.select('roles.rolename');
  290. }
  291. }
  292. ]}).
  293. then(function(data) {
  294. res.json(data);
  295. })
  296. .catch(function(err) {
  297. next(err);
  298. });
  299. }
  300.  
  301. // Get user by ID
  302. export function userById(req, res, next) {
  303. if (req.params.id == null) {
  304. return res.status(500).end();
  305. }
  306.  
  307. models.User
  308. .query({where: {id: req.params.id}})
  309. .fetch({columns: ['id', 'firstname', 'lastname', 'username', 'providerName']})
  310. .then(function(data) {
  311. res.json(data);
  312. })
  313. .catch(function(err) {
  314. next(err);
  315. });
  316. }
  317.  
  318. export function inviteUser(req, res) {
  319. let userId = req.user.attributes.id;
  320. let invitationToken = generateRandomId();
  321.  
  322. models.User
  323. .query({where: {id: userId}})
  324. .fetch({
  325. columns: ['name']
  326. }).then((user)=> {
  327. let name = `${_.capitalize(user.attributes.name)}`;
  328. bookshelf.knex.insert({
  329. email: req.body.userData.invitedUserEmail,
  330. inviteToken: invitationToken,
  331. organizationId: req.body.currentOrganizationId
  332. }, 'email')
  333. .into('invited_users')
  334. .then((invitedUserEmail) => {
  335. return mail.sendInvitationForNonRegistered(name, req.body.userData.invitedUserEmail, req.body.currentOrganizationName, invitationToken);
  336. })
  337. .then(() => {
  338. res.json({
  339. invitedUserEmail: req.body.userData.invitedUserEmail
  340. });
  341. })
  342. .catch((err) => {
  343. res.status(400).send({
  344. error: err.message
  345. });
  346. })
  347. .done();
  348.  
  349. });
  350. }
  351.  
  352. export function setUserRole(req, res) {
  353. let data = {};
  354. let previousRoleId = null;
  355. let newRoleId = req.body.roleId;
  356. models.UsersOrganizations.forge({userId: req.params.id})
  357. .fetch({require: true})
  358. .then(function(userOrganization) {
  359. previousRoleId = userOrganization.toJSON().roleId;
  360. return bookshelf.knex('users_organizations').where({userId: req.params.id}).update({roleId: newRoleId});
  361. })
  362. .then(function() {
  363. return models.User
  364. .query({where: {id: req.params.id}})
  365. .fetch({
  366. columns: ['name']
  367. });
  368. })
  369. .then(function(usr) {
  370. data.user = usr;
  371. return Role.query({where: {id: previousRoleId}}).fetch({columns: ['rolename']});
  372. })
  373. .then(function(previousRole) {
  374. data.previousRole = previousRole;
  375. })
  376. .then(function() {
  377. return Role.query({where: {id: newRoleId}}).fetch({columns: ['rolename']});
  378. })
  379. .then(function(newRole) {
  380. data.newRole = newRole;
  381. })
  382. .then(function() {
  383. res.json({
  384. error: false,
  385. data: data
  386. });
  387. })
  388. .catch(function (err) {
  389. res.status(500).json({error: true, data: {message: err.message}});
  390. })
  391. .done();
  392. }
  393.  
  394.  
  395. export function payout(req, res) {
  396. bookshelf.knex('event_currencies').where({sign: req.body.payoutCurrencySign}).select('id')
  397. .then((updatedRowsIdArray) => {
  398. return bookshelf.knex('payouts').insert({payoutAmount: req.body.payoutAmount, userId: req.user.attributes.id, currencyId: updatedRowsIdArray[0].id, companyId: req.body.orgId});
  399. })
  400. .then((payoutId) => {
  401. return bookshelf.knex('payouts')
  402. .select('payoutAmount','sign as currencySign', 'name as currencyName', 'payoutStatus', 'companyId', 'created_at')
  403. .where({'payouts.id': payoutId[0]})
  404. .innerJoin('event_currencies', 'payouts.currencyId', 'event_currencies.id')
  405. })
  406. .then((data) => {
  407. res.json(data[0]);
  408. })
  409. .catch(function (err) {
  410. res.sendStatus(500);
  411. })
  412. .done();
  413. }
  414.  
  415. export function removeUserFromOrganization(req, res) {
  416. let data = {};
  417. models.UsersOrganizations.forge({userId: req.params.id, organizationId: req.params.orgId})
  418. .fetch({require: true})
  419. .then(function(userOrganization) {
  420. userOrganization.destroy();
  421. return userOrganization.toJSON();
  422. })
  423. .then(function(userOrganization) {
  424. return models.User.query({where: {id: userOrganization.userId}})
  425. .fetch({columns: ['name']});
  426. })
  427. .then(function(user) {
  428. data.user = user;
  429. return Organization
  430. .query({where: {id: req.params.orgId}})
  431. .fetch({
  432. columns: ['name']
  433. });
  434. })
  435. .then(function(organization) {
  436. data.organization = organization;
  437. res.json({
  438. error: false,
  439. data: data
  440. });
  441. })
  442. .catch(function (err) {
  443. res.status(500).json({error: true, data: {message: err.message}});
  444. })
  445. .done();
  446. }
  447.  
  448. export function activateInvitation(req, res, next) {
  449. let token = req.body.token;
  450. bookshelf.knex('invited_users')
  451. .where('inviteToken', token)
  452. .update({
  453. active: 1
  454. })
  455. .then(() => {
  456. res.sendStatus(200);
  457. })
  458. .catch((err) => {
  459. next(err);
  460. })
  461. .done();
  462. }
  463.  
  464. export function userInviteVerification(req, res) {
  465. let token = req.body.token;
  466. let inviteData = [];
  467. let userData = [];
  468. let userExist = false;
  469.  
  470. models.UserInvites
  471. .query({where: {inviteToken: token}})
  472. .fetch()
  473. .then((data) => {
  474. inviteData = data.toJSON();
  475. return models.User.query({where: {username: inviteData.email}}).fetch();
  476. })
  477. .then((result) => {
  478. if (result) {
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement