Merge branch 'feat/roles' into 'main'

Implemented roles management

See merge request stackspin/dashboard!29
This commit is contained in:
Maarten de Waard 2022-05-26 09:49:14 +00:00
commit 87007c95c5
20 changed files with 480 additions and 285 deletions

View file

@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { Helmet } from 'react-helmet'; import { Helmet } from 'react-helmet';
import { Routes, Route, Navigate } from 'react-router-dom'; import { Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { Toaster } from 'react-hot-toast'; import { Toaster } from 'react-hot-toast';
import { useAuth } from 'src/services/auth'; import { useAuth } from 'src/services/auth';
@ -10,7 +10,13 @@ import { LoginCallback } from './modules/login/LoginCallback';
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
function App() { function App() {
const { authToken } = useAuth(); const { authToken, currentUser, isAdmin } = useAuth();
const redirectToLogin = !authToken || !currentUser?.app_roles;
const ProtectedRoute = () => {
return isAdmin ? <Outlet /> : <Navigate to="/dashboard" />;
};
return ( return (
<> <>
@ -26,7 +32,7 @@ function App() {
</Helmet> </Helmet>
<div className="app bg-gray-50 min-h-screen flex flex-col"> <div className="app bg-gray-50 min-h-screen flex flex-col">
{!authToken ? ( {redirectToLogin ? (
<Routes> <Routes>
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
<Route path="/login-callback" element={<LoginCallback />} /> <Route path="/login-callback" element={<LoginCallback />} />
@ -36,7 +42,9 @@ function App() {
<Layout> <Layout>
<Routes> <Routes>
<Route path="/dashboard" element={<Dashboard />} /> <Route path="/dashboard" element={<Dashboard />} />
<Route path="/users" element={<Users />} /> <Route path="/users" element={<ProtectedRoute />}>
<Route path="/users" element={<Users />} />
</Route>
<Route path="*" element={<Navigate to="/dashboard" />} /> <Route path="*" element={<Navigate to="/dashboard" />} />
</Routes> </Routes>
</Layout> </Layout>

View file

@ -8,20 +8,28 @@ import clsx from 'clsx';
import { CurrentUserModal } from './components/CurrentUserModal'; import { CurrentUserModal } from './components/CurrentUserModal';
const navigation = [ const navigation = [
{ name: 'Dashboard', to: '/dashboard' }, { name: 'Dashboard', to: '/dashboard', requiresAdmin: false },
{ name: 'Users', to: '/users' }, { name: 'Users', to: '/users', requiresAdmin: true },
]; ];
function classNames(...classes: any[]) { function classNames(...classes: any[]) {
return classes.filter(Boolean).join(' '); return classes.filter(Boolean).join(' ');
} }
function filterNavigationByDashboardRole(isAdmin: boolean) {
if (isAdmin) {
return navigation;
}
return navigation.filter((item) => !item.requiresAdmin);
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface // eslint-disable-next-line @typescript-eslint/no-empty-interface
interface HeaderProps {} interface HeaderProps {}
const Header: React.FC<HeaderProps> = () => { const Header: React.FC<HeaderProps> = () => {
const [currentUserModal, setCurrentUserModal] = useState(false); const [currentUserModal, setCurrentUserModal] = useState(false);
const { logOut, currentUser } = useAuth(); const { logOut, currentUser, isAdmin } = useAuth();
const { pathname } = useLocation(); const { pathname } = useLocation();
@ -30,6 +38,8 @@ const Header: React.FC<HeaderProps> = () => {
}; };
const currentUserModalClose = () => setCurrentUserModal(false); const currentUserModalClose = () => setCurrentUserModal(false);
const navigationItems = filterNavigationByDashboardRole(isAdmin);
return ( return (
<> <>
<Disclosure as="nav" className="bg-white shadow relative z-10"> <Disclosure as="nav" className="bg-white shadow relative z-10">
@ -55,7 +65,7 @@ const Header: React.FC<HeaderProps> = () => {
</Link> </Link>
<div className="hidden sm:ml-6 sm:flex sm:space-x-8"> <div className="hidden sm:ml-6 sm:flex sm:space-x-8">
{/* Current: "border-primary-500 text-gray-900", Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */} {/* Current: "border-primary-500 text-gray-900", Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */}
{navigation.map((item) => ( {navigationItems.map((item) => (
<Link <Link
key={item.name} key={item.name}
to={item.to} to={item.to}

View file

@ -1,31 +1,33 @@
import _ from 'lodash';
import React, { useEffect } from 'react'; import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form'; import { useFieldArray, useForm } from 'react-hook-form';
import { Modal, Banner } from 'src/components'; import { Modal } from 'src/components';
import { Input, Select } from 'src/components/Form'; import { Input, Select } from 'src/components/Form';
import { useAuth } from 'src/services/auth';
import { User, UserRole, useUsers } from 'src/services/users'; import { User, UserRole, useUsers } from 'src/services/users';
import { appAccessList } from './consts'; import { appAccessList, initialUserForm } from './consts';
import { UserModalProps } from './types'; import { UserModalProps } from './types';
export const CurrentUserModal = ({ open, onClose, user }: UserModalProps) => { export const CurrentUserModal = ({ open, onClose, user }: UserModalProps) => {
const { editUserById, userModalLoading } = useUsers(); const { editUserById, userModalLoading } = useUsers();
const { isAdmin } = useAuth();
const { control, reset, handleSubmit } = useForm<User>({ const { control, reset, handleSubmit } = useForm<User>({
defaultValues: { defaultValues: initialUserForm,
name: null, });
email: null,
id: null, const { fields } = useFieldArray({
role_id: null, control,
status: null, name: 'app_roles',
},
}); });
useEffect(() => { useEffect(() => {
if (user) { if (user && !_.isEmpty(user)) {
reset(user); reset(user);
} }
return () => { return () => {
reset({ name: null, email: null, id: null }); reset(initialUserForm);
}; };
}, [user, reset]); }, [user, reset]);
@ -54,7 +56,7 @@ export const CurrentUserModal = ({ open, onClose, user }: UserModalProps) => {
return ( return (
<Modal onClose={handleClose} open={open} onSave={handleSave} isLoading={userModalLoading} useCancelButton> <Modal onClose={handleClose} open={open} onSave={handleSave} isLoading={userModalLoading} useCancelButton>
<div className="bg-white px-4"> <div className="bg-white px-4">
<div className="space-y-4 divide-y divide-gray-200"> <div className="space-y-10 divide-y divide-gray-200">
<div> <div>
<div> <div>
<h3 className="text-lg leading-6 font-medium text-gray-900">Profile</h3> <h3 className="text-lg leading-6 font-medium text-gray-900">Profile</h3>
@ -69,77 +71,90 @@ export const CurrentUserModal = ({ open, onClose, user }: UserModalProps) => {
<Input control={control} name="email" label="Email" type="email" onKeyPress={handleKeyPress} /> <Input control={control} name="email" label="Email" type="email" onKeyPress={handleKeyPress} />
</div> </div>
<div className="sm:col-span-6"> {isAdmin && (
<Select <>
control={control} <div className="sm:col-span-3">
name="role_id" {fields
label="Role" .filter((field) => field.name === 'dashboard')
options={[ .map((item, index) => (
{ value: UserRole.Admin, name: 'Admin' }, <Select
{ value: UserRole.User, name: 'User' }, key={item.id}
]} control={control}
/> name={`app_roles.${index}.role`}
label="Role"
options={[
{ value: UserRole.Admin, name: 'Admin' },
{ value: UserRole.User, name: 'User' },
]}
/>
))}
</div>
<div className="sm:col-span-3 opacity-40 cursor-default pointer-events-none select-none">
{/* <Select control={control} name="status" label="Status" options={['Admin', 'Inactive']} /> */}
<label htmlFor="status" className="block text-sm font-medium text-gray-700">
Status
</label>
<div className="mt-1">
<select
id="status"
name="status"
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
>
<option>Active</option>
<option>Inactive</option>
<option>Banned</option>
</select>
</div>
</div>
</>
)}
</div>
</div>
{isAdmin && (
<div>
<div className="mt-8">
<h3 className="text-lg leading-6 font-medium text-gray-900">App Access</h3>
</div> </div>
<div className="sm:col-span-6"> <div>
<Banner title="Editing user status and app access coming soon." titleSm="Comming soon!" /> <div className="flow-root mt-6">
</div> <ul className="-my-5 divide-y divide-gray-200 ">
{fields
<div className="sm:col-span-3 opacity-40 cursor-default pointer-events-none select-none"> .filter((field) => field.name !== 'dashboard')
{/* <Select control={control} name="status" label="Status" options={['Admin', 'Inactive']} /> */} .map((item, index) => (
<label htmlFor="status" className="block text-sm font-medium text-gray-700"> <li className="py-4" key={item.name}>
Status <div className="flex items-center space-x-4">
</label> <div className="flex-shrink-0 flex-1 flex items-center">
<div className="mt-1"> <img
<select className="h-10 w-10 rounded-md overflow-hidden"
id="status" src={_.find(appAccessList, ['name', item.name!])?.image}
name="status" alt={item.name ?? 'Image'}
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md" />
> <h3 className="ml-4 text-md leading-6 font-medium text-gray-900">
<option>Active</option> {_.find(appAccessList, ['name', item.name!])?.label}
<option>Inactive</option> </h3>
<option>Banned</option> </div>
</select> <div>
<Select
key={item.id}
control={control}
name={`app_roles.${index}.role`}
options={[
{ value: UserRole.Admin, name: 'Admin' },
{ value: UserRole.User, name: 'User' },
]}
/>
</div>
</div>
</li>
))}
</ul>
</div> </div>
</div> </div>
</div> </div>
</div> )}
<div className="opacity-40 cursor-default pointer-events-none select-none">
<div className="mt-4">
<h3 className="text-lg leading-6 font-medium text-gray-900">App Access</h3>
</div>
<div>
<div className="flow-root mt-6">
<ul className="-my-5 divide-y divide-gray-200 ">
{appAccessList.map((app: any) => {
return (
<li className="py-4" key={app.name}>
<div className="flex items-center space-x-4">
<div className="flex-shrink-0 flex-1 flex items-center">
<img className="h-10 w-10 rounded-md overflow-hidden" src={app.image} alt={app.name} />
<h3 className="ml-4 text-md leading-6 font-medium text-gray-900">{app.name}</h3>
</div>
<div>
<select
id={app.name}
name={app.name}
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
>
<option>User</option>
<option>Admin</option>
<option>Super Admin</option>
</select>
</div>
</div>
</li>
);
})}
</ul>
</div>
</div>
</div>
</div> </div>
</div> </div>
</Modal> </Modal>

View file

@ -1,18 +1,55 @@
import { UserRole } from 'src/services/users';
export const appAccessList = [ export const appAccessList = [
{ {
name: 'wekan',
image: '/assets/wekan.svg', image: '/assets/wekan.svg',
name: 'Wekan', label: 'Wekan',
}, },
{ {
name: 'wordpress',
image: '/assets/wordpress.svg', image: '/assets/wordpress.svg',
name: 'Wordpress', label: 'Wordpress',
}, },
{ {
name: 'next-cloud',
image: '/assets/nextcloud.svg', image: '/assets/nextcloud.svg',
name: 'NextCloud', label: 'NextCloud',
}, },
{ {
name: 'zulip',
image: '/assets/zulip.svg', image: '/assets/zulip.svg',
name: 'Zulip', label: 'Zulip',
}, },
]; ];
const initialAppRoles = [
{
name: 'dashboard',
role: UserRole.User,
},
{
name: 'wekan',
role: UserRole.User,
},
{
name: 'wordpress',
role: UserRole.User,
},
{
name: 'next-cloud',
role: UserRole.User,
},
{
name: 'zulip',
role: UserRole.User,
},
];
export const initialUserForm = {
id: '',
name: '',
email: '',
app_roles: initialAppRoles,
status: '',
};

View file

@ -3,5 +3,5 @@ import { User } from 'src/services/users';
export type UserModalProps = { export type UserModalProps = {
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
user: User; user: User | null;
}; };

View file

@ -148,26 +148,28 @@ export const Table = <T extends Record<string, unknown>>({
); );
}) })
) : ( ) : (
<td colSpan={4} className="py-24"> <tr>
<div className="flex flex-col justify-center items-center"> <td colSpan={4} className="py-24">
<div className="flex justify-center items-center border border-transparent text-base font-medium rounded-md text-white transition ease-in-out duration-150"> <div className="flex flex-col justify-center items-center">
<svg <div className="flex justify-center items-center border border-transparent text-base font-medium rounded-md text-white transition ease-in-out duration-150">
className="animate-spin h-6 w-6 text-primary" <svg
xmlns="http://www.w3.org/2000/svg" className="animate-spin h-6 w-6 text-primary"
fill="none" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24" fill="none"
> viewBox="0 0 24 24"
<circle className="opacity-50" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /> >
<path <circle className="opacity-50" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
className="opacity-100" <path
fill="currentColor" className="opacity-100"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" fill="currentColor"
/> d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
</svg> />
</svg>
</div>
<p className="text-sm text-primary-600 mt-2">Loading users</p>
</div> </div>
<p className="text-sm text-primary-600 mt-2">Loading users</p> </td>
</div> </tr>
</td>
)} )}
</tbody> </tbody>
</table> </table>

View file

@ -5,6 +5,7 @@ import { CogIcon, TrashIcon } from '@heroicons/react/outline';
import { useUsers } from 'src/services/users'; import { useUsers } from 'src/services/users';
import { Table } from 'src/components'; import { Table } from 'src/components';
import { debounce } from 'lodash'; import { debounce } from 'lodash';
import { useAuth } from 'src/services/auth';
import { UserModal } from './components/UserModal'; import { UserModal } from './components/UserModal';
export const Users: React.FC = () => { export const Users: React.FC = () => {
@ -13,6 +14,7 @@ export const Users: React.FC = () => {
const [userId, setUserId] = useState(null); const [userId, setUserId] = useState(null);
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const { users, loadUsers, userTableLoading } = useUsers(); const { users, loadUsers, userTableLoading } = useUsers();
const { isAdmin } = useAuth();
const handleSearch = (event: any) => { const handleSearch = (event: any) => {
setSearch(event.target.value); setSearch(event.target.value);
@ -60,23 +62,27 @@ export const Users: React.FC = () => {
Cell: (props: any) => { Cell: (props: any) => {
const { row } = props; const { row } = props;
return ( if (isAdmin) {
<div className="text-right lg:opacity-0 group-hover:opacity-100 transition-opacity"> return (
<button <div className="text-right lg:opacity-0 group-hover:opacity-100 transition-opacity">
onClick={() => configureModalOpen(row.original.id)} <button
type="button" onClick={() => configureModalOpen(row.original.id)}
className="inline-flex items-center px-4 py-2 border border-gray-200 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500" type="button"
> className="inline-flex items-center px-4 py-2 border border-gray-200 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
<CogIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" /> >
Configure <CogIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" />
</button> Configure
</div> </button>
); </div>
);
}
return null;
}, },
width: 'auto', width: 'auto',
}, },
], ],
[], [isAdmin],
); );
const selectedRows = useCallback((rows: Record<string, boolean>) => { const selectedRows = useCallback((rows: Record<string, boolean>) => {
@ -88,16 +94,19 @@ export const Users: React.FC = () => {
<div className="max-w-7xl mx-auto py-4 px-3 sm:px-6 lg:px-8 h-full flex-grow"> <div className="max-w-7xl mx-auto py-4 px-3 sm:px-6 lg:px-8 h-full flex-grow">
<div className="pb-5 mt-6 border-b border-gray-200 sm:flex sm:items-center sm:justify-between"> <div className="pb-5 mt-6 border-b border-gray-200 sm:flex sm:items-center sm:justify-between">
<h1 className="text-3xl leading-6 font-bold text-gray-900">Users</h1> <h1 className="text-3xl leading-6 font-bold text-gray-900">Users</h1>
<div className="mt-3 sm:mt-0 sm:ml-4">
<button {isAdmin && (
onClick={() => configureModalOpen(null)} <div className="mt-3 sm:mt-0 sm:ml-4">
type="button" <button
className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-700 hover:bg-primary-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-800" onClick={() => configureModalOpen(null)}
> type="button"
<PlusIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" /> className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-700 hover:bg-primary-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-800"
Add new user >
</button> <PlusIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" />
</div> Add new user
</button>
</div>
)}
</div> </div>
<div className="flex justify-between w-100 my-3 items-center mb-5 "> <div className="flex justify-between w-100 my-3 items-center mb-5 ">
@ -153,7 +162,7 @@ export const Users: React.FC = () => {
</div> </div>
</div> </div>
<UserModal open={configureModal} onClose={configureModalClose} userId={userId} /> <UserModal open={configureModal} onClose={configureModalClose} userId={userId} setUserId={setUserId} />
</div> </div>
</div> </div>
); );

View file

@ -1,26 +1,27 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { TrashIcon } from '@heroicons/react/outline'; import { TrashIcon } from '@heroicons/react/outline';
import { useForm } from 'react-hook-form'; import { useFieldArray, useForm } from 'react-hook-form';
import { Modal, Banner, ConfirmationModal } from 'src/components'; import { Modal, ConfirmationModal } from 'src/components';
import { Input, Select } from 'src/components/Form'; import { Input, Select } from 'src/components/Form';
import { User, UserRole, useUsers } from 'src/services/users'; import { User, UserRole, useUsers } from 'src/services/users';
import { useAuth } from 'src/services/auth'; import { useAuth } from 'src/services/auth';
import { appAccessList } from './consts'; import { appAccessList, initialUserForm } from './consts';
import { UserModalProps } from './types'; import { UserModalProps } from './types';
export const UserModal = ({ open, onClose, userId }: UserModalProps) => { export const UserModal = ({ open, onClose, userId, setUserId }: UserModalProps) => {
const [deleteModal, setDeleteModal] = useState(false); const [deleteModal, setDeleteModal] = useState(false);
const { user, loadUser, editUserById, createNewUser, userModalLoading, deleteUserById } = useUsers(); const { user, loadUser, editUserById, createNewUser, userModalLoading, deleteUserById, clearSelectedUser } =
const { currentUser } = useAuth(); useUsers();
const { currentUser, isAdmin } = useAuth();
const { control, reset, handleSubmit } = useForm<User>({ const { control, reset, handleSubmit } = useForm<User>({
defaultValues: { defaultValues: initialUserForm,
name: null, });
email: null,
id: null, const { fields } = useFieldArray({
role_id: null, control,
status: null, name: 'app_roles',
},
}); });
useEffect(() => { useEffect(() => {
@ -28,19 +29,19 @@ export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
loadUser(userId); loadUser(userId);
} }
reset({ name: null, email: null, id: null, status: null }); reset(initialUserForm);
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId]); }, [userId, open]);
useEffect(() => { useEffect(() => {
if (user) { if (!_.isEmpty(user)) {
reset(user); reset(user);
} }
return () => { return () => {
reset({ name: null, email: null, id: null, status: null }); reset(initialUserForm);
}; };
}, [user, reset]); }, [user, reset, open]);
const handleSave = async () => { const handleSave = async () => {
try { try {
@ -48,13 +49,14 @@ export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
await handleSubmit((data) => editUserById(data))(); await handleSubmit((data) => editUserById(data))();
} else { } else {
await handleSubmit((data) => createNewUser(data))(); await handleSubmit((data) => createNewUser(data))();
reset({ name: null, email: null, id: null, status: null });
} }
onClose();
} catch (e: any) { } catch (e: any) {
// Continue // Continue
} }
onClose();
clearSelectedUser();
setUserId(null);
}; };
const handleKeyPress = (e: any) => { const handleKeyPress = (e: any) => {
@ -65,6 +67,8 @@ export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
const handleClose = () => { const handleClose = () => {
onClose(); onClose();
clearSelectedUser();
setUserId(null);
}; };
const deleteModalOpen = () => setDeleteModal(true); const deleteModalOpen = () => setDeleteModal(true);
@ -74,6 +78,9 @@ export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
if (userId) { if (userId) {
deleteUserById(userId); deleteUserById(userId);
} }
clearSelectedUser();
setUserId(null);
handleClose(); handleClose();
deleteModalClose(); deleteModalClose();
}; };
@ -87,7 +94,7 @@ export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
isLoading={userModalLoading} isLoading={userModalLoading}
leftActions={ leftActions={
userId && userId &&
user.email !== currentUser.email && ( user.email !== currentUser?.email && (
<button <button
onClick={deleteModalOpen} onClick={deleteModalOpen}
type="button" type="button"
@ -101,7 +108,7 @@ export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
useCancelButton useCancelButton
> >
<div className="bg-white px-4"> <div className="bg-white px-4">
<div className="space-y-4 divide-y divide-gray-200"> <div className="space-y-10 divide-y divide-gray-200">
<div> <div>
<div> <div>
<h3 className="text-lg leading-6 font-medium text-gray-900">{userId ? 'Edit user' : 'Add new user'}</h3> <h3 className="text-lg leading-6 font-medium text-gray-900">{userId ? 'Edit user' : 'Add new user'}</h3>
@ -116,77 +123,91 @@ export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
<Input control={control} name="email" label="Email" type="email" onKeyPress={handleKeyPress} /> <Input control={control} name="email" label="Email" type="email" onKeyPress={handleKeyPress} />
</div> </div>
<div className="sm:col-span-6"> <div className="sm:col-span-3">
<Select {fields
control={control} .filter((field) => field.name === 'dashboard')
name="role_id" .map((item, index) => (
label="Role" <Select
options={[ key={item.name}
{ value: UserRole.Admin, name: 'Admin' }, control={control}
{ value: UserRole.User, name: 'User' }, name={`app_roles.${index}.role`}
]} label="Role"
/> options={[
{ value: UserRole.User, name: 'User' },
{ value: UserRole.Admin, name: 'Admin' },
]}
/>
))}
</div> </div>
<div className="sm:col-span-6"> {isAdmin && (
<Banner title="Editing user status and app access coming soon." titleSm="Comming soon!" /> <div className="sm:col-span-3 opacity-40 cursor-default pointer-events-none select-none">
<label htmlFor="status" className="block text-sm font-medium text-gray-700">
Status
</label>
<div className="mt-1">
<select
id="status"
name="status"
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
>
<option>Active</option>
<option>Inactive</option>
<option>Banned</option>
</select>
</div>
</div>
)}
</div>
</div>
{isAdmin && (
<div>
<div className="mt-8">
<h3 className="text-lg leading-6 font-medium text-gray-900">App Access</h3>
</div> </div>
<div className="sm:col-span-3 opacity-40 cursor-default pointer-events-none select-none"> <div>
{/* <Select control={control} name="status" label="Status" options={['Active', 'Inactive']} /> */} <div className="flow-root mt-6">
<label htmlFor="status" className="block text-sm font-medium text-gray-700"> <ul className="-my-5 divide-y divide-gray-200 ">
Status {fields.map((item, index) => {
</label> if (item.name === 'dashboard') {
<div className="mt-1"> return null;
<select }
id="status"
name="status" return (
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md" <li className="py-4" key={item.name}>
> <div className="flex items-center space-x-4">
<option>Active</option> <div className="flex-shrink-0 flex-1 flex items-center">
<option>Inactive</option> <img
<option>Banned</option> className="h-10 w-10 rounded-md overflow-hidden"
</select> src={_.find(appAccessList, ['name', item.name!])?.image}
alt={item.name ?? 'Image'}
/>
<h3 className="ml-4 text-md leading-6 font-medium text-gray-900">
{_.find(appAccessList, ['name', item.name!])?.label}
</h3>
</div>
<div>
<Select
key={item.id}
control={control}
name={`app_roles.${index}.role`}
options={[
{ value: UserRole.User, name: 'User' },
{ value: UserRole.Admin, name: 'Admin' },
]}
/>
</div>
</div>
</li>
);
})}
</ul>
</div> </div>
</div> </div>
</div> </div>
</div> )}
<div className="opacity-40 cursor-default pointer-events-none select-none">
<div className="mt-4">
<h3 className="text-lg leading-6 font-medium text-gray-900">App Access</h3>
</div>
<div>
<div className="flow-root mt-6">
<ul className="-my-5 divide-y divide-gray-200 ">
{appAccessList.map((app: any) => {
return (
<li className="py-4" key={app.name}>
<div className="flex items-center space-x-4">
<div className="flex-shrink-0 flex-1 flex items-center">
<img className="h-10 w-10 rounded-md overflow-hidden" src={app.image} alt={app.name} />
<h3 className="ml-4 text-md leading-6 font-medium text-gray-900">{app.name}</h3>
</div>
<div>
<select
id={app.name}
name={app.name}
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
>
<option>User</option>
<option>Admin</option>
<option>Super Admin</option>
</select>
</div>
</div>
</li>
);
})}
</ul>
</div>
</div>
</div>
</div> </div>
</div> </div>
</Modal> </Modal>

View file

@ -1,18 +1,55 @@
import { UserRole } from 'src/services/users';
export const appAccessList = [ export const appAccessList = [
{ {
name: 'wekan',
image: '/assets/wekan.svg', image: '/assets/wekan.svg',
name: 'Wekan', label: 'Wekan',
}, },
{ {
name: 'wordpress',
image: '/assets/wordpress.svg', image: '/assets/wordpress.svg',
name: 'Wordpress', label: 'Wordpress',
}, },
{ {
name: 'nextcloud',
image: '/assets/nextcloud.svg', image: '/assets/nextcloud.svg',
name: 'NextCloud', label: 'NextCloud',
}, },
{ {
name: 'zulip',
image: '/assets/zulip.svg', image: '/assets/zulip.svg',
name: 'Zulip', label: 'Zulip',
}, },
]; ];
const initialAppRoles = [
{
name: 'dashboard',
role: UserRole.User,
},
{
name: 'wekan',
role: UserRole.User,
},
{
name: 'wordpress',
role: UserRole.User,
},
{
name: 'nextcloud',
role: UserRole.User,
},
{
name: 'zulip',
role: UserRole.User,
},
];
export const initialUserForm = {
id: '',
name: '',
email: '',
app_roles: initialAppRoles,
status: '',
};

View file

@ -2,4 +2,5 @@ export type UserModalProps = {
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
userId: string | null; userId: string | null;
setUserId: any;
}; };

View file

@ -1,11 +1,12 @@
import { useCallback } from 'react'; import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { getAuthToken, getCurrentUser, signIn, signOut } from '../redux'; import { getAuthToken, getCurrentUser, getIsAdmin, signIn, signOut } from '../redux';
export function useAuth() { export function useAuth() {
const dispatch = useDispatch(); const dispatch = useDispatch();
const currentUser = useSelector(getCurrentUser); const currentUser = useSelector(getCurrentUser);
const authToken = useSelector(getAuthToken); const authToken = useSelector(getAuthToken);
const isAdmin = useSelector(getIsAdmin);
const logIn = useCallback( const logIn = useCallback(
(params) => { (params) => {
@ -21,6 +22,7 @@ export function useAuth() {
return { return {
authToken, authToken,
currentUser, currentUser,
isAdmin,
logIn, logIn,
logOut, logOut,
}; };

View file

@ -1,4 +1,4 @@
export { signIn, signOut, AuthActionTypes } from './actions'; export { signIn, signOut, AuthActionTypes } from './actions';
export { default as reducer } from './reducers'; export { default as reducer } from './reducers';
export { getAuth, getIsAuthLoading, getAuthToken, getCurrentUser } from './selectors'; export { getAuth, getIsAuthLoading, getAuthToken, getCurrentUser, getIsAdmin } from './selectors';
export * from './types'; export * from './types';

View file

@ -6,12 +6,12 @@ import { AuthActionTypes } from './actions';
import { transformAuthUser } from '../transformations'; import { transformAuthUser } from '../transformations';
const initialCurrentUserState: User = { const initialCurrentUserState: User = {
email: null, email: '',
name: null, name: '',
id: null, id: '',
role_id: null, app_roles: [],
status: null, status: '',
preferredUsername: null, preferredUsername: '',
}; };
const initialState: AuthState = { const initialState: AuthState = {

View file

@ -1,6 +1,7 @@
import { State } from 'src/redux'; import { State } from 'src/redux';
import { isLoading } from 'src/services/api'; import { isLoading } from 'src/services/api';
import { UserRole } from 'src/services/users';
export const getAuth = (state: State) => state.auth; export const getAuth = (state: State) => state.auth;
@ -8,6 +9,20 @@ export const getAuthToken = (state: State) => state.auth.token;
export const getCurrentUser = (state: State) => state.auth.userInfo; export const getCurrentUser = (state: State) => state.auth.userInfo;
export const getIsAdmin = (state: State) => {
// check since old users wont have this
if (state.auth.userInfo) {
if (!state.auth.userInfo.app_roles) {
return false;
}
const isAdmin = state.auth.userInfo.app_roles.find(
(role) => role.name === 'dashboard' && role.role === UserRole.Admin,
);
return !!isAdmin;
}
return false;
};
export const getIsAuthLoading = (state: State) => isLoading(getAuth(state)); export const getIsAuthLoading = (state: State) => isLoading(getAuth(state));
export const getToken = (state: State) => state.auth.token; export const getToken = (state: State) => state.auth.token;

View file

@ -1,18 +1,21 @@
import { UserRole } from '../users'; import { User } from '../users';
import { Auth } from './types'; import { Auth } from './types';
import { transformAppRoles } from '../users/transformations';
export const transformAuthUser = (response: any): Auth => { const transformUser = (response: any): User => {
const resolvedUserRole = !response.userInfo.role_id ? UserRole.User : response.userInfo.role_id;
return { return {
token: response.accessToken, id: response.id ?? '',
userInfo: { app_roles: response.app_roles ? response.app_roles.map(transformAppRoles) : [],
id: response.userInfo.id, email: response.email ?? '',
role_id: resolvedUserRole, name: response.name ?? '',
email: response.userInfo.email ?? null, preferredUsername: response.preferredUsername ?? '',
name: response.userInfo.name ?? null, status: response.state ?? '',
preferredUsername: response.userInfo.preferredUsername, };
status: response.userInfo.state ?? null, };
},
export const transformAuthUser = (response: any): Auth => {
return {
token: response.accessToken,
userInfo: response.userInfo ? transformUser(response.userInfo) : null,
}; };
}; };

View file

@ -2,5 +2,5 @@ import { User } from '../users';
export interface Auth { export interface Auth {
token: string | null; token: string | null;
userInfo: User; userInfo: User | null;
} }

View file

@ -1,5 +1,13 @@
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { getUsers, fetchUsers, fetchUserById, updateUserById, createUser, deleteUser } from '../redux'; import {
getUsers,
fetchUsers,
fetchUserById,
updateUserById,
createUser,
deleteUser,
clearCurrentUser,
} from '../redux';
import { getUserById, getUserModalLoading, getUserslLoading } from '../redux/selectors'; import { getUserById, getUserModalLoading, getUserslLoading } from '../redux/selectors';
export function useUsers() { export function useUsers() {
@ -17,6 +25,10 @@ export function useUsers() {
return dispatch(fetchUserById(id)); return dispatch(fetchUserById(id));
} }
function clearSelectedUser() {
return dispatch(clearCurrentUser());
}
function editUserById(data: any) { function editUserById(data: any) {
return dispatch(updateUserById(data)); return dispatch(updateUserById(data));
} }
@ -39,5 +51,6 @@ export function useUsers() {
userTableLoading, userTableLoading,
createNewUser, createNewUser,
deleteUserById, deleteUserById,
clearSelectedUser,
}; };
} }

View file

@ -1,5 +1,6 @@
import { Dispatch } from 'redux'; import { Dispatch } from 'redux';
import { showToast, ToastType } from 'src/common/util/show-toast'; import { showToast, ToastType } from 'src/common/util/show-toast';
import { State } from 'src/redux/types';
import { performApiCall } from 'src/services/api'; import { performApiCall } from 'src/services/api';
import { AuthActionTypes } from 'src/services/auth'; import { AuthActionTypes } from 'src/services/auth';
import { transformRequestUser, transformUser } from '../transformations'; import { transformRequestUser, transformUser } from '../transformations';
@ -68,9 +69,11 @@ export const fetchUserById = (id: string) => async (dispatch: Dispatch<any>) =>
dispatch(setUserModalLoading(false)); dispatch(setUserModalLoading(false));
}; };
export const updateUserById = (user: any) => async (dispatch: Dispatch<any>) => { export const updateUserById = (user: any) => async (dispatch: Dispatch<any>, getState: any) => {
dispatch(setUserModalLoading(true)); dispatch(setUserModalLoading(true));
const state: State = getState();
try { try {
const { data } = await performApiCall({ const { data } = await performApiCall({
path: `/users/${user.id}`, path: `/users/${user.id}`,
@ -83,10 +86,12 @@ export const updateUserById = (user: any) => async (dispatch: Dispatch<any>) =>
payload: transformUser(data), payload: transformUser(data),
}); });
dispatch({ if (state.auth.userInfo?.id === user.id) {
type: AuthActionTypes.UPDATE_AUTH_USER, dispatch({
payload: transformUser(data), type: AuthActionTypes.UPDATE_AUTH_USER,
}); payload: transformUser(data),
});
}
showToast('User updated successfully.', ToastType.Success); showToast('User updated successfully.', ToastType.Success);
@ -148,3 +153,10 @@ export const deleteUser = (id: string) => async (dispatch: Dispatch<any>) => {
dispatch(setUserModalLoading(false)); dispatch(setUserModalLoading(false));
}; };
export const clearCurrentUser = () => (dispatch: Dispatch<any>) => {
dispatch({
type: UserActionTypes.DELETE_USER,
payload: {},
});
};

View file

@ -1,33 +1,38 @@
import _ from 'lodash'; import { AppRoles, User, UserRole } from './types';
import { User, UserRole } from './types'; export const transformAppRoles = (data: any): AppRoles => {
const resolvedAdminRole = data.role_id === 1 ? UserRole.Admin : UserRole.User;
return {
name: data.name ?? '',
role: resolvedAdminRole ?? UserRole.User,
};
};
export const transformRequestAppRoles = (data: AppRoles): any => {
const resolvedRequestRole = data.role === UserRole.Admin ? 1 : null;
return {
name: data.name ?? '',
role_id: resolvedRequestRole,
};
};
export const transformUser = (response: any): User => { export const transformUser = (response: any): User => {
const userResponse = _.get(response, 'user', response);
const resolvedUserRole = !userResponse.traits.role_id ? UserRole.User : userResponse.traits.role_id;
return { return {
id: userResponse.id, id: response.id ?? '',
role_id: resolvedUserRole, app_roles: response.traits.app_roles ? response.traits.app_roles.map(transformAppRoles) : [],
email: userResponse.traits.email, email: response.traits.email ?? '',
name: userResponse.traits.name ?? null, name: response.traits.name ?? '',
preferredUsername: userResponse.preferredUsername, preferredUsername: response.preferredUsername ?? '',
status: userResponse.state, status: response.state ?? '',
}; };
}; };
export const transformRequestUser = (data: Pick<User, 'role_id' | 'name' | 'email'>) => { export const transformRequestUser = (data: Pick<User, 'app_roles' | 'name' | 'email'>) => {
if (data.role_id === UserRole.User) {
return {
email: data.email,
name: data.name,
};
}
return { return {
role_id: Number(data.role_id), app_roles: data.app_roles.map(transformRequestAppRoles),
email: data.email, email: data.email ?? '',
name: data.name, name: data.name ?? '',
}; };
}; };

View file

@ -1,10 +1,10 @@
export interface User { export interface User {
id: number | null; id: string;
role_id: UserRole | null; app_roles: AppRoles[];
email: string | null; email: string;
name: string | null; name: string;
preferredUsername: string | null; preferredUsername: string;
status: string | null; status: string;
} }
export interface FormUser extends User { export interface FormUser extends User {
@ -13,8 +13,13 @@ export interface FormUser extends User {
} }
export enum UserRole { export enum UserRole {
Admin = '1', Admin = 'admin',
User = '2', User = 'user',
}
export interface AppRoles {
name: string | null;
role: UserRole | null;
} }
export interface UserApiRequest { export interface UserApiRequest {