CoreID/app/models/auth/Group.model.js

92 lines
2.5 KiB
JavaScript
Raw Normal View History

const { Model } = require('flitter-orm')
2020-05-21 01:35:17 +00:00
const LDAP = require('ldapjs')
// For organizational purposes only.
class GroupModel extends Model {
static get services() {
2020-05-21 01:35:17 +00:00
return [...super.services, 'models', 'ldap_server', 'configs']
}
static get schema() {
return {
name: String,
user_ids: [String],
posix_user_id: String,
posix_group_id: Number,
active: { type: Boolean, default: true },
2020-05-21 01:35:17 +00:00
ldap_visible: { type: Boolean, default: true },
}
}
identifier() {
return this.name.toLowerCase().replace(/\s/g, '_')
}
2020-05-21 01:35:17 +00:00
get dn() {
return LDAP.parseDN(`cn=${this.name},${this.ldap_server.group_dn().format(this.configs.get('ldap:server.format'))}`)
}
async users() {
const User = this.models.get('auth:User')
return await User.find({ _id: { $in: this.user_ids.map(x => this.constructor.to_object_id(x)) } })
}
2020-05-21 01:35:17 +00:00
async to_ldap() {
const users = await this.users()
const data = {
2020-05-21 01:35:17 +00:00
cn: this.name,
dn: this.dn.format(this.configs.get('ldap:server.format')),
objectClass: ['groupOfNames'],
2020-05-21 01:35:17 +00:00
member: users.map(x => x.dn.format(this.configs.get('ldap:server.format'))),
}
if ( this.posix_group_id ) {
data.objectClass.push('posixGroup')
data.gidNumber = String(this.posix_group_id)
}
return data
2020-05-21 01:35:17 +00:00
}
static async ldap_directory() {
const User = this.prototype.models.get('auth:User')
const groups = await this.find({ ldap_visible: true, active: true })
const posix_user_ids = groups.map(group => group.posix_user_id)
.filter(Boolean)
.map(id => User.to_object_id(id))
const missing_posix_users = await User.find({
ldap_visible: true,
_id: {
$nin: posix_user_ids
}
})
for ( const user of missing_posix_users ) {
const group = new this({
name: `${user.uid} (posix)`,
user_ids: [user.id],
posix_user_id: user.id,
posix_group_id: await user.get_uid_number(),
})
await group.save()
groups.push(group)
}
return groups
2020-05-21 01:35:17 +00:00
}
async to_api() {
return {
id: this.id,
name: this.name,
user_ids: this.user_ids,
2020-05-21 01:35:17 +00:00
ldap_visible: this.ldap_visible,
}
}
}
module.exports = exports = GroupModel