From c7256d42b48b517a71a397b70eefb80c638fae54 Mon Sep 17 00:00:00 2001 From: dm Date: Sat, 27 Feb 2021 11:47:24 +0100 Subject: [PATCH] add usersHelper --- helpers/users.js | 97 ++++++++++++++++++++++++++++++ routes/api/passport-ldap.js | 115 +++++++++++++++++++++++------------- routes/api/users.js | 73 +++-------------------- 3 files changed, 178 insertions(+), 107 deletions(-) create mode 100644 helpers/users.js diff --git a/helpers/users.js b/helpers/users.js new file mode 100644 index 00000000..18503bbe --- /dev/null +++ b/helpers/users.js @@ -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 +} \ No newline at end of file diff --git a/routes/api/passport-ldap.js b/routes/api/passport-ldap.js index 30f3c013..e6e50b19 100644 --- a/routes/api/passport-ldap.js +++ b/routes/api/passport-ldap.js @@ -1,83 +1,97 @@ "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('/'); }); @@ -85,4 +99,21 @@ router.post('/', (req, res, next) => { })(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; \ No newline at end of file diff --git a/routes/api/users.js b/routes/api/users.js index e2e5b2b3..dcbcc419 100644 --- a/routes/api/users.js +++ b/routes/api/users.js @@ -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) { @@ -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) {