React admin firebase

React admin firebase DEFAULT

react-admin-firebase

NPM VersionLicenseDownloads/weekGithub Issues

A firebase data provider for the React-Admin framework. It maps collections from the Firebase database (Firestore) to your react-admin application. It's an npm package!


Features

Pull requests welcome!!

Firestore Dataprovider Features

Get Started

or

Demos Basic

A simple example based on the React Admin Tutorial.

Prerequisits

  • Create a collection in the firebase firestore database
  • Get config credentials using the dashboard

Options

import{FirebaseAuthProvider,FirebaseDataProvider,FirebaseRealTimeSaga}from'react-admin-firebase';constconfig={apiKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",authDomain: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",databaseURL: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",projectId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",storageBucket: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",messagingSenderId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",};// All options are optionalconstoptions={// Use a different root document to set your resource collections, by default it uses the root collections of firestorerootRef: 'root-collection/some-doc'|()=>'root-collection/some-doc',// Your own, previously initialized firebase app instanceapp: firebaseAppInstance,// Enable logging of react-admin-firebaselogging: true,// Resources to watch for realtime updates, will implicitly watch all resources by default, if not set.watch: ['posts'],// Resources you explicitly dont want realtime updates fordontwatch: ['comments'],// Authentication persistence, defaults to 'session', options are 'session' | 'local' | 'none'persistence: 'session',// Disable the metadata; 'createdate', 'lastupdate', 'createdby', 'updatedby'disableMeta: false,// Have custom metadata field names instead of: 'createdate', 'lastupdate', 'createdby', 'updatedby'renameMetaFields: {created_at: 'my_created_at',// default: 'createdate'created_by: 'my_created_by',// default: 'createdby'updated_at: 'my_updated_at',// default: 'lastupdate'updated_by: 'my_updated_by',// default: 'updatedby'},// Prevents document from getting the ID field added as a propertydontAddIdFieldToDoc: false,// Adds 'deleted' meta field for non-destructive deleting functionality// NOTE: Hides 'deleted' records from list views unless overridden by filtering for {deleted: true} softDelete: false,// Changes meta fields like 'createdby' and 'updatedby' to store user IDs instead of email addressesassociateUsersById: false,// Casing for meta fields like 'createdby' and 'updatedby', defaults to 'lower', options are 'lower' | 'camel' | 'snake' | 'pascal' | 'kebab'metaFieldCasing: 'lower',// Instead of saving full download url for file, save just relative path and then get download url// when getting docs - main use case is handling multiple firebase projects (environments)// and moving/copying documents/storage files between them - with relativeFilePaths, download url// always point to project own storagerelativeFilePaths: false,// Add file name to storage path, when set to true the file name is included in the pathuseFileNamesInStorage: false// Use firebase sdk queries for pagination, filtering and sortinglazyLoading: {enabled: false},// Logging of all reads performed by app (additional feature, for lazy-loading testing)firestoreCostsLogger: {enabled: false, localStoragePrefix // optional}}constdataProvider=FirebaseDataProvider(config,options);constauthProvider=FirebaseAuthProvider(config,options);constfirebaseRealtime=FirebaseRealTimeSaga(dataProvider,options);

Data Provider

import*asReactfrom'react';import{Admin,Resource}from'react-admin';import{PostList,PostShow,PostCreate,PostEdit}from"./posts";import{FirebaseAuthProvider,FirebaseDataProvider,FirebaseRealTimeSaga}from'react-admin-firebase';constconfig={apiKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",authDomain: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",databaseURL: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",projectId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",storageBucket: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",messagingSenderId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",};constoptions={};constdataProvider=FirebaseDataProvider(config,options); ... <AdmindataProvider={dataProvider}><Resourcename="posts"list={PostList}show={PostShow}create={PostCreate}edit={PostEdit}/></Admin>...

Auth Provider

Using the you can allow authentication in the application.

constdataProvider=FirebaseDataProvider(config);constauthProvider=FirebaseAuthProvider(config); ... <AdmindataProvider={dataProvider}authProvider={authProvider}> ...

Also checkout how to login with: Google, Facebook, Github etc... (Example Here)

And you might want a "Forgot password" button... (Example Here)

Note

To get the currently logged in user run , this will return the firebase user object, or null if there is no currently logged in user.

Realtime Updates!

NOTE: Realtime updates were removed in v3.x (see https://github.com/marmelab/react-admin/pull/3908). As such, v3.x also does not support Realtime Updates. However, much of the original code used for this functionalaity in v2.x remains - including the documentation below. For updates on the implementation of realtime please follow these issues:

Get realtime updates from the firebase server instantly on your tables, with minimal overheads, using rxjs observables!

... import{FirebaseRealTimeSaga,FirebaseDataProvider}from'react-admin-firebase'; ... constdataProvider=FirebaseDataProvider(config);constfirebaseRealtime=FirebaseRealTimeSaga(dataProvider); ... <AdmindataProvider={dataProvider}customSagas={[firebaseRealtime]}> ...

Realtime Options

Trigger realtime on only some routes using the options object.

... constdataProvider=FirebaseDataProvider(config);constoptions={watch: ['posts','comments'],dontwatch: ['users']}constfirebaseRealtime=FirebaseRealTimeSaga(dataProvider,options); ...

    Now all local changes in the library source code can be tested immediately in the demo app.

    Run tests

    To run the tests, either watch for changes or just run all tests.

      paypal

      Sours: https://github.com/benwinding/react-admin-firebase

      Data Providers

      Whenever react-admin needs to communicate with the API, it calls methods on the Data Provider object.

      It’s the Data Provider’s job to turn these method calls into HTTP requests, and transform the HTTP responses to the data format expected by react-admin. In technical terms, a Data Provider is an adapter for an API.

      And to inject a Data Provider in a react-admin application, pass it as the prop of the component, as follows:

      Thanks to this adapter injection system, react-admin can communicate with any API, whether it uses REST, GraphQL, RPC, or even SOAP, regardless of the dialect it uses. The Data Provider is also the ideal place to add custom HTTP headers, authentication, etc.

      Data Provider architecture

      A Data Provider must have the following methods:

      You can find an example Data Provider implementation at the end of this chapter.

      Tip: A Data Provider can have more methods than the 9 methods listed above. For instance, you create a dataProvider with custom methods for calling non-REST API endpoints, manipulating tree structures, subscribing to real time updates, etc.

      Tip: In react-admin v2, Data Providers used to be functions, not objects. React-admin v3 can detect a legacy Data Provider and wrap an object around it. So Data Providers developed for react-admin v2 still work with react-admin v3.

      Available Providers

      The react-admin project includes 5 Data Providers:

      Developers from the react-admin community have open-sourced Data Providers for many more backends:

      If you’ve written a Data Provider for another backend, and open-sourced it, please help complete this list with your package.

      Tip: In version 1, react-admin was called admin-on-rest (AOR), and developers shared Data Providers for even more backends. Due to breaking changes in v2, these providers are no longer working. Fortunately, Data Providers aren’t complex pieces of code, and using legacy Data Provider with a recent react-admin version requires minimal changes. If you are a maintainer of one of these projects, we would warmly welcome an upgrade.

      Usage

      As an example, let’s focus on the Simple REST data provider. It fits REST APIs using simple GET parameters for filters and sorting.

      Install the package to use this provider.

      Then, initialize the provider with the REST backend URL, and pass the result to the prop of the component:

      Here is how this Data Provider maps react-admin calls to API calls:

      Method nameAPI call
      Multiple calls to
      Multiple calls to

      Note: The simple REST client expects the API to include a header in the response to calls. The value must be the total number of resources in the collection. This allows react-admin to know how many pages of resources there are in total, and build the pagination controls.

      If your API is on another domain as the JS code, you’ll need to whitelist this header with an CORS header.

      The function accepts an HTTP client function as second argument. By default, it uses react-admin’s function as HTTP client. It’s similar to HTML5 , except it handles JSON decoding and HTTP error codes automatically.

      That means that if you need to add custom headers to your requests, you can just wrap the call inside your own function:

      Now all the requests to the REST API will contain the header.

      Tip: The most common usage of custom headers is for authentication. has built-on support for the token header:

      Now all the requests to the REST API will contain the header.

      Extending a Data Provider (Example of File Upload)

      As Data Providers are just objects, you can extend them with custom logic for a given method, or a given resource.

      For instance, the following Data Provider extends the provider, and adds image upload support for the call (react-admin offers an component that allows image upload).

      Using this technique, you can also combine two Data Providers for two backends into a single object, or use a Proxy to transform responses for all methods.

      Writing Your Own Data Provider

      APIs are so diverse that quite often, none of the available Data Providers suit you API. In such cases, you’ll have to write your own Data Provider. Don’t worry, it usually takes only a couple of hours.

      The methods of a Data Provider receive a request, and return a promise for a response. Both the request and the response format are standardized.

      Caution: A Data Provider should return the same shape in and for a given resource. This is because react-admin uses “optimistic rendering”, and renders the Edit and Show view before calling by reusing the response from if the user has displayed the List view before. If your API has different shapes for a query for a unique record and for a query for a list of records, your Data Provider should make these records consistent in shape before returning them to react-admin.

      For instance, the following Data Provider returns more details in than in :

      This will cause the Edit view to blink on load. If you have this problem, modify your Data Provider to return the same shape for all methods.

      Request Format

      Data queries require a method (e.g. ), a resource (e.g. ‘posts’) and a set of parameters.

      Tip: In comparison, HTTP requests require a verb (e.g. ‘GET’), an url (e.g. ‘http://myapi.com/posts’), a list of headers (like ) and a body.

      Standard methods are:

      MethodUsageParameters format
      Search for resources
      Read a single resource, by id
      Read a list of resource, by ids
      Read a list of resources related to another one
      Create a single resource
      Update a single resource
      Update multiple resources
      Delete a single resource
      Delete multiple resources

      Here are several examples of how react-admin can call the Data Provider:

      Tip: If your API supports more request types, you can add more methods to the Data Provider (for instance to support upserts, aggregations, or Remote Procedure Call). React-admin won’t call these methods directly, but you can call them in your own component thanks to the hook described in the Querying the API documentation.

      Response Format

      Data Providers methods must return a Promise for an object with a property.

      MethodResponse format
      The ids which have been updated
      The record that has been deleted
      The ids of the deleted records (optional)

      A is an object literal with at least an property, e.g. .

      Building up on the previous example, here are example responses matching the format expected by react-admin:

      Tip: The field in the response is optional. It enables the Application cache, a client-side optimization to speed up rendering and reduce network traffic. Check the Caching documentation for more details.

      Error Format

      When the API backend returns an error, the Data Provider should return a rejected Promise containing an object. This object should contain a property with the HTTP response code (404, 500, etc.). React-admin inspects this error code, and uses it for authentication (in case of 401 or 403 errors). Besides, react-admin displays the error on screen in a temporary notification.

      If you use , you don’t need to do anything: HTTP errors are automatically decorated as expected by react-admin.

      If you use another HTTP client, make sure you return a rejected Promise. You can use the class to throw an error with status in one line:

      Example Implementation

      Let’s say that you want to map the react-admin requests to a REST backend exposing the following API:

      getList

      getOne

      getMany

      getManyReference

      create

      update

      updateMany

      delete

      deleteMany

      Here is an example implementation, that you can use as a base for your own Data Providers:

      Using The Data Provider In Components

      React-admin stores the Data Provider passed to in a React context, so you can access it from anywhere in your code. To facilitate usage, react-admin provides many data provider hooks:

        Here is a glimpse of the hook usage:

        You will find complete usage documentation for the data provider hooks in the Querying the API documentation chapter.

        Real-Time Updates And Locks

        Teams where several people work in parallel on a common task need to allow live updates, real-time notifications, and prevent data loss when two editors work on the same resource concurrently.

        (an Enterprise Edition module) provides hooks and UI components to lock records, and update views when the underlying data changes. It’s based on the Publish / Subscribe (PubSub) pattern, and requires a backend supporting this pattern (like GraphQL, Mercure).

        For instance, here is how to enable live updates on a List view:

        Check the documentation for more details.

        Sours: https://marmelab.com/react-admin/DataProviders.html
        1. Tab acoustic guitar
        2. Gospel songs 2016
        3. Copart des moines
        4. Gravity 5 design
        5. Glade pods

        npm

        NPM VersionLicenseDownloads/weekGithub Issues

        A firebase data provider for the React-Admin framework. It maps collections from the Firebase database (Firestore) to your react-admin application. It's an npm package!


        Features

        • [x] Firestore Dataprovider (details below)
        • [x] Firebase AuthProvider (email, password)
        • [x] Login with: Google, Facebook, Github etc... (Example Here)
        • [x] Forgot password button... (Example Here)
        • [x] Firebase storage upload functionality

        Pull requests welcome!!

        Firestore Dataprovider Features

        • [x] Dynamic caching of resources
        • [x] All methods implemented;
        • [x] Filtering, sorting etc...
        • [x] Ability to manage sub collections through app configuration
        • [x] Ability to use externally initialized firebaseApp instance
        • [x] Override firestore random id by using "id" as a field in the Create part of the resource
        • [x] Upload to the firebase storage bucket using the standard field
        • [ ] Realtime updates, using ra-realtime
          • Optional watch collection array or dontwatch collection array

        Get Started

        or

        Demos Basic

        A simple example based on the React Admin Tutorial.

        Prerequisits

        • Create a collection in the firebase firestore database
        • Get config credentials using the dashboard

        Options

        import{FirebaseAuthProvider,FirebaseDataProvider,FirebaseRealTimeSaga}from'react-admin-firebase';constconfig={apiKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",authDomain: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",databaseURL: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",projectId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",storageBucket: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",messagingSenderId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",};// All options are optionalconstoptions={// Use a different root document to set your resource collections, by default it uses the root collections of firestorerootRef: 'root-collection/some-doc'|()=>'root-collection/some-doc',// Your own, previously initialized firebase app instanceapp: firebaseAppInstance,// Enable logging of react-admin-firebaselogging: true,// Resources to watch for realtime updates, will implicitly watch all resources by default, if not set.watch: ['posts'],// Resources you explicitly dont want realtime updates fordontwatch: ['comments'],// Authentication persistence, defaults to 'session', options are 'session' | 'local' | 'none'persistence: 'session',// Disable the metadata; 'createdate', 'lastupdate', 'createdby', 'updatedby'disableMeta: false,// Have custom metadata field names instead of: 'createdate', 'lastupdate', 'createdby', 'updatedby'renameMetaFields: {created_at: 'my_created_at',// default: 'createdate'created_by: 'my_created_by',// default: 'createdby'updated_at: 'my_updated_at',// default: 'lastupdate'updated_by: 'my_updated_by',// default: 'updatedby'},// Prevents document from getting the ID field added as a propertydontAddIdFieldToDoc: false,// Adds 'deleted' meta field for non-destructive deleting functionality// NOTE: Hides 'deleted' records from list views unless overridden by filtering for {deleted: true} softDelete: false,// Changes meta fields like 'createdby' and 'updatedby' to store user IDs instead of email addressesassociateUsersById: false,// Casing for meta fields like 'createdby' and 'updatedby', defaults to 'lower', options are 'lower' | 'camel' | 'snake' | 'pascal' | 'kebab'metaFieldCasing: 'lower',// Instead of saving full download url for file, save just relative path and then get download url// when getting docs - main use case is handling multiple firebase projects (environments)// and moving/copying documents/storage files between them - with relativeFilePaths, download url// always point to project own storagerelativeFilePaths: false,// Add file name to storage path, when set to true the file name is included in the pathuseFileNamesInStorage: false// Use firebase sdk queries for pagination, filtering and sortinglazyLoading: {enabled: false},// Logging of all reads performed by app (additional feature, for lazy-loading testing)firestoreCostsLogger: {enabled: false, localStoragePrefix // optional}}constdataProvider=FirebaseDataProvider(config,options);constauthProvider=FirebaseAuthProvider(config,options);constfirebaseRealtime=FirebaseRealTimeSaga(dataProvider,options);

        Data Provider

        import*asReactfrom'react';import{Admin,Resource}from'react-admin';import{PostList,PostShow,PostCreate,PostEdit}from"./posts";import{FirebaseAuthProvider,FirebaseDataProvider,FirebaseRealTimeSaga}from'react-admin-firebase';constconfig={apiKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",authDomain: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",databaseURL: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",projectId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",storageBucket: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",messagingSenderId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",};constoptions={};constdataProvider=FirebaseDataProvider(config,options); ... <AdmindataProvider={dataProvider}><Resourcename="posts"list={PostList}show={PostShow}create={PostCreate}edit={PostEdit}/></Admin>...

        Auth Provider

        Using the you can allow authentication in the application.

        constdataProvider=FirebaseDataProvider(config);constauthProvider=FirebaseAuthProvider(config); ... <AdmindataProvider={dataProvider}authProvider={authProvider}> ...

        Also checkout how to login with: Google, Facebook, Github etc... (Example Here)

        And you might want a "Forgot password" button... (Example Here)

        Note

        To get the currently logged in user run , this will return the firebase user object, or null if there is no currently logged in user.

        Realtime Updates!

        NOTE: Realtime updates were removed in v3.x (see https://github.com/marmelab/react-admin/pull/3908). As such, v3.x also does not support Realtime Updates. However, much of the original code used for this functionalaity in v2.x remains - including the documentation below. For updates on the implementation of realtime please follow these issues:

        Get realtime updates from the firebase server instantly on your tables, with minimal overheads, using rxjs observables!

        ... import{FirebaseRealTimeSaga,FirebaseDataProvider}from'react-admin-firebase'; ... constdataProvider=FirebaseDataProvider(config);constfirebaseRealtime=FirebaseRealTimeSaga(dataProvider); ... <AdmindataProvider={dataProvider}customSagas={[firebaseRealtime]}> ...

        Realtime Options

        Trigger realtime on only some routes using the options object.

        ... constdataProvider=FirebaseDataProvider(config);constoptions={watch: ['posts','comments'],dontwatch: ['users']}constfirebaseRealtime=FirebaseRealTimeSaga(dataProvider,options); ...

          Now all local changes in the library source code can be tested immediately in the demo app.

          Run tests

          To run the tests, either watch for changes or just run all tests.

            paypal

            Keywords

            none

            Sours: https://www.npmjs.com/package/react-admin-firebase
            React JS, Material UI \u0026 Firebase Dashboard Tutorial #2 - Navigation

            Auth Providers

            Login

            React-admin lets you secure your admin app with the authentication strategy of your choice. Since there are many possible strategies (Basic Auth, JWT, OAuth, etc.), react-admin delegates authentication logic to an .

            Enabling Auth Features

            By default, react-admin apps don’t require authentication. To restrict access to the admin, pass an to the component.

            React-admin delegates the Authentication and Authorization logic to an object that you must write, the .

            • “Authentication” logic allows to restrict an app to identified users only, and reject anonymous users
            • “Authorization” logic allows to tweak the features based on user permissions

            Anatomy Of An

            What’s an ? Just like a , an is an object that handles authentication and authorization logic. It exposes methods that react-admin calls when needed, and that you can call manually through specialized hooks. The methods must return a Promise. The simplest is:

            You can get more details about input params, response and error formats in the Building Your Own Auth Provider section below.

            Tip: In react-admin version 2.0, the used to be a function instead of an object. React-admin 3.0 accepts both object and (legacy) function authProviders.

            Available Providers

            It’s very common that your auth logic is so specific that you’ll need to write your own . However, the community has built a few open-source Auth Providers that may fit your need:

            Beyond ready-to-use providers, you may find help in these third-party tutorials about integrating more authentication backends:

            If you have released a reusable , or a tutorial for another auth backend, please open a PR to add it to this list!

            Authentication

            Let’s see when react-admin calls the , and how customize it depending on your authentication strategy and backend.

            Login Configuration

            Once an admin has an , react-admin enables a new page on the route, which displays a login form asking for a username and password.

            Default Login Form

            Upon submission, this form calls the method. React-admin expects this method to return a resolved Promise if the credentials are correct, and a rejected Promise if they’re not.

            For instance, to query an authentication route via HTTPS and store the credentials (a token) in local storage, configure the as follows:

            Once the promise resolves, the login form redirects to the previous page, or to the admin index if the user just arrived.

            Tip: It’s a good idea to store credentials in , as in this example, to avoid reconnection when opening a new browser tab. But this makes your application open to XSS attacks, so you’d better double down on security, and add an cookie on the server side, too.

            If the login fails, should return a rejected Promise with an Error object. React-admin displays the Error message to the user in a notification.

            Sending Credentials To The API

            Now the user has logged in, you can use their credentials in the to communicate with the data API. As explained in the Data providers documentation, and take an as second parameter. That’s the place where you can change request headers, cookies, etc.

            For instance, to pass the token obtained during login as an header, configure the Data Provider as follows:

            Now the admin is secured: The user can be authenticated and use their credentials to communicate with a secure API.

            If you have a custom REST client, don’t forget to add credentials yourself.

            Catching Authentication Errors On The API

            When the user credentials are missing or become invalid, a secure API usually answers to the with an HTTP error code 401 or 403.

            Fortunately, each time the returns an error, react-admin calls the method. If it returns a rejected promise, react-admin calls the method immediately, and asks the user to log in again.

            So it’s up to you to decide which HTTP status codes should let the user continue (by returning a resolved promise) or log them out (by returning a rejected promise).

            For instance, to log the user out for both 401 and 403 codes:

            When returns a rejected Promise, react-admin redirects to the page, or to the url. That means you can override the default redirection as follows:

            It’s possible to not log the user out, and to instead redirect them. You can do this by passing to the along with an url.

            When returns a rejected Promise, react-admin displays a notification to the end user, unless the is . That means you can disable the notification on error as follows:

            Checking Credentials During Navigation

            Redirecting to the login page whenever a REST response uses a 401 status code is usually not enough. React-admin keeps data on the client side, and could briefly display stale data while contacting the server - even after the credentials are no longer valid.

            Fortunately, each time the user navigates to a list, edit, create or show page, react-admin calls the method. If this method returns a rejected Promise, react-admin calls and redirects the user to the login page. So it’s the ideal place to make sure the credentials are still valid.

            For instance, to check for the existence of the authentication data in local storage:

            If the promise is rejected, react-admin redirects by default to the page. You can override where to redirect the user in , by rejecting an object with a property:

            Tip: If both and return a redirect URL, the one from takes precedence.

            If the promise is rejected, react-admin displays a notification to the end user. You can customize this message by rejecting an error with a property:

            You can also disable this notification completely by rejecting an error with a with a value:

            Logout Configuration

            If you enable authentication, react-admin adds a logout button in the user menu in the top bar (or in the sliding menu on mobile). When the user clicks on the logout button, this calls the method, and removes potentially sensitive data from the Redux store. Then the user gets redirected to the login page. The two previous sections also illustrated that react-admin can call itself, when the API returns a 403 error or when the local credentials expire.

            It’s the responsibility of the method to clean up the current authentication data. For instance, if the authentication was a token stored in local storage, here is the code to remove it:

            Logout button

            The method is also a good place to notify the authentication backend that the user credentials are no longer valid after logout.

            After logout, react-admin redirects the user to the string returned by - or to the url if the method returns nothing. You can customize the redirection url by returning a route string, or to disable redirection after logout.

            User Identity

            React-admin can display the current user name and avatar on the top right side of the screen. To enable this feature, implement the method:

            React-admin uses the and the (an image source, or a data-uri) in the App Bar:

            User identity

            Tip: You can use the field to identify the current user in your code, by calling the hook:

            Authorization

            Some applications may require fine-grained permissions to enable or disable access to certain features depending on user permissions. Since there are many possible strategies (single role, multiple roles or rights, ACLs, etc.), react-admin delegates the permission logic to .

            By default, a react-admin app doesn’t require any special permission on list, create, edit, and show pages. However, react-admin calls the method before navigating to these pages, and passes the result to the main page component (, , etc.). You can then tweak the content of these pages based on permissions.

            Additionally, in custom pages, you can call the hook to grab the user permissions.

            User Permissions

            React-admin calls the whenever it needs the user permissions. These permissions can take the shape you want:

            • a string (e.g. ),
            • an array of roles (e.g. )
            • an object with fine-grained permissions (e.g. )
            • or even a function

            The format of permissions is free because react-admin never actually uses the permissions itself. It’s up to you to use them in your code to hide or display content, redirect the user to another page, or display warnings.

            Following is an example where the stores the user’s permissions in upon authentication, and returns these permissions when called with :

            Getting User Permissions In CRUD Pages

            By default, react-admin calls for each resource route, and passes the permissions to the , , , and view components. So the , , and components all receive a prop containing what returned.

            Here is an example of a view with a conditional Input based on permissions:

            Getting User Permissions In Custom Pages

            In custom pages, react-admin doesn’t call . It’s up to you to call it yourself, using the hook:

            Role-Based Access Control (RBAC)

            React-admin Enterprise Edition contains the ra-rbac module, which adds fine-grained permissions to your admin.

            You can define permissions for pages, fields, buttons, etc. in the . This means this RBAC system can use any data source you want (even an ActiveDirectory).

            For instance, the above demo uses the following set of permissions:

            Ra-rbac lets you add fine-grained permissions (almost) without touching your application code (you don’t need to add blocks everywhere).

            Check the module documentation to learn more.

            Building Your Own Auth Provider

            Here is the interface react-admin expect objects to implement.

            Tip: If you’re a TypeScript user, you can check that your is correct at compile-time using the type:

            Request Format

            React-admin calls the methods with the following params:

            MethodUsageParameters format
            Log a user in whatever fields the login form contains
            Check if a dataProvider error is an authentication error the error returned by the
            Check credentials before moving to a new route whatever params passed to - empty for react-admin default routes
            Log a user out
            Get the current user identity
            Get the current user credentials whatever params passed to - empty for react-admin default routes

            Response Format

            methods must return a Promise. In case of success, the Promise should resolve to the following value:

            MethodResolve ifResponse format
            Login credentials were accepted
            Error is not an auth error
            User is authenticated
            Auth backend acknowledged logout route to redirect to after logout, defaults to
            Auth backend returned identity
            Auth backend returned permissions free format - the response will be returned when is called

            Error Format

            When the auth backend returns an error, the Auth Provider should return a rejected Promise, with the following value:

            MethodReject ifError format
            Login credentials weren’t accepted error message to display
            Error is an auth error route to redirect to after logout, and whether to disable error notification
            User is not authenticated route to redirect to after logout, message to notify the user
            Auth backend failed to log the user out
            Auth backend failed to return identity free format - returned as when is called
            Auth backend failed to return permissions free format - returned as when is called

            Hooks

            Hook

            This hook returns a callback allowing to call , so it’s used in Login forms.

            For instance, here is how to build a custom Login page based on email rather than login for authentication:

            Then pass the custom Login form to , as follows:

            Hook

            If you add custom pages, or if you create an admin app from scratch, you may need to secure access to pages manually. That’s the purpose of the hook, which calls the method on mount, and redirects to login if it returns a rejected Promise.

            If you call with a parameter, this parameter is passed to the call as second parameter. that allows you to add authentication logic depending on the context of the call:

            The hook is optimistic: it doesn’t block rendering during the call. In the above example, the component renders even before getting the response from the . If the call returns a rejected promise, the hook redirects to the login page, but the user may have seen the content of the component for a brief moment.

            Hook

            To avoid rendering a component, and to force waiting for the response, use instead of . It calls on mount and returns an object with 3 properties:

            • : just after mount, while the is being called. once the has answered.
            • : the opposite of .
            • : while loading. then or depending on the response.

            You can render different content depending on the authenticated status.

            Hook

            Just like , returns a callback that you can use to call . Use it to build a custom Logout button, like the following:

            Then pass the Logout button to the component, as follows:

            Hook

            You may want to use the current user name, avatar, or id in your code. for that purpose, call the hook, which calls on mount.

            Here is an example Edit component, which falls back to a Show component is the record is locked for edition by another user:

            Hook

            You might want to check user permissions inside a custom page. That’s the purpose of the hook, which calls the method on mount, and returns the result when available:

            The hook is optimistic: it doesn’t block rendering during the call. In the above example, the component renders even before getting the response from the . To avoid a blink in the interface while the is answering, use the return value of :

            Hook

            React-admin also exposes a hook, returning a callback to call on demand. In practice, you seldom need this hook - covers most authorization needs, and manages the loading state for you.

            Here is an example usage:

            Components

            Component

            The component calls the hook, and renders its child component - unless the authentication check fails. Use it as an alternative to the hook when you can’t use a hook, e.g. inside a function:

            Recipes

            Customizing The Login and Logout Components

            Using is enough to implement a full-featured authorization system if the authentication relies on a username and password.

            But what if you want to use an email instead of a username? What if you want to use a Single-Sign-On (SSO) with a third-party authentication service? What if you want to use two-factor authentication?

            For all these cases, it’s up to you to implement your own component, which will be displayed under the route instead of the default username/password form, and your own component, which will be displayed in the sidebar. Pass both these components to the component:

            Use the and hooks in your custom and components.

            Tip: By default, react-admin redirects the user to ‘/login’ after they log out. This can be changed by passing the url to redirect to as parameter to the function:

            Restricting Access to Resources or Views

            Permissions can be useful to restrict access to resources or their views. To do so, you must use a function as the only child. React-admin will call this function with the permissions returned by the .

            Note that the function returns an array of React elements. This is required to avoid having to wrap them in a container element which would prevent the from working.

            Tip: Even if that’s possible, be careful when completely excluding a resource (like with the resource in this example) as it will prevent you to reference this resource in the other resource views, too.

            Restricting Access to Fields and Inputs

            You might want to display some fields or inputs only to users with specific permissions. By default, react-admin calls the for permissions for each resource routes, and passes them to the , , , and components.

            Here is an example of a view with a conditional Input based on permissions:

            This also works inside an view with a , and you can even hide a completely:

            What about the view, the , ? It works there, too. And in the next example, the prop is passed down to a custom selector.

            Restricting Access to the Dashboard

            React-admin injects the permissions into the component provided as a , too:

            What if you want to check the permissions inside a custom menu? Much like getting permissions inside a custom page, you’ll have to use the hook:

            Sours: https://marmelab.com/react-admin/Authentication.html

            Firebase react admin

            Building an admin console in react-admin

            I’m going to make a wild guess here – if you’ve ever had to build an admin panel at work, you probably weren’t incredibly excited about it. Every business needs an admin UI to manage the day to day – looking up a user’s address, marking an order as refunded, resetting a password – but they can be a bit of a pain to build and maintain. If you’re using React though, react-admin might just make things a bit easier.

            This tutorial is going to walk through how to build a fully functional admin panel in react-admin with auth. To get the most out of this tutorial, you'll want to be comfortable with React and basic frontend/backend interaction.

            Sidebar: With Retool, you can build admin panels and internal tools remarkably fast. Get started for free 👉

            What's react-admin?

            React-admin is a framework that uses React, Material UI, React Router, Redux, and React-final-form to give you a unified admin framework that you can customize to fit your dashboard building needs. It’s developed and maintained by a dev shop called Marme Lab (I’m guessing they got tired of building the same admin UIs for their clients over and over again).

            React-admin is a frontend framework, so it’s built to use your ** existing ** REST / GraphQL APIs. It allows you to easily create frontend admin applications that interact with your backend in a standardized way through data providers.

            What are data providers, you say?

            React-admin is unique in the way that it processes the interactions between your frontend and backend:

            image6

            It uses something called an adapter approach (data providers): the data provider acts as the interface between the framework and your backend → it takes care of the querying and response handling between the frontend & your respective backend API(s) to allow you to focus on your dashboard building in modular steps.

            To start, react-admin gives us data providers that can be used to backwards engineer our API’s if they haven’t already been built, or in the more likely scenario that they already exist, you can write your own data providers to interface with your existing APIs**.**

            At a high level, react-admin offers some pretty interesting features (we’ll dive into one of them later):

            • Relationship support
            • Conditional formatting
            • Full-featured datagrids
            • Optimistic rendering

            Long story short: it’s a powerful framework.

            How to build your own admin app

            Prerequisites:

            • Install ( version should be > 8)
            • Install

            Let’s start out by creating a new folder to store our codebase for our new admin app. I’m going to call mine react-admin-tutorial (very creative, I know). After dropping into your new directory, let’s create a new react application with create-react-app:

            This will create a new empty React app that we can use to jumpstart our development through Facebook's tool. Now we can move into the directory holding our new app:

            That will install the react-admin package and the data provider we need to connect to our fake API. Our app will be running at localhost:3000. Now it’s time to work on building out the app.


            Subscribe to the Retool monthly newsletter
            Once a month, we send out top stories (like this one) along with Retool tutorials, templates, and product releases.


            Building the admin app

            For this tutorial, we are going to use JSONPlaceholder - this is a fake REST API that we can use to develop our frontend with fake data. This way, we’ll be able to focus on the core of react-admin without worrying too much about writing custom data providers yet.

            First off, replace with the following to get us off the ground:

            Now you should see something like the screenshot below; this is the default page you get when you supply react-admin with the data provider it expects.

            Image-2020-03-23-at-4.13.04-PM

            Now we’ll bring in our first resource:

            The component allows us to tell react-admin that we’d like to fetch and display a resource with the name “users.” The dataprovider processes this and makes a request according to its interface – in this case to https://jsonplaceholder.typicode.com/users – and then displays that to the user using the component. This “list” prop tells react-admin to use to take whatever data the resource receives and make it’s best guest to format the initial data grid.

            We’ll use this initial with all of our resources to generate some initial list code - it spits out its best guess to the console for us to use. Here’s what things should look like:

            Image-2020-03-23-at-4.20.34-PM

            The guesser gets us 90% of the way there, but we want to customize the columns to have slightly more human-readable labels. Inspect the table element in your browser, and copy the Guessed List that you see in your console (inspect element → console). It should look something like this:

            We’ll create a new component that overrides these suggestions. Create a folder called in and paste the copied code in a new file called (). It should look like this :

            The list is the main component here, handling the majority of the work (pagination, etc.) but the actual rendering of the data is left to the , which renders a table where each record has one of the child components / fields. These fields’ data is sourced based on the source name that you provide, which matches up with what is received by the dataprovider from the API.

            While we’re here, let's refine this list a bit to show how you can customize it. Here’s what I am going to do:

            • Get rid of the id and username field to save screen space
            • Disable sorting in the phone field, as all fields default to being sortable
            • Change the street address & company name field label with the label prop

            The changed fields should look like this :

            Now we’ll need to replace the with our new list in the component. Head back to , and add in a line up top to import our new component:

            Now replace in the prop of our with the UserList:

            With those changes, we should have a more concise and usable view of the users resource:

            image1-1

            It’s worth mentioning that you can replace any of the components inside the datagrid with your own, so if you want to create your own fields to suit your needs, just drop them in and make sure to include the source prop.

            To show you what this would look like:

            Paste this in and modify the email field in to reflect our new custom field.

            By swapping out the email fields, we customize the component that’ll render the email data record. As you can see above, we modified the original functionality to have the link be a mailto so you can click on it and open an email to the person. We also added an email icon with custom styles using .

            Note: You can do plenty more in customizing the fields to your heart's desire that won’t be covered here, but this gives you a solid template to build off and create your own custom fields.

            Let’s repeat this process with posts. There’s something else we need to tackle here: relationship handling. In our sample API, querying the posts resource gives us this JSON:

            image3

            Notice how in each document there’s a attached. This allows us to create a reference between the user and the post within the admin panel, and thankfully react-admin automatically detects this for us.

            To show the posts resource in our panel, let’s add another resource component:

            Again, we’ll use the to generate the guessed fields. If you can see something like this (click on the “posts” tab), you should be in good shape.

            Image-2020-03-23-at-4.49.55-PM

            We’re going to want to update these column names, so we’ll go through the same workflow as above. Go ahead and copy the code from the guessed list in the console and paste into a new file: .

            It should look like this:

            The component above allows us to create a relationship with the user resource. We identify the foreign key with the prop and create the relationship with the reference prop.

            Also, make sure to change the list prop for the new posts resource to reference our custom in – import the and then replace in the post resource’s list prop.

            Note: I went ahead and changed the , what is actually displayed for the reference inside the table, to display the name. You can display anything contained within a user object by passing the source name for the user resource. Logically speaking, any child of a reference field will be working with the record of the referenced resource. In this case, the user resource is referenced so the child textfield’s source will be derived from the user resource.

            Next, we’re going to add an edit button to set us up to be able to modify content. We’ll start by adding a new component into our : an at the bottom (and adding it into the import from react-admin up top).

            Much like the list prop, we need to pass an edit prop to our resource in order to be able to have react-admin generate edit capabilities. We’ll use a component called and pass that to the posts resource in (make sure to add it into the import up top):

            This guesser will generate the initial edit code for the posts that we can then customize.

            Once you have the edit guesser wired in, check that the edit functionality works by clicking edit on one of the post records. It should bring you to a screen where you can make edits to the fields of the object being modified – since we’re using a test api, changes made will not persist beyond the local frontend state. In a real application though, the edit functionality would interface with the backend to make the necessary changes as you make them to the objects on the frontend.

            Once you verify this is working, take the guessed code from the console, and put it in . It should look something like this:

            Note: you’ll have to import previously unused components – , , , , and .

            Let’s copy and paste the edit code now and create a component. It takes almost the same structure of the edit component. Your file should like this:

            The only difference between the edit and create components is that we’re using two different wrapper components – and – which each handle the data processing & interfacing with the backend uniquely. Make sure to add the component into your import statement up top.

            As you might expect, we need to supply the create prop in our resource too. Start by adding our two new components from into the import on top of ( and ), and then add them into the posts resource:

            While it’s not apparent in our code, react-admin bakes in a feature into our admin dashboard that enables deletion for every resource that has an edit component. If you check your edit screen on the Posts resource, you’ll see the delete button in the bottom right.

            (Note that after clicking delete, the frontend will show that it was deleted due to optimistic rendering, but since our fake api disallows PUT/DELETE requests, this should error out after a few seconds. Not to worry though, once you’re hooked up to your live API, you’ll be fine.)

            Although we only covered the basics with edit/create components, you can customize them even further with these props:

            Also, if we want to create a rich input experience, we can customize the input fields with props like:

            • source
            • label
            • validate
            • helperText
            • className: A class name (usually generated by JSS) to customize the look and feel of the input element itself
            • formClassName: Class name to be applied to the container of the input (e.g. the <div> forming each row in <SimpleForm>)
            • fullWidth: If true, the input will expand to fill the form width. Defaults to false.

            Optimistic Rendering

            Let’s talk a bit about why react-admin is so fast. Optimistic rendering means that react-admin renders changes to the client side state before the server has returned with a response for a particular action. For example, if you deleted a user, react-admin will render the user as deleted before the request actually goes through and responds. In reality, react-admin puts an approximately 5 second delay on requests to resources initiated by the user. This allows for this kind of fast rendering and also the ability to undo actions.

            Say you accidentally hit delete: you can undo your actions quickly with an undo button and react-admin will cancel the request to delete the user before even sending it to the server. Overall, optimistic rendering let’s the user experience a more seamless UX when compared to a more traditional model that waits for the server to return in order to render. That being said, there are obviously tradeoffs inherent in each model.

            Some notes about

            If you’ve been following along, you’ve seen that the component is integral to building out an admin app with react-admin, so it’s worth understanding what’s going on behind the scenes. The lists acts as the data facilitator / processor / interface for the application’s data List components – i.e. the components that render resource data for, say, users in a list. All the children of that list can be thought of as dumb, as they are mainly presentational in nature, whereas the itself handles the connection to the data and all the associated processes. For example, if you want to control a filter, pagination, or sorting, you need to deal with the components of a parent component.

            As your application grows (and maybe scope creep starts happening), being able to leverage these customizable capabilities becomes important to fit your needs.

            Adding Authentication

            Nobody wants their internal APIs to be publicly accessible, so let’s quickly run through how we’d add some authentication into our admin console. By default, react-admin has a login page ready and setup, but it’s authentication provider agnostic, meaning you can use whatever identity service you want with react-admin, assuming you write an authentication provider.

            React-admin expects five methods from our authentication provider: login, logout, checkError, checkAuth, and getPermissions . We’ll add our own basic ones in. Let’s put them in a new directory and file, :

            Then go to your admin component in and add the prop . Make sure to remember to add a new import statement for the component as well:

            After that, you’ll have a functioning admin app with a login page. Granted, some of the services and backend still need to be wired up in a production app, but you’ve still accomplished a lot! The big thing to take away from this is that react-admin makes it insanely easy to interact with your existing data that sit behind existing APIs, as long as you can fulfill the data contracts between the data providers and the API services.

            For now, let’s implement a real authentication service, firebase auth. First you’re going to need to install : this package is an built specifically for use with react-admin and firebase.

            Next, you’ll need to go to firebase and create a new project, and then go to settings to retrieve your auth config. Once you have it, create an auth object in src/app.js like below below:

            You’ll notice that the main piece is the firebase config, and beyond that you can set options and pass them as an optional argument to . These options would allow you to customize the authentication handling, but we’ll leave it to the defaults for now.

            This should set us up with a fully functioning login page. If we create a user in the firebase console with a username(email) and password then try to login to our admin app, we should be able to successfully get through.

            Screen-Recording-2020-03-23-at-05.44-PM--1-

            The Final Code

            You see the code for the final functioning app on GitHub.

            Retool gives you a complete set powerful building blocks for building internal tools: Assemble your app in 30 seconds by dragging and dropping from 50+ pre-built components. Connect to dozens of data integrations and anything with a REST or GraphQL API. Get started for free 👉

            Where to go from here

            React-admin lets us get off the ground and build a super functional admin app in minutes, not months. It abstracts the nasty building and maintaining that us developers are usually tasked with. But where do you go from here if you want keep building?

            If you want to use your own API, react-admin’s tutorial is a must read. At a high level, this is what the dataProvider interface needs to look like:

            The following is a list of existing data providers I got from marmelab.com (the developers and maintainers of react-admin):

            Check these out to see if any fit your stack before you try and write your own. Many of these will allow you to jumpstart your dataprovider development, if not eliminate you having to write one.

            I will say that what you need to do to write your dataprovider is highly dependent on your api schema. If it’s standard, it will probably either fall under one of the prebuilt data providers listed above, or be fairly easy to implement. But if your api isn’t as standard, it might take more than a few minutes to get the data provider working.

            If you’re building an admin app or custom dashboard or for your organization, check out Retool! Retool saves you a bunch of time and hassle by letting you drag and drop components like tables, search boxes, and buttons, and connecting them to SQL or Javascript on the backend. You can also build off of templates to customize your dashboard with custom components that interface with your backend.

            Sours: https://retool.com/blog/building-an-admin-console-in-react-admin/
            React JS, Material UI \u0026 Firebase Dashboard Tutorial #2 - Navigation

            .

            Similar news:

            .



            61 62 63 64 65