Updated frontend
This commit is contained in:
+474
-163
@@ -1,16 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const { Client, Attribute, Change } = require('ldapts');
|
||||
const { LRUCache } = require('lru-cache');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const {Mail} = require('./email');
|
||||
const {Token, InviteToken, PasswordResetToken} = require('./token');
|
||||
const conf = require('../app').conf.ldap;
|
||||
const {Group} = require('./group_ldap');
|
||||
const {UserVerification} = require('./verification');
|
||||
const conf = require('@simpleworkjs/conf').ldap;
|
||||
|
||||
const client = new Client({
|
||||
url: conf.url,
|
||||
function hashPasswordSSHA512(password) {
|
||||
const salt = crypto.randomBytes(8);
|
||||
const hash = crypto.createHash('sha512').update(password).update(salt).digest();
|
||||
return '{SSHA512}' + Buffer.concat([hash, salt]).toString('base64');
|
||||
}
|
||||
|
||||
const cache = new LRUCache({
|
||||
// how long to live in ms
|
||||
ttlAutopurge: true,
|
||||
ttl: 1000 * 60 * 5,
|
||||
});
|
||||
|
||||
function makeClient() {
|
||||
return new Client({ url: conf.url });
|
||||
}
|
||||
|
||||
async function withClient(fn) {
|
||||
const client = makeClient();
|
||||
try {
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
return await fn(client);
|
||||
} finally {
|
||||
await client.unbind().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to escape LDAP filter values (crucial for security)
|
||||
function escapeLDAPSearchValue(val) {
|
||||
return val.replace(/\\/g, '\\5c')
|
||||
.replace(/\*/g, '\\2a')
|
||||
.replace(/\(/g, '\\28')
|
||||
.replace(/\)/g, '\\29')
|
||||
.replace(/\0/g, '\\00');
|
||||
}
|
||||
|
||||
async function addPosixGroup(client, data){
|
||||
|
||||
try{
|
||||
@@ -43,7 +77,7 @@ async function addPosixAccount(client, data){
|
||||
|
||||
data.uidNumber = (Math.max(...people.map(i => i.uidNumber))+1)+'';
|
||||
|
||||
await client.add(`cn=${data.cn},${conf.userBase}`, {
|
||||
const entry = {
|
||||
cn: data.cn,
|
||||
sn: data.sn,
|
||||
uid: data.uid,
|
||||
@@ -51,17 +85,29 @@ async function addPosixAccount(client, data){
|
||||
gidNumber: data.gidNumber,
|
||||
givenName: data.givenName,
|
||||
mail: data.mail,
|
||||
mobile: data.mobile,
|
||||
loginShell: data.loginShell,
|
||||
homeDirectory: data.homeDirectory,
|
||||
userPassword: data.userPassword,
|
||||
description: data.description || ' ',
|
||||
description: data.description || ' ',
|
||||
sudoHost: 'ALL',
|
||||
sudoCommand: 'ALL',
|
||||
sudoUser: data.uid,
|
||||
sshPublicKey: data.sshPublicKey,
|
||||
objectclass: ['inetOrgPerson', 'sudoRole', 'ldapPublicKey', 'posixAccount', 'top' ]
|
||||
});
|
||||
objectclass: ['inetOrgPerson', 'sudoRole', 'ldapPublicKey', 'posixAccount', 'top', 'theta42Person'],
|
||||
};
|
||||
|
||||
if (data.mobile) {
|
||||
entry.mobile = data.mobile;
|
||||
}
|
||||
|
||||
if (data.sshPublicKey) {
|
||||
entry.sshPublicKey = data.sshPublicKey;
|
||||
}
|
||||
|
||||
if (data.dob) {
|
||||
entry.dateOfBirth = data.dob;
|
||||
}
|
||||
|
||||
await client.add(`cn=${data.cn},${conf.userBase}`, entry);
|
||||
|
||||
return data
|
||||
|
||||
@@ -75,36 +121,40 @@ async function addLdapUser(client, data){
|
||||
|
||||
var group;
|
||||
|
||||
try{
|
||||
data.uid = `${data.givenName[0]}${data.sn}`.toLowerCase();
|
||||
data.cn = data.uid;
|
||||
data.loginShell = '/bin/bash';
|
||||
data.homeDirectory= `/home/${data.uid}`;
|
||||
data.userPassword = '{MD5}'+crypto.createHash('md5').update(data.userPassword, "binary").digest('base64');
|
||||
|
||||
group = await addPosixGroup(client, data);
|
||||
data = await addPosixAccount(client, group);
|
||||
try{
|
||||
if (!data.uid) {
|
||||
data.uid = `${data.givenName[0]}${data.sn}`.toLowerCase();
|
||||
}
|
||||
data.cn = data.uid;
|
||||
data.loginShell = '/bin/bash';
|
||||
data.homeDirectory= `/home/${data.uid}`;
|
||||
data.userPassword = hashPasswordSSHA512(data.userPassword);
|
||||
|
||||
return data;
|
||||
console.log('addLdapUser', data)
|
||||
group = await addPosixGroup(client, data);
|
||||
data = await addPosixAccount(client, group);
|
||||
|
||||
}catch(error){
|
||||
await deleteLdapDN(client, `cn=${data.uid},${conf.groupBase}`, true);
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
|
||||
}catch(error){
|
||||
await deleteLdapDN(client, `cn=${data.uid},${conf.groupBase}`, true);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLdapUser(client, data){
|
||||
try{
|
||||
await client.del(`cn=${data.cn},${conf.groupBase}`);
|
||||
await client.del(data.dn);
|
||||
}catch(error){
|
||||
throw error;
|
||||
if (error.code !== 0x20) throw error; // ignore NoSuchObject — personal group may not exist
|
||||
}
|
||||
await client.del(data.dn);
|
||||
}
|
||||
|
||||
async function deleteLdapDN(client, dn, ignoreError){
|
||||
try{
|
||||
client.del(dn)
|
||||
await client.del(dn);
|
||||
}catch(error){
|
||||
if(!ignoreError) throw error;
|
||||
console.error('ERROR: deleteLdapDN', error)
|
||||
@@ -116,6 +166,9 @@ const user_parse = function(data){
|
||||
data.username = data[conf.userNameAttribute]
|
||||
data.userPassword = undefined;
|
||||
}
|
||||
// Use truthy strings so jq-repeat section blocks ({{#isActive}}) fire correctly
|
||||
data.isActive = data.pwdAccountLockedTime ? '' : 'active';
|
||||
data.isInactive = data.pwdAccountLockedTime ? 'inactive' : '';
|
||||
|
||||
return data;
|
||||
}
|
||||
@@ -124,19 +177,18 @@ var User = {}
|
||||
|
||||
User.backing = "LDAP";
|
||||
|
||||
User.clearCache = function() { cache.clear(); };
|
||||
|
||||
User.list = async function(){
|
||||
try{
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
|
||||
const res = await client.search(conf.userBase, {
|
||||
scope: 'sub',
|
||||
filter: conf.userFilter,
|
||||
attributes: ['*', 'createTimestamp', 'modifyTimestamp'],
|
||||
return await withClient(async (client) => {
|
||||
const res = await client.search(conf.userBase, {
|
||||
scope: 'sub',
|
||||
filter: conf.userFilter,
|
||||
attributes: ['*', '+'],
|
||||
});
|
||||
return res.searchEntries.map(function(user){return user.uid});
|
||||
});
|
||||
|
||||
await client.unbind();
|
||||
|
||||
return res.searchEntries.map(function(user){return user.uid});
|
||||
}catch(error){
|
||||
throw error;
|
||||
}
|
||||
@@ -144,26 +196,49 @@ User.list = async function(){
|
||||
|
||||
User.listDetail = async function(){
|
||||
try{
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
const hit = cache.get('__list__');
|
||||
if (hit) return hit;
|
||||
|
||||
const res = await client.search(conf.userBase, {
|
||||
scope: 'sub',
|
||||
filter: conf.userFilter,
|
||||
attributes: ['*', 'createTimestamp', 'modifyTimestamp'],
|
||||
const searchEntries = await withClient(async (client) => {
|
||||
const res = await client.search(conf.userBase, {
|
||||
scope: 'sub',
|
||||
filter: conf.userFilter,
|
||||
attributes: ['*', '+'],
|
||||
});
|
||||
return res.searchEntries;
|
||||
});
|
||||
|
||||
await client.unbind();
|
||||
const users = await Promise.all(searchEntries.map(async (entry) => {
|
||||
const rawPassword = entry.userPassword ? entry.userPassword.toString() : '';
|
||||
const isLegacyMD5 = rawPassword.toUpperCase().startsWith('{MD5}');
|
||||
|
||||
let users = []
|
||||
|
||||
for(let user of res.searchEntries){
|
||||
let obj = Object.create(this);
|
||||
Object.assign(obj, user_parse(user));
|
||||
|
||||
users.push(obj)
|
||||
Object.assign(obj, user_parse(entry));
|
||||
|
||||
}
|
||||
const verif = await UserVerification.getOrCreate(obj.uid);
|
||||
|
||||
if (isLegacyMD5 && !verif.password_must_change) {
|
||||
await verif.update({ password_must_change: true });
|
||||
}
|
||||
|
||||
const passwordMustChange = isLegacyMD5 || verif.password_must_change;
|
||||
|
||||
obj.emailVerified = verif.email_verified ? 'verified' : '';
|
||||
obj.phoneVerified = verif.phone_verified ? 'verified' : '';
|
||||
obj.tosAccepted = verif.tos_accepted ? 'accepted' : '';
|
||||
obj.tosNotAccepted = verif.tos_accepted ? '' : 'pending';
|
||||
obj.passwordMustChange = passwordMustChange ? 'yes' : '';
|
||||
obj.onboardingNeeds = [
|
||||
!verif.tos_accepted && 'tos',
|
||||
!obj.dateOfBirth && 'dob',
|
||||
passwordMustChange && 'password',
|
||||
].filter(Boolean);
|
||||
obj.onboardingRequired = obj.onboardingNeeds.length > 0 ? 'yes' : '';
|
||||
|
||||
return obj;
|
||||
}));
|
||||
|
||||
cache.set('__list__', users);
|
||||
return users;
|
||||
|
||||
}catch(error){
|
||||
@@ -171,89 +246,132 @@ User.listDetail = async function(){
|
||||
}
|
||||
};
|
||||
|
||||
User.get = async function(data, key){
|
||||
try{
|
||||
if(typeof data !== 'object'){
|
||||
let uid = data;
|
||||
data = {};
|
||||
data.uid = uid;
|
||||
}
|
||||
|
||||
User.get = async function(data, key) {
|
||||
if (typeof data !== 'object') {
|
||||
data = { uid: data };
|
||||
}
|
||||
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
const searchKey = data.searchKey || key || conf.userNameAttribute;
|
||||
const searchValue = escapeLDAPSearchValue(data.searchValue || data.uid);
|
||||
const filter = `(&${conf.userFilter}(${searchKey}=${searchValue}))`;
|
||||
|
||||
data.searchKey = data.searchKey || key || conf.userNameAttribute;
|
||||
data.searchValue = data.searchValue || data.uid;
|
||||
// Check cache for an existing result or active promise
|
||||
const cached = cache.get(filter);
|
||||
if (cached) return cached;
|
||||
|
||||
let filter = `(&${conf.userFilter}(${data.searchKey}=${data.searchValue}))`;
|
||||
// Define the execution logic as a discrete promise
|
||||
const fetchPromise = (async () => {
|
||||
const res = await withClient(async (client) => {
|
||||
return await client.search(conf.userBase, {
|
||||
scope: 'sub',
|
||||
filter: filter,
|
||||
attributes: ['*', '+'],
|
||||
});
|
||||
});
|
||||
|
||||
const res = await client.search(conf.userBase, {
|
||||
scope: 'sub',
|
||||
filter: filter,
|
||||
attributes: ['*', 'createTimestamp', 'modifyTimestamp'],
|
||||
});
|
||||
const user = res.searchEntries[0];
|
||||
|
||||
await client.unbind();
|
||||
if (!user) {
|
||||
let error = new Error('UserNotFound');
|
||||
error.name = 'UserNotFound';
|
||||
error.message = `LDAP:${searchValue} does not exist`;
|
||||
error.status = 404;
|
||||
throw error;
|
||||
}
|
||||
|
||||
let user = res.searchEntries[0]
|
||||
// Check password hash type before user_parse wipes the field
|
||||
const rawPassword = user.userPassword ? user.userPassword.toString() : '';
|
||||
const isLegacyMD5 = rawPassword.toUpperCase().startsWith('{MD5}');
|
||||
|
||||
if(user){
|
||||
let obj = Object.create(this);
|
||||
Object.assign(obj, user_parse(user));
|
||||
|
||||
return obj;
|
||||
}else{
|
||||
let error = new Error('UserNotFound');
|
||||
error.name = 'UserNotFound';
|
||||
error.message = `LDAP:${data.searchValue} does not exists`;
|
||||
error.status = 404;
|
||||
throw error;
|
||||
}
|
||||
}catch(error){
|
||||
throw error;
|
||||
}
|
||||
let obj = Object.create(this);
|
||||
Object.assign(obj, user_parse(user));
|
||||
|
||||
const verif = await UserVerification.getOrCreate(obj.uid);
|
||||
|
||||
// Auto-flag legacy MD5 password users — persist so subsequent cache hits see it
|
||||
if (isLegacyMD5 && !verif.password_must_change) {
|
||||
await verif.update({ password_must_change: true });
|
||||
}
|
||||
|
||||
const passwordMustChange = isLegacyMD5 || verif.password_must_change;
|
||||
|
||||
obj.emailVerified = verif.email_verified ? 'verified' : '';
|
||||
obj.phoneVerified = verif.phone_verified ? 'verified' : '';
|
||||
obj.tosAccepted = verif.tos_accepted ? 'accepted' : '';
|
||||
obj.tosNotAccepted = verif.tos_accepted ? '' : 'pending';
|
||||
obj.passwordMustChange = passwordMustChange ? 'yes' : '';
|
||||
obj.onboardingNeeds = [
|
||||
!verif.tos_accepted && 'tos',
|
||||
!obj.dateOfBirth && 'dob',
|
||||
passwordMustChange && 'password',
|
||||
].filter(Boolean);
|
||||
obj.onboardingRequired = obj.onboardingNeeds.length > 0 ? 'yes' : '';
|
||||
|
||||
// Replace the promise in the cache with the actual parsed object
|
||||
cache.set(filter, obj);
|
||||
return obj;
|
||||
})();
|
||||
|
||||
// Cache the promise immediately to prevent stampedes
|
||||
cache.set(filter, fetchPromise);
|
||||
|
||||
// If the promise fails, evict it from the cache immediately
|
||||
fetchPromise.catch(() => {
|
||||
cache.delete(filter);
|
||||
});
|
||||
|
||||
return fetchPromise;
|
||||
};
|
||||
|
||||
User.exists = async function(data, key){
|
||||
// Return true or false if the requested entry exists ignoring error's.
|
||||
try{
|
||||
await this.get(data, key);
|
||||
|
||||
return true
|
||||
return await this.get(data, key);
|
||||
}catch(error){
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
User.add = async function(data) {
|
||||
try{
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
if (await this.exists(data.mail, 'mail')) {
|
||||
throw Object.assign(new Error('Email already in use'), {status: 409, name: 'EmailInUse'});
|
||||
}
|
||||
if (data.mobile && await this.exists(data.mobile, 'mobile')) {
|
||||
throw Object.assign(new Error('Phone number already in use'), {status: 409, name: 'PhoneInUse'});
|
||||
}
|
||||
|
||||
await addLdapUser(client, data);
|
||||
|
||||
await client.unbind();
|
||||
await withClient(async (client) => {
|
||||
await addLdapUser(client, data);
|
||||
});
|
||||
cache.clear();
|
||||
|
||||
let user = await this.get(data.uid);
|
||||
|
||||
await UserVerification.getOrCreate(user.uid);
|
||||
|
||||
await Mail.sendTemplate(
|
||||
user.mail,
|
||||
'welcome',
|
||||
{
|
||||
user: user
|
||||
}
|
||||
)
|
||||
try {
|
||||
await Mail.sendTemplate(
|
||||
user.mail,
|
||||
'welcome',
|
||||
{
|
||||
user: user
|
||||
}
|
||||
);
|
||||
} catch(mailErr) {
|
||||
console.error(`User.add: welcome email failed for ${user.uid}:`, mailErr.message);
|
||||
}
|
||||
|
||||
return user;
|
||||
|
||||
}catch(error){
|
||||
if(error.message.includes('exists')){
|
||||
let error = new Error('UserNameUsed');
|
||||
error.name = 'UserNameUsed';
|
||||
error.message = `LDAP:${data.uid} already exists`;
|
||||
error.status = 409;
|
||||
if(error.message && error.message.includes('exists')){
|
||||
let err = new Error('UserNameUsed');
|
||||
err.name = 'UserNameUsed';
|
||||
err.message = `LDAP:${data.uid} already exists`;
|
||||
err.status = 409;
|
||||
|
||||
throw error;
|
||||
throw err;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
@@ -261,25 +379,63 @@ User.add = async function(data) {
|
||||
|
||||
User.update = async function(data){
|
||||
try{
|
||||
let editableFeilds = ['mobile', 'sshPublicKey', 'description'];
|
||||
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
|
||||
for(let field of editableFeilds){
|
||||
if(data[field]){
|
||||
await client.modify(this.dn, [
|
||||
new Change({
|
||||
operation: 'replace',
|
||||
modification: new Attribute({
|
||||
type: field,
|
||||
values: [data[field]]
|
||||
})
|
||||
}),
|
||||
]);
|
||||
if (data.mobile) {
|
||||
const existing = await User.exists(data.mobile, 'mobile');
|
||||
if (existing && existing.uid !== this.uid) {
|
||||
throw Object.assign(new Error('Phone number already in use'), {status: 409, name: 'PhoneInUse'});
|
||||
}
|
||||
}
|
||||
|
||||
await client.unbind()
|
||||
let editableFeilds = ['mobile', 'description'];
|
||||
|
||||
await withClient(async (client) => {
|
||||
for(let field of editableFeilds){
|
||||
if(data[field]){
|
||||
await client.modify(this.dn, [
|
||||
new Change({
|
||||
operation: 'replace',
|
||||
modification: new Attribute({
|
||||
type: field,
|
||||
values: [data[field]]
|
||||
})
|
||||
}),
|
||||
]);
|
||||
this[field] = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
if(data.sshPublicKey){
|
||||
await client.modify(this.dn, [
|
||||
new Change({
|
||||
operation: 'replace',
|
||||
modification: new Attribute({ type: 'sshPublicKey', values: [data.sshPublicKey] }),
|
||||
}),
|
||||
]);
|
||||
this.sshPublicKey = data.sshPublicKey;
|
||||
}
|
||||
|
||||
if(data.dateOfBirth){
|
||||
// Ensure the auxiliary objectClass is present before setting the attribute
|
||||
try {
|
||||
await client.modify(this.dn, [
|
||||
new Change({
|
||||
operation: 'add',
|
||||
modification: new Attribute({ type: 'objectClass', values: ['theta42Person'] }),
|
||||
}),
|
||||
]);
|
||||
} catch(e) {
|
||||
if(e.name !== 'TypeOrValueExistsError') throw e;
|
||||
}
|
||||
await client.modify(this.dn, [
|
||||
new Change({
|
||||
operation: 'replace',
|
||||
modification: new Attribute({ type: 'dateOfBirth', values: [data.dateOfBirth] }),
|
||||
}),
|
||||
]);
|
||||
this.dateOfBirth = data.dateOfBirth;
|
||||
}
|
||||
});
|
||||
cache.clear();
|
||||
|
||||
return this;
|
||||
|
||||
@@ -288,6 +444,50 @@ User.update = async function(data){
|
||||
}
|
||||
};
|
||||
|
||||
User.usernameSuggestions = async function(givenName, sn, dob) {
|
||||
const fn = (givenName || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
const ln = (sn || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
if (!fn || !ln) return [];
|
||||
const gi = fn[0];
|
||||
const li = ln[0];
|
||||
|
||||
const candidates = [
|
||||
`${gi}${ln}`, // jsmith
|
||||
`${fn}${ln}`, // johnsmith
|
||||
`${fn}_${ln}`, // john_smith
|
||||
`${fn}${li}`, // johns
|
||||
`${ln}${gi}`, // smithj
|
||||
];
|
||||
|
||||
if (dob) {
|
||||
const year = new Date(dob).getFullYear();
|
||||
if (!isNaN(year)) {
|
||||
const y4 = String(year);
|
||||
const y2 = y4.slice(2);
|
||||
candidates.push(
|
||||
`${gi}${ln}${y2}`, // jsmith90
|
||||
`${fn}${ln}${y2}`, // johnsmith90
|
||||
`${fn}_${ln}${y2}`, // john_smith90
|
||||
`${gi}${ln}${y4}`, // jsmith1990
|
||||
`${fn}${ln}${y4}`, // johnsmith1990
|
||||
`${fn}_${ln}${y4}`, // john_smith1990
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const available = [];
|
||||
for (const uid of [...new Set(candidates)]) {
|
||||
if (!(await this.exists(uid))) available.push(uid);
|
||||
}
|
||||
if (!available.length) {
|
||||
for (let i = 2; i <= 9; i++) {
|
||||
const uid = `${gi}${ln}${i}`;
|
||||
if (!(await this.exists(uid))) { available.push(uid); break; }
|
||||
}
|
||||
}
|
||||
return available;
|
||||
};
|
||||
|
||||
User.addByInvite = async function(data){
|
||||
try{
|
||||
let token = await InviteToken.get(data.token);
|
||||
@@ -302,10 +502,33 @@ User.addByInvite = async function(data){
|
||||
|
||||
data.mail = token.mail;
|
||||
|
||||
const suggestions = await this.usernameSuggestions(data.givenName, data.sn, data.dob);
|
||||
if (!data.uid || !suggestions.includes(data.uid)) {
|
||||
const err = new Error('Invalid username selection');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
|
||||
let user = await this.add(data);
|
||||
|
||||
if(user){
|
||||
await token.consume({claimed_by: user.uid});
|
||||
const verif = await UserVerification.getOrCreate(user.uid);
|
||||
await verif.markEmailVerified();
|
||||
await verif.markTosAccepted();
|
||||
await verif.update({ password_must_change: false });
|
||||
cache.clear(); // evict the cached user so the next get() reads fresh verification flags
|
||||
|
||||
const groupNames = JSON.parse(token.groups || '[]');
|
||||
for (const groupName of groupNames) {
|
||||
try {
|
||||
const group = await Group.get(groupName);
|
||||
await group.addMember(user);
|
||||
} catch(e) {
|
||||
console.error(`invite: could not add ${user.uid} to group ${groupName}:`, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
@@ -323,15 +546,20 @@ User.verifyEmail = async function(data){
|
||||
if(exists) throw new Error('EmailInUse');
|
||||
|
||||
let token = await InviteToken.get(data.token);
|
||||
await token.update({mail: data.mail})
|
||||
const mail_token = crypto.randomUUID();
|
||||
await token.update({mail: data.mail, mail_token});
|
||||
|
||||
await Mail.sendTemplate(
|
||||
data.mail,
|
||||
'validate_link',
|
||||
{
|
||||
link:`${data.url}/login/invite/${token.token}/${token.mail_token}`
|
||||
}
|
||||
)
|
||||
try {
|
||||
await Mail.sendTemplate(
|
||||
data.mail,
|
||||
'validate_link',
|
||||
{
|
||||
link:`${data.url}/login/invite/${token.token}/${token.mail_token}`
|
||||
}
|
||||
);
|
||||
} catch(mailErr) {
|
||||
console.error(`verifyEmail: email failed for ${data.mail}:`, mailErr.message);
|
||||
}
|
||||
|
||||
return this;
|
||||
}catch(error){
|
||||
@@ -347,16 +575,20 @@ User.passwordReset = async function(url, mail){
|
||||
searchValue: mail
|
||||
});
|
||||
|
||||
let token = await PasswordResetToken.add(user);
|
||||
let token = await PasswordResetToken.create({created_by: user.uid});
|
||||
|
||||
await Mail.sendTemplate(
|
||||
user.mail,
|
||||
'reset_link',
|
||||
{
|
||||
user: user,
|
||||
link:`${url}/login/resetpassword/${token.token}`
|
||||
}
|
||||
)
|
||||
try {
|
||||
await Mail.sendTemplate(
|
||||
user.mail,
|
||||
'reset_link',
|
||||
{
|
||||
user: user,
|
||||
link:`${url}/login/resetpassword/${token.token}`
|
||||
}
|
||||
);
|
||||
} catch(mailErr) {
|
||||
console.error(`passwordReset: email failed for ${user.uid}:`, mailErr.message);
|
||||
}
|
||||
|
||||
return true;
|
||||
}catch(error){
|
||||
@@ -369,11 +601,10 @@ User.passwordReset = async function(url, mail){
|
||||
User.remove = async function(data){
|
||||
try{
|
||||
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
|
||||
await deleteLdapUser(client, this);
|
||||
|
||||
await client.unbind();
|
||||
await withClient(async (client) => {
|
||||
await deleteLdapUser(client, this);
|
||||
});
|
||||
cache.clear();
|
||||
|
||||
return true;
|
||||
|
||||
@@ -385,18 +616,16 @@ User.remove = async function(data){
|
||||
User.setPassword = async function(data){
|
||||
try{
|
||||
|
||||
await client.bind(conf.bindDN, conf.bindPassword);
|
||||
|
||||
await client.modify(this.dn, [
|
||||
new Change({
|
||||
operation: 'replace',
|
||||
modification: new Attribute({
|
||||
type: 'userPassword',
|
||||
values: ['{MD5}'+crypto.createHash('md5').update(data.userPassword, "binary").digest('base64')]
|
||||
})}),
|
||||
]);
|
||||
|
||||
await client.unbind();
|
||||
await withClient(async (client) => {
|
||||
await client.modify(this.dn, [
|
||||
new Change({
|
||||
operation: 'replace',
|
||||
modification: new Attribute({
|
||||
type: 'userPassword',
|
||||
values: [hashPasswordSSHA512(data.userPassword)]
|
||||
})}),
|
||||
]);
|
||||
});
|
||||
|
||||
return this;
|
||||
}catch(error){
|
||||
@@ -404,12 +633,90 @@ User.setPassword = async function(data){
|
||||
}
|
||||
};
|
||||
|
||||
User.invite = async function(){
|
||||
try{
|
||||
let token = await InviteToken.add({created_by: this.uid});
|
||||
|
||||
return token;
|
||||
User.addTempPassword = async function(hash) {
|
||||
await withClient(async (client) => {
|
||||
await client.modify(this.dn, [
|
||||
new Change({ operation: 'add', modification: new Attribute({ type: 'userPassword', values: [hash] }) }),
|
||||
]);
|
||||
});
|
||||
};
|
||||
|
||||
User.removeTempPassword = async function(hash) {
|
||||
await withClient(async (client) => {
|
||||
await client.modify(this.dn, [
|
||||
new Change({ operation: 'delete', modification: new Attribute({ type: 'userPassword', values: [hash] }) }),
|
||||
]);
|
||||
});
|
||||
};
|
||||
|
||||
User.setActive = async function(active) {
|
||||
try {
|
||||
await withClient(async (client) => {
|
||||
if (active) {
|
||||
await client.modify(this.dn, [
|
||||
new Change({ operation: 'delete', modification: new Attribute({ type: 'pwdAccountLockedTime', values: [] }) }),
|
||||
]);
|
||||
} else {
|
||||
await client.modify(this.dn, [
|
||||
new Change({ operation: 'replace', modification: new Attribute({ type: 'pwdAccountLockedTime', values: ['000001010000Z'] }) }),
|
||||
]);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
if (active && e.name === 'NoSuchAttributeError') {
|
||||
// Already active — nothing to do
|
||||
} else if (e.name === 'UndefinedTypeError' || (e.message && e.message.includes('pwdAccountLockedTime'))) {
|
||||
const err = new Error('OpenLDAP ppolicy overlay is not configured. See README for setup instructions.');
|
||||
err.status = 503;
|
||||
throw err;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
this.pwdAccountLockedTime = active ? undefined : '000001010000Z';
|
||||
this.isActive = active ? 'active' : '';
|
||||
this.isInactive = active ? '' : 'inactive';
|
||||
cache.clear();
|
||||
return this;
|
||||
};
|
||||
|
||||
User.addSSHkey = async function(data) {
|
||||
const user = await this.get(data.uid);
|
||||
let result;
|
||||
try {
|
||||
await withClient(async (client) => {
|
||||
await client.modify(user.dn, [
|
||||
new Change({
|
||||
operation: 'add',
|
||||
modification: new Attribute({ type: 'sshPublicKey', values: [data.key] }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
result = true;
|
||||
} catch(e) {
|
||||
if (e.name === 'TypeOrValueExistsError') {
|
||||
result = 'Key already added';
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
if (result === true) cache.clear();
|
||||
return result;
|
||||
};
|
||||
|
||||
User.invite = async function(data = {}){
|
||||
try{
|
||||
let token = await InviteToken.create({
|
||||
created_by: this.uid,
|
||||
groups: JSON.stringify([].concat(data.groups || [])),
|
||||
});
|
||||
|
||||
if (data.mail) {
|
||||
await User.verifyEmail({ token: token.token, mail: data.mail, url: data.url });
|
||||
return InviteToken.get(token.token);
|
||||
}
|
||||
|
||||
return token;
|
||||
}catch(error){
|
||||
throw error;
|
||||
}
|
||||
@@ -417,21 +724,25 @@ User.invite = async function(){
|
||||
|
||||
User.login = async function(data){
|
||||
try{
|
||||
let user = await this.get(data.uid);
|
||||
let user = await this.get(data.uid || data.username);
|
||||
|
||||
await client.bind(user.dn, data.password);
|
||||
|
||||
await client.unbind();
|
||||
const loginClient = makeClient();
|
||||
try {
|
||||
await loginClient.bind(user.dn, data.password);
|
||||
} finally {
|
||||
await loginClient.unbind().catch(() => {});
|
||||
}
|
||||
|
||||
return user;
|
||||
|
||||
}catch(error){
|
||||
console.error("USER LOGIN error:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
module.exports = {User};
|
||||
module.exports = {User, hashPasswordSSHA512};
|
||||
|
||||
|
||||
// (async function(){
|
||||
|
||||
Reference in New Issue
Block a user