Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var _ = require('lodash');
- var sha512 = require('js-sha512');
- var md5 = require('md5');
- var jwt = require('jsonwebtoken');
- var moment = require('moment');
- var jwtBlacklist = require('express-jwt-blacklist');
- var PhoneNumber = require( 'awesome-phonenumber');
- module.exports = function(app, Sequelize, db)
- {
- let Groups = require('../groups/index')(app, Sequelize);
- return controller = {
- index: (req, res) =>
- {
- let limit = req.query.limit || 10;
- let page = req.query.page || 1;
- return app.api.models.users.findAndCountAll(
- {
- attributes: [
- 'id',
- 'firstname',
- 'lastname',
- 'email',
- 'role',
- 'createdAt',
- 'updatedAt'
- ],
- limit: limit,
- offset: (page - 1) * limit,
- order: 'createdAt DESC, updatedAt DESC',
- })
- .then(data =>
- {
- var users = [];
- data.rows.forEach(u =>
- {
- var user = {
- id: u.id,
- firstname: u.firstname,
- lastname: u.lastname,
- email: u.email,
- email_md5 : md5(u.email),
- role: u.role,
- status: 'offline',
- createdAt: u.createdAt,
- updatedAt: u.updatedAt,
- isFriend: false,
- friendship_status: null
- };
- var clients = app.socketManager.getClients();
- clients.forEach(c => {
- if(c.id == u.id)
- user.status = 'online';
- });
- if(user.id !== req.session.user.id)
- users.push(user);
- });
- return controller.getFriends(req.session.user.id)
- .then(friends =>
- {
- users.forEach((usr, i) => {
- friends.forEach(friend => {
- if (friend.friend_id == usr.id || friend.friendship_author == usr.id) {
- users[i].isFriend = true;
- users[i].friendship_status = friend.friendship_status;
- }
- });
- });
- app.success(res, {
- count : data.count,
- rows : users,
- nbPages : Math.ceil(data.count / limit)
- });
- })
- .catch(error => {
- app.error(res, error);
- })
- })
- .catch(error => app.error(res, error))
- },
- getGroups: (req, res) => {
- if(typeof req.session.user !== 'undefined') {
- return Groups.getUserGroups(req.session.user.id)
- .then(groups => {
- app.success(res, groups);
- })
- .catch(err => {
- app.error(res, error);
- })
- }
- },
- search: (req, res) =>
- {
- if(typeof req.session.user !== 'undefined') {
- return app.api.models.users.findAll({
- attributes: [
- 'id',
- 'firstname',
- 'lastname',
- 'email',
- 'role'
- ],
- where: { $or: [
- {firstname: {$like: '%' + req.body.q + '%'}},
- {lastname: {$like: '%' + req.body.q + '%'}}
- ]},
- order: 'createdAt DESC, updatedAt DESC'
- })
- .then(data => {
- var users = [];
- data.forEach((u) => {
- var user = {
- id: u.id,
- firstname: u.firstname,
- lastname: u.lastname,
- fullname: [u.firstname, u.lastname].join(' '),
- email: u.email,
- email_md5: md5(u.email),
- role: u.role,
- status: 'offline',
- };
- var clients = app.socketManager.getClients();
- clients.forEach((c) => {
- if (c.id == u.id)
- user.status = 'online';
- });
- users.push(user)
- });
- app.success(res, users);
- })
- .catch(error => app.error(res, error))
- }
- },
- delete: (req, res) =>
- {
- if(typeof req.session.user !== 'undefined') {
- return app.api.models.users.destroy({
- where: {
- id: req.params.id
- }
- })
- .then(user => {
- if (user > 0) {
- app.success(res, user, 'Deleted');
- app.logger.warn('The user "%s" has unregister', req.params.id);
- }
- else
- app.error(res, {statusCode: 404, message: 'Not found'});
- })
- .catch(error => app.error(res, error))
- }
- },
- logout: function(req, res)
- {
- if(typeof req.session.user !== 'undefined')
- {
- var client = app.socketManager.getClientSocket(req.session.user.id);
- req.session.user.status = 'offline';
- if(client)
- client.broadcast.emit('onUserStatus', req.session.user);
- let now = new Date();
- now.setHours(now.getHours() + 1);
- return app.api.models.users.update({
- lastSeen: now
- }, {
- where: {
- id: req.session.user.id
- }
- })
- .then(updated => {
- //Todo: revoke jwt token
- app.logger.info('%s %s has disconnected' , req.session.user.firstname, req.session.user.lastname);
- delete req.session.user;
- app.success(res, null, 'Disconnected');
- })
- .catch(error => {
- console.log(error);
- app.error(res, error);
- });
- }
- else
- app.error(res, {statusCode: 404, message: 'No session to logout'});
- },
- email: function(req, res)
- {
- },
- isAuth: function(req, res)
- {
- if(typeof req.session.user !== 'undefined')
- app.success(res, null, 'Authentified');
- else
- app.error(res, {statusCode: 401, message: 'Not authentified'});
- },
- auth: function(req, res)
- {
- return app.api.models.users.findAndCountAll(
- {
- attributes: [
- 'id',
- 'firstname',
- 'lastname',
- 'biography',
- 'email',
- 'activated',
- 'role'
- ],
- include: [
- {model : app.api.models.walls}
- ],
- where: {
- email : req.body.email || '',
- password : sha512(req.body.password || '')
- }
- })
- .then(function(data)
- {
- if(data.rows.length == 0)
- app.error(res, {statusCode: 401, message: 'Invalid credentials'});
- else
- {
- data = data.rows[0];
- var user = {
- id: data.get('id'),
- firstname: data.get('firstname'),
- lastname: data.get('lastname'),
- biography: data.get('biography'),
- email: data.get('email'),
- email_md5 : md5(data.get('email')),
- role: data.get('role'),
- activated: data.get('activated'),
- wallId: data.get('walls')[0].get('id')
- };
- if(user.activated)
- {
- user.email_md5 = md5(user.email);
- delete user.activated;
- delete user.email;
- user.token = jwt.sign(user, app.config.apis.jwt.key, {
- expiresIn: 7 * 24 * 60 * 60
- });
- req.session.user = data;
- app.logger.info(
- '%s %s has just connected',
- req.session.user.firstname,
- req.session.user.lastname
- );
- app.success(res, user, 'Authentified');
- }
- else
- app.error(res, {
- statusCode: 401,
- message: 'Your account is not activated. Please check your emails.'
- });
- }
- })
- .catch(function(error)
- { app.error(res, error) });
- },
- recover: function(req, res)
- {
- },
- view: function(req, res)
- {
- let usersFields = ['id', 'firstname', 'lastname', 'email'];
- return app.api.models.users.findAndCountAll({
- where: {
- id: req.params.id
- },
- include: [
- {
- model : app.api.models.posts,
- limit : 10,
- order : [['createdAt', 'DESC']]
- },
- {
- model : app.api.models.groups,
- limit : 10
- },
- {
- model : app.api.models.walls,
- limit : 1,
- include: [
- {
- model: app.api.models.posts,
- limit: 10,
- order : [['createdAt', 'DESC']],
- include: [
- { model : app.api.models.users, attributes: usersFields},
- { model : app.api.models.medias},
- ]
- }
- ]
- }
- ]
- })
- .then(function(data)
- {
- if(data)
- {
- var u = data.rows[0];
- var wall = typeof u.walls[0] !== 'undefined' ? u.walls[0] : null;
- var user =
- {
- id : u.id,
- isFriend : false,
- friendship_status : null,
- firstname : u.firstname,
- lastname : u.lastname,
- fullname : [u.firstname, u.lastname].join(' '),
- biography : u.biography,
- birthdate : u.birthdate,
- phone : u.phone,
- city : u.city,
- country : u.country,
- postal_code : u.postal_code,
- road_number : u.road_number,
- road_name : u.road_name,
- createdAt : u.createdAt,
- updatedAt : u.updatedAt,
- lastSeen : u.lastSeen,
- activated : u.activated,
- passwordAt : u.passwordAt,
- email : u.email,
- email_md5 : md5(u.email),
- role : u.role,
- status : 'offline',
- posts : u.posts,
- wall : wall,
- groups : u.groups,
- };
- var clients = app.socketManager.getClients();
- clients.forEach((c) => {
- if(c.id == u.id)
- user.status = 'online';
- });
- return controller.getFriends(u.id)
- .then(friends =>
- {
- user.friends = friends;
- user.friends.forEach(friend => {
- if(friend.friend_id == req.session.user.id) {
- user.isFriend = true;
- user.friendship_status = friend.friendship_status
- }
- });
- app.success(res, user);
- })
- .catch(error => {
- app.error(res, error);
- })
- }
- else
- app.error(res, {statusCode: 404, message: 'User not found'});
- })
- .catch(function(error)
- { app.error(res, error) })
- },
- getFriends: userId => {
- return new Promise((resolve, reject) => {
- if(typeof db !== 'undefined') {
- db.query
- (`
- SELECT
- m.id as friend_id,
- m.firstname as friend_firstname,
- m.lastname as friend_lastname,
- md5(m.email) as friend_email_md5,
- x.id as friendship_id,
- x.author as friendship_author,
- x.createdAt as friendship_createdAt,
- x.updatedAt as friendship_updatedAt,
- x.status as friendship_status
- FROM
- users m
- JOIN
- (
- (
- SELECT
- f.id,
- f.friendId as user_id,
- f.status,
- f.author,
- f.createdAt,
- f.updatedAt
- FROM
- friends f
- WHERE
- f.userId = ?
- )
- UNION
- (
- SELECT
- t.id,
- t.userId as user_id,
- t.status,
- t.author,
- t.createdAt,
- t.updatedAt
- FROM
- friends t
- WHERE
- t.friendId = ?
- )
- ) x
- ON
- x.user_id = m.id`,
- {
- replacements: [userId, userId]
- }
- )
- .then(friendships => resolve(_.uniqBy(friendships, 'friend_id')[0]))
- .catch(error => reject(error))
- }
- else
- reject('No db instance')
- });
- },
- setActivationKey: function(email, key, cb) {
- return app.api.models.users.update({activationKey: key}, {where: {email: email}}).then(data =>
- {
- if(typeof cb == 'function')
- cb(data);
- }).catch(error => { console.log(error) });
- },
- setResetKey: function(email, key, cb) {
- return app.api.models.users.update({resetKey: key}, {where: {email: email}}).then(data =>
- {
- if(typeof cb == 'function')
- cb(data);
- }).catch(error => { console.log(error) });
- },
- generateToken: function(cb) {
- require('crypto').randomBytes(48, function(err, buffer) {
- if(!err && typeof cb == 'function')
- cb(buffer.toString('hex'));
- else
- cb(false);
- });
- },
- activation: function(req, res) {
- app.success(res, {}, 'Ok');
- },
- request: function(req, res)
- {
- return app.api.models.users.findOne({
- where: {email: req.body.email}
- }).then(exists =>
- {
- if(exists !== null)
- {
- return controller.generateToken(token =>
- {
- let template = null, action = {};
- if(req.params.type == 'activation') {
- template = 'register';
- action.url = `${app.config.application.hostname}/#/activation/${exists.email}/${token}`;
- controller.setActivationKey(exists.email, token);
- }
- else if(req.params.type == 'password') {
- template = 'password';
- action.url = `${app.config.application.hostname}/#/passwordReset/${exists.email}/${token}`;
- controller.setResetKey(exists.email, token);
- }
- if(template)
- {
- app.mailer.send(template, {
- from: 'no-reply@network.crafting.fr',
- to: exists.email,
- action: action
- });
- app.success(res, {}, 'Email sent');
- }
- });
- }
- else
- app.error(res, {statusCode: 409, message: 'This user doesn\'t exists'});
- });
- },
- validateEmail(email) {
- let sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
- let sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
- let sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
- let sQuotedPair = '\\x5c[\\x00-\\x7f]';
- let sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
- let sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
- let sDomain_ref = sAtom;
- let sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
- let sWord = '(' + sAtom + '|' + sQuotedString + ')';
- let sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
- let sLocalPart = sWord + '(\\x2e' + sWord + ')*';
- let sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
- let sValidEmail = '^' + sAddrSpec + '$'; // as whole string
- var reValidEmail = new RegExp(sValidEmail);
- return reValidEmail.test(email);
- },
- save: function(req, res)
- {
- if(!req.body.id)
- app.error(res, {statusCode: 409, message: 'This user doesn\'t exists'});
- else {
- return app.api.models.users.findOne({
- where: {id: req.body.id}
- })
- .then(exists =>
- {
- if(req.session.user.role == 'user' && req.body.id != req.session.user.id)
- app.error(res, {statusCode: 401, message: 'You dont have the permission to edit this data'});
- else
- {
- if(exists !== null)
- {
- let user = {
- updatedAt: new Date()
- };
- if(req.body.firstname)
- user.firstname = req.body.firstname;
- if(req.body.lastname)
- user.lastname = req.body.lastname;
- if(req.body.biography)
- user.biography = req.body.biography;
- if(req.body.birthdate)
- user.birthdate = moment(req.body.birthdate).format('YYYY-MM-DD');
- if(req.body.email && controller.validateEmail(req.body.email))
- user.email = req.body.email;
- if(req.body.activated)
- user.activated = req.body.activated === true ? 1 : 0;
- if(req.body.role)
- user.role = req.body.role;
- if(typeof req.body.phone !== 'undefined')
- {
- if(req.body.phone.toString().length > 0) {
- let pn = new PhoneNumber(req.body.phone, 'FR');
- if(pn.a.valid !== true) {
- app.error(res, {statusCode: 406, message: 'The phone number is not valid'});
- return false;
- }
- else if(pn.a.type !== 'mobile') {
- app.error(res, {statusCode: 406, message: 'Only mobile numbers are allowed'});
- return false;
- }
- else
- user.phone = req.body.phone;
- }
- else
- user.phone = null
- }
- if(typeof req.body.city !== 'undefined')
- user.city = req.body.city;
- if(typeof req.body.country !== 'undefined')
- user.country = req.body.country;
- if(typeof req.body.postal_code !== 'undefined')
- user.postal_code = req.body.postal_code;
- if(typeof req.body.road_number !== 'undefined')
- user.road_number = req.body.road_number;
- if(typeof req.body.road_name !== 'undefined')
- user.road_name = req.body.road_name;
- if(typeof req.body.actual_password !== 'undefined'
- && typeof req.body.new_password !== 'undefined'
- && typeof req.body.confirm_password !== 'undefined') {
- if(sha512(req.body.actual_password) == exists.password)
- {
- if(req.body.confirm_password == req.body.new_password) {
- user.password = sha512(req.body.new_password);
- user.passwordAt = new Date();
- }
- else
- {
- app.error(res, {
- statusCode: 406,
- message: 'The new password doesn\'t match the confirmation'
- });
- return false;
- }
- }
- else {
- app.error(res, {
- statusCode: 406,
- message: 'The actual password is wrong'
- });
- return false;
- }
- }
- return app.api.models.users.update(user, {where: {id: exists.id}}).then(function(data)
- {
- return app.api.models.users.findAndCountAll({where: {id: exists.id}}).then(function(payload) {
- let u = payload.rows[0];
- app.success(res, {
- id: u.get('id'),
- firstname: u.get('firstname'),
- lastname: u.get('lastname'),
- biography: u.get('biography'),
- birthdate: u.get('birthdate'),
- phone: u.get('phone'),
- city: u.get('city'),
- country: u.get('country'),
- postal_code: u.get('postal_code'),
- road_number: u.get('road_number'),
- road_name: u.get('road_name'),
- email: u.get('email'),
- email_md5: md5(u.get('email')),
- activated: u.get('activated'),
- ban: u.get('ban'),
- ban_start: u.get('ban_start'),
- ban_end: u.get('ban_end'),
- role: u.get('role'),
- passwordAt: u.get('passwordAt'),
- activatedAt: u.get('activatedAt'),
- resetAt: u.get('resetAt'),
- createdAt: u.get('createdAt'),
- updatedAt: u.get('updatedAt')
- });
- })
- })
- .catch(error => { app.error(res, error); });
- }
- else
- app.error(res, {statusCode: 409, message: 'This user doesn\'t exists'});
- }
- });
- }
- },
- create: function(req, res)
- {
- return app.api.models.users.findOne({
- where: {email: req.body.email}
- })
- .then(function(exists)
- {
- if(exists === null)
- {
- req.body.password = sha512(req.body.password);
- req.body.activated = 1;
- req.body.role = 'user';
- return app.api.models.users.create(req.body)
- .then(user =>
- {
- var u =
- {
- id : user.id,
- firstname : user.firstname,
- lastname : user.lastname,
- birthdate : '0000-00-00 00:00:00',
- email_md5 : md5(user.email),
- role : user.role,
- status : 'offline'
- };
- return app.api.models.walls.create({
- privacy : 'public',
- userId : user.id
- })
- .then(wall =>
- {
- app.events.emit('mail:send', {
- template: 'register',
- to: user.email
- });
- app.success(res, u, 'Created');
- })
- .catch(error => console.log(error))
- })
- .catch(error => app.error(res, error));
- }
- else
- app.error(res, {
- statusCode: 409,
- message: 'Email already used'
- });
- });
- }
- };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement