CoreID/app/models/vault/Vault.model.js

67 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-04-15 20:34:13 +00:00
const { Model } = require('flitter-orm')
class VaultModel extends Model {
static get services() {
return [...super.services, 'models']
}
static get schema() {
return {
active: { type: Boolean, default: true },
name: String,
user_id: String,
}
}
static async for_user(user) {
const existing = await this.findOne({
user_id: user.id,
})
if ( existing ) return existing
const vault = new this({
name: `${user.first_name} ${user.last_name}'s Vault`,
user_id: user.id,
})
await vault.save()
await vault.grant_default(user)
return vault
}
async grant_default(user) {
const Policy = this.models.get('iam:Policy')
const grants = ['view', 'read', 'update', 'delete', undefined]
for ( const grant of grants ) {
const policy = new Policy({
entity_type: 'user',
entity_id: user.id,
access_type: 'allow',
target_type: 'vault',
target_id: this.id,
...(grant ? {
for_permission: true,
permission: grant
} : {})
})
await policy.save()
}
}
async to_api() {
return {
id: this.id,
_id: this.id,
name: this.name,
active: this.active,
user_id: this.user_id,
}
}
}
module.exports = exports = VaultModel