marmelab / aor-permissions Goto Github PK
View Code? Open in Web Editor NEWA component for Admin-on-rest allowing to switch views depending on user permissions. Eg: having different PostEdit components for different users
License: MIT License
A component for Admin-on-rest allowing to switch views depending on user permissions. Eg: having different PostEdit components for different users
License: MIT License
Can we have something like below. So that we can declare resources at higher instead of multiple edit/create layout for same resource
<SwitchResourceWithPermission> <Permission value="admin"> <Resource name="user" create={} edit={} list={}> </Permission> <Permission value="user"> <Resource name="user" list={}> </Permission> </SwitchResourceWithPermission>
Hi there!
Perhaps that ticket could be marked as feature request
So, details:
aor - v.1.2.0
aor-permissions - v1.1.0
here is the snippet of my app
import {
Admin
} from 'aor-permissions';
<Admin
appLayout={AppLayout}
menu={AppMenu}
authClient={authClient}
restClient={restClient}
customReducers={{auth: authReducer}}
messages={translations}
>
<Resource
name="users"
list={UsersList}
create={UserCreate}
edit={UserEdit}
remove={UserDelete}
permissions={'manager'}
/>
<Resource
name="clients"
list={ClientsList}
create={ClientCreate}
edit={ClientEdit}
remove={ClientDelete}
permissions={['advisor', 'manager']}
/>
</Admin>
I faced the following problem:
UserA
which has role, lets say, 'manager'
based on that role I've exposed to him some of the resources - Users
and Clients
UserB
which has role 'advisor'
I was still able to see <Resource name="users"/>
in my sidebar menu despite inappropriate permissions. Moreover the resource pages were also available to me (list, create, edit pages).Only after page refresh (Ctrl + F5) the <Resources/>
were re-evaluated against permissions again and <Resource name="users" />
was not avail anymore to UserB
In other words current implementation exposes to unprivileged users resources that were available to previously logged in user.
Hi I am using WithPermission
around an EditButton
:
const cardActionStyle = {
zIndex: 2,
display: 'inline-block',
float: 'right',
};
const Actions = ({ resource, filters, displayedFilters, filterValues, basePath, showFilter, refresh }) => (
<CardActions style={cardActionStyle}>
{filters && React.cloneElement(filters, { resource, showFilter, displayedFilters, filterValues, context: 'button' }) }
<WithPermission authClient={authClient} value={['admin']}>
<CreateButton basePath={basePath} translate={true}/>
</WithPermission>
<FlatButton primary label="refresh" onClick={refresh} icon={<NavigationRefresh />} />
</CardActions>
);
export const CompanyList = (props) => (
<List title="All companies" {...props} filters={<CompanyFilter/>} actions={<Actions />} sort={{field: 'id', order: 'DESC'}} perPage={2}>
<Datagrid>
<TextField source="id"/>
<TextField source="name"/>
<ReferenceArrayField label="Client" source="clientId" reference="clients" sortable={false}>
<SingleFieldList>
<ChipField source="name"/>
</SingleFieldList>
</ReferenceArrayField>
<WithPermission authClient={authClient} value={['admin']}>
<EditButton/>
</WithPermission>
</Datagrid>
</List>
);
it makes so that the request when I press edit for a company is companies/undefined
! while if I remove the WithPermission
tag around EditButton
it has the correct url for edit form companies/{companyId}
I am using those versions:
"admin-on-rest": "1.2.3",
"aor-permissions": "1.1.2"
I have a project with admin-on-rest where I need to condition permissions granted to the user, through the roles, to enable or disable the created, delete, edit, show and list actions.
The aor-permissions component does not seem to allow this.
I just managed to disable the buttons in the list, but of course, if you disable, for example, the delete in the list, it still appears in the show.
The ideal would be to act when defining the resource with something like this code:
import React from 'react';
import { simpleRestClient, Admin, Resource, Delete } from 'admin-on-rest';
import { can } from 'aor-roles';
import { PostList, PostCreate, PostEdit, PostShow } from './posts';
const App = () => (
<AuthProvider authClient={authClient}>
<Admin restClient={simpleRestClient('http://path.to.my.api')}>
<Resource
name="posts"
list={can('posts.list') && PostList}
create={can('posts.create') && PostCreate}
edit={can('posts.edit') && PostEdit}
show={can('posts.show') && PostShow}
remove={can('posts.remove') && Delete}
} />
</Admin>
</AuthProvider>
);
export default App;
I did not find a method to let inject a function like can over it to be re-evaluated after a disconnect and a connect of another user with different permissions.
Is there a way for hiding/showing some filter inputs based on role/permission?
Using
admin-on-rest 1.0.2
aor-permissions 1.0.0
<WithPermission>
and <SwitchPermission>
work fine, they provide much more clarity than my previous tweaks for conditionnal rendering. Good job !
However, when I try to use <AuthProvider>
nothing renders (blank page) and this error is yield in JS Console :
Error: withContext(AuthProviderComponent).getChildContext(): key "authClientFromContext" is not defined in childContextTypes.
My code is straightforward :
const App = () => (
<AuthProvider authClient={authClient}>
<Admin locale="fr" messages={messages} menu={menu} restClient={restClient} >
{ }
</Admin>
</AuthProvider>
);
export default App;
export const PhotoList = (props) => (
...
<WithPermission value={['admin', 'editor']} >
<WithPermission value={['admin', 'editor']} >
<DeleteButton />
</WithPermission>
</Datagrid>
In this design the buttons: DeleteButton / ShowButton create first request: GET/photos/undefined
instead of (for example): GET/photos/8ba93c09-468d-49ac-bbc2-90f2af0ae4b1
Getting below uncaught exception when used for menu rendering
withPermission.js:182 Uncaught (in promise) TypeError: Cannot read property 'source' of undefined
Have Used authprovider for authclient
Code:
const Menu = ({onMenuTap, translate, logout}) => (
<div style={styles.main}>
<WithPermission value="Admin">
<DashboardMenuItem onTouchTap={onMenuTap}/> {adminItems.map(item => (
<MenuItem
key={item.resource}
containerElement={< Link to = {
`/${item.resource}`
} />}
primaryText={item.name}
leftIcon={item.icon}
onTouchTap={onMenuTap}/>
))}
</WithPermission>
{logout}
</div>
);
Hi!
Maybe I'm missing something but for me the is not working correctly on List views.
And here is the code for it:
export const TrainingList = (props) => {
return <List {...props} perPage={25} filters={<TrainingFilter />}>
<Datagrid>
{/* Other stuff */}
<WithPermission value={["gymadmin", "mainAdmin"]} >
<AcivateTraining label="Aktíválás" addLabel/>
</WithPermission>
{/* Other stuff */}
</Datagrid>
</List>
};
When addLabel
prop was not present the label wasn't even showing up anywhere.
And the code
export const GymUsersList = (props) => (
<List {...props} perPage={25}>
<Datagrid>
<WithPermission value={"mainAdmin"}>
<TextField source="gymId" />
</WithPermission>
{/* Other stuff */}
</Datagrid>
</List>
);
Are these the expected behaviour?
Thanks in advance!
P.S: in Edit or Create view everything works as expected, this only shows up List view.
When I've used <Admin />
from aor there were no problems with assigning some custom props to <Resource />
tags in order to have ability to make some manipulations in component that I've specified in menu
prop of <Admin />
(i.e. menu={CustomMenu}
)
Now I am using Admin
from aor-permissions and those custom props are not passed down anymore
Could we apply this patch to bring back this ability?
diff --git a/src/Admin.js b/src/Admin.js
index 46c9629..563d185 100644
--- a/src/Admin.js
+++ b/src/Admin.js
@@ -56,6 +56,7 @@
edit: await applyPermissionsToAction({ permissions, resource, action: 'edit' }),
show: await applyPermissionsToAction({ permissions, resource, action: 'show' }),
remove: await applyPermissionsToAction({ permissions, resource, action: 'remove' }),
+ ...resource.props
};
return newResource;
Hello
Firstly, thanks for this fantastic package. Has been tremendously useful.
Issue:
My App.js
<Admin menu={Menu} authClient={authClient} restClient={uploadCapableRESTClient}>
<Resource name="appUsers" list={UserList} edit={AdminUserEdit} options={{ label: 'Users' }} />
<Resource name="trackTale" list={BrandEditorTaleTrack} edit={EditTale} />
<Resource name="tales" list={ AllEditorTaleDisplaySwitch } edit={EditTale} options={{ label: 'Assigned Tales' }}/>
</Admin>
In my custom Menu I am showing only role related links appropriately.
For user Admin the first route is /appusers
For user Editor the first route displayed is /tales.
When logging in as Editor however the app goes to the first route /appusers and since this user has no components attached to this route, the page only displays the menu. After clicking on the menu all behaviour is as expected.
Look into it when can.
Please advise on how to add Search, filter, pagination for Datagrid as a child of
Thanks!
I am trying to let Resources and their presence in the menu be controlled via permissions as shown in the code below, but it doesn't seem to work. Currently the menu item for the Resource just disappears permanently, and the authclient never even gets queried via AUTH_GET_PERMISSIONS. If it's supposed to work, what am I doing wrong? If it's not implemented for Resources yet, I think this would be an immensely useful feature to have!
const App = () => (
<AuthProvider authClient={authClient}>
<Admin restClient={restClient}>
<WithPermission value="can_see_secret_data">
<Resource name="secret_data" list={SecretDataList} />
</WithPermission>
<Resource name="public_data" list={PublicDataList} />
</Admin>
</AuthProvider>
);
There is Warning about unknown prop if used inside menu
Warning: Unknown prop
resolve on <a> tag. Remove this prop from the element.
When used like in example for menu, just with resolve
const checkPermission = (params) => { return true; };
<WithPermission authClient={authClient} resolve={checkPermission}> <MenuItem containerElement={<Link to="/configuration" />} primaryText="Configuration" leftIcon={<SettingsIcon />} onTouchTap={onMenuTap} /> </WithPermission>
yarn emits a warning:
warning "[email protected]" has incorrect peer dependency "admin-on-rest@~0.9.1".
I believe it is caused by this incorrect directive in package.json:
"peerDependencies": {
"admin-on-rest": "~0.9.1",
"material-ui": "~0.17.4"
}
instead of
"peerDependencies": {
"admin-on-rest": "~1.0.2",
"material-ui": "~0.17.4"
}
Hi Guys.
This is in reference to this issue #9
Have been trying this for a while today with this saga on login.
const permission = localStorage.getItem('permissions')
function* userLoginSuccess() {
if (permission === 'publishing') {
yield put(push('/tales'))
} else {
yield put(push('/tales/talesByRelation'))
}
}
export default function* userLoginSaga() {
yield all ([
takeEvery('AOR/USER_LOGIN_SUCCESS', userLoginSuccess),
])
}
But no redirect happens. I get a warning from the SwitchPermissionsComponent
`
setState(…): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op
`
Please do advise.
It would be nice to be able to use the permissions component to display or not the actions buttons for a list...etc
Guys. I think you have a little bit confused yourselfs with those funky args naming in aor-permissions/src/resolvePermissions.js
Snippet of code from my app:
<WithPermission resolve={someFunc} value={'manager'}>
const someFunc = ({permissions, resource, value, exact, record}) => {
...
}
The problem - the value
arg is always undefined inside someFunc
no matter of what.
After spending some time on debugging the transpiled code I've figured out that reason of bug is the following line of code (sorry, I don't have enough time right now for patches so I will provide image :) )
After I made the mentioned fix in node_modules/aor-permissions/lib/resolvePermissions.js
I was able to receive the value I've passed through value
prop to WithPermission elem
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.