Commit 7793df9b authored by NGPixel's avatar NGPixel

feat: admin groups - list + create, gql refactoring

parent cb253f7b
......@@ -2,7 +2,7 @@
v-card(flat)
v-card(flat, color='grey lighten-5').pa-3.pt-4
.headline.blue--text.text--darken-2 Groups
.subheading.grey--text Manage groups
.subheading.grey--text Manage groups and their permissions
v-card
v-card-title
v-dialog(v-model='newGroupDialog', max-width='500')
......@@ -17,7 +17,7 @@
v-spacer
v-btn(flat, @click='newGroupDialog = false') Cancel
v-btn(color='primary', @click='createGroup') Create
v-btn(icon)
v-btn(icon, @click='refresh')
v-icon.grey--text refresh
v-spacer
v-text-field(append-icon='search', label='Search', single-line, hide-details, v-model='search')
......@@ -44,6 +44,11 @@
</template>
<script>
import _ from 'lodash'
import groupsQuery from 'gql/admin-groups-query-list.gql'
import createGroupMutation from 'gql/admin-groups-mutation-create.gql'
export default {
data() {
return {
......@@ -71,18 +76,53 @@ export default {
}
},
methods: {
async refresh() {
await this.$apollo.queries.groups.refetch()
this.$store.commit('showNotification', {
message: 'Groups have been refreshed.',
style: 'success',
icon: 'cached'
})
},
async createGroup() {
// try {
// const resp = await this.$apollo.mutate({
// mutation: CONSTANTS.GRAPH.GROUPS.CREATE,
// variables: {
// name: this.newGroupName
// }
// })
this.newGroupDialog = false
try {
await this.$apollo.mutate({
mutation: createGroupMutation,
variables: {
name: this.newGroupName
},
update (store, resp) {
const data = _.get(resp, 'data.groups.create', { responseResult: {} })
if (data.responseResult.succeeded === true) {
const apolloData = store.readQuery({ query: groupsQuery })
apolloData.groups.list.push(data.group)
store.writeQuery({ query: groupsQuery, data: apolloData })
} else {
throw new Error(data.responseResult.message)
}
},
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-groups-create')
}
})
this.$store.commit('showNotification', {
style: 'success',
message: `Group has been created successfully.`,
icon: 'check'
})
} catch (err) {
// } catch (err) {
// }
}
}
},
apollo: {
groups: {
query: groupsQuery,
update: (data) => data.groups.list,
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-groups-refresh')
}
}
}
}
......
......@@ -93,24 +93,15 @@
v-list-tile-content
v-list-tile-title {{ info.postgreVersion }}
v-list-tile-sub-title {{ info.postgreHost }}
v-snackbar(
color='success'
top
v-model='refreshCompleted'
)
v-icon.mr-3(dark) cached
| System Info has been refreshed.
</template>
<script>
import gql from 'graphql-tag'
import IconCube from 'mdi/cube'
import IconDatabase from 'mdi/database'
import IconNodeJs from 'mdi/nodejs'
import systemInfoQuery from 'gql/admin-system-query-info.gql'
export default {
components: {
IconCube,
......@@ -119,42 +110,26 @@ export default {
},
data() {
return {
info: {},
refreshCompleted: false
}
},
apollo: {
info: {
query: gql`
query {
system {
info {
currentVersion
latestVersion
latestVersionReleaseDate
operatingSystem
hostname
cpuCores
ramTotal
workingDirectory
nodeVersion
redisVersion
redisUsedRAM
redisTotalRAM
redisHost
postgreVersion
postgreHost
}
}
}
`,
update: (data) => data.system.info
info: {}
}
},
methods: {
async refresh() {
await this.$apollo.queries.info.refetch()
this.refreshCompleted = true
this.$store.commit('showNotification', {
message: 'System Info has been refreshed.',
style: 'success',
icon: 'cached'
})
}
},
apollo: {
info: {
query: systemInfoQuery,
update: (data) => data.system.info,
watchLoading (isLoading) {
this.$store.commit(`loading${isLoading ? 'Start' : 'Stop'}`, 'admin-system-refresh')
}
}
}
}
......
......@@ -69,10 +69,22 @@
v-footer.py-2.justify-center(app, absolute, color='grey lighten-3', inset, height='auto')
.caption.grey--text.text--darken-1 Powered by Wiki.js
v-snackbar(
:color='notification.style'
bottom,
right,
multi-line,
v-model='notificationState'
)
.text-xs-left
v-icon.mr-3(dark) {{ notification.icon }}
span {{ notification.message }}
</template>
<script>
import VueRouter from 'vue-router'
import { mapState } from 'vuex'
const router = new VueRouter({
mode: 'history',
......@@ -105,6 +117,13 @@ export default {
adminDrawerShown: true
}
},
computed: {
...mapState(['notification']),
notificationState: {
get() { return this.notification.isActive },
set(newState) { this.$store.commit('updateNotificationState', newState) }
}
},
router
}
</script>
......
......@@ -38,10 +38,13 @@
</template>
<script>
/* global graphQL, siteConfig */
/* global siteConfig */
import _ from 'lodash'
import gql from 'graphql-tag'
import strategiesQuery from 'gql/login-query-strategies.gql'
import loginMutation from 'gql/login-mutation-login.gql'
import tfaMutation from 'gql/login-mutation-tfa.gql'
export default {
data () {
......@@ -81,22 +84,8 @@ export default {
},
refreshStrategies () {
this.isLoading = true
graphQL.query({
query: gql`
query {
authentication {
providers(
filter: "isEnabled eq true",
orderBy: "title ASC"
) {
key
title
useForm
icon
}
}
}
`
this.$apollo.query({
query: strategiesQuery
}).then(resp => {
if (_.has(resp, 'data.authentication.providers')) {
this.strategies = _.get(resp, 'data.authentication.providers', [])
......@@ -131,23 +120,8 @@ export default {
this.$refs.iptPassword.focus()
} else {
this.isLoading = true
graphQL.mutate({
mutation: gql`
mutation($username: String!, $password: String!, $provider: String!) {
authentication {
login(username: $username, password: $password, provider: $provider) {
operation {
succeeded
code
slug
message
}
tfaRequired
tfaLoginToken
}
}
}
`,
this.$apollo.mutate({
mutation: loginMutation,
variables: {
username: this.username,
password: this.password,
......@@ -199,21 +173,8 @@ export default {
this.$refs.iptTFA.focus()
} else {
this.isLoading = true
graphQL.mutate({
mutation: gql`
mutation($loginToken: String!, $securityCode: String!) {
authentication {
loginTFA(loginToken: $loginToken, securityCode: $securityCode) {
operation {
succeeded
code
slug
message
}
}
}
}
`,
this.$apollo.mutate({
mutation: tfaMutation,
variables: {
loginToken: this.loginToken,
securityCode: this.securityCode
......
......@@ -61,7 +61,7 @@
color='blue'
)
v-spacer
v-progress-circular.mr-3(indeterminate, color='blue', v-show='$apollo.loading')
v-progress-circular.mr-3(indeterminate, color='blue', v-show='isLoading')
slot(name='actions')
transition(name='navHeaderSearch')
v-btn(icon, @click='searchToggle', v-if='!searchIsShown')
......@@ -88,6 +88,8 @@
</template>
<script>
import { mapGetters } from 'vuex'
export default {
data() {
return {
......@@ -97,6 +99,9 @@ export default {
search: ''
}
},
computed: {
...mapGetters(['isLoading'])
},
methods: {
searchToggle() {
this.searchIsLoading = false
......
mutation ($name: String!) {
groups {
create(name: $name) {
responseResult {
succeeded
errorCode
slug
message
}
group {
id
name
createdAt
updatedAt
}
}
}
}
query {
groups {
list {
id
name
userCount
createdAt
updatedAt
}
}
}
query {
system {
info {
currentVersion
latestVersion
latestVersionReleaseDate
operatingSystem
hostname
cpuCores
ramTotal
workingDirectory
nodeVersion
redisVersion
redisUsedRAM
redisTotalRAM
redisHost
postgreVersion
postgreHost
}
}
}
mutation($username: String!, $password: String!, $provider: String!) {
authentication {
login(username: $username, password: $password, provider: $provider) {
responseResult {
succeeded
errorCode
slug
message
}
tfaRequired
tfaLoginToken
}
}
}
mutation($loginToken: String!, $securityCode: String!) {
authentication {
loginTFA(loginToken: $loginToken, securityCode: $securityCode) {
responseResult {
succeeded
errorCode
slug
message
}
}
}
}
query {
authentication {
providers(
filter: "isEnabled eq true",
orderBy: "title ASC"
) {
key
title
useForm
icon
}
}
}
import _ from 'lodash'
import Vue from 'vue'
import Vuex from 'vuex'
import navigator from './modules/navigator'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
loading: false
loadingStack: [],
notification: {
message: '',
style: 'primary',
icon: 'cached',
isActive: false
}
},
mutations: {
loadingChange: (state, loadingState) => { state.loading = loadingState }
getters: {
isLoading: state => { return state.loadingStack.length > 0 }
},
actions: {
alert({ dispatch }, opts) { dispatch('navigator/alert', opts) },
startLoading({ commit }) { commit('loadingChange', true) },
stopLoading({ commit }) { commit('loadingChange', false) }
mutations: {
loadingStart (state, stackName) {
state.loadingStack = _.union(state.loadingStack, [stackName])
},
loadingStop (state, stackName) {
state.loadingStack = _.without(state.loadingStack, stackName)
},
showNotification (state, opts) {
state.notification = _.defaults(opts, {
message: '',
style: 'primary',
icon: 'cached',
isActive: true
})
},
updateNotificationState (state, newState) {
state.notification.isActive = newState
}
},
getters: {},
modules: {
navigator
}
actions: { },
modules: { }
})
import debounce from 'lodash/debounce'
export default {
namespaced: true,
state: {
subtitleShown: false,
subtitleStyle: '',
subtitleIcon: false,
subtitleText: '',
subtitleStatic: 'Welcome'
},
getters: {},
mutations: {
subtitleChange (state, opts) {
state.subtitleShown = (opts.shown === true)
state.subtitleStyle = opts.style || ''
state.subtitleIcon = opts.icon || false
state.subtitleText = opts.msg || ''
},
subtitleStatic (state, text) {
state.subtitleText = text
state.subtitleStatic = text
}
},
actions: {
alert ({ commit, dispatch }, opts) {
opts.shown = true
commit('subtitleChange', opts)
dispatch('alertDismiss')
},
alertDismiss: debounce(({ commit, state }) => {
let opts = {
shown: false,
style: state.subtitleStyle,
msg: state.subtitleStatic
}
commit('subtitleChange', opts)
}, 5000)
}
}
......@@ -21,14 +21,21 @@ paths:
# ---------------------------------------------------------------------
# Database
# ---------------------------------------------------------------------
# PostgreSQL 9.5 or later required
# Supported Database Engines:
# - postgres = PostgreSQL 9.5 or later
# - mysql = MySQL 5.7.8 or later
# - sqlite = SQLite 3.9 or later
db:
type: postgres
# PostgreSQL and MySQL only:
host: localhost
port: 5432
user: wikijs
pass: wikijsrocks
db: wiki
# SQLite only:
storage: path/to/database.sqlite
# ---------------------------------------------------------------------
# Redis
......
......@@ -163,6 +163,11 @@ module.exports = {
]
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader'
},
{
test: /.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
......@@ -226,7 +231,8 @@ module.exports = {
alias: {
'@': path.join(process.cwd(), 'client'),
'vue$': 'vue/dist/vue.esm.js',
'mdi': path.resolve(process.cwd(), 'node_modules/vue-material-design-icons'),
'gql': path.join(process.cwd(), 'client/graph'),
'mdi': path.join(process.cwd(), 'node_modules/vue-material-design-icons'),
// Duplicates fixes:
'apollo-link': path.join(process.cwd(), 'node_modules/apollo-link'),
'apollo-utilities': path.join(process.cwd(), 'node_modules/apollo-utilities'),
......
......@@ -170,6 +170,11 @@ module.exports = {
]
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader'
},
{
test: /.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
......@@ -255,6 +260,7 @@ module.exports = {
alias: {
'@': path.join(process.cwd(), 'client'),
'vue$': 'vue/dist/vue.esm.js',
'gql': path.join(process.cwd(), 'client/graph'),
'mdi': path.resolve(process.cwd(), 'node_modules/vue-material-design-icons'),
// Duplicates fixes:
'apollo-link': path.join(process.cwd(), 'node_modules/apollo-link'),
......
......@@ -98,6 +98,7 @@
"moment-timezone": "0.5.14",
"mongodb": "3.0.4",
"multer": "1.3.0",
"mysql2": "1.5.3",
"node-2fa": "1.1.2",
"oauth2orize": "1.11.0",
"ora": "2.0.0",
......@@ -130,6 +131,7 @@
"semver": "5.5.0",
"sequelize": "4.37.1",
"serve-favicon": "2.4.5",
"sqlite3": "4.0.0",
"uuid": "3.2.1",
"validator": "9.4.1",
"validator-as-promised": "1.0.2",
......
......@@ -11,11 +11,13 @@ defaults:
repo: ./repo
data: ./data
db:
type: postgres
host: localhost
port: 5432
user: wikijs
pass: wikijsrocks
db: wiki
storage: ./db.sqlite
redis:
host: localhost
port: 6379
......
......@@ -64,7 +64,8 @@ module.exports = {
this.inst = new this.Sequelize(WIKI.config.db.db, WIKI.config.db.user, WIKI.config.db.pass, {
host: WIKI.config.db.host,
port: WIKI.config.db.port,
dialect: 'postgres',
dialect: WIKI.config.db.type,
storage: WIKI.config.db.storage,
pool: {
max: 10,
min: 0,
......@@ -77,9 +78,9 @@ module.exports = {
// Attempt to connect and authenticate to DB
this.inst.authenticate().then(() => {
WIKI.logger.info('Database (PostgreSQL) connection: [ OK ]')
WIKI.logger.info(`Database (${WIKI.config.db.type}) connection: [ OK ]`)
}).catch(err => {
WIKI.logger.error('Failed to connect to PostgreSQL instance.')
WIKI.logger.error(`Failed to connect to ${WIKI.config.db.type} instance.`)
WIKI.logger.error(err)
process.exit(1)
})
......@@ -112,7 +113,10 @@ module.exports = {
},
// -> Set Connection App Name
setAppName() {
return self.inst.query(`set application_name = 'WIKI.js'`, { raw: true })
switch (WIKI.config.db.type) {
case 'postgres':
return self.inst.query(`set application_name = 'WIKI.js'`, { raw: true })
}
}
}
......
......@@ -35,7 +35,7 @@ module.exports = {
let authResult = await WIKI.db.User.login(args, context)
return {
...authResult,
operation: graphHelper.generateSuccess('Login success')
responseResult: graphHelper.generateSuccess('Login success')
}
} catch (err) {
return graphHelper.generateError(err)
......@@ -46,7 +46,7 @@ module.exports = {
let authResult = await WIKI.db.User.loginTFA(args, context)
return {
...authResult,
operation: graphHelper.generateSuccess('TFA success')
responseResult: graphHelper.generateSuccess('TFA success')
}
} catch (err) {
return graphHelper.generateError(err)
......
const graphHelper = require('../../helpers/graph')
/* global WIKI */
......@@ -11,8 +12,22 @@ module.exports = {
async groups() { return {} }
},
GroupQuery: {
list(obj, args, context, info) {
return WIKI.db.Group.findAll({ where: args })
async list(obj, args, context, info) {
return WIKI.db.Group.findAll({
attributes: {
include: [[WIKI.db.inst.fn('COUNT', WIKI.db.inst.col('users.id')), 'userCount']]
},
include: [{
model: WIKI.db.User,
attributes: [],
through: {
attributes: []
}
}],
raw: true,
// TODO: Figure out how to exclude these extra fields...
group: ['group.id', 'users->userGroups.createdAt', 'users->userGroups.updatedAt', 'users->userGroups.version', 'users->userGroups.userId', 'users->userGroups.groupId']
})
}
},
GroupMutation: {
......@@ -29,8 +44,15 @@ module.exports = {
})
})
},
create(obj, args) {
return WIKI.db.Group.create(args)
async create(obj, args) {
const group = await WIKI.db.Group.create({
name: args.name
})
console.info(group)
return {
responseResult: graphHelper.generateSuccess('Group created successfully.'),
group
}
},
delete(obj, args) {
return WIKI.db.Group.destroy({
......
......@@ -59,7 +59,7 @@ type AuthenticationProvider {
}
type AuthenticationLoginResponse {
operation: ResponseStatus
responseResult: ResponseStatus
tfaRequired: Boolean
tfaLoginToken: String
}
......@@ -39,12 +39,12 @@ input KeyValuePairInput {
}
type DefaultResponse {
operation: ResponseStatus
responseResult: ResponseStatus
}
type ResponseStatus {
succeeded: Boolean!
code: Int!
errorCode: Int!
slug: String!
message: String
}
......
......@@ -55,7 +55,7 @@ type GroupMutation {
# -----------------------------------------------
type GroupResponse {
operation: ResponseStatus!
responseResult: ResponseStatus!
group: Group
}
......@@ -64,6 +64,7 @@ type Group {
name: String!
rights: [String]
users: [User]
userCount: Int
createdAt: Date!
updatedAt: Date!
}
......@@ -5,7 +5,7 @@ module.exports = {
generateSuccess (msg) {
return {
succeeded: true,
code: 0,
errorCode: 0,
slug: 'ok',
message: _.defaultTo(msg, 'Operation succeeded.')
}
......@@ -13,11 +13,11 @@ module.exports = {
generateError (err, complete = true) {
const error = {
succeeded: false,
code: err.code || 1,
errorCode: err.code || 1,
slug: err.name,
message: err.message || 'An unexpected error occured.'
}
return (complete) ? { operation: error } : error
return (complete) ? { responseResult: error } : error
},
filter (arr, filterString) {
const prvFilter = new Filter(_.toString(filterString).replace(/'/g, `"`))
......
......@@ -14,7 +14,7 @@ module.exports = (sequelize, DataTypes) => {
defaultValue: 'application/octet-stream'
},
extra: {
type: DataTypes.JSONB,
type: DataTypes.JSON,
allowNull: true
},
filename: {
......
......@@ -8,7 +8,7 @@ module.exports = (sequelize, DataTypes) => {
allowNull: false
},
config: {
type: DataTypes.JSONB,
type: DataTypes.JSON,
allowNull: false
}
}, {
......
This diff was suppressed by a .gitattributes entry.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment