portal
-
Why do I insist on getting up at six
-
Vite + React + TS
-
# Vite react + TS
preface
-
The permission questions in the project are very frequent in the interview. Whether it is VUE or React, you look bored and strange when asked. In fact, it is good to answer according to your project, and give you your own plan corresponding to business scenarios. It’s not that weird.
-
Permissions are closely related to businesses, and application scenarios are also extensive, such as PC and APP. Now you can see the distinction of permissions in any commercial website.
-
On the authority of the problem, we do not think too complex, according to their actual business, to achieve the login authority, routing authority, button level authority
-
This tutorial is more to provide you with a permission of an idea, if you encounter more complex business scenarios to comb out and then make the corresponding implementation is good, you can also ask me to exchange links.
Permission Application Scenarios
- What we care about is not the user login permission, how to put the token, usually put headers in the backend, how to deal with the expiration time of the token, etc. It depends on their design, we just need to deal with our own business logic, whether to put it in the browser, whether it needs to exist for a long time. Or the browser closes and disappears, etc. These are to communicate with the product side
- What are the unlogged permissions of the user, what are the forms of expression, and what functions can be used in the project, etc. When triggering functions requiring permissions, whether to prompt the user to login, or directly jump to the login page, or pop up a login box for the user to login directly?
- Route permission Whether a route is a dynamic route is generated by the configuration page. The route data is returned by the back end, the front end dynamically renders the route, or the front end writes a dead-end route. Determine whether the route is displayed by flag. Removing the token, or displaying a prompt page, reminding users that they do not have this permission and so on, are all based on your specific business scenarios. It is good to display different product ideas
const PrivateRoute: FC<RouteProps> = (props) = > {
const logged = sessionStorage.getItem("token");
const history = useHistory();
// Check whether there is a token. If there is a token, display it. If there is no route, do not display it
return logged ? (
<Route {. props} / >
) : (
<Result
status="403"
title="403"
subTitle={"No permissions "}extra={
<Button type="primary" onClick={()= >History. push("/login")}> Jump to login</Button>} / >
);
};
Copy the code
- Role authorization
- Module permissions include super administrator, general administrator, non-administrator, visitor, and so on. What kind of permissions and functions each role corresponds to and how to display, which is well connected with the product business, corresponding to display different permissions information is good.
- Component permissions
- Component permissions are rarely used in services. They are similar to button permissions. The specific business that still wants to see your project, do processing again
- Button permissions
- Button is also a component button permissions are basically relatively simple, is to show not to show, or button display, when requesting the interface, thickness to make a judgment, whether the operation has permissions.
- The following is the permission processing of our project
/** * button permission check */
function AuthorizedButton({ children, authority, render, noMatch, }: AuthorizedProps) {
// The current write dead button permission, real scenarios should have configuration pages, through the interface to return the corresponding permission, and then put in permission
const [permissions] = useState<string[] > ["button"."button1"."button2"]);
const result = checkPermissions(
authority,
permissions,
render ? render() : children,
noMatch
);
return <>{result}</>;
}
Copy the code
-
The core logic
export type IAuthorityType =
| undefined
| string
| string[]
| Promise<boolean>
| ((permissions: string[]) = > boolean | Promise<boolean>);
/** * General permission check method *@param authority- Button permission determination *@param permissions- Current permission *@param target- Passed components *@param Exception- Failed component */
constcheckPermissions = <T, K>( authority: IAuthorityType, permissions: string[] = [], target: T, Exception: K ): T | | K React. ReactNode = > {/ / not determine permissions. View all if (! authority) { return target; IsArray (authority)) {if (permissions. Some ((item) => author.includes (item))) {return target; } if ( permissions.length > 0 && permissions.every((item) => authority.includes(item)) ) { return target; } return Exception; } // String handles if (Typeof Authority === "string") {if (permissions. Some ((item) => authority === = item)) {return target; } return Exception; If (authority instanceof Promise) {return (<PromiseRender<T, K> ok={target} error={Exception} promise={authority} /> ); } // Function handle if (typeof Authority === "Function ") {const promise = authority(permissions); Promiseif ((Promise as Promise< Boolean >) instanceof Promise) {return (<PromiseRender<T, K> ok={target} error={Exception} promise={promise as Promise<boolean>} /> ); } if (promise) { return target; } return Exception; } throw new Error("Unsupported parameters"); };Copy the code
- Page use Cases
import React from "react";
import Authorized from "@/components/Authorized";
// General permission wrapper processing permission design must be determined with the back segment, which has permissions, which does not, including routing permissions, page permissions, button level permissions.
export default function Demo() {
return (
<>
<AuthorizedButton authority="hello">Hello world</AuthorizedButton>
<AuthorizedButton authority={["hello","word"]} >
Hello world
</AuthorizedButton>
<AuthorizedButton
authority={["hello","word"]}
render={()= > <div>Hello world</div>} / ><AuthorizedButton
authority={()= > true}
render={() => <div>Hello world</div>} / ></>
);
}
Copy the code
Interconnecting with the back-end
-
Generally we have a permission configuration page, the permission configuration page can configure the project administrator, non-administrator permissions, and the corresponding role permissions, each permission corresponds to the code, whether it is 1,2,3, or something you and the background handle it, ok
-
Level, including button said, actually button is also a component, the key is how do you want to show, have permissions show, is nothing to show, this not settled yet, look at your products business mood, you according to the business to do good, the second is the encapsulation of the code, because your configuration access data, finally will want to return to the corresponding project, Or front-end processing, the back-end is just a transfer, the final processing data are to you yourself. Don’t dig a hole for yourself.
conclusion
- Permissions are a simple thing, true or false,
- Click to join the 6 a.m. clock group
- Github address (Github updates faster than documents, with lots of comments added to documents) Github address