@open-commune/web 0.2.14 → 0.2.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/app.config.ts +7 -0
  2. package/components/audience/audience-bar-list.vue +29 -0
  3. package/components/audience/audience-panel.vue +230 -0
  4. package/components/data/lists/data-table.vue +203 -0
  5. package/components/data/lists/row-actions.vue +41 -0
  6. package/components/elements/badges/status-badge.vue +23 -0
  7. package/components/elements/media/media-image.vue +26 -0
  8. package/components/forms/fields/input-files-media.vue +87 -0
  9. package/components/forms/{inputs → fields}/input-filter-status.vue +2 -2
  10. package/components/forms/{inputs → fields}/input-search.vue +8 -2
  11. package/components/forms/fields/input-text-area.vue +86 -0
  12. package/components/forms/fields/input-text.vue +47 -0
  13. package/components/forms/fields/select-enum.vue +69 -0
  14. package/components/forms/handlers/handler-collections.vue +100 -170
  15. package/components/forms/handlers/handler-list.vue +187 -0
  16. package/components/forms/handlers/handler-members.vue +171 -0
  17. package/components/forms/handlers/handler-password-reset.vue +45 -0
  18. package/components/forms/handlers/handler-roles.vue +28 -166
  19. package/components/forms/handlers/handler-sessions.vue +77 -0
  20. package/components/forms/handlers/handler-tokens.vue +54 -69
  21. package/components/forms/layouts/form-default.vue +99 -0
  22. package/components/forms/layouts/form.vue +4 -0
  23. package/components/forms/layouts/forms-layout.vue +236 -0
  24. package/components/forms/layouts/forms-section.vue +186 -0
  25. package/components/forms/layouts/layout.vue +4 -0
  26. package/components/forms/layouts/modal.vue +4 -0
  27. package/components/forms/layouts/section.vue +4 -0
  28. package/components/layout/shell/shell-account-menu.vue +10 -2
  29. package/composables/core/domains/use-api-tokens.ts +80 -0
  30. package/composables/core/domains/use-audience.ts +26 -0
  31. package/composables/core/domains/use-auth.ts +56 -2
  32. package/composables/core/domains/use-definitions.ts +18 -5
  33. package/composables/core/domains/use-entries.ts +125 -3
  34. package/composables/core/domains/use-media.ts +24 -1
  35. package/composables/core/domains/use-members.ts +68 -0
  36. package/composables/core/domains/use-organization.ts +53 -0
  37. package/composables/use-models.js +1 -7
  38. package/constants/errors.ts +29 -0
  39. package/constants/forms/account.ts +62 -0
  40. package/constants/forms/collections.ts +39 -0
  41. package/constants/forms/members.ts +40 -0
  42. package/constants/forms/organization.ts +188 -0
  43. package/constants/forms/tokens.ts +15 -0
  44. package/constants/roles.ts +57 -0
  45. package/constants/settings.ts +26 -0
  46. package/constants/statuses.ts +8 -5
  47. package/nuxt.config.ts +4 -1
  48. package/package.json +4 -3
  49. package/pages/[collection]/[record]/index.vue +7 -0
  50. package/pages/[collection]/index.vue +117 -97
  51. package/pages/account.vue +40 -0
  52. package/pages/overview.vue +106 -2
  53. package/pages/settings.vue +26 -181
  54. package/plugins/01.validation.client.ts +23 -0
  55. package/store/layout/workspace.js +4 -28
  56. package/utils/colors.ts +26 -0
  57. package/utils/errors.ts +13 -0
  58. package/utils/forms.ts +67 -0
  59. package/utils/list-columns.ts +90 -0
  60. package/utils/settings.ts +38 -0
  61. package/utils/statuses.ts +4 -0
  62. package/models/role.js +0 -66
  63. package/models/token.js +0 -56
  64. package/models/user.js +0 -97
  65. package/pages/management/index.vue +0 -15
  66. package/pages/management/members.vue +0 -176
  67. package/pages/management/organizations.vue +0 -192
  68. package/pages/management/roles.vue +0 -183
  69. /package/components/forms/{inputs → fields}/input-filter.vue +0 -0
@@ -0,0 +1,187 @@
1
+ <template>
2
+ <div>
3
+ <!-- The gesture sits OVER the list it adds to, at the left edge where
4
+ reading starts: on an empty list it is the first thing to reach for,
5
+ on a long one it stays where the eye enters rather than hiding under
6
+ the last row. At the weight of a « Enregistrer », because it is the one
7
+ thing to do here. It used to be declared through `useSectionAction` and
8
+ drawn by the enclosing section, an injection that existed only because
9
+ the handler had no way up. -->
10
+ <div v-if="actionLabel" class="mb-3 flex justify-end">
11
+ <UButton
12
+ color="neutral"
13
+ size="md"
14
+ :label="actionLabel"
15
+ class="p-2.5"
16
+ @click="$emitters('add')"
17
+ />
18
+ </div>
19
+
20
+ <!-- The default slot REPLACES the list, for a handler that draws its own
21
+ table and comes here only for the button and the modal. Nobody
22
+ overrides it since `handler-records` was deleted: the fallback below is
23
+ what every caller renders today. -->
24
+ <slot>
25
+ <div class="overflow-hidden rounded-lg border border-default bg-elevated shadow-xs plain:bg-default">
26
+ <p v-if="loading" class="px-4 py-6 text-center text-sm text-muted">
27
+ Chargement…
28
+ </p>
29
+ <p v-else-if="!rows.length" class="px-4 py-6 text-center text-sm text-muted">
30
+ {{ empty }}
31
+ </p>
32
+ <div
33
+ v-for="row in rows"
34
+ :key="row.key"
35
+ class="group flex items-center gap-3 border-t border-default px-4 py-3 first:border-t-0"
36
+ >
37
+ <slot name="row" :row="row" />
38
+ </div>
39
+ </div>
40
+ </slot>
41
+
42
+ <UModal
43
+ :open="open"
44
+ :title="title"
45
+ :description="description"
46
+ :ui="{ content: 'sm:max-w-4xl bg-elevated plain:bg-default' }"
47
+ @update:open="$emitters('update:open', $event)"
48
+ >
49
+ <template #body>
50
+ <!-- The modal's fields are a form of their own: the schema refuses
51
+ under the field, before anything leaves. -->
52
+ <UForm
53
+ v-if="form.length"
54
+ :id="formId"
55
+ novalidate
56
+ :state="state"
57
+ :schema="narrowed"
58
+ @submit="_submit"
59
+ >
60
+ <form-default :state="state" :attributes="form" />
61
+ </UForm>
62
+ </template>
63
+
64
+ <template #footer>
65
+ <div class="grid w-full grid-cols-1 gap-3 sm:grid-flow-row-dense sm:grid-cols-2">
66
+ <UButton
67
+ v-if="cancelLabel"
68
+ color="neutral"
69
+ variant="outline"
70
+ class="justify-center bg-elevated"
71
+ :label="cancelLabel"
72
+ @click="_close"
73
+ />
74
+ <UButton
75
+ v-if="submitLabel"
76
+ color="neutral"
77
+ class="justify-center"
78
+ :label="submitLabel"
79
+ type="submit"
80
+ :form="formId"
81
+ />
82
+ </div>
83
+ </template>
84
+ </UModal>
85
+ </div>
86
+ </template>
87
+
88
+ <script setup lang="ts">
89
+ import formDefault from '~/components/forms/layouts/form-default.vue'
90
+ import type { FormControl } from '~/types'
91
+ import { narrowSchema, propertiesOf, valuesOf } from '~/utils/forms'
92
+
93
+ export interface ListRow {
94
+ key: string
95
+ [field: string]: unknown
96
+ }
97
+
98
+ /** A record the modal is creating or editing. */
99
+ export type ListRecord = Record<string, unknown>
100
+
101
+ // Prepare props
102
+ const $props = withDefaults(
103
+ defineProps<{
104
+ rows?: ListRow[]
105
+ loading?: boolean
106
+ empty?: string
107
+ /** The word on the button that opens the modal. No word, no button. */
108
+ actionLabel?: string
109
+ open?: boolean
110
+ /** The fields the modal renders, described as data. No field, no form. */
111
+ form?: FormControl[]
112
+ /** The server's schema for what the modal submits: the core's DTO. */
113
+ schema?: object
114
+ /** The record being edited — empty on a creation. */
115
+ record?: ListRecord
116
+ title?: string
117
+ description?: string
118
+ submitLabel?: string
119
+ cancelLabel?: string
120
+ }>(),
121
+ {
122
+ rows: () => [],
123
+ loading: false,
124
+ empty: 'Aucun élément.',
125
+ actionLabel: '',
126
+ open: false,
127
+ form: () => [],
128
+ record: () => ({}),
129
+ title: '',
130
+ description: '',
131
+ submitLabel: 'Créer',
132
+ cancelLabel: 'Annuler'
133
+ }
134
+ )
135
+
136
+ // Prepare emitters
137
+ const $emitters = defineEmits<{
138
+ 'update:open': [boolean]
139
+ add: []
140
+ submit: [ListRecord]
141
+ /** The record being edited, at each keystroke. */
142
+ change: [ListRecord]
143
+ }>()
144
+
145
+ // Prepare reactive
146
+ /** What the modal's controls write into, rebuilt each time it opens. */
147
+ const state = reactive<ListRecord>({})
148
+ const formId = useId()
149
+
150
+ // Prepare computed
151
+ const properties = computed(() => propertiesOf($props.form))
152
+ const narrowed = computed(() => narrowSchema($props.schema, properties.value))
153
+
154
+ // Prepare methods
155
+ const _close = () => $emitters('update:open', false)
156
+
157
+ /**
158
+ * The record as it stands AFTER the edit: the original, with the modal's
159
+ * fields laid over it. A field left empty on a creation is not sent at all,
160
+ * so the server derives what it derives (a slug from a name).
161
+ */
162
+ const _edited = () => ({
163
+ ...$props.record,
164
+ ...Object.fromEntries(Object.entries(state).filter(([, value]) => value !== undefined)),
165
+ })
166
+
167
+ const _submit = () => {
168
+ $emitters('submit', _edited())
169
+ _close()
170
+ }
171
+
172
+ // Prepare watchers
173
+ // A modal reopened must not carry the previous edit. Rebuilt on OPENING, not
174
+ // on closing: the closing animation still reads the form.
175
+ watch(
176
+ [() => $props.open, properties],
177
+ ([open]) => {
178
+ if (!open) return
179
+ for (const key of Object.keys(state)) delete state[key]
180
+ Object.assign(state, valuesOf($props.record, properties.value))
181
+ },
182
+ { immediate: true }
183
+ )
184
+ // A form whose fields depend on another field cannot wait for the submission
185
+ // to know what was chosen.
186
+ watch(state, () => $emitters('change', _edited()), { deep: true })
187
+ </script>
@@ -0,0 +1,171 @@
1
+ <template>
2
+ <handler-list
3
+ v-model:open="isModalOpen"
4
+ :rows="rows"
5
+ :loading="isLoading"
6
+ empty="Aucun membre."
7
+ action-label="Inviter une personne"
8
+ :form="action === 'create' ? MEMBER_INVITE_FORM : MEMBER_UPDATE_FORM"
9
+ :schema="action === 'create' ? inviteDto : userUpdateDto.shape.data"
10
+ :record="editing"
11
+ :title="modalTitle"
12
+ :description="modalDescription"
13
+ :submit-label="submitLabel"
14
+ @add="_openModalForm('create', { role: 'redacteur' })"
15
+ @submit="_submitMember"
16
+ >
17
+ <template #row="{ row }">
18
+ <UAvatar
19
+ :alt="row.pending ? '?' : row.name"
20
+ :ui="{ root: 'size-8 shrink-0 bg-accented text-muted text-xs' }"
21
+ />
22
+ <component
23
+ :is="row.pending ? 'div' : 'button'"
24
+ :type="row.pending ? undefined : 'button'"
25
+ class="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 text-left"
26
+ :class="row.pending ? '' : 'cursor-pointer'"
27
+ @click="row.pending ? undefined : _openModalForm('update', row.source)"
28
+ >
29
+ <span class="truncate text-sm font-medium text-highlighted">{{ row.name }}</span>
30
+ <span class="truncate text-sm text-dimmed">{{ row.detail }}</span>
31
+ </component>
32
+ <span
33
+ v-if="row.pending"
34
+ class="flex shrink-0 items-center gap-1.5 text-3xs font-semibold tracking-[0.14em] text-warning uppercase"
35
+ >
36
+ <span class="size-1.5 rounded-full bg-current" />
37
+ En attente
38
+ </span>
39
+ <span v-else class="shrink-0 text-3xs font-semibold tracking-[0.14em] text-muted uppercase">
40
+ {{ row.role }}
41
+ </span>
42
+ <UButton
43
+ icon="i-lucide-trash-2"
44
+ color="neutral"
45
+ variant="ghost"
46
+ size="sm"
47
+ class="shrink-0 text-dimmed opacity-0 transition hover:text-error group-hover:opacity-100 focus-visible:opacity-100"
48
+ :aria-label="row.pending ? `Annuler l'invitation de ${row.name}` : `Retirer ${row.name}`"
49
+ @click="row.pending ? _revokeInvitation(row.source) : _remove(row.source)"
50
+ />
51
+ </template>
52
+ </handler-list>
53
+ </template>
54
+
55
+ <script setup>
56
+ import { inviteDto, userUpdateDto } from '@open-commune/core/dtos'
57
+ import handlerList from '~/components/forms/handlers/handler-list.vue'
58
+ import { DateTime } from 'luxon'
59
+ import { roleNamed } from '~/constants/roles'
60
+ import { MEMBER_INVITE_FORM, MEMBER_UPDATE_FORM } from '~/constants/forms/members'
61
+
62
+ // Prepare composables
63
+ const $toast = useToast()
64
+ const $members = useMembers()
65
+ const { mutateAsync: invite } = $members.invite()
66
+ const { mutateAsync: revokeInvitation } = $members.revokeInvitation()
67
+ const { mutateAsync: updateMember } = $members.update()
68
+ const { mutateAsync: removeMember } = $members.remove()
69
+
70
+ // Prepare reactive
71
+ const isModalOpen = ref(false)
72
+ /** Which gesture the open modal is serving, and on which member. */
73
+ const action = ref('create')
74
+ const editing = ref({})
75
+
76
+ // Fetch data
77
+ const { data: accounts, isLoading } = $members.list()
78
+ const { data: invitations } = $members.pending()
79
+
80
+ // Prepare computed
81
+ /**
82
+ * Members and invitations, in ONE list.
83
+ *
84
+ * Someone who has not opened their link has no name yet: their address stands
85
+ * in for one, rather than half an empty row.
86
+ */
87
+ const rows = computed(() => [
88
+ ...(accounts.value ?? []).map((member) => ({
89
+ key: `m-${member.id}`,
90
+ name: member.name || member.email,
91
+ detail: member.name ? member.email : '',
92
+ role: roleNamed(member.role)?.name ?? member.role,
93
+ pending: false,
94
+ source: member,
95
+ })),
96
+ ...(invitations.value ?? []).map((invitation) => ({
97
+ key: `i-${invitation.id}`,
98
+ name: invitation.email,
99
+ detail: `invitée ${DateTime.fromISO(invitation.expiresAt).setLocale('fr').toRelative()}`,
100
+ pending: true,
101
+ source: invitation,
102
+ })),
103
+ ])
104
+
105
+ const modalTitle = computed(() => `${action.value === 'create' ? 'Inviter' : 'Modifier'} un membre`)
106
+
107
+ const modalDescription = computed(() => (action.value === 'create'
108
+ ? 'Un lien d\'invitation sera généré pour ce nouveau membre.'
109
+ : 'Modifiez les informations du membre.'))
110
+
111
+ const submitLabel = computed(() => (action.value === 'create' ? 'Inviter' : 'Modifier'))
112
+
113
+ // Prepare methods
114
+ const _invite = async ({ email, role }) => {
115
+ const { token } = await invite({ email, role })
116
+ // The origin comes from the browser, never from a URL baked at build time —
117
+ // the instance image is shared by every client.
118
+ const link = `${window.location.origin}/welcome/${token}`
119
+ // The email leaves server side; the copied link is the second recourse.
120
+ try {
121
+ await navigator.clipboard.writeText(link)
122
+ $toast.add({
123
+ icon: 'iconoir:mail-out',
124
+ color: 'success',
125
+ title: 'Lien d\'invitation copié dans le presse-papier (valable 7 jours).'
126
+ })
127
+ } catch {
128
+ $toast.add({
129
+ icon: 'iconoir:mail-out',
130
+ color: 'success',
131
+ title: 'Invitation envoyée (lien valable 7 jours).',
132
+ description: link,
133
+ duration: 0,
134
+ })
135
+ }
136
+ }
137
+
138
+ const _remove = ({ id }) => removeMember(id)
139
+
140
+ /**
141
+ * Cancelling an invitation is NOT removing a member: the person has no account
142
+ * yet, and `users.remove` left the invitation — and its link — alive.
143
+ * A failure is SHOWN: silently keeping the row would read as a bug.
144
+ */
145
+ const _revokeInvitation = async ({ id, email }) => {
146
+ try {
147
+ await revokeInvitation(id)
148
+ $toast.add({ title: `Invitation de ${email} annulée.` })
149
+ } catch {
150
+ $toast.add({
151
+ color: 'error',
152
+ title: "L'invitation n'a pas pu être annulée",
153
+ description: 'Elle a peut-être déjà été acceptée ou expirée. Rechargez l\'écran.',
154
+ })
155
+ }
156
+ }
157
+
158
+ /**
159
+ * The modal hands back the member it was given, covered by the fields that
160
+ * were touched — so `id` is there without being carried in a closure.
161
+ */
162
+ const _submitMember = (record) => (action.value === 'create'
163
+ ? _invite(record)
164
+ : updateMember({ id: record.id, data: { name: record.name, role: record.role } }))
165
+
166
+ const _openModalForm = (nextAction, record = {}) => {
167
+ action.value = nextAction
168
+ editing.value = record
169
+ isModalOpen.value = true
170
+ }
171
+ </script>
@@ -0,0 +1,45 @@
1
+ <template>
2
+ <div class="relative block w-full">
3
+ <UButton
4
+ color="neutral"
5
+ variant="outline"
6
+ class="bg-elevated"
7
+ :label="sent ? 'Email envoyé' : 'Recevoir un lien de réinitialisation'"
8
+ :disabled="sent"
9
+ :loading="isLoading"
10
+ @click="_request"
11
+ />
12
+ </div>
13
+ </template>
14
+
15
+ <script setup>
16
+ /**
17
+ * Changing one's password goes through the reset email, not a form. Two
18
+ * reasons: no new server procedure to write, and the link PROVES access to
19
+ * the mailbox — which a current-password field does not, on a session
20
+ * left open on an unattended machine.
21
+ */
22
+
23
+ // Prepare composables
24
+ const $auth = useAuth()
25
+ const $session = useSession()
26
+
27
+ // Prepare reactive
28
+ const sent = ref(false)
29
+
30
+ // Prepare computed
31
+ const isLoading = computed(() => $auth.isRequestingPasswordReset.value)
32
+
33
+ // Prepare methods
34
+ const _request = async () => {
35
+ const address = $session.user.value?.email
36
+ if (!address) return
37
+
38
+ // `requestPasswordReset` now carries its own catch, its pending state and
39
+ // both toasts, and answers rather than throwing. `sent` stays here: locking
40
+ // the button is this screen's business, not the request's.
41
+ if (await $auth.requestPasswordReset(address)) {
42
+ sent.value = true
43
+ }
44
+ }
45
+ </script>
@@ -1,176 +1,38 @@
1
1
  <template>
2
- <div class="relative block w-full">
3
- <label
4
- v-if="label"
5
- id="listbox-label"
6
- class="block text-2xs font-light tracking-wider text-gray-500 uppercase"
2
+ <div class="grid gap-4 sm:grid-cols-2">
3
+ <div
4
+ v-for="role in ROLES"
5
+ :key="role.id"
6
+ class="rounded-xl bg-elevated p-7 shadow-card dark:shadow-none dark:ring dark:ring-[var(--ui-border)] plain:bg-default plain:ring plain:ring-default"
7
7
  >
8
- {{ label }}
9
- </label>
10
- <div class="grid grid-cols-5 space-x-2 mb-2" :class="{ 'mt-1': label }">
11
- <div class="inline-flex col-span-4 space-x-1">
12
- <select-enum
13
- :items="organizations"
14
- :value="currentOrganization"
15
- place-holder="Organisation"
16
- class="w-full"
17
- @change="currentOrganization = $event"
18
- />
19
- <select-enum
20
- :items="roles"
21
- :value="currentRole"
22
- :item-key="'name'"
23
- :read-only="!currentOrganization"
24
- place-holder="Role"
25
- class="w-full"
26
- @change="currentRole = $event"
27
- />
28
- <select-enum
29
- :items="collections"
30
- :value="currentCollections"
31
- :read-only="!currentOrganization || !currentRole"
32
- place-holder="Collection(s)"
33
- class="w-full"
34
- enable-multiple
35
- @change="currentCollections = $event"
36
- />
37
- </div>
38
- <button-secondary class="col-span-1" label="Ajouter un rôle" @click="_addRole" />
39
- <!-- @click="_openModalForm('add')" -->
8
+ <h3 class="text-base font-semibold text-highlighted">{{ role.name }}</h3>
9
+ <p class="mt-0.5 text-sm text-muted">{{ role.description }}</p>
10
+
11
+ <ul class="mt-5 space-y-2.5">
12
+ <li
13
+ v-for="capability in CAPABILITIES"
14
+ :key="capability.label"
15
+ class="flex items-start gap-2 text-sm"
16
+ >
17
+ <UIcon
18
+ :name="_can(role, capability) ? 'i-lucide-check' : 'i-lucide-x'"
19
+ class="mt-0.5 size-4 shrink-0"
20
+ :class="_can(role, capability) ? 'text-success' : 'text-dimmed'"
21
+ />
22
+ <span :class="_can(role, capability) ? 'text-default' : 'text-dimmed'">
23
+ {{ capability.label }}
24
+ </span>
25
+ </li>
26
+ </ul>
40
27
  </div>
41
- <list-table
42
- :headers="TABLE_HEADERS"
43
- :items="selection"
44
- :actions="['remove']"
45
- class="bg-gray-100 p-2"
46
- @remove="_removeRole"
47
- />
48
- <!-- @update="_openModalForm('update', $event)"
49
- @remove="_handle('remove', $event)" -->
50
28
  </div>
51
29
  </template>
52
30
 
53
31
  <script setup>
54
- import { computedAsync } from '@vueuse/core'
55
- import listTable from '~/components/data/lists/data-lists-table'
56
- import selectEnum from '~/components/forms/selects/select-enum'
57
- import buttonSecondary from '~/components/elements/buttons/secondary'
58
-
59
- // Prepare composable
60
- const { Organization, Role, Collection } = useModels()
61
-
62
- // Prepare constants
63
- const TABLE_HEADERS = [
64
- {
65
- title: 'Organisation',
66
- nestedValue: false,
67
- component: 'data-summary',
68
- componentOptions: {
69
- titleKey: 'organization',
70
- descriptionKey: 'role',
71
- }
72
- },
73
- {
74
- property: 'collections',
75
- component: 'data-text'
76
- },
77
- {
78
- component: 'data-spacer',
79
- grow: true
80
- },
81
- {
82
- title: '',
83
- component: 'actions',
84
- componentOptions: {
85
- options: [
86
- { label: 'Supprimer', action: 'remove' }
87
- ]
88
- }
89
- }
90
- ]
91
-
92
- // Prepare props
93
- const $props = defineProps({
94
- label: {
95
- type: String,
96
- default: ''
97
- },
98
- value: {
99
- type: Array,
100
- default: () => []
101
- }
102
- })
103
-
104
- // Prepare $emitters
105
- const $emitters = defineEmits(['keyup.enter', 'change'])
106
-
107
- // Prepare data
108
- const selection = ref([])
109
- const currentOrganization = ref(null)
110
- const currentRole = ref(null)
111
- const currentCollections = ref([])
112
-
113
- // Prepare computed
114
- const organizations = computed(() => Organization.repo.all())
115
- const roles = computed(() => Role.repo.all())
116
- const collections = computedAsync(
117
- async () => {
118
- if (currentOrganization.value) {
119
- const collections = await Collection.list(undefined, currentOrganization.value)
120
- console.log(collections)
121
- return [{ _id: '*', name: 'Toutes les collections (*)'}, ...collections]
122
- }
123
- return []
124
- },
125
- [],
126
- )
127
-
32
+ import { CAPABILITIES, ROLES } from '~/constants/roles'
128
33
 
129
34
  // Prepare methods
130
- const _addRole = () => {
131
- selection.value.push({
132
- organization: currentOrganization.value,
133
- role: currentRole.value,
134
- collections: currentCollections.value
135
- })
136
- currentOrganization.value = null
137
- currentRole.value = null
138
- currentCollections.value = []
139
- }
140
- const _removeRole = (val) => {
141
- const indexToRemove = selection.value.findIndex(
142
- ({ organization, collections, role }) =>organization === val.organization
143
- && role === val.role
144
- && val.collections.every((_id) => collections.includes(_id))
145
- )
146
- if (indexToRemove >= 0) {
147
- selection.value.splice(indexToRemove, 1)
148
- }
149
- }
150
-
151
- // prepare watchers
152
- watch(
153
- () => $props.value,
154
- (newValue) => {
155
- if (newValue) {
156
- selection.value = newValue
157
- }
158
- },
159
- { immediate: true }
160
- )
161
- watch(
162
- selection,
163
- (newValue) => $emitters('change', newValue),
164
- { immediate: true }
165
- )
166
-
167
- // Prepare lifecycle hook
168
- onMounted(async () => {
169
- if (!roles.value.length) {
170
- await Role.list()
171
- }
172
- if (!organizations.value.length) {
173
- await Organization.list()
174
- }
175
- })
35
+ // `manage:all` is CASL's joker: it opens everything without being listed.
36
+ const _can = (role, { ability }) =>
37
+ role.permissions.includes('manage:all') || role.permissions.includes(ability)
176
38
  </script>
@@ -0,0 +1,77 @@
1
+ <template>
2
+ <handler-list :rows="rows" :loading="isLoading" empty="Aucune session ouverte.">
3
+ <template #row="{ row }">
4
+ <span class="min-w-0 flex-1 truncate text-sm font-medium text-highlighted">{{ row.device }}</span>
5
+ <span class="shrink-0 text-[13px] text-dimmed">{{ row.opened }}</span>
6
+ <UButton
7
+ v-if="!row.current"
8
+ icon="i-lucide-trash-2"
9
+ color="neutral"
10
+ variant="ghost"
11
+ size="sm"
12
+ class="shrink-0 text-dimmed opacity-0 transition hover:text-error group-hover:opacity-100 focus-visible:opacity-100"
13
+ :aria-label="`Fermer la session ${row.device}`"
14
+ @click="revoke(row.id)"
15
+ />
16
+ <span v-else class="w-8 shrink-0" />
17
+ </template>
18
+ </handler-list>
19
+ </template>
20
+
21
+ <script setup>
22
+ import handlerList from '~/components/forms/handlers/handler-list.vue'
23
+ import { DateTime } from 'luxon'
24
+
25
+ // Prepare constants
26
+ /**
27
+ * How many sessions the table shows.
28
+ *
29
+ * A session lives thirty days: someone signing in daily from two devices
30
+ * piles up sixty, and the screen becomes a wall where the intruder one is
31
+ * looking for is invisible. Ten are shown, and the rest are counted.
32
+ */
33
+ const VISIBLE = 10
34
+
35
+ // Prepare composables
36
+ const $auth = useAuth()
37
+
38
+ // Fetch data
39
+ // The query hands back the list AND the gesture that closes one of them: the
40
+ // close button calls `revoke` directly, the list refreshes through its key.
41
+ const { data: sessions, isLoading, revoke } = $auth.sessions()
42
+
43
+ // Prepare computed
44
+ /** Most recent first, the current session ahead of them all. */
45
+ const sorted = computed(() =>
46
+ [...(sessions.value ?? [])].sort((a, b) => (
47
+ // Current session first: it is the one to recognize before the others.
48
+ Number(b.current) - Number(a.current) || b.createdAt.localeCompare(a.createdAt)
49
+ ))
50
+ )
51
+
52
+ const rows = computed(() => sorted.value.slice(0, VISIBLE).map(session => ({
53
+ key: session.id,
54
+ // The id the close button hands back — `key` belongs to the list that renders
55
+ // the row, and reusing it as data would tie one to the other.
56
+ id: session.id,
57
+ current: session.current,
58
+ device: [
59
+ _device(session.ua),
60
+ session.ip,
61
+ session.current ? 'session courante' : null
62
+ ].filter(Boolean).join(' · '),
63
+ opened: DateTime.fromISO(session.createdAt).setLocale('fr').toRelative(),
64
+ })))
65
+
66
+ // Prepare methods
67
+ /**
68
+ * A full user-agent is unreadable in a table. Only what helps someone
69
+ * recognize their own device is kept: the browser and the system.
70
+ */
71
+ const _device = (ua) => {
72
+ if (!ua) return 'Appareil inconnu'
73
+ const browser = /Firefox\/|Edg\/|Chrome\/|Safari\//.exec(ua)?.[0]?.replace('/', '') ?? 'Navigateur'
74
+ const system = /Mac OS X|Windows|Android|iPhone|iPad|Linux/.exec(ua)?.[0] ?? ''
75
+ return system ? `${browser} sur ${system}` : browser
76
+ }
77
+ </script>