High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
SSR: Port user and role management pages.
Kailash Nadh884e6a6e6ccc
diff --git a/cmd/admin.go b/cmd/admin.goindex 34810f54..c01d01e3 100644--- a/cmd/admin.go+++ b/cmd/admin.go@@ -53,6 +53,10 @@ var adminJSI18nKeys = []string{"globals.messages.selectAll","globals.messages.updated","globals.terms.list",+ "globals.terms.user",+ "globals.fields.name",+ "users.passwordMismatch",+ "campaigns.copyOf","globals.terms.second","globals.terms.minute","globals.terms.minute",diff --git a/cmd/handlers.go b/cmd/handlers.goindex f19ac585..68c05af0 100644--- a/cmd/handlers.go+++ b/cmd/handlers.go@@ -85,6 +85,17 @@ func initHTTPHandlers(e *echo.Echo, a *App) {g.GET(path.Join(uriAdmin, "/subscribers/:id/lists"), hasID(a.ViewSubscriber))g.GET(path.Join(uriAdmin, "/subscribers/:id/bounces"), hasID(a.ViewSubscriberBounces))g.GET(path.Join(uriAdmin, "/subscribers/:id/activity"), hasID(a.ViewSubscriberActivity))++ // Users and roles. Static segments are registered before the :id param routes.+ g.GET(path.Join(uriAdmin, "/users"), a.ViewUsers)+ g.GET(path.Join(uriAdmin, "/users/new"), a.ViewUser)+ g.GET(path.Join(uriAdmin, "/users/roles"), a.ViewUserRoles)+ g.GET(path.Join(uriAdmin, "/users/roles/new"), a.ViewUserRole)+ g.GET(path.Join(uriAdmin, "/users/roles/lists"), a.ViewListRoles)+ g.GET(path.Join(uriAdmin, "/users/roles/lists/new"), a.ViewListRole)+ g.GET(path.Join(uriAdmin, "/users/roles/lists/:id"), hasID(a.ViewListRole))+ g.GET(path.Join(uriAdmin, "/users/roles/:id"), hasID(a.ViewUserRole))+ g.GET(path.Join(uriAdmin, "/users/:id"), hasID(a.ViewUser))}// =================================================================diff --git a/cmd/roles.go b/cmd/roles.goindex 2806e0e3..1eb644db 100644--- a/cmd/roles.go+++ b/cmd/roles.go@@ -1,14 +1,199 @@package mainimport (+ "encoding/json""fmt""net/http""strings""github.com/knadh/listmonk/internal/auth"+ "github.com/knadh/listmonk/models""github.com/labstack/echo/v4"+ "gopkg.in/volatiletech/null.v6")+// roleRow is the normalized shape of a user/list role for the roles table view.+type roleRow struct {+ ID int+ Name string+ CreatedAt null.Time+ UpdatedAt null.Time+}++// rolesView is the admin page view listing user or list roles.+type rolesView struct {+ adminView++ Type string+ Roles []roleRow+}++// permGroup is a group of granular permissions as defined in permissions.json.+type permGroup struct {+ Group string `json:"group"`+ Permissions []string `json:"permissions"`+}++// roleFormView is the admin page view for a single role's add/edit form.+type roleFormView struct {+ adminView++ IsEditing bool+ Role any+ PermGroups []permGroup+ AllLists []models.List+}++// ViewUserRoles renders the HTML view listing user roles.+func (a *App) ViewUserRoles(c echo.Context) error {+ if !can(auth.GetUser(c), auth.PermRolesGet) {+ return auth.ErrPermDenied+ }++ roles, err := a.core.GetRoles()+ if err != nil {+ return err+ }++ rows := make([]roleRow, 0, len(roles))+ for _, r := range roles {+ rows = append(rows, roleRow{ID: r.ID, Name: r.Name.String, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt})+ }++ data := rolesView{+ adminView: newAdminView(c, a.i18n.T("users.userRoles"), ""),+ Type: "user",+ Roles: rows,+ }++ return c.Render(http.StatusOK, "admin-roles", data)+}++// ViewListRoles renders the HTML view listing list roles.+func (a *App) ViewListRoles(c echo.Context) error {+ if !can(auth.GetUser(c), auth.PermRolesGet) {+ return auth.ErrPermDenied+ }++ roles, err := a.core.GetListRoles()+ if err != nil {+ return err+ }++ rows := make([]roleRow, 0, len(roles))+ for _, r := range roles {+ rows = append(rows, roleRow{ID: r.ID, Name: r.Name.String, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt})+ }++ data := rolesView{+ adminView: newAdminView(c, a.i18n.T("users.listRoles"), ""),+ Type: "list",+ Roles: rows,+ }++ return c.Render(http.StatusOK, "admin-roles", data)+}++// ViewUserRole renders the HTML add/edit form for a user role.+func (a *App) ViewUserRole(c echo.Context) error {+ if !can(auth.GetUser(c), auth.PermRolesGet) {+ return auth.ErrPermDenied+ }++ var (+ role auth.Role+ isEditing bool+ )+ if c.Get("id") != nil {+ r, err := a.core.GetRole(getID(c))+ if err != nil {+ return err+ }+ role = r+ isEditing = true+ }++ groups, err := a.parsePermGroups()+ if err != nil {+ return err+ }++ title := a.i18n.T("users.newUserRole")+ if isEditing {+ title = role.Name.String+ }++ data := roleFormView{+ adminView: newAdminView(c, title, ""),+ IsEditing: isEditing,+ Role: role,+ PermGroups: groups,+ }++ return c.Render(http.StatusOK, "admin-user-role", data)+}++// ViewListRole renders the HTML add/edit form for a list role.+func (a *App) ViewListRole(c echo.Context) error {+ if !can(auth.GetUser(c), auth.PermRolesGet) {+ return auth.ErrPermDenied+ }++ var (+ role auth.ListRole+ isEditing bool+ )+ if c.Get("id") != nil {+ // There's no core getter for a single list role, so fetch all and pick the one.+ id := getID(c)+ roles, err := a.core.GetListRoles()+ if err != nil {+ return err+ }+ found := false+ for _, r := range roles {+ if r.ID == id {+ role = r+ found = true+ break+ }+ }+ if !found {+ return echo.NewHTTPError(http.StatusNotFound, a.i18n.Ts("globals.messages.notFound", "name", "{users.listRole}"))+ }+ isEditing = true+ }++ // All lists for the list-permission selector.+ lists, err := a.core.GetLists("", models.ListStatusActive, true, nil)+ if err != nil {+ return err+ }++ title := a.i18n.T("users.newListRole")+ if isEditing {+ title = role.Name.String+ }++ data := roleFormView{+ adminView: newAdminView(c, title, ""),+ IsEditing: isEditing,+ Role: role,+ AllLists: lists,+ }++ return c.Render(http.StatusOK, "admin-list-role", data)+}++// parsePermGroups parses the raw permissions.json config into permission groups.+func (a *App) parsePermGroups() ([]permGroup, error) {+ var groups []permGroup+ if err := json.Unmarshal(a.cfg.PermissionsRaw, &groups); err != nil {+ return nil, err+ }+ return groups, nil+}+// GetUserRoles retrieves roles.func (a *App) GetUserRoles(c echo.Context) error {// Get all roles.diff --git a/cmd/users.go b/cmd/users.goindex 4796d3e5..e0f98929 100644--- a/cmd/users.go+++ b/cmd/users.go@@ -18,6 +18,103 @@ var (reUsername = regexp.MustCompile(`^[a-zA-Z0-9_\-\.@]+$`))+// usersView is the admin page view for the users list page.+type usersView struct {+ adminView++ Users []auth.User+}++// userView is the admin page view for a single user's add/edit form.+type userView struct {+ adminView++ User auth.User+ IsEditing bool+ UserRoles []auth.Role+ ListRoles []auth.ListRole+}++// ViewUsers renders the HTML view listing all users.+func (a *App) ViewUsers(c echo.Context) error {+ if !can(auth.GetUser(c), auth.PermUsersGet) {+ return auth.ErrPermDenied+ }++ users, err := a.core.GetUsers()+ if err != nil {+ return err+ }++ // Blank out the password hashes.+ for n := range users {+ users[n].Password = null.String{}+ }++ data := usersView{+ adminView: newAdminView(c, a.i18n.T("globals.terms.users"), ""),+ Users: users,+ }++ return c.Render(http.StatusOK, "admin-users", data)+}++// ViewUser renders the HTML add/edit form for a user. It handles both the "new user"+// (no ID) and the "edit user" (ID in the URI) cases.+func (a *App) ViewUser(c echo.Context) error {+ if !can(auth.GetUser(c), auth.PermUsersGet) {+ return auth.ErrPermDenied+ }++ var (+ user auth.User+ isEditing bool+ )+ if c.Get("id") != nil {+ out, err := a.core.GetUser(getID(c), "", "")+ if err != nil {+ return err+ }+ out.Password = null.String{}+ user = out+ isEditing = true+ }++ // Roles for the role selectors.+ userRoles, listRoles, err := a.getRoles()+ if err != nil {+ return err+ }++ title := a.i18n.T("users.newUser")+ if isEditing {+ title = user.Name+ }++ data := userView{+ adminView: newAdminView(c, title, ""),+ User: user,+ IsEditing: isEditing,+ UserRoles: userRoles,+ ListRoles: listRoles,+ }++ return c.Render(http.StatusOK, "admin-user", data)+}++// getRoles fetches user and list roles for the user-form role selectors.+func (a *App) getRoles() ([]auth.Role, []auth.ListRole, error) {+ userRoles, err := a.core.GetRoles()+ if err != nil {+ return nil, nil, err+ }+ listRoles, err := a.core.GetListRoles()+ if err != nil {+ return nil, nil, err+ }+ return userRoles, listRoles, nil+}+// GetUser retrieves a single user by ID.func (a *App) GetUser(c echo.Context) error {// Get the user from the DB.diff --git a/frontend-vue/feathericons/icons.txt b/frontend-vue/feathericons/icons.txtindex e38200d1..8fe26ebb 100644--- a/frontend-vue/feathericons/icons.txt+++ b/frontend-vue/feathericons/icons.txt@@ -39,4 +39,6 @@ toolcoderefresh-cwmore-vertical-check-square\ No newline at end of file+check-square+star+alert-triangle\ No newline at end of filediff --git a/frontend-vue/src/router/index.js b/frontend-vue/src/router/index.jsindex 40b5d532..b0fbbc85 100644--- a/frontend-vue/src/router/index.js+++ b/frontend-vue/src/router/index.js@@ -65,24 +65,6 @@ const routes = [meta: { title: 'logs.title', group: 'settings' },component: () => import('../views/Logs.vue'),},- {- path: '/users',- name: 'users',- meta: { title: 'globals.terms.users', group: 'users' },- component: () => import('../views/Users.vue'),- },- {- path: '/users/roles/users',- name: 'userRoles',- meta: { title: 'users.userRoles', group: 'users' },- component: () => import('../views/Roles.vue'),- },- {- path: '/users/roles/lists',- name: 'listRoles',- meta: { title: 'users.listRoles', group: 'users' },- component: () => import('../views/Roles.vue'),- },{path: '/settings/maintenance',name: 'maintenance',diff --git a/frontend-vue/src/views/RoleForm.vue b/frontend-vue/src/views/RoleForm.vuedeleted file mode 100644index 5a897894..00000000--- a/frontend-vue/src/views/RoleForm.vue+++ /dev/null@@ -1,285 +0,0 @@-<template>- <form @submit.prevent="onSubmit">- <div class="dialog-card content" style="width: auto">- <header class="dialog-head">- <p v-if="isEditing" class="text-lighter text-7 ">- {{ $t('globals.fields.id') }}: <copy-text :text="`${data.id}`" />- </p>- <h4 v-if="isEditing">- {{ data.name }}- </h4>- <h4 v-else>- {{ type === 'user' ? $t('users.newUserRole') : $t('users.newListRole') }}- </h4>- </header>-- <section class="dialog-body">- <b-field :label="$t('globals.fields.name')">- <input aria-label="field" :disabled="disabled" :maxlength="200" v-model="form.name" name="name" ref="focus"- required>- </b-field>-- <div v-if="type === 'list'" class="card">- <h5>{{ $t('users.listPerms') }}</h5>- <div class="mb-5">- <div class="row">- <div class="col-9">- <select aria-label="field" :placeholder="$tc('globals.terms.list')" v-model="form.curList" name="list"- :disabled="disabled || filteredLists.length < 1" class="mb-3">- <template v-for="l in filteredLists">- <option :value="l.id" :key="l.id">- {{ l.name }}- </option>- </template>- </select>- </div>- <div class="col-12">- <button type="button" @click="onAddListPerm" :disabled="!form.curList" data-variant="primary">- {{ $t('globals.buttons.add') }}- </button>- </div>- </div>- <span- v-if="form.lists.length > 0 && (form.permissions['lists:get_all'] || form.permissions['lists:manage_all'])"- class="text-danger text-6">- <b-icon icon="warning-empty" />- {{ $t('users.listPermsWarning') }}- </span>- </div>-- <b-table :data="form.lists">- <b-table-column v-slot="props" field="name" :label="$tc('globals.terms.list')">- <a :href="`/admin/lists/${props.row.id}`" target="_blank" rel="noopener noreferrer">- {{ props.row.name }}- </a>- </b-table-column>-- <b-table-column v-slot="props" field="permissions" :label="$t('users.perms')" width="40%">- <b-checkbox v-model="props.row.permissions" native-value="list:get">- {{ $t('globals.buttons.view') }}- </b-checkbox>- <b-checkbox v-model="props.row.permissions" native-value="list:manage">- {{ $t('globals.buttons.manage') }}- </b-checkbox>- </b-table-column>-- <b-table-column v-slot="props" width="10%">- <a href="#" @click.prevent="onDeleteListPerm(props.row.id)" data-cy="btn-delete"- :aria-label="$t('globals.buttons.delete')">-- <b-icon icon="trash-can-outline" />-- </a>- </b-table-column>- </b-table>- </div>-- <template v-if="type === 'user'">- <div class="row">- <div class="col-7">- <h5 class="mb-0">- {{ $t('users.perms') }}- </h5>- </div>- <div class="col-12 align-right" v-if="!disabled">- <a href="#" @click.prevent="onToggleSelect">{{ $t('globals.buttons.toggleSelect') }}</a>- </div>- </div>-- <b-table :data="serverConfig.permissions">- <b-table-column v-slot="props" field="group" :label="$t('users.roleGroup')">- {{ $tc(`globals.terms.${props.row.group}`) }}- </b-table-column>-- <b-table-column v-slot="props" field="permissions" label="Permissions">- <div v-for="p in props.row.permissions" :key="p">- <b-checkbox v-model="form.permissions" :native-value="p" :disabled="disabled">- {{ p }}- <a v-if="p === 'subscribers:sql_query'"- href="https://listmonk.app/docs/roles-and-permissions/#subscriberssql_query" target="_blank"- rel="noopener noreferrer" aria-label="Warning: high risk permission">- <b-icon icon="warning-empty" data-variant="danger" />- </a>- </b-checkbox>- </div>- </b-table-column>- </b-table>- </template>- <a href="https://listmonk.app/docs/roles-and-permissions" target="_blank" rel="noopener noreferrer">- <b-icon icon="link-variant" /> {{ $t('globals.buttons.learnMore') }}- </a>- </section>-- <footer class="dialog-foot align-right">- <button type="button" class="outline" @click="$parent.close()">- {{ $t('globals.buttons.close') }}- </button>- <button v-if="!disabled" type="submit" data-variant="primary" :loading="loading.roles" data-cy="btn-save">- {{ $t('globals.buttons.save') }}- </button>- </footer>- </div>- </form>-</template>--<script>-import Vue from 'vue';-import { mapState } from 'vuex';-import CopyText from '../components/CopyText.vue';--export default Vue.extend({- name: 'RoleForm',-- components: {- CopyText,- },-- props: {- data: { type: Object, default: () => ({}) },- isEditing: { type: Boolean, default: false },- type: { type: String, default: 'user' },- },-- data() {- return {- // Binds form input values.- form: {- curList: null,- lists: [],- name: null,- permissions: {},- },- hasToggle: false,- disabled: false,- };- },-- methods: {- onAddListPerm() {- const list = this.lists.results.find((l) => l.id === this.form.curList);- this.form.lists.push({ id: list.id, name: list.name, permissions: ['list:get', 'list:manage'] });-- this.form.curList = (this.filteredLists.length > 0) ? this.filteredLists[0].id : null;- },-- onDeleteListPerm(id) {- this.form.lists = this.form.lists.filter((p) => p.id !== id);- this.form.curList = (this.filteredLists.length > 0) ? this.filteredLists[0].id : null;- },-- onSubmit() {- if (this.isEditing) {- this.updateRole();- return;- }-- this.createRole();- },-- onToggleSelect() {- if (this.hasToggle) {- this.form.permissions = [];- } else {- this.form.permissions = this.serverConfig.permissions.reduce((acc, item) => {- item.permissions.forEach((p) => {- acc.push(p);- });- return acc;- }, []);- }-- this.hasToggle = !this.hasToggle;- },-- createRole() {- let fn;- const form = { name: this.form.name };-- if (this.$props.type === 'user') {- fn = this.$api.createUserRole;- form.permissions = this.form.permissions;- } else {- fn = this.$api.createListRole;- form.lists = this.form.lists.reduce((acc, item) => {- acc.push({ id: item.id, permissions: item.permissions });- return acc;- }, []);- }-- fn(form).then((data) => {- this.$emit('finished');- this.$utils.toast(this.$t('globals.messages.created', { name: data.name }));- this.$parent.close();- });- },-- updateRole() {- let fn;- const form = { id: this.$props.data.id, name: this.form.name };-- if (this.$props.type === 'user') {- fn = this.$api.updateUserRole;- form.permissions = this.form.permissions;- } else {- fn = this.$api.updateListRole;- form.lists = this.form.lists.reduce((acc, item) => {- acc.push({ id: item.id, permissions: item.permissions });- return acc;- }, []);- }-- fn(form).then((data) => {- this.$emit('finished');- this.$utils.toast(this.$t('globals.messages.updated', { name: data.name }));- this.$parent.close();- });- },- },-- computed: {- ...mapState(['loading', 'serverConfig', 'lists']),-- // Return the list of unselected lists.- filteredLists() {- if (!this.lists.results || this.type !== 'list') {- return [];- }-- const subIDs = this.form.lists.reduce((obj, item) => ({ ...obj, [item.id]: true }), {});- return this.lists.results.filter((l) => (!(l.id in subIDs)));- },-- },-- mounted() {- if (this.isEditing) {- this.form = { ...this.form, ...this.$props.data };-- // It's the superadmin role. Disable the form.- if (this.$props.data.id === 1 || !this.$can('roles:manage')) {- this.disabled = true;- }- } else {- const skip = ['admin', 'users'];- this.form.permissions = this.serverConfig.permissions.reduce((acc, item) => {- if (skip.includes(item.group)) {- return acc;- }- item.permissions.forEach((p) => {- if (p !== 'subscribers:sql_query' && !p.startsWith('lists:') && !p.startsWith('settings:')) {- acc.push(p);- }- });- return acc;- }, []);- }-- this.$nextTick(() => {- if (this.filteredLists.length > 0) {- this.form.curList = this.filteredLists[0].id;- }- this.$refs.focus.focus();- });- },-});-</script>diff --git a/frontend-vue/src/views/Roles.vue b/frontend-vue/src/views/Roles.vuedeleted file mode 100644index a5b9dcf3..00000000--- a/frontend-vue/src/views/Roles.vue+++ /dev/null@@ -1,195 +0,0 @@-<template>- <section class="roles">- <header class="row page-header">- <div class="col-8">- <h1>- {{ $t(isUser ? 'users.userRoles' : 'users.listRoles') }}- <span v-if="!isNaN(roles.length)">({{ roles.length }})</span>- </h1>- </div>- <div class="col-4 col-end align-right">- <b-field v-if="$can('users:manage')">- <button type="button" data-variant="primary" class="btn-new" @click="showNewForm('user')" data-cy="btn-new">- <b-icon icon="plus" />- {{ $t('globals.buttons.new') }}- </button>- </b-field>- </div>- </header>- <div class="card page-content">- <b-table :data="roles" :loading="isLoading()">- <b-table-column v-slot="props" field="role" :label="$tc('users.role')" sortable>- <a href="#" @click.prevent="showEditForm(props.row, 'user')">- <b-tag v-if="props.row.id === 1" type="enabled">- {{ props.row.name }}- </b-tag>- <template v-else>{{ props.row.name }}</template>- </a>- </b-table-column>-- <b-table-column v-slot="props" field="created_at" :label="$t('globals.fields.createdAt')"- header-class="cy-created_at" sortable>- {{ $utils.niceDate(props.row.createdAt) }}- </b-table-column>-- <b-table-column v-slot="props" field="updated_at" :label="$t('globals.fields.updatedAt')"- header-class="cy-updated_at" sortable>- {{ $utils.niceDate(props.row.updatedAt) }}- </b-table-column>-- <b-table-column v-slot="props" cell-class="actions align-right">- <template v-if="$can('roles:manage')">- <a href="#" @click.prevent="$utils.prompt($t('globals.buttons.clone'),- {- placeholder: $t('globals.fields.name'),- value: $t('campaigns.copyOf', { name: props.row.name }),- },- (name) => onCloneRole(name, props.row))" data-cy="btn-clone" :aria-label="$t('globals.buttons.clone')">-- <b-icon icon="file-multiple-outline" />-- </a>-- <template v-if="props.row.id !== 1">- <a href="#" @click.prevent="showEditForm(props.row, 'user')" data-cy="btn-edit"- :aria-label="$t('globals.buttons.edit')">-- <b-icon icon="pencil-outline" />-- </a>-- <a href="#" @click.prevent="onDeleteRole(props.row)" data-cy="btn-delete"- :aria-label="$t('globals.buttons.delete')">-- <b-icon icon="trash-can-outline" />-- </a>- </template>- </template>- </b-table-column>-- <template #empty v-if="!isLoading()">- <empty-placeholder />- </template>- </b-table>-- <!-- Add / edit form modal -->- <b-modal :active.sync="isFormVisible" :width="700" @close="onFormClose">- <role-form :data="curItem" :type="curType" :is-editing="isEditing" @finished="formFinished" />- </b-modal>- </div>- </section>-</template>--<script>-import Vue from 'vue';-import { mapState } from 'vuex';-import EmptyPlaceholder from '../components/EmptyPlaceholder.vue';-import RoleForm from './RoleForm.vue';--export default Vue.extend({- components: {- EmptyPlaceholder,- RoleForm,- },-- data() {- return {- curItem: null,- curType: null,- isEditing: false,- isFormVisible: false,- };- },-- methods: {- isLoading() {- return this.curType === 'user' ? this.loading.userRoles : this.loading.listRoles;- },-- fetchRoles() {- if (this.isUser) {- this.$api.getUserRoles();- } else {- this.$api.getListRoles();- }- },-- // Show the edit form.- showEditForm(item) {- this.curItem = item;- this.curType = this.isUser ? 'user' : 'list';- this.isFormVisible = true;- this.isEditing = true;- },-- // Show the new form.- showNewForm() {- this.isEditing = false;- this.isFormVisible = true;- },-- formFinished() {- this.fetchRoles();- },-- onFormClose() {- if (this.$route.params.id) {- this.$router.push({ name: 'users' });- }- },-- onCloneRole(name, item) {- const form = { name };- let fn;- if (this.isUser) {- fn = this.$api.createUserRole;- form.permissions = item.permissions;- } else {- fn = this.$api.createListRole;- form.lists = item.lists;- }-- fn(form).then(() => {- this.fetchRoles();- this.$utils.toast(this.$t('globals.messages.created', { name }));- });- },-- onDeleteRole(item) {- this.$utils.confirm(- this.$t('globals.messages.confirm'),- () => {- this.$api.deleteRole(item.id).then(() => {- this.fetchRoles();-- this.$utils.toast(this.$t('globals.messages.deleted', { name: item.name }));- });- },- );- },-- },-- computed: {- ...mapState(['loading', 'userRoles', 'listRoles']),-- isUser() {- return this.curType === 'user';- },-- isList() {- return this.curType === 'list';- },-- roles() {- return this.isUser ? this.userRoles : this.listRoles;- },- },-- mounted() {- this.curType = this.$route.name === 'userRoles' ? 'user' : 'list';- this.fetchRoles();- },-});-</script>diff --git a/frontend-vue/src/views/UserForm.vue b/frontend-vue/src/views/UserForm.vuedeleted file mode 100644index 5502d416..00000000--- a/frontend-vue/src/views/UserForm.vue+++ /dev/null@@ -1,245 +0,0 @@-<template>- <form @submit.prevent="onSubmit">- <div class="dialog-card content" style="width: auto">- <header class="dialog-head">- <p v-if="isEditing" class="text-lighter text-7 ">- {{ $t('globals.fields.id') }}: <copy-text :text="`${data.id}`" />- </p>- <h4 v-if="isEditing">- {{ data.name }}- </h4>- <h4 v-else>- {{ $t('users.newUser') }}- </h4>- </header>- <section class="dialog-body">- <div class="row">- <div class="col-6">- <b-field class="mb-6">- <b-radio v-model="form.type" name="type" native-value="user" :disabled="isEditing">- <b-icon icon="account-outline" />- {{ $t('users.type.user') }}- </b-radio>- <b-radio v-model="form.type" name="type" native-value="api" :disabled="isEditing">- <b-icon icon="code" />- {{ $t('users.type.api') }}- </b-radio>- </b-field>- </div>- <div class="col-6">- <b-field :label="$t('globals.fields.status')">- <select aria-label="field" v-model="form.status" name="status" required>- <option value="enabled">- {{ $t('users.status.enabled') }}- </option>- <option value="disabled">- {{ $t('users.status.disabled') }}- </option>- </select>- </b-field>- </div>- </div>-- <b-field :label="$t('users.username')">- <input aria-label="field" :maxlength="200" v-model="form.username" name="username" ref="focus"- :placeholder="$t('users.username')" required :message="$t('users.usernameHelp')" autocomplete="off"- pattern="[a-zA-Z0-9_\-\.@]+$">- </b-field>-- <b-field :label="$t('globals.fields.name')">- <input aria-label="field" :maxlength="200" v-model="form.name" name="name"- :placeholder="$t('globals.fields.name')">- </b-field>-- <b-field v-if="form.type !== 'api'" :label="$t('subscribers.email')">- <input aria-label="field" :maxlength="200" v-model="form.email" name="email"- :placeholder="$t('subscribers.email')" required>- </b-field>-- <template v-if="form.type !== 'api'">- <div class="card">- <b-field>- <b-checkbox v-model="form.passwordLogin" :native-value="true" name="password_login">- {{ $t('users.passwordEnable') }}- </b-checkbox>- </b-field>-- <div class="row">- <div class="col-6">- <b-field :label="$t('users.password')">- <input aria-label="field" :disabled="!form.passwordLogin" minlength="8" :maxlength="200"- v-model="form.password" type="password" name="password" :placeholder="$t('users.password')"- :required="form.passwordLogin && !isEditing">- </b-field>- </div>- <div class="col-6">- <b-field :label="$t('users.passwordRepeat')">- <input aria-label="field" :disabled="!form.passwordLogin" minlength="8" :maxlength="200"- v-model="form.password2" type="password" name="password2"- :required="form.passwordLogin && !isEditing && form.password">- </b-field>- </div>- </div>- </div>- </template>-- <h5>{{ $tc('users.roles') }}</h5>- <div class="card">- <div class="row">- <div class="col-6">- <b-field :label="$tc('users.userRole')">- <select aria-label="field" v-model="form.userRoleId" name="user_role" required>- <option v-for="r in userRoles" :value="r.id" :key="r.id">- {{ r.name }}- </option>- </select>- </b-field>- </div>-- <div class="col-6">- <b-field :label="$tc('users.listRole', 0)">- <select aria-label="field" v-model="form.listRoleId" name="list_role">- <option value="">— {{ $t("globals.terms.none") }} —</option>- <option v-for="r in listRoles" :value="r.id" :key="r.id">- {{ r.name }}- </option>- </select>- </b-field>- </div>- </div>- </div>-- <div v-if="apiToken" class="user-api-token">- <p>{{ $t('users.apiOneTimeToken') }}</p>- <copy-text :text="apiToken" />- </div>- </section>- <footer class="dialog-foot align-right">- <button type="button" class="outline" @click="$parent.close()">- {{ $t('globals.buttons.close') }}- </button>- <button v-if="$can('users:manage') && !apiToken" type="submit" data-variant="primary" :loading="loading.lists"- data-cy="btn-save">- {{ $t('globals.buttons.save') }}- </button>- </footer>- </div>- </form>-</template>--<script>-import Vue from 'vue';-import { mapState } from 'vuex';-import CopyText from '../components/CopyText.vue';--export default Vue.extend({- name: 'UserForm',-- components: {- CopyText,- },-- props: {- data: { type: Object, default: () => ({}) },- isEditing: { type: Boolean, default: false },- },-- data() {- return {- // Binds form input values.- form: {- username: '',- email: '',- name: '',- password: '',- passwordLogin: false,- type: 'user',- status: 'enabled',- },- apiToken: null,- };- },-- methods: {- onSubmit() {- if (!this.form.passwordLogin) {- this.form.password = null;- this.form.password2 = null;- }-- if (this.isEditing) {- if (this.form.type !== 'api' && this.form.passwordLogin && this.form.password && this.form.password !== this.form.password2) {- this.$utils.toast(this.$t('users.passwordMismatch'), '');- return;- }-- this.updateUser();- return;- }-- if (this.form.type !== 'api' && this.form.passwordLogin && this.form.password !== this.form.password2) {- this.$utils.toast(this.$t('users.passwordMismatch'), '');- return;- }-- this.createUser();- },-- createUser() {- const form = {- ...this.form, password_login: this.form.passwordLogin, user_role_id: this.form.userRoleId, list_role_id: this.form.listRoleId || null,- };- this.$api.createUser(form).then((data) => {- this.$emit('finished');- this.$utils.toast(this.$t('globals.messages.created', { name: data.name }));-- // If the user is an API user, show the one-time token.- if (form.type === 'api') {- this.apiToken = data.password;- return;- }-- this.$emit('finished');- this.$parent.close();- });- },-- updateUser() {- const form = {- ...this.form, password_login: this.form.passwordLogin, user_role_id: this.form.userRoleId, list_role_id: this.form.listRoleId || null,- };- this.$api.updateUser({ id: this.data.id, ...form }).then((data) => {- this.$emit('finished');- this.$parent.close();- this.$utils.toast(this.$t('globals.messages.updated', { name: data.name }));- });- },-- hasType(t) {- // If the user being edited is API, then the only valid field is API.- // Otherwise, all fields are valid except API.- return !this.$props.isEditing || (this.form.type === 'api' ? t === 'api' : t !== 'api');- },- },-- computed: {- ...mapState(['loading', 'userRoles', 'listRoles']),- },-- mounted() {- this.form = { ...this.form, ...this.$props.data };- if (this.$props.data.userRole) {- this.form.userRoleId = this.$props.data.userRole.id;- }-- this.form.listRoleId = this.$props.data.listRole ? this.$props.data.listRole.id : '';-- this.$api.getUserRoles();- this.$api.getListRoles();-- this.$nextTick(() => {- this.$refs.focus.focus();- });- },-});-</script>diff --git a/frontend-vue/src/views/Users.vue b/frontend-vue/src/views/Users.vuedeleted file mode 100644index 646418db..00000000--- a/frontend-vue/src/views/Users.vue+++ /dev/null@@ -1,245 +0,0 @@-<template>- <section class="users">- <header class="row page-header">- <div class="col-8">- <h1>- {{ $t('globals.terms.users') }}- <span v-if="!isNaN(users.length)">({{ users.length }})</span>- </h1>- </div>- <div class="col-4 col-end align-right">- <b-field v-if="$can('users:manage')">- <button type="button" data-variant="primary" class="btn-new" @click="showNewForm" data-cy="btn-new">- <b-icon icon="plus" />- {{ $t('globals.buttons.new') }}- </button>- </b-field>- </div>- </header>-- <div class="card page-content">- <b-table :data="users" :loading="loading.users" checkable :checked-rows.sync="checked"- default-sort="createdAt" backend-sorting @sort="onSort" @check-all="onTableCheck" @check="onTableCheck">- <template #top-left>- <div class="row">- <div class="col-6">- <form @submit.prevent="getUsers">- <fieldset class="group">- <input aria-label="Search" v-model="queryParams.query" name="query" ref="query" data-cy="query"- placeholder="Search">- <button type="submit" data-variant="primary" data-cy="btn-query" aria-label="Search">- <b-icon icon="magnify" />- </button>- </fieldset>- </form>- </div>- </div>- </template>-- <b-table-column v-slot="props" field="username" :label="$t('users.username')" header-class="cy-username"- sortable :td-attrs="$utils.tdID">- <a :href="`/users/${props.row.id}`" @click.prevent="showEditForm(props.row)"- :class="{ 'text-light': props.row.status === 'disabled' }">- {{ props.row.username }}- </a>- <b-tag v-if="props.row.status === 'disabled'" type="disabled">- {{ $t(`users.status.${props.row.status}`) }}- </b-tag>- <b-tag v-if="props.row.type === 'api'" type="api">- <b-icon icon="code" />- {{ $t(`users.type.${props.row.type}`) }}- </b-tag>- <div class="text-light text-7 mt-2">- {{ props.row.name }}- </div>- </b-table-column>-- <b-table-column v-slot="props" field="status" :label="$tc('users.role')" header-class="cy-status" sortable- :td-attrs="$utils.tdID">- <router-link :to="{ name: 'userRoles' }">- <b-tag v-if="props.row.userRole" :type="props.row.userRole.id === 1 ? 'enabled' : 'primary'">- <b-icon icon="account-outline" />- {{ props.row.userRole.name }}- </b-tag>- </router-link>- <router-link :to="{ name: 'listRoles' }">- <span v-if="props.row.listRole" class="badge secondary">- <b-icon icon="newspaper-variant-outline" />- {{ props.row.listRole.name }}- </span>- </router-link>- </b-table-column>-- <b-table-column v-slot="props" field="name" :label="$t('subscribers.email')" header-class="cy-name" sortable- :td-attrs="$utils.tdID">- <div>- <a v-if="props.row.email" :href="`/users/${props.row.id}`" @click.prevent="showEditForm(props.row)"- :class="{ 'text-light': props.row.status === 'disabled' }">- {{ props.row.email }}- </a>- <template v-else>- —- </template>- </div>- </b-table-column>-- <b-table-column v-slot="props" field="created_at" :label="$t('globals.fields.createdAt')"- header-class="cy-created_at" sortable>- {{ $utils.niceDate(props.row.createdAt) }}- </b-table-column>-- <b-table-column v-slot="props" field="updated_at" :label="$t('globals.fields.updatedAt')"- header-class="cy-updated_at" sortable>- {{ $utils.niceDate(props.row.updatedAt) }}- </b-table-column>-- <b-table-column v-slot="props" field="last_login" :label="$t('users.lastLogin')" header-class="cy-updated_at"- sortable>- {{ props.row.loggedinAt ? $utils.niceDate(props.row.loggedinAt, true) : '—' }}- </b-table-column>-- <b-table-column v-slot="props" cell-class="actions" align="right">- <div>- <a v-if="$can('users:manage')" href="#" @click.prevent="showEditForm(props.row)" data-cy="btn-edit"- :aria-label="$t('globals.buttons.edit')">-- <b-icon icon="pencil-outline" />-- </a>-- <a v-if="$can('users:manage')" href="#" @click.prevent="deleteUser(props.row)" data-cy="btn-delete"- :aria-label="$t('globals.buttons.delete')">-- <b-icon icon="trash-can-outline" />-- </a>- </div>- </b-table-column>-- <template #empty v-if="!loading.users">- <empty-placeholder />- </template>- </b-table>-- <!-- Add / edit form modal -->- <b-modal :active.sync="isFormVisible" :width="600" @close="onFormClose">- <user-form :data="curItem" :is-editing="isEditing" @finished="formFinished" />- </b-modal>- </div>- </section>-</template>--<script>-import Vue from 'vue';-import { mapState } from 'vuex';-import EmptyPlaceholder from '../components/EmptyPlaceholder.vue';--import UserForm from './UserForm.vue';--export default Vue.extend({- components: {- EmptyPlaceholder,- UserForm,- },-- data() {- return {- curItem: null,- isEditing: false,- isFormVisible: false,- users: [],- checked: [],- queryParams: {- page: 1,- query: '',- orderBy: 'id',- order: 'asc',- },- };- },-- methods: {- onSort(field, direction) {- this.queryParams.orderBy = field;- this.queryParams.order = direction;- this.getUsers();- },-- onTableCheck() {- // Disable bulk.all selection if there are no rows checked in the table.- if (this.checked.length === 0) {- this.checked = [];- }- },-- // Show the edit form.- showEditForm(item) {- this.curItem = item;- this.isFormVisible = true;- this.isEditing = true;- },-- // Show the new form.- showNewForm() {- this.curItem = {};- this.isFormVisible = true;- this.isEditing = false;- },-- formFinished() {- this.getUsers();- },-- onFormClose() {- if (this.$route.params.id) {- this.$router.push({ name: 'users' });- }- },-- getUsers() {- this.$api.queryUsers({- query: this.queryParams.query.replace(/[^\p{L}\p{N}\s]/gu, ' '),- order_by: this.queryParams.orderBy,- order: this.queryParams.order,- }).then((resp) => {- this.users = resp;- });- },-- deleteUser(item) {- this.$utils.confirm(- this.$t('globals.messages.confirm'),- () => {- this.$api.deleteUser(item.id).then(() => {- this.getUsers();-- this.$utils.toast(this.$t('globals.messages.deleted', { name: item.name }));- });- },- );- },- },-- computed: {- ...mapState(['loading', 'settings']),- },-- created() {- this.$root.$on('page.refresh', this.getUsers);- },-- destroyed() {- this.$root.$off('page.refresh', this.getUsers);- },-- mounted() {- if (this.$route.params.id) {- this.$api.getUser(parseInt(this.$route.params.id, 10)).then((data) => {- this.showEditForm(data);- });- } else {- this.getUsers();- }- },-});-</script>diff --git a/static/admin/src/css/style.css b/static/admin/src/css/style.cssindex 9100ea15..759927bc 100644--- a/static/admin/src/css/style.css+++ b/static/admin/src/css/style.css@@ -78,6 +78,18 @@ table {border-bottom: 1px solid var(--border);}+ td {+ .tag {+ border-radius: var(--radius-small);+ color: var(--muted-foreground);+ padding: calc(var(--space-1) / 4) var(--space-2);++ &:hover {+ color: var(--foreground);+ }+ }+ }+.view {color: var(--faint-foreground);font-size: var(--text-8);@@ -620,20 +632,24 @@ ol.no {svg.icon {display: inline-block;- height: 1.5em;+ height: 1em;margin-inline-end: 0.2em;vertical-align: -0.125em;width: 1em;+ align-self: center;}.page-404 h1 {font-size: 6rem;}+.page-header .back {+ display: inline-flex;+ align-items: center;+}.page-header .back .icon {font-size: var(--text-1);margin: 0;- vertical-align: -0.225em;}.page-header h1,.page-header h4 {@@ -830,18 +846,6 @@ section.lists {text-align: center;}}- td {- .tag {- border-radius: var(--radius-small);- color: var(--muted-foreground);- padding: calc(var(--space-1) / 4) var(--space-2);-- &:hover {- color: var(--foreground);- }- }- }-.subscriber-stats {label {font-size: var(--text-8);diff --git a/static/admin/src/js/main.js b/static/admin/src/js/main.jsindex 735437a4..8e87f86a 100644--- a/static/admin/src/js/main.js+++ b/static/admin/src/js/main.js@@ -107,9 +107,8 @@ export async function api(name, uri, method, data) {return out.data;}- const message = out.message || resp.statusText;- u.toast(message, 'danger');- throw new Error(message);+ // Throw with the server message; the single .catch below shows the toast.+ throw new Error(out.message || resp.statusText);}).catch((err) => {getStore().loading[name] = false;u.toast(err.message, 'danger');diff --git a/static/admin/src/js/utils.js b/static/admin/src/js/utils.jsindex c6d727e3..c30e3f38 100644--- a/static/admin/src/js/utils.js+++ b/static/admin/src/js/utils.js@@ -175,6 +175,16 @@ export function reload(toast) {window.location.reload();}+// Navigate to a URL. If a toast object is given, it's put in+// sessionStorage and shown as a toast after the navigation.+export function redirect(url, toast) {+ if (toast) {+ sessionStorage.setItem('reload-toast', JSON.stringify(toast));+ }++ window.location.href = url;+}+export function copyToClipboard(text) {if (!navigator.clipboard) {diff --git a/static/admin/src/js/views/roles.js b/static/admin/src/js/views/roles.jsnew file mode 100644index 00000000..3b9124df--- /dev/null+++ b/static/admin/src/js/views/roles.js@@ -0,0 +1,164 @@+import {+ api,+ urls,+ i18n,+} from '../main.js';+import * as u from '../utils.js';++// rolesView is the list page component (user or list roles).+function rolesView({ type = 'user' } = {}) {+ const path = type === 'list' ? '/roles/lists' : '/roles/users';++ return {+ // Clone a role by fetching its full definition and creating a copy.+ async onCloneRole(id, name) {+ const newName = window.prompt(i18n.t('globals.fields.name'), i18n.ts('campaigns.copyOf', { name }));+ if (!newName) {+ return;+ }++ const roles = await api('roles', path);+ const r = (roles || []).find((x) => x.id === id);+ if (!r) {+ return;+ }++ const payload = { name: newName };+ if (type === 'list') {+ payload.lists = (r.lists || []).map((l) => ({ id: l.id, permissions: l.permissions }));+ } else {+ payload.permissions = r.permissions;+ }++ await api('roles', path, 'POST', payload);+ u.reload({ message: i18n.ts('globals.messages.created', { name: newName }) });+ },++ async onDeleteRole(id, name) {+ if (!(await u.confirm(i18n.t('globals.messages.confirm')))) {+ return;+ }+ await api('roles', `/roles/${id}`, 'DELETE');+ u.reload({ message: i18n.ts('globals.messages.deleted', { name }) });+ },+ };+}++// roleForm is the add/edit form page component (user or list roles).+function roleForm({ type = 'user', isEditing = false, canManage = false } = {}) {+ const role = window._role || {};+ const permGroups = window._permGroups || [];+ const allLists = window._lists || [];+ const path = type === 'list' ? '/roles/lists' : '/roles/users';++ const makeForm = () => ({+ id: null, name: '', permissions: [], lists: [], curList: null,+ });++ // The default set of permissions pre-selected for a new user role.+ const defaultUserPerms = () => permGroups.reduce((acc, g) => {+ if (g.group === 'admin' || g.group === 'users') {+ return acc;+ }+ g.permissions.forEach((p) => {+ if (p !== 'subscribers:sql_query' && !p.startsWith('lists:') && !p.startsWith('settings:')) {+ acc.push(p);+ }+ });+ return acc;+ }, []);++ const fromRole = () => {+ const f = { ...makeForm(), id: role.id, name: role.name || '' };+ if (type === 'list') {+ f.lists = (role.lists || []).map((l) => ({ id: l.id, name: l.name, permissions: [...(l.permissions || [])] }));+ } else {+ f.permissions = [...(role.permissions || [])];+ }+ return f;+ };++ return {+ // The primordial super admin role (id 1) or lacking manage permission disables the form.+ disabled: !canManage || (isEditing && role.id === 1),+ form: isEditing ? fromRole() : { ...makeForm(), permissions: type === 'user' ? defaultUserPerms() : [] },++ get isEditing() {+ return isEditing;+ },++ // Lists not yet added to the role.+ get filteredLists() {+ const chosen = new Set(this.form.lists.map((l) => l.id));+ return allLists.filter((l) => !chosen.has(l.id));+ },++ init() {+ if (type === 'list' && this.filteredLists.length > 0) {+ this.form.curList = this.filteredLists[0].id;+ }+ },++ onAddListPerm() {+ const l = allLists.find((x) => x.id === this.form.curList);+ if (!l) {+ return;+ }+ this.form.lists.push({ id: l.id, name: l.name, permissions: ['list:get', 'list:manage'] });+ this.form.curList = this.filteredLists.length > 0 ? this.filteredLists[0].id : null;+ },++ onDeleteListPerm(id) {+ this.form.lists = this.form.lists.filter((l) => l.id !== id);+ this.form.curList = this.filteredLists.length > 0 ? this.filteredLists[0].id : null;+ },++ onToggleSelect() {+ if (this.form.permissions.length > 0) {+ this.form.permissions = [];+ } else {+ this.form.permissions = permGroups.reduce((acc, g) => acc.concat(g.permissions), []);+ }+ },++ onSubmit() {+ if (this.disabled) {+ return;+ }+ if (this.isEditing) {+ this.updateRole();+ } else {+ this.createRole();+ }+ },++ _payload() {+ const payload = { name: this.form.name };+ if (type === 'list') {+ payload.lists = this.form.lists.map((l) => ({ id: l.id, permissions: l.permissions }));+ } else {+ payload.permissions = this.form.permissions;+ }+ return payload;+ },++ _listURL() {+ return type === 'list' ? `${urls.admin}/users/roles/lists` : `${urls.admin}/users/roles`;+ },++ async createRole() {+ const data = await api('roles.save', path, 'POST', this._payload());+ u.redirect(this._listURL(), { message: i18n.ts('globals.messages.created', { name: data.name }) });+ },++ async updateRole() {+ const data = await api('roles.save', `${path}/${this.form.id}`, 'PUT', this._payload());+ u.reload({ message: i18n.ts('globals.messages.updated', { name: data.name }) });+ },+ };+}++document.addEventListener('alpine:init', () => {+ window.Alpine.data('rolesView', rolesView);+ window.Alpine.data('roleForm', roleForm);+}, { once: true });diff --git a/static/admin/src/js/views/users.js b/static/admin/src/js/views/users.jsnew file mode 100644index 00000000..c261ac0c--- /dev/null+++ b/static/admin/src/js/views/users.js@@ -0,0 +1,148 @@+import {+ api,+ urls,+ i18n,+} from '../main.js';+import * as u from '../utils.js';++// usersView is the users list page component.+function usersView() {+ return {+ // ===============+ // Table actions.+ async onDeleteUser(id, name) {+ if (!(await u.confirm(i18n.t('globals.messages.confirm')))) {+ return;+ }++ await api('users', `/users/${id}`, 'DELETE');+ u.reload({ message: i18n.ts('globals.messages.deleted', { name }) });+ },++ async onDeleteSelected(count, params) {+ if (count === 0 || !(await u.confirm(i18n.ts('globals.messages.confirmDelete', {+ num: count,+ name: i18n.tc('globals.terms.user', count).toLowerCase(),+ })))) {+ return;+ }++ await api('users', `/users?${params}`, 'DELETE');+ u.reload({+ message: i18n.ts('globals.messages.deletedCount', {+ num: count,+ name: i18n.tc('globals.terms.user', count),+ }),+ });+ },+ };+}++// userForm is the add/edit form page component.+function userForm({ isEditing = false, canSave = false } = {}) {+ const user = window._user || {};+ const userRoles = window._userRoles || [];++ // Init a fresh form payload.+ const makeForm = () => ({+ id: null,+ username: '',+ name: '',+ email: '',+ password: '',+ password2: '',+ password_login: false,+ type: 'user',+ status: 'enabled',+ user_role_id: userRoles.length > 0 ? userRoles[0].id : null,+ list_role_id: '',+ });++ const fromUser = (us) => ({+ ...makeForm(),+ ...us,+ email: us.email || '',+ password: '',+ password2: '',+ user_role_id: us.user_role ? us.user_role.id : us.user_role_id,+ list_role_id: us.list_role ? us.list_role.id : '',+ });++ return {+ form: isEditing ? fromUser(user) : makeForm(),+ apiToken: null,+ createdName: '',++ get isEditing() {+ return isEditing;+ },++ onSubmit() {+ if (!canSave || !this._validate()) {+ return;+ }+ if (isEditing) {+ this.updateUser();+ } else {+ this.createUser();+ }+ },++ // Redirect to the users list once the one-time API token dialog is dismissed.+ onTokenDialogClose() {+ u.redirect(`${urls.admin}/users`, { message: i18n.ts('globals.messages.created', { name: this.createdName }) });+ },++ async createUser() {+ const data = await api('users.save', '/users', 'POST', this._payload());++ // For API users, show the one-time token in a dialog before redirecting.+ if (data.type === 'api') {+ this.apiToken = data.password;+ this.createdName = data.name;+ this.$refs.tokenDialog.showModal();+ return;+ }++ u.redirect(`${urls.admin}/users`, { message: i18n.ts('globals.messages.created', { name: data.name }) });+ },++ async updateUser() {+ const data = await api('users.save', `/users/${this.form.id}`, 'PUT', this._payload());+ u.reload({ message: i18n.ts('globals.messages.updated', { name: data.name }) });+ },++ // ===============+ // Private functions.+ _validate() {+ const f = this.form;+ const withPassword = f.type !== 'api' && f.password_login;+ if (withPassword && f.password && f.password !== f.password2) {+ u.toast(i18n.t('users.passwordMismatch'), 'danger');+ return false;+ }++ return true;+ },++ _payload() {+ const f = this.form;+ return {+ username: f.username,+ name: f.name,+ email: f.email,+ type: f.type,+ status: f.status,+ password_login: f.type !== 'api' ? f.password_login : false,+ password: (f.type !== 'api' && f.password_login && f.password) ? f.password : null,+ user_role_id: Number(f.user_role_id),+ list_role_id: f.list_role_id ? Number(f.list_role_id) : null,+ };+ },+ };+}++document.addEventListener('alpine:init', () => {+ window.Alpine.data('usersView', usersView);+ window.Alpine.data('userForm', userForm);+}, { once: true });diff --git a/static/admin/src/static/icons.svg b/static/admin/src/static/icons.svgindex 2fb96275..5acee9f9 100644--- a/static/admin/src/static/icons.svg+++ b/static/admin/src/static/icons.svg@@ -1,8 +1,4 @@<svg xmlns="http://www.w3.org/2000/svg" style="display:none">- <symbol id="icon-menu" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">- <line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="18" x2="21" y2="18" />- </symbol>-<symbol id="icon-grid" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7" /><rect x="14" y="3" width="7" height="7" /><rect x="14" y="14" width="7" height="7" /><rect x="3" y="14" width="7" height="7" /></symbol>@@ -166,4 +162,16 @@<symbol id="icon-more-vertical" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1" /><circle cx="12" cy="5" r="1" /><circle cx="12" cy="19" r="1" /></symbol>++ <symbol id="icon-check-square" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <polyline points="9 11 12 14 22 4" /><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />+ </symbol>++ <symbol id="icon-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />+ </symbol>++ <symbol id="icon-alert-triangle" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />+ </symbol></svg>diff --git a/static/admin/views/list-role.html b/static/admin/views/list-role.htmlnew file mode 100644index 00000000..7ab6b95f--- /dev/null+++ b/static/admin/views/list-role.html@@ -0,0 +1,100 @@+{{ define "admin-list-role" -}}+{{ template "admin-header" . }}+{{- $d := .Data -}}+{{- $canManage := $d.Can "roles:manage" -}}+{{- $base := URI "/admin/users/roles/lists" -}}++<script>+ window._role = {{ ToJSON $d.Role }};+ window._lists = {{ ToJSON $d.AllLists }};+</script>+<section class="roles" x-data="roleForm({ type: 'list', isEditing: {{ $d.IsEditing }}, canManage: {{ $canManage }} })">+ <header class="row page-header">+ <div class="col-6">+ <div class="hstack gap-1">+ <a href="{{ $base }}" class="back" aria-label="{{ .L.T "globals.buttons.back" }}">{{ Icon "chevron-left" }}</a>+ <h1 class="page-title">+ {{- if $d.IsEditing }}{{ $d.Role.Name.String }}{{ else }}{{ .L.T "users.newListRole" }}{{ end -}}+ </h1>+ </div>+ </div>+ {{- if $d.IsEditing }}+ <div class="col-6 align-right">+ <button class="small" data-variant="secondary" title="{{ .L.T "globals.messages.clickToCopy" }}" aria-label="{{ .L.T "globals.fields.id" }}" @click="copyToClipboard(form.id)">+ <strong>{{ .L.T "globals.fields.id" }}</strong> <span x-text="form.id"></span>+ </button>+ </div>+ {{- end }}+ </header>++ <form method="post" @submit.prevent="onSubmit">+ <div class="card page-content content">+ <section class="dialog-body">+ <label data-field>+ {{ .L.T "globals.fields.name" }}+ <input name="name" maxlength="200" autofocus required :disabled="disabled" x-model="form.name" />+ </label>++ <div data-field>+ <label>{{ .L.T "globals.terms.list" }}</label>+ <fieldset class="group">+ <select aria-label="{{ .L.Tc "globals.terms.list" 1 }}" x-model.number="form.curList" :disabled="disabled || filteredLists.length < 1">+ <template x-for="l in filteredLists" :key="l.id">+ <option :value="l.id" x-text="l.name"></option>+ </template>+ </select>+ <button type="button" data-variant="primary" @click="onAddListPerm" :disabled="disabled || !form.curList">{{ .L.T "globals.buttons.add" }}</button>+ </fieldset>+ </div>++ <table>+ <thead>+ <tr>+ <th width="50%">{{ .L.Tc "globals.terms.list" 1 }}</th>+ <th width="20%">{{ .L.T "users.perms" }}</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ <template x-for="l in form.lists" :key="l.id">+ <tr>+ <td><a :href="`{{ URI "/admin/lists" }}/${l.id}`" x-text="l.name"></a></td>+ <td>+ <div class="hstack gap-3">+ <label><input type="checkbox" value="list:get" x-model="l.permissions" :disabled="disabled" /> {{ .L.T "globals.buttons.view" }}</label>+ <label><input type="checkbox" value="list:manage" x-model="l.permissions" :disabled="disabled" /> {{ .L.T "globals.buttons.manage" }}</label>+ </div>+ </td>+ <td class="align-right">+ <button type="button" class="ghost icon" data-variant="danger" :disabled="disabled" @click="onDeleteListPerm(l.id)" :aria-label="`{{ .L.T "globals.buttons.delete" }} ${l.name}`">{{ Icon "trash-2" }}</button>+ </td>+ </tr>+ </template>+ <template x-if="form.lists.length === 0">+ <tr><td colspan="3" class="align-center text-light">{{ .L.T "globals.messages.emptyState" }}</td></tr>+ </template>+ </tbody>+ </table>+ </section>++ <footer class="dialog-foot">+ <div class="row mt-6">+ <div class="col-6">+ <a href="https://listmonk.app/docs/roles-and-permissions" target="_blank" rel="noopener noreferrer" class="text-light text-8">+ {{ Icon "link-2" }} {{ .L.T "globals.buttons.learnMore" }}+ </a>+ </div>+ <div class="col-6 hstack justify-end">+ <a href="{{ $base }}" class="button outline">{{ .L.T "globals.buttons.back" }}</a>+ <button type="submit" data-variant="primary" data-cy="btn-save" x-show="!disabled" :disabled="isLoading('roles.save')" :aria-busy="isLoading('roles.save')">{{ .L.T "globals.buttons.save" }}</button>+ </div>+ </div>+ </footer>+ </div>+ </form>+</section>++<script type="module" src="{{ URI "/admin/static/js/views/roles.js" }}?v={{ .AssetVersion }}" defer></script>++{{ template "admin-footer" . -}}+{{ end }}diff --git a/static/admin/views/roles.html b/static/admin/views/roles.htmlnew file mode 100644index 00000000..35a82215--- /dev/null+++ b/static/admin/views/roles.html@@ -0,0 +1,76 @@+{{ define "admin-roles" -}}+{{ template "admin-header" . }}+{{- $d := .Data -}}+{{- $base := URI "/admin/users/roles" -}}+{{- if eq $d.Type "list" }}{{ $base = URI "/admin/users/roles/lists" }}{{ end -}}++<section class="roles" x-data="rolesView({ type: {{ ToJSON $d.Type }} })">+ <header class="row page-header">+ <div class="col-6">+ <div class="hstack">+ <h1 class="page-title">+ {{ if eq $d.Type "list" }}{{ .L.T "users.listRoles" }}{{ else }}{{ .L.T "users.userRoles" }}{{ end }}+ <span>({{ len $d.Roles }})</span>+ </h1>+ </div>+ </div>+ <div class="col-6 col-end align-right hstack justify-end">+ {{- if $d.Can "roles:manage" }}+ <a href="{{ $base }}/new" class="button" data-variant="primary" data-cy="btn-new">+ {{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}+ </a>+ {{- end }}+ </div>+ </header>++ <div class="card page-content has-table">+ <div class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th class="cy-name">{{ .L.Tc "users.role" 1 }}</th>+ <th class="cy-created_at">{{ .L.T "globals.fields.createdAt" }}</th>+ <th class="cy-updated_at">{{ .L.T "globals.fields.updatedAt" }}</th>+ <th class="actions align-right"></th>+ </tr>+ </thead>+ <tbody>+ {{- range $d.Roles }}+ <tr data-id="{{ .ID }}">+ <td>+ <a href="{{ $base }}/{{ .ID }}">+ {{- if eq .ID 1 }}<span class="badge enum super">{{ Icon "star" }}{{ .Name }}</span>{{ else }}{{ .Name }}{{ end -}}+ </a>+ </td>+ <td class="date-stack">{{ NiceDate .CreatedAt }}</td>+ <td class="date-stack">{{ NiceDate .UpdatedAt }}</td>+ <td class="actions align-right">+ {{- if $d.Can "roles:manage" }}+ <ot-dropdown>+ <button popovertarget="role-actions-{{ .ID }}" type="button" class="ghost small icon" aria-label="{{ $.L.T "globals.buttons.more" }}">+ {{ Icon "more-vertical" }}+ </button>+ <menu popover id="role-actions-{{ .ID }}">+ <a href="{{ $base }}/{{ .ID }}" role="menuitem" class="button ghost" data-cy="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>+ <button type="button" role="menuitem" class="ghost" data-cy="btn-clone" :disabled="isLoading('roles')" @click.prevent="onCloneRole({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "copy" }} {{ $.L.T "globals.buttons.clone" }}</button>+ {{- if ne .ID 1 }}+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" :disabled="isLoading('roles')" @click.prevent="onDeleteRole({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>+ {{- end }}+ </menu>+ </ot-dropdown>+ {{- end }}+ </td>+ </tr>+ {{- else }}+ <tr><td colspan="4" class="align-center text-light">{{ .L.T "globals.messages.emptyState" }}</td></tr>+ {{- end }}+ </tbody>+ </table>+ </div>+ </div>+</section>++<script type="module" src="{{ URI "/admin/static/js/views/roles.js" }}?v={{ .AssetVersion }}" defer></script>++{{ template "admin-footer" . -}}+{{ end }}diff --git a/static/admin/views/user-role.html b/static/admin/views/user-role.htmlnew file mode 100644index 00000000..df817656--- /dev/null+++ b/static/admin/views/user-role.html@@ -0,0 +1,104 @@+{{ define "admin-user-role" -}}+{{ template "admin-header" . }}+{{- $d := .Data -}}+{{- $canManage := $d.Can "roles:manage" -}}+{{- $base := URI "/admin/users/roles" -}}++<script>+ window._role = {{ ToJSON $d.Role }};+ window._permGroups = {{ ToJSON $d.PermGroups }};+</script>+<section class="roles" x-data="roleForm({ type: 'user', isEditing: {{ $d.IsEditing }}, canManage: {{ $canManage }} })">+ <header class="row page-header">+ <div class="col-6">+ <div class="hstack gap-1">+ <a href="{{ $base }}" class="back" aria-label="{{ .L.T "globals.buttons.back" }}">{{ Icon "chevron-left" }}</a>+ <h1 class="page-title">+ {{- if $d.IsEditing }}{{ $d.Role.Name.String }}{{ else }}{{ .L.T "users.newUserRole" }}{{ end -}}+ </h1>+ </div>+ </div>+ {{- if $d.IsEditing }}+ <div class="col-6 align-right">+ <button class="small" data-variant="secondary" title="{{ .L.T "globals.messages.clickToCopy" }}" aria-label="{{ .L.T "globals.fields.id" }}" @click="copyToClipboard(form.id)">+ <strong>{{ .L.T "globals.fields.id" }}</strong> <span x-text="form.id"></span>+ </button>+ </div>+ {{- end }}+ </header>++ <form method="post" @submit.prevent="onSubmit">+ <div class="card page-content content">+ <section class="dialog-body">+ <label data-field>+ {{ .L.T "globals.fields.name" }}+ <input name="name" maxlength="200" autofocus required :disabled="disabled" x-model="form.name" />+ </label>++ <div class="row">+ <div class="col-9"><label>{{ .L.T "users.perms" }}</label></div>+ <div class="col-3 align-right">+ <button type="button" class="small outline" :disabled="disabled" @click.prevent="onToggleSelect">{{ .L.T "globals.buttons.toggleSelect" }}</button>+ </div>+ </div>++ <table>+ <thead>+ <tr>+ <th>{{ .L.T "users.roleGroup" }}</th>+ <th>{{ .L.T "users.perms" }}</th>+ </tr>+ </thead>+ <tbody>+ {{- range $d.PermGroups }}+ <tr>+ <td>{{ $.L.T (printf "globals.terms.%s" .Group) }}</td>+ <td>+ <div class="vstack gap-1">+ {{- range .Permissions }}+ <label>+ <input type="checkbox" value="{{ . }}" x-model="form.permissions" :disabled="disabled" />+ {{- if eq . "subscribers:sql_query" }}+ <span class="text-danger">{{ . }}</span>+ <a href="https://listmonk.app/docs/roles-and-permissions/#subscriberssql_query" target="_blank" rel="noopener noreferrer" class="text-danger" aria-label="Warning: high risk permission">+ {{ Icon "alert-triangle" }}+ </a>+ {{- else if eq . "users:manage" }}+ <span class="text-danger">{{ . }}</span>+ <a href="https://listmonk.app/docs/roles-and-permissions/#:~:text=users:manage" target="_blank" rel="noopener noreferrer" class="text-danger" aria-label="Warning: high risk permission">+ {{ Icon "alert-triangle" }}+ </a>+ {{ else }}+ {{ . }}+ {{- end }}+ </label>+ {{- end }}+ </div>+ </td>+ </tr>+ {{- end }}+ </tbody>+ </table>+ </section>++ <footer class="dialog-foot">+ <div class="row mt-6">+ <div class="col-6">+ <a href="https://listmonk.app/docs/roles-and-permissions" target="_blank" rel="noopener noreferrer" class="text-light text-8">+ {{ Icon "link-2" }} {{ .L.T "globals.buttons.learnMore" }}+ </a>+ </div>+ <div class="col-6 hstack justify-end">+ <a href="{{ $base }}" class="button outline">{{ .L.T "globals.buttons.back" }}</a>+ <button type="submit" data-variant="primary" data-cy="btn-save" x-show="!disabled" :disabled="isLoading('roles.save')" :aria-busy="isLoading('roles.save')">{{ .L.T "globals.buttons.save" }}</button>+ </div>+ </div>+ </footer>+ </div>+ </form>+</section>++<script type="module" src="{{ URI "/admin/static/js/views/roles.js" }}?v={{ .AssetVersion }}" defer></script>++{{ template "admin-footer" . -}}+{{ end }}diff --git a/static/admin/views/user.html b/static/admin/views/user.htmlnew file mode 100644index 00000000..b82296a3--- /dev/null+++ b/static/admin/views/user.html@@ -0,0 +1,138 @@+{{ define "admin-user" -}}+{{ template "admin-header" . }}+{{- $d := .Data -}}+{{- $base := URI "/admin/users" -}}+{{- $canSave := $d.Can "users:manage" -}}++<script>+ window._user = {{ ToJSON $d.User }};+ window._userRoles = {{ ToJSON $d.UserRoles }};+</script>+<section class="users" x-data="userForm({ isEditing: {{ $d.IsEditing }}, canSave: {{ $canSave }} })">+ <header class="row page-header">+ <div class="col-6">+ <div class="hstack gap-1">+ <a href="{{ $base }}" class="back" aria-label="{{ .L.T "globals.buttons.back" }}">{{ Icon "chevron-left" }}</a>+ <h1 class="page-title">+ {{- if $d.IsEditing }}{{ $d.User.Name }}{{ else }}{{ .L.T "users.newUser" }}{{ end -}}+ </h1>+ {{- if and $d.IsEditing (eq $d.User.Status "disabled") }}<span class="badge enum" data-variant="danger">{{ $.L.T "users.status.disabled" }}</span>{{ end }}+ </div>+ </div>+ {{- if $d.IsEditing }}+ <div class="col-6 align-right">+ <button class="small" data-variant="secondary" title="{{ .L.T "globals.messages.clickToCopy" }}" aria-label="{{ .L.T "globals.fields.id" }}" @click="copyToClipboard(form.id)">+ <strong>{{ .L.T "globals.fields.id" }}</strong> <span x-text="form.id"></span>+ </button>+ </div>+ {{- end }}+ </header>++ <form method="post" @submit.prevent="onSubmit">+ <div class="card page-content content">+ <section class="dialog-body">+ <div data-field>+ <label for="user-type">{{ .L.T "users.type" }}</label>+ <select name="type" id="user-type" autofocus x-model="form.type" :disabled="isEditing">+ <option value="user">{{ .L.T "users.type.user" }}</option>+ <option value="api">{{ .L.T "users.type.api" }}</option>+ </select>+ </div>++ <fieldset>+ <legend>{{ .L.T "users.profile" }}</legend>+ <label data-field>+ {{ .L.T "users.username" }}+ <input name="username" maxlength="200" required autocomplete="off" pattern="[a-zA-Z0-9_\-\.@]+$" autofocus x-model="form.username" />+ <small data-hint>{{ .L.T "users.usernameHelp" }}</small>+ </label>++ <label data-field>+ {{ .L.T "globals.fields.name" }}+ <input name="name" maxlength="200" x-model="form.name" />+ </label>++ <label data-field :aria-disabled="form.type === 'api'">+ {{ .L.T "subscribers.email" }}+ <input name="email" type="email" maxlength="200" :required="form.type !== 'api'" x-model="form.email" :disabled="form.type === 'api'" />+ </label>++ <div data-field>+ <label for="user-status">{{ .L.T "globals.fields.status" }}</label>+ <select name="status" id="user-status" required x-model="form.status">+ <option value="enabled">{{ .L.T "users.status.enabled" }}</option>+ <option value="disabled">{{ .L.T "users.status.disabled" }}</option>+ </select>+ </div>+ </fieldset>++ <fieldset :disabled="form.type === 'api'">+ <legend>{{ .L.T "users.password" }}</legend>+ <label data-field>+ <input type="checkbox" x-model="form.password_login" /> {{ .L.T "users.passwordEnable" }}+ </label>+ <label data-field>+ {{ .L.T "users.password" }}+ <input type="password" name="password" minlength="8" maxlength="200" autocomplete="new-password" :disabled="!form.password_login" :required="form.password_login && !isEditing" x-model="form.password" />+ </label>+ <label data-field>+ {{ .L.T "users.passwordRepeat" }}+ <input type="password" name="password2" minlength="8" maxlength="200" autocomplete="new-password" :disabled="!form.password_login" :required="form.password_login && !isEditing && form.password" x-model="form.password2" />+ </label>+ </fieldset>++ <fieldset>+ <legend>{{ .L.Tc "users.roles" 2 }}</legend>+ <div data-field>+ <label for="user-role">{{ .L.Tc "users.userRole" 1 }}</label>+ <select name="user_role" id="user-role" required x-model.number="form.user_role_id">+ {{- range $d.UserRoles }}+ <option value="{{ .ID }}">{{ .Name.String }}</option>+ {{- end }}+ </select>+ </div>+ <div data-field>+ <label for="list-role">{{ .L.Tc "users.listRole" 2 }}</label>+ <select name="list_role" id="list-role" x-model="form.list_role_id">+ <option value="">— {{ .L.T "globals.terms.none" }} —</option>+ {{- range $d.ListRoles }}+ <option value="{{ .ID }}">{{ .Name.String }}</option>+ {{- end }}+ </select>+ </div>+ </fieldset>+ </section>++ <footer class="dialog-foot hstack gap-3 justify-end">+ <a href="{{ $base }}" class="button outline">{{ .L.T "globals.buttons.back" }}</a>+ {{- if $canSave }}+ <button type="submit" data-variant="primary" data-cy="btn-save" :disabled="isLoading('users.save')" :aria-busy="isLoading('users.save')">{{ .L.T "globals.buttons.save" }}</button>+ {{- end }}+ </footer>+ </div>+ </form>++ {{- if $canSave }}+ <dialog class="b-modal" x-ref="tokenDialog" @close="onTokenDialogClose">+ <div class="dialog-card content">+ <header class="dialog-head">+ <h3 class="dialog-title">{{ .L.T "users.type.api" }}</h3>+ </header>+ <section class="dialog-body">+ <p class="text-light">{{ .L.T "users.apiOneTimeToken" }}</p>+ <button type="button" class="w-100" data-variant="secondary" title="{{ .L.T "globals.messages.clickToCopy" }}" @click="copyToClipboard(apiToken)">+ <span x-text="apiToken"></span> {{ Icon "copy" }}+ </button>+ </section>+ <footer class="dialog-foot align-right">+ <button type="button" data-variant="primary" @click="$refs.tokenDialog.close()">{{ .L.T "globals.buttons.close" }}</button>+ </footer>+ </div>+ </dialog>+ {{- end }}+</section>++<script type="module" src="{{ URI "/admin/static/js/views/users.js" }}?v={{ .AssetVersion }}" defer></script>++{{ template "admin-footer" . -}}+{{ end }}diff --git a/static/admin/views/users.html b/static/admin/views/users.htmlnew file mode 100644index 00000000..cf0e634b--- /dev/null+++ b/static/admin/views/users.html@@ -0,0 +1,113 @@+{{ define "admin-users" -}}+{{ template "admin-header" . }}+{{- $d := .Data -}}++<section class="users" x-data="usersView()">+ <header class="row page-header">+ <div class="col-6">+ <div class="hstack">+ <h1 class="page-title">+ {{ .L.T "globals.terms.users" }}+ <span>({{ len $d.Users }})</span>+ </h1>+ </div>+ </div>+ <div class="col-6 col-end align-right hstack justify-end">+ {{- if $d.Can "users:manage" }}+ <a href="{{ URI "/admin/users" }}/new" class="button" data-variant="primary" data-cy="btn-new">+ {{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}+ </a>+ {{- end }}+ </div>+ </header>++ <div class="card page-content has-table">+ <div class="table-wrapper" x-data="table({ total: {{ len $d.Users }} })" @change="onChange($event)">+ {{- if $d.Can "users:manage" }}+ <template x-if="numSelected > 0">+ <ot-dropdown class="bulk-actions">+ <button popovertarget="bulk-actions" type="button" class="small" data-cy="btn-bulk-actions">+ <span x-text="numSelectedLabel"></span> {{ Icon "more-vertical" }}+ </button>+ <menu popover id="bulk-actions">+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete-users" :disabled="isLoading('users')" @click.prevent="onDeleteSelected(numSelected, selectedQueryParams().toString())">+ {{ Icon "trash-2" }} {{ .L.T "globals.buttons.delete" }} <span x-text="numSelected"></span>+ </button>+ </menu>+ </ot-dropdown>+ </template>+ {{- end }}++ <table>+ <thead>+ <tr>+ {{- if $d.Can "users:manage" }}+ <th width="5%"><input type="checkbox" aria-label="{{ .L.T "globals.buttons.toggleSelect" }}"></th>+ {{- end }}+ <th class="cy-username">{{ .L.T "users.username" }}</th>+ <th class="cy-role">{{ .L.Tc "users.role" 1 }}</th>+ <th class="cy-name">{{ .L.T "subscribers.email" }}</th>+ <th class="cy-created_at">{{ .L.T "globals.fields.createdAt" }}</th>+ <th>{{ .L.T "users.lastLogin" }}</th>+ <th class="actions align-right"></th>+ </tr>+ </thead>+ <tbody>+ {{- range $d.Users }}+ <tr data-id="{{ .ID }}">+ {{- if $d.Can "users:manage" }}+ <td><input name="id" type="checkbox" value="{{ .ID }}"></td>+ {{- end }}+ <td>+ {{- if $d.Can "users:manage" }}+ <a href="{{ URI "/admin/users" }}/{{ .ID }}" class="{{ if eq .Status "disabled" }}text-light{{ end }}">{{ .Username }}</a>+ {{- else }}+ <span class="{{ if eq .Status "disabled" }}text-danger{{ end }}">{{ .Username }}</span>+ {{- end }}+ {{- if eq .Type "api" }}<span class="badge outline tag">{{ Icon "code" }} {{ $.L.T "users.type.api" }}</span>{{ end }}+ {{- if eq .Status "disabled" }}<span class="badge enum" data-variant="danger">{{ $.L.T "users.status.disabled" }}</span>{{ end }}+ {{- if .Name }}<div class="text-light text-8">{{ .Name }}</div>{{ end }}+ </td>+ <td>+ <div class="hstack gap-1">+ {{- if eq .UserRole.ID 1 }}+ <a href="{{ URI "/admin/users/roles" }}/{{ .UserRole.ID }}" class="badge">{{ Icon "star" }} {{ .UserRole.Name }}</a>+ {{- else }}+ <a href="{{ URI "/admin/users/roles" }}/{{ .UserRole.ID }}" class="badge" data-variant="secondary">{{ Icon "user" }} {{ .UserRole.Name }}</a>+ {{- end }}+ {{- with .ListRole }}+ <a href="{{ URI "/admin/users/roles/lists" }}/{{ .ID }}" class="badge outline">{{ Icon "list" }} {{ .Name }}</a>+ {{- end }}+ </div>+ </td>+ <td>{{ if .Email.Valid }}{{ .Email.String }}{{ else }}<span class="text-light">—</span>{{ end }}</td>+ <td class="date-stack">{{ NiceDate .CreatedAt }}</td>+ <td class="date-stack">{{ if .LoggedInAt.Valid }}{{ NiceDate .LoggedInAt }}{{ else }}<span class="text-light">—</span>{{ end }}</td>+ <td class="actions align-right">+ {{- if $d.Can "users:manage" }}+ <ot-dropdown>+ <button popovertarget="user-actions-{{ .ID }}" type="button" class="ghost small icon" aria-label="{{ $.L.T "globals.buttons.more" }}">+ {{ Icon "more-vertical" }}+ </button>+ <menu popover id="user-actions-{{ .ID }}">+ <a href="{{ URI "/admin/users" }}/{{ .ID }}" role="menuitem" class="button ghost" data-cy="btn-edit">{{ Icon "edit-2" }} {{ $.L.T "globals.buttons.edit" }}</a>+ <button type="button" role="menuitem" class="ghost" data-variant="danger" data-cy="btn-delete" :disabled="isLoading('users')" @click.prevent="onDeleteUser({{ .ID }}, {{ ToJSON .Name }})">{{ Icon "trash-2" }} {{ $.L.T "globals.buttons.delete" }}</button>+ </menu>+ </ot-dropdown>+ {{- end }}+ </td>+ </tr>+ {{- else }}+ <tr><td colspan="8" class="align-center text-light">{{ .L.T "globals.messages.emptyState" }}</td></tr>+ {{- end }}+ </tbody>+ </table>+ </div>+ </div>++</section>++<script type="module" src="{{ URI "/admin/static/js/views/users.js" }}?v={{ .AssetVersion }}" defer></script>++{{ template "admin-footer" . -}}+{{ end }}