CoreID/app/models/vault/Vault.model.js
garrettmills 3730ddc2f2
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing
Add basic logic for managing vaults
2021-04-15 15:34:13 -05:00

67 lines
1.6 KiB
JavaScript

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