Skip to content

Commit

Permalink
add usersHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
banglashi committed Feb 27, 2021
1 parent c22b99f commit c7256d4
Show file tree
Hide file tree
Showing 3 changed files with 178 additions and 107 deletions.
97 changes: 97 additions & 0 deletions helpers/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"use strict";

const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const db = require('../models/db');
const uuidv4 = require('uuid/v4');

var createUser = function(email, nickname, password, locale, homeFolderName) {
return new Promise((resolve, reject) => {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(password, salt, function(err, hash) {
crypto.randomBytes(16, function(ex, buf) {
var token = buf.toString('hex');

var u = {
_id: uuidv4(),
email: email,
account_type: "email",
nickname: nickname,
password_hash: hash,
prefs_language: locale,
confirmation_token: token
};

db.User.create(u)
.error(err => {
reject(err);
})
.then(u => {
var homeFolder = {
_id: uuidv4(),
name: homeFolderName,
space_type: "folder",
creator_id: u._id
};
db.Space.create(homeFolder)
.error(err => {
reject(err);
// res.sendStatus(400);
})
.then(homeFolder => {
u.home_folder_id = homeFolder._id;
u.save()
.then(() => {
// home folder created,
// auto accept pending invites
db.Membership.update({
"state": "active"
}, {
where: {
"email_invited": u.email,
"state": "pending"
}
});
resolve(u)
})
.error(err => {
reject(err);
});
})
});
});
});
});
});
};
var createSession = function(user, ip){
return new Promise((resolve, reject) => {
crypto.randomBytes(48, function(ex, buf) {
var token = buf.toString('hex');
var session = {
user_id: user._id,
token: token,
ip: ip,
device: "web",
created_at: new Date()
};

db.Session.create(session)
.error(err => {
console.error("Error creating Session:", err);
reject(err);
// res.sendStatus(500);
})
.then(() => {
resolve(session)
// var domain = (process.env.NODE_ENV == "production") ? new URL(config.get('endpoint')).hostname : req.headers.hostname;
// res.cookie('sdsession', token, { domain: domain, httpOnly: true });
// res.status(201).json(session);
});
});
});
}
module.exports = {
createUser,
createSession
}
115 changes: 73 additions & 42 deletions routes/api/passport-ldap.js
Original file line number Diff line number Diff line change
@@ -1,88 +1,119 @@
"use strict";

const db = require('../../models/db');
var express = require('express');
var router = express.Router();

var config = require('config');
var crypto = require('crypto');
const db = require('../../models/db');
const usersHelper = require('../../helpers/users');


var passport = require('passport')
, LdapStrategy = require('passport-ldapauth');

var opts = {
usernameField: 'email',
passwordField: 'password',
server: {
url: 'ldaps://ad.corporate.com:636',
bindDN: 'cn=non-person,ou=system,dc=corp,dc=corporate,dc=com',
bindCredentials: 'secret',
searchBase: 'dc=corp,dc=corporate,dc=com',
searchFilter: '(&(objectcategory=person)(objectclass=user)(|(samaccountname={{username}})(mail={{username}})))',
searchAttributes: ['displayName', 'mail'],
tlsOptions: {
ca: [
tfs.readFileSync('/path/to/root_ca_cert.crt')
]
}
url: config.get("auth_ldap_server"),
bindDN: config.get("auth_ldap_bind_dn"),
bindCredentials: config.get("auth_ldap_bind_credentials"),
searchBase: config.get("auth_ldap_search_base"),
searchFilter: config.get("auth_ldap_search_filter"),
searchAttributes: config.get("auth_ldap_search_attributes")
// tlsOptions: {
// ca: [
// tfs.readFileSync('/path/to/root_ca_cert.crt')
// ]
// }
}
};

passport.use(new LdapStrategy(opts));

passport.serializeUser(function(user, done) {
done(null, user._id);
done(null, user);
});

passport.deserializeUser(function(id, done) {
db.User.findById(id).then(function(user) {
done(null, user);
}).error(err => {
done(err);
passport.deserializeUser(function(user, done) {
db.User.findOne({where: {email: user.uid}})
.error(err => {
return done(err);
})
.then(user => {
if (!user) {
return done(null, false, { message: 'User not found.' });
}
return done(null, user);
});
});

router.post('/', (req, res, next) => {
passport.authenticate('ldapauth',
(err, user, info) => {
console.log('LDAPSTRATEGY');
if (err) {
return next(err);
}

if (!user) {
return res.redirect('/login?info=' + info);
}

req.logIn(user, function(err) {
if (err) {
return next(err);
}
crypto.randomBytes(48, function(ex, buf) {
var token = buf.toString('hex');

var session = {
user_id: user._id,
token: token,
ip: req.ip,
device: "web",
created_at: new Date()
};

db.Session.create(session)
.error(err => {
console.error("Error creating Session:",err);
res.sendStatus(500);
})
.then(() => {
var domain = (process.env.NODE_ENV == "production") ? new URL(config.get('endpoint')).hostname : req.headers.hostname;
res.cookie('sdsession', token, { domain: domain, httpOnly: true });
var email = user.mail.toLowerCase();
var nickname = user.uid.toLowerCase();
var password = "";
var domain = (process.env.NODE_ENV == "production") ? new URL(config.get('endpoint')).hostname : req.headers.hostname;

db.User.findAll({where: {email: email}})
.then(users => {
if (users.length == 0) {
usersHelper.createUser(email, nickname, password, "en", "Home")
.then((user) => {
usersHelper.createSession(user, req.ip)
.then((session) => {
res.cookie('sdsession', session.token, { domain: domain, httpOnly: true });
res.status(201).json(session);
}).catch((err) => {
res.status(400).json(err);
});
}).catch((err) => {
res.status(500).json(err);
});
} else {
usersHelper.createSession(users[0], req.ip)
.then((session) => {
res.cookie('sdsession', session.token, { domain: domain, httpOnly: true });
res.status(201).json(session);
}).catch((err) => {
res.status(500).json(err);
});
// res.status(400).json({"error":"user_email_already_used"});
}
});

// res.status(201).json(user);
// return res.redirect('/');
});

})(req, res, next);
});

router.delete('/current', function(req, res, next) {
if (req.user) {
req.logout();
var token = req.cookies['sdsession'];
db.Session.findOne({where: {token: token}})
.then(session => {
session.destroy();
});
var domain = (process.env.NODE_ENV == "production") ? new URL(config.get('endpoint')).hostname : req.headers.hostname;
res.clearCookie('sdsession', { domain: domain });
res.sendStatus(204);
} else {
res.sendStatus(404);
}
});


module.exports = router;
73 changes: 8 additions & 65 deletions routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,21 @@

var config = require('config');
const db = require('../../models/db');
const uuidv4 = require('uuid/v4');
const os = require('os');

var usersHelper = require('../../helpers/users');
var mailer = require('../../helpers/mailer');
var uploader = require('../../helpers/uploader');
var importer = require('../../helpers/importer');

var bcrypt = require('bcryptjs');
var crypto = require('crypto');
var async = require('async');
var _ = require('underscore');
var fs = require('fs');
var request = require('request');
var gm = require('gm');
var validator = require('validator');
var URL = require('url').URL;

var express = require('express');
var router = express.Router();
var glob = require('glob');

router.get('/current', function(req, res, next) {
if (req.user) {
Expand Down Expand Up @@ -67,71 +62,19 @@ router.post('/', function(req, res) {
return;
}

var createUser = function() {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(password, salt, function(err, hash) {
crypto.randomBytes(16, function(ex, buf) {
var token = buf.toString('hex');

var u = {
_id: uuidv4(),
email: email,
account_type: "email",
nickname: nickname,
password_hash: hash,
prefs_language: req.i18n.locale,
confirmation_token: token
};

db.User.create(u)
.error(err => {
res.sendStatus(400);
})
.then(u => {
var homeFolder = {
_id: uuidv4(),
name: req.i18n.__("home"),
space_type: "folder",
creator_id: u._id
};
db.Space.create(homeFolder)
.error(err => {
res.sendStatus(400);
})
.then(homeFolder => {
u.home_folder_id = homeFolder._id;
u.save()
.then(() => {
// home folder created,
// auto accept pending invites
db.Membership.update({
"state": "active"
}, {
where: {
"email_invited": u.email,
"state": "pending"
}
});
res.status(201).json({});
})
.error(err => {
res.status(400).json(err);
});
})
});
});
});
});
};

db.User.findAll({where: {email: email}})
.then(users => {
if (users.length == 0) {
createUser();
usersHelper.createUser(email, nickname, password, req.i18n.locale, req.i18n.__("home"))
.then((user) => {
res.status(201).json({});
}).catch((err) => {
res.status(400).json(err);
});
} else {
res.status(400).json({"error":"user_email_already_used"});
}
})
});
});

router.get('/current', function(req, res, next) {
Expand Down

0 comments on commit c7256d4

Please sign in to comment.