feat: manage / create API keys (#1516)

* fix: admin api UI update

* feat: admin api - create dialog UI

* feat: admin api - create + list keys

* feat: admin api localization (wip)

* feat: admin api localization

* feat: admin api - toggle state

* feat: process API keys + format gql request errors to json
pull/1528/head
Nicolas Giard 4 years ago committed by GitHub
parent f6b048f148
commit f72cf664eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -83,8 +83,8 @@
template(v-if='hasPermission([`manage:system`, `manage:api`])') template(v-if='hasPermission([`manage:system`, `manage:api`])')
v-divider.my-2 v-divider.my-2
v-subheader.pl-4 {{ $t('admin:nav.system') }} v-subheader.pl-4 {{ $t('admin:nav.system') }}
v-list-item(to='/api', v-if='hasPermission([`manage:system`, `manage:api`])', disabled) v-list-item(to='/api', v-if='hasPermission([`manage:system`, `manage:api`])')
v-list-item-avatar(size='24', tile): v-icon(color='grey lighten-2') mdi-call-split v-list-item-avatar(size='24', tile): v-icon mdi-call-split
v-list-item-title {{ $t('admin:api.title') }} v-list-item-title {{ $t('admin:api.title') }}
v-list-item(to='/mail', color='primary', v-if='hasPermission(`manage:system`)') v-list-item(to='/mail', color='primary', v-if='hasPermission(`manage:system`)')
v-list-item-avatar(size='24', tile): v-icon mdi-email-multiple-outline v-list-item-avatar(size='24', tile): v-icon mdi-email-multiple-outline

@ -0,0 +1,236 @@
<template lang="pug">
div
v-dialog(v-model='isShown', max-width='650', persistent)
v-card
.dialog-header.is-short
v-icon.mr-3(color='white') mdi-plus
span {{$t('admin:api.newKeyTitle')}}
v-card-text.pt-5
v-text-field(
outlined
prepend-icon='mdi-format-title'
v-model='name'
:label='$t(`admin:api.newKeyName`)'
persistent-hint
ref='keyNameInput'
:hint='$t(`admin:api.newKeyNameHint`)'
counter='255'
)
v-select.mt-3(
:items='expirations'
outlined
prepend-icon='mdi-clock'
v-model='expiration'
:label='$t(`admin:api.newKeyExpiration`)'
:hint='$t(`admin:api.newKeyExpirationHint`)'
persistent-hint
)
v-divider.mt-4
v-subheader.pl-2: strong.indigo--text {{$t('admin:api.newKeyPermissionScopes')}}
v-list.pl-8(nav)
v-list-item-group(v-model='fullAccess')
v-list-item(
:value='true'
active-class='indigo--text'
)
template(v-slot:default='{ active, toggle }')
v-list-item-action
v-checkbox(
:input-value='active'
:true-value='true'
color='indigo'
@click='toggle'
)
v-list-item-content
v-list-item-title {{$t('admin:api.newKeyFullAccess')}}
v-divider.mt-3
v-subheader.caption.indigo--text {{$t('admin:api.newKeyGroupPermissions')}}
v-list-item
v-select(
:disabled='fullAccess'
:items='groups'
item-text='name'
item-value='id'
outlined
color='indigo'
v-model='group'
:label='$t(`admin:api.newKeyGroup`)'
:hint='$t(`admin:api.newKeyGroupHint`)'
persistent-hint
)
v-card-chin
v-spacer
v-btn(text, @click='isShown = false', :disabled='loading') {{$t('common:actions.cancel')}}
v-btn.px-3(depressed, color='primary', @click='generate', :loading='loading')
v-icon(left) mdi-chevron-right
span {{$t('common:actions.generate')}}
v-dialog(
v-model='isCopyKeyDialogShown'
max-width='750'
persistent
overlay-color='blue darken-5'
overlay-opacity='.9'
)
v-card
v-toolbar(dense, flat, color='primary', dark) {{$t('admin:api.newKeyTitle')}}
v-card-text.pt-5
.body-2.text-center
i18next(tag='span', path='admin:api.newKeyCopyWarn')
strong(place='bold') {{$t('admin:api.newKeyCopyWarnBold')}}
v-textarea.mt-3(
ref='keyContentsIpt'
filled
no-resize
readonly
v-model='key'
:rows='10'
hide-details
)
v-card-chin
v-spacer
v-btn.px-3(depressed, dark, color='primary', @click='isCopyKeyDialogShown = false') {{$t('common:actions.close')}}
</template>
<script>
import _ from 'lodash'
import gql from 'graphql-tag'
import groupsQuery from 'gql/admin/users/users-query-groups.gql'
export default {
props: {
value: {
type: Boolean,
default: false
}
},
data() {
return {
loading: false,
name: '',
expiration: '1y',
fullAccess: true,
groups: [],
group: null,
isCopyKeyDialogShown: false,
key: ''
}
},
computed: {
isShown: {
get() { return this.value },
set(val) { this.$emit('input', val) }
},
expirations() {
return [
{ value: '30d', text: this.$t('admin:api.expiration30d') },
{ value: '90d', text: this.$t('admin:api.expiration90d') },
{ value: '180d', text: this.$t('admin:api.expiration180d') },
{ value: '1y', text: this.$t('admin:api.expiration1y') },
{ value: '3y', text: this.$t('admin:api.expiration3y') }
]
}
},
watch: {
value (newValue, oldValue) {
if (newValue) {
setTimeout(() => {
this.$refs.keyNameInput.focus()
}, 400)
}
}
},
methods: {
async generate () {
try {
if (_.trim(this.name).length < 2 || this.name.length > 255) {
throw new Error(this.$t('admin:api.newKeyNameError'))
} else if (!this.fullAccess && !this.group) {
throw new Error(this.$t('admin:api.newKeyGroupError'))
} else if (!this.fullAccess && this.group === 2) {
throw new Error(this.$t('admin:api.newKeyGuestGroupError'))
}
} catch (err) {
return this.$store.commit('showNotification', {
style: 'red',
message: err,
icon: 'alert'
})
}
this.loading = true
try {
const resp = await this.$apollo.mutate({
mutation: gql`
mutation ($name: String!, $expiration: String!, $fullAccess: Boolean!, $group: Int) {
authentication {
createApiKey (name: $name, expiration: $expiration, fullAccess: $fullAccess, group: $group) {
key
responseResult {
succeeded
errorCode
slug
message
}
}
}
}
`,
variables: {
name: this.name,
expiration: this.expiration,
fullAccess: (this.fullAccess === true),
group: this.group
},
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-create')
}
})
if (_.get(resp, 'data.authentication.createApiKey.responseResult.succeeded', false)) {
this.$store.commit('showNotification', {
style: 'success',
message: this.$t('admin:api.newKeySuccess'),
icon: 'check'
})
this.name = ''
this.expiration = '1y'
this.fullAccess = true
this.group = null
this.isShown = false
this.$emit('refresh')
this.key = _.get(resp, 'data.authentication.createApiKey.key', '???')
this.isCopyKeyDialogShown = true
setTimeout(() => {
this.$refs.keyContentsIpt.$refs.input.select()
}, 400)
} else {
this.$store.commit('showNotification', {
style: 'red',
message: _.get(resp, 'data.authentication.createApiKey.responseResult.message', 'An unexpected error occured.'),
icon: 'alert'
})
}
} catch (err) {
this.$store.commit('pushGraphError', err)
}
this.loading = false
}
},
apollo: {
groups: {
query: groupsQuery,
fetchPolicy: 'network-only',
update: (data) => data.groups.list,
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-groups-refresh')
}
}
}
}
</script>

@ -3,128 +3,232 @@
v-layout(row, wrap) v-layout(row, wrap)
v-flex(xs12) v-flex(xs12)
.admin-header .admin-header
img(src='/svg/icon-rest-api.svg', alt='API', style='width: 80px;') img.animated.fadeInUp(src='/svg/icon-rest-api.svg', alt='API', style='width: 80px;')
.admin-header-title .admin-header-title
.headline.blue--text.text--darken-2 API Access .headline.primary--text.animated.fadeInLeft {{$t('admin:api.title')}}
.subtitle-1.grey--text Manage keys to access the API #[v-chip(label, color='primary', small).white--text coming soon] .subtitle-1.grey--text.animated.fadeInLeft {{$t('admin:api.subtitle')}}
v-spacer v-spacer
v-btn(outline, color='grey', large, @click='refresh', disabled) template(v-if='enabled')
v-icon refresh status-indicator.mr-3(positive, pulse)
v-btn(color='green', disabled, depressed, large, @click='globalSwitch') .caption.green--text.animated.fadeInLeft {{$t('admin:api.enabled')}}
v-icon(left) power_settings_new template(v-else)
| Enable API status-indicator.mr-3(negative, pulse)
v-btn(color='primary', depressed, large, @click='newKey', disabled) .caption.red--text.animated.fadeInLeft {{$t('admin:api.disabled')}}
v-icon(left) add v-spacer
| New API Key v-btn.mr-3.animated.fadeInDown.wait-p2s(outlined, color='grey', large, @click='refresh')
v-card.mt-3 v-icon mdi-refresh
v-data-table( v-btn.mr-3.animated.fadeInDown.wait-p1s(:color='enabled ? `red` : `green`', depressed, large, @click='globalSwitch', dark, :loading='isToggleLoading')
v-model='selected' v-icon(left) mdi-power
:items='items', span(v-if='!enabled') {{$t('admin:api.enableButton')}}
:headers='headers', span(v-else) {{$t('admin:api.disableButton')}}
:search='search', v-btn.animated.fadeInDown(color='primary', depressed, large, @click='newKey', dark)
:pagination.sync='pagination', v-icon(left) mdi-plus
:rows-per-page-items='[15]' span {{$t('admin:api.newKeyButton')}}
select-all, v-card.mt-3.animated.fadeInUp
hide-actions, v-simple-table(v-if='keys && keys.length > 0')
disable-initial-sort template(v-slot:default)
) thead
template(slot='headers', slot-scope='props') tr.grey(:class='$vuetify.theme.dark ? `darken-4-d5` : `lighten-5`')
tr th {{$t('admin:api.headerName')}}
th(width='50') th {{$t('admin:api.headerKeyEnding')}}
th.text-xs-right( th {{$t('admin:api.headerExpiration')}}
width='80' th {{$t('admin:api.headerCreated')}}
:class='[`column sortable`, pagination.descending ? `desc` : `asc`, pagination.sortBy === `id` ? `active` : ``]' th {{$t('admin:api.headerLastUpdated')}}
@click='changeSort(`id`)' th(width='100') {{$t('admin:api.headerRevoke')}}
) tbody
v-icon(small) arrow_upward tr(v-for='key of keys', :key='`key-` + key.id')
| ID td
th.text-xs-left( strong(:class='key.isRevoked ? `red--text` : ``') {{ key.name }}
v-for='header in props.headers' em.caption.ml-1.red--text(v-if='key.isRevoked') (revoked)
:key='header.text' td.caption {{ key.keyShort }}
:width='header.width' td(:style='key.isRevoked ? `text-decoration: line-through;` : ``') {{ key.expiration | moment('LL') }}
:class='[`column sortable`, pagination.descending ? `desc` : `asc`, header.value === pagination.sortBy ? `active` : ``]' td {{ key.createdAt | moment('calendar') }}
@click='changeSort(header.value)' td {{ key.updatedAt | moment('calendar') }}
) td: v-btn(icon, @click='revoke(key)', :disabled='key.isRevoked'): v-icon(color='error') mdi-cancel
| {{ header.text }} v-card-text(v-else)
v-icon(small) arrow_upward v-alert.mb-0(icon='mdi-information', :value='true', outlined, color='info') {{$t('admin:api.noKeyInfo')}}
template(slot='items', slot-scope='props')
tr(:active='props.selected') create-api-key(v-model='isCreateDialogShown', @refresh='refresh(false)')
td
v-checkbox(hide-details, :input-value='props.selected', color='blue darken-2', @click='props.selected = !props.selected') v-dialog(v-model='isRevokeConfirmDialogShown', max-width='500', persistent)
td.text-xs-right {{ props.item.id }} v-card
td {{ props.item.name }} .dialog-header.is-red {{$t('admin:api.revokeConfirm')}}
td {{ props.item.key }} v-card-text.pa-4
td {{ props.item.createdOn }} i18next(tag='span', path='admin:api.revokeConfirmText')
td {{ props.item.updatedOn }} strong(place='name') {{ current.name }}
td: v-btn(icon): v-icon.grey--text.text--darken-1 more_horiz v-card-actions
template(slot='no-data') v-spacer
v-alert.mt-3(icon='info', :value='true', outline, color='info') No API keys have been generated yet. v-btn(text, @click='isRevokeConfirmDialogShown = false', :disabled='revokeLoading') {{$t('common:actions.cancel')}}
.text-xs-center.py-2 v-btn(color='red', dark, @click='revokeConfirm', :loading='revokeLoading') {{$t('admin:api.revoke')}}
v-pagination(v-model='pagination.page', :length='pages')
</template> </template>
<script> <script>
import _ from 'lodash'
import gql from 'graphql-tag'
import { StatusIndicator } from 'vue-status-indicator'
import CreateApiKey from './admin-api-create.vue'
export default { export default {
components: {
StatusIndicator,
CreateApiKey
},
data() { data() {
return { return {
selected: [], enabled: false,
pagination: {}, isToggleLoading: false,
items: [], keys: [],
headers: [ isCreateDialogShown: false,
{ text: 'Name', value: 'name' }, isRevokeConfirmDialogShown: false,
{ text: 'Key', value: 'key' }, revokeLoading: false,
{ text: 'Created On', value: 'createdOn' }, current: {}
{ text: 'Updated On', value: 'updatedOn' },
{ text: '', value: 'actions', sortable: false, width: 50 }
],
search: ''
}
},
computed: {
pages () {
if (this.pagination.rowsPerPage == null || this.pagination.totalItems == null) {
return 0
}
return Math.ceil(this.pagination.totalItems / this.pagination.rowsPerPage)
} }
}, },
methods: { methods: {
changeSort (column) { async refresh (notify = true) {
if (this.pagination.sortBy === column) { this.$apollo.queries.keys.refetch()
this.pagination.descending = !this.pagination.descending if (notify) {
} else { this.$store.commit('showNotification', {
this.pagination.sortBy = column message: this.$t('admin:api.refreshSuccess'),
this.pagination.descending = false style: 'success',
icon: 'cached'
})
} }
}, },
toggleAll () { async globalSwitch () {
if (this.selected.length) { this.isToggleLoading = true
this.selected = [] try {
} else { const resp = await this.$apollo.mutate({
this.selected = this.items.slice() mutation: gql`
mutation ($enabled: Boolean!) {
authentication {
setApiState (enabled: $enabled) {
responseResult {
succeeded
errorCode
slug
message
}
}
}
}
`,
variables: {
enabled: !this.enabled
},
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-toggle')
}
})
if (_.get(resp, 'data.authentication.setApiState.responseResult.succeeded', false)) {
this.$store.commit('showNotification', {
style: 'success',
message: this.enabled ? this.$t('admin:api.toggleStateDisabledSuccess') : this.$t('admin:api.toggleStateEnabledSuccess'),
icon: 'check'
})
await this.$apollo.queries.enabled.refetch()
} else {
this.$store.commit('showNotification', {
style: 'red',
message: _.get(resp, 'data.authentication.setApiState.responseResult.message', 'An unexpected error occured.'),
icon: 'alert'
})
}
} catch (err) {
this.$store.commit('pushGraphError', err)
} }
this.isToggleLoading = false
}, },
async refresh() { async newKey () {
this.$store.commit('showNotification', { this.isCreateDialogShown = true
style: 'indigo',
message: `Coming soon...`,
icon: 'directions_boat'
})
}, },
async globalSwitch() { revoke (key) {
this.$store.commit('showNotification', { this.current = key
style: 'indigo', this.isRevokeConfirmDialogShown = true
message: `Coming soon...`, },
icon: 'directions_boat' async revokeConfirm () {
}) this.revokeLoading = true
try {
const resp = await this.$apollo.mutate({
mutation: gql`
mutation ($id: Int!) {
authentication {
revokeApiKey (id: $id) {
responseResult {
succeeded
errorCode
slug
message
}
}
}
}
`,
variables: {
id: this.current.id
},
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-revoke')
}
})
if (_.get(resp, 'data.authentication.revokeApiKey.responseResult.succeeded', false)) {
this.$store.commit('showNotification', {
style: 'success',
message: this.$t('admin:api.revokeSuccess'),
icon: 'check'
})
this.refresh(false)
} else {
this.$store.commit('showNotification', {
style: 'red',
message: _.get(resp, 'data.authentication.revokeApiKey.responseResult.message', 'An unexpected error occured.'),
icon: 'alert'
})
}
} catch (err) {
this.$store.commit('pushGraphError', err)
}
this.isRevokeConfirmDialogShown = false
this.revokeLoading = false
}
},
apollo: {
enabled: {
query: gql`
{
authentication {
apiState
}
}
`,
fetchPolicy: 'network-only',
update: (data) => data.authentication.apiState,
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-state-refresh')
}
}, },
async newKey() { keys: {
this.$store.commit('showNotification', { query: gql`
style: 'indigo', {
message: `Coming soon...`, authentication {
icon: 'directions_boat' apiKeys {
}) id
name
keyShort
expiration
isRevoked
createdAt
updatedAt
}
}
}
`,
fetchPolicy: 'network-only',
update: (data) => data.authentication.apiKeys,
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-api-keys-refresh')
}
} }
} }
} }

@ -114,6 +114,7 @@
"moment": "2.24.0", "moment": "2.24.0",
"moment-timezone": "0.5.27", "moment-timezone": "0.5.27",
"mongodb": "3.5.2", "mongodb": "3.5.2",
"ms": "2.1.2",
"mssql": "6.0.1", "mssql": "6.0.1",
"multer": "1.4.2", "multer": "1.4.2",
"mysql2": "2.1.0", "mysql2": "2.1.0",

@ -29,6 +29,8 @@ defaults:
maxFiles: 10 maxFiles: 10
offline: false offline: false
# DB defaults # DB defaults
api:
isEnabled: false
graphEndpoint: 'https://graph.requarks.io' graphEndpoint: 'https://graph.requarks.io'
lang: lang:
code: en code: en

@ -17,6 +17,7 @@ module.exports = {
cacheExpiration: moment.utc().subtract(1, 'd') cacheExpiration: moment.utc().subtract(1, 'd')
}, },
groups: {}, groups: {},
validApiKeys: [],
/** /**
* Initialize the authentication module * Initialize the authentication module
@ -44,6 +45,7 @@ module.exports = {
}) })
this.reloadGroups() this.reloadGroups()
this.reloadApiKeys()
return this return this
}, },
@ -64,7 +66,8 @@ module.exports = {
jwtFromRequest: securityHelper.extractJWT, jwtFromRequest: securityHelper.extractJWT,
secretOrKey: WIKI.config.certs.public, secretOrKey: WIKI.config.certs.public,
audience: WIKI.config.auth.audience, audience: WIKI.config.auth.audience,
issuer: 'urn:wiki.js' issuer: 'urn:wiki.js',
algorithms: ['RS256']
}, (jwtPayload, cb) => { }, (jwtPayload, cb) => {
cb(null, jwtPayload) cb(null, jwtPayload)
})) }))
@ -135,6 +138,31 @@ module.exports = {
return next() return next()
} }
// Process API tokens
if (_.has(user, 'api')) {
if (_.includes(WIKI.auth.validApiKeys, user.api)) {
req.user = {
id: 1,
email: 'api@localhost',
name: 'API',
pictureUrl: null,
timezone: 'America/New_York',
localeCode: 'en',
permissions: _.get(WIKI.auth.groups, `${user.grp}.permissions`, []),
groups: [user.grp],
getGlobalPermissions () {
return req.user.permissions
},
getGroups () {
return req.user.groups
}
}
return next()
} else {
return next(new Error('API Key is invalid or was revoked.'))
}
}
// JWT is valid // JWT is valid
req.logIn(user, { session: false }, (errc) => { req.logIn(user, { session: false }, (errc) => {
if (errc) { return next(errc) } if (errc) { return next(errc) }
@ -248,15 +276,23 @@ module.exports = {
/** /**
* Reload Groups from DB * Reload Groups from DB
*/ */
async reloadGroups() { async reloadGroups () {
const groupsArray = await WIKI.models.groups.query() const groupsArray = await WIKI.models.groups.query()
this.groups = _.keyBy(groupsArray, 'id') this.groups = _.keyBy(groupsArray, 'id')
}, },
/**
* Reload valid API Keys from DB
*/
async reloadApiKeys () {
const keys = await WIKI.models.apiKeys.query().select('id').where('isRevoked', false).andWhere('expiration', '>', moment.utc().toISOString())
this.validApiKeys = _.map(keys, 'id')
},
/** /**
* Generate New Authentication Public / Private Key Certificates * Generate New Authentication Public / Private Key Certificates
*/ */
async regenerateCertificates() { async regenerateCertificates () {
WIKI.logger.info('Regenerating certificates...') WIKI.logger.info('Regenerating certificates...')
_.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex')) _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))

@ -0,0 +1,14 @@
exports.up = knex => {
return knex.schema
.createTable('apiKeys', table => {
table.increments('id').primary()
table.string('name').notNullable()
table.text('key').notNullable()
table.string('expiration').notNullable()
table.boolean('isRevoked').notNullable().defaultTo(false)
table.string('createdAt').notNullable()
table.string('updatedAt').notNullable()
})
}
exports.down = knex => { }

@ -0,0 +1,20 @@
/* global WIKI */
exports.up = knex => {
const dbCompat = {
charset: (WIKI.config.db.type === `mysql` || WIKI.config.db.type === `mariadb`)
}
return knex.schema
.createTable('apiKeys', table => {
if (dbCompat.charset) { table.charset('utf8mb4') }
table.increments('id').primary()
table.string('name').notNullable()
table.text('key').notNullable()
table.string('expiration').notNullable()
table.boolean('isRevoked').notNullable().defaultTo(false)
table.string('createdAt').notNullable()
table.string('updatedAt').notNullable()
})
}
exports.down = knex => { }

@ -13,6 +13,27 @@ module.exports = {
async authentication () { return {} } async authentication () { return {} }
}, },
AuthenticationQuery: { AuthenticationQuery: {
/**
* List of API Keys
*/
async apiKeys (obj, args, context) {
const keys = await WIKI.models.apiKeys.query().orderBy(['isRevoked', 'name'])
return keys.map(k => ({
id: k.id,
name: k.name,
keyShort: '...' + k.key.substring(k.key.length - 20),
isRevoked: k.isRevoked,
expiration: k.expiration,
createdAt: k.createdAt,
updatedAt: k.updatedAt
}))
},
/**
* Current API State
*/
apiState () {
return WIKI.config.api.isEnabled
},
/** /**
* Fetch active authentication strategies * Fetch active authentication strategies
*/ */
@ -41,6 +62,19 @@ module.exports = {
} }
}, },
AuthenticationMutation: { AuthenticationMutation: {
/**
* Create New API Key
*/
async createApiKey (obj, args, context) {
try {
return {
key: await WIKI.models.apiKeys.createNewKey(args),
responseResult: graphHelper.generateSuccess('API Key created successfully')
}
} catch (err) {
return graphHelper.generateError(err)
}
},
/** /**
* Perform Login * Perform Login
*/ */
@ -101,6 +135,36 @@ module.exports = {
return graphHelper.generateError(err) return graphHelper.generateError(err)
} }
}, },
/**
* Set API state
*/
async setApiState (obj, args, context) {
try {
WIKI.config.api.isEnabled = args.enabled
await WIKI.configSvc.saveToDb(['api'])
return {
responseResult: graphHelper.generateSuccess('API State changed successfully')
}
} catch (err) {
return graphHelper.generateError(err)
}
},
/**
* Revoke an API key
*/
async revokeApiKey (obj, args, context) {
try {
await WIKI.models.apiKeys.query().findById(args.id).patch({
isRevoked: true
})
await WIKI.auth.reloadApiKeys()
return {
responseResult: graphHelper.generateSuccess('API Key revoked successfully')
}
} catch (err) {
return graphHelper.generateError(err)
}
},
/** /**
* Update Authentication Strategies * Update Authentication Strategies
*/ */

@ -15,6 +15,10 @@ extend type Mutation {
# ----------------------------------------------- # -----------------------------------------------
type AuthenticationQuery { type AuthenticationQuery {
apiKeys: [AuthenticationApiKey] @auth(requires: ["manage:system", "manage:api"])
apiState: Boolean! @auth(requires: ["manage:system", "manage:api"])
strategies( strategies(
isEnabled: Boolean isEnabled: Boolean
): [AuthenticationStrategy] ): [AuthenticationStrategy]
@ -25,6 +29,13 @@ type AuthenticationQuery {
# ----------------------------------------------- # -----------------------------------------------
type AuthenticationMutation { type AuthenticationMutation {
createApiKey(
name: String!
expiration: String!
fullAccess: Boolean!
group: Int
): AuthenticationCreateApiKeyResponse @auth(requires: ["manage:system", "manage:api"])
login( login(
username: String! username: String!
password: String! password: String!
@ -47,12 +58,21 @@ type AuthenticationMutation {
name: String! name: String!
): AuthenticationRegisterResponse ): AuthenticationRegisterResponse
revokeApiKey(
id: Int!
): DefaultResponse @auth(requires: ["manage:system", "manage:api"])
setApiState(
enabled: Boolean!
): DefaultResponse @auth(requires: ["manage:system", "manage:api"])
updateStrategies( updateStrategies(
strategies: [AuthenticationStrategyInput]! strategies: [AuthenticationStrategyInput]!
config: AuthenticationConfigInput config: AuthenticationConfigInput
): DefaultResponse @auth(requires: ["manage:system"]) ): DefaultResponse @auth(requires: ["manage:system"])
regenerateCertificates: DefaultResponse @auth(requires: ["manage:system"]) regenerateCertificates: DefaultResponse @auth(requires: ["manage:system"])
resetGuestUser: DefaultResponse @auth(requires: ["manage:system"]) resetGuestUser: DefaultResponse @auth(requires: ["manage:system"])
} }
@ -105,3 +125,18 @@ input AuthenticationConfigInput {
tokenExpiration: String! tokenExpiration: String!
tokenRenewal: String! tokenRenewal: String!
} }
type AuthenticationApiKey {
id: Int!
name: String!
keyShort: String!
expiration: Date!
createdAt: Date!
updatedAt: Date!
isRevoked: Boolean!
}
type AuthenticationCreateApiKeyResponse {
responseResult: ResponseStatus
key: String
}

@ -167,12 +167,22 @@ module.exports = async () => {
}) })
app.use((err, req, res, next) => { app.use((err, req, res, next) => {
res.status(err.status || 500) if (req.path === '/graphql') {
_.set(res.locals, 'pageMeta.title', 'Error') res.status(err.status || 500).json({
res.render('error', { data: {},
message: err.message, errors: [{
error: WIKI.IS_DEBUG ? err : {} message: err.message,
}) path: []
}]
})
} else {
res.status(err.status || 500)
_.set(res.locals, 'pageMeta.title', 'Error')
res.render('error', {
message: err.message,
error: WIKI.IS_DEBUG ? err : {}
})
}
}) })
// ---------------------------------------- // ----------------------------------------

@ -0,0 +1,71 @@
/* global WIKI */
const Model = require('objection').Model
const moment = require('moment')
const ms = require('ms')
const jwt = require('jsonwebtoken')
/**
* Users model
*/
module.exports = class ApiKey extends Model {
static get tableName() { return 'apiKeys' }
static get jsonSchema () {
return {
type: 'object',
required: ['name', 'key'],
properties: {
id: {type: 'integer'},
name: {type: 'string'},
key: {type: 'string'},
expiration: {type: 'string'},
isRevoked: {type: 'boolean'},
createdAt: {type: 'string'},
validUntil: {type: 'string'}
}
}
}
async $beforeUpdate(opt, context) {
await super.$beforeUpdate(opt, context)
this.updatedAt = moment.utc().toISOString()
}
async $beforeInsert(context) {
await super.$beforeInsert(context)
this.createdAt = moment.utc().toISOString()
this.updatedAt = moment.utc().toISOString()
}
static async createNewKey ({ name, expiration, fullAccess, group }) {
const entry = await WIKI.models.apiKeys.query().insert({
name,
key: 'pending',
expiration: moment.utc().add(ms(expiration), 'ms').toISOString(),
isRevoked: true
})
const key = jwt.sign({
api: entry.id,
grp: fullAccess ? 1 : group
}, {
key: WIKI.config.certs.private,
passphrase: WIKI.config.sessionSecret
}, {
algorithm: 'RS256',
expiresIn: expiration,
audience: WIKI.config.auth.audience,
issuer: 'urn:wiki.js'
})
await WIKI.models.apiKeys.query().findById(entry.id).patch({
key,
isRevoked: false
})
return key
}
}

@ -26,7 +26,6 @@ module.exports = class User extends Model {
name: {type: 'string', minLength: 1, maxLength: 255}, name: {type: 'string', minLength: 1, maxLength: 255},
providerId: {type: 'string'}, providerId: {type: 'string'},
password: {type: 'string'}, password: {type: 'string'},
role: {type: 'string', enum: ['admin', 'guest', 'user']},
tfaIsActive: {type: 'boolean', default: false}, tfaIsActive: {type: 'boolean', default: false},
tfaSecret: {type: 'string'}, tfaSecret: {type: 'string'},
jobTitle: {type: 'string'}, jobTitle: {type: 'string'},

@ -10304,7 +10304,7 @@ ms@2.1.1:
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a"
integrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg== integrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==
ms@^2.1.1: ms@2.1.2, ms@^2.1.1:
version "2.1.2" version "2.1.2"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==

Loading…
Cancel
Save