preface

In daily business development, we often have a similar requirement: edit function can only be operated by part of the whitelist, otherwise set to Disabled. So how do we implement the whitelist requirement?

Whitelist: The concept of whitelist corresponds to blacklist. Whitelisted users are allowed to pass. Users that are not on the whitelist cannot pass. The blacklist allows users who are not on the blacklist to pass.

implementation

Principle: The user’s login account is obtained through the cookie and whitelisted

Cookie handling

throughdocument.cookieThe cookie is a string, and each pair of key-values needs to be converted into an object

/** ** @param STR document.cookie * @returns */ function cookieParse(STR: string): any {const cookie: any = {}; const cookieArr = str.split('; '); for (let i = 0; i < cookieArr.length; i++) { const cookieItem = cookieArr[i].split('='); CookieItem [0].length > 1 && cookieItem[1]) {cookie[cookieItem[0].trim()] = cookie[cookieItem[0].trim()] =  cookieItem[1]; } } return cookie; }Copy the code

Method to obtain the cookie format

Whitelist processing

Principle: By judging whether the user in the cookie can be obtained in the specified whitelist list, return true if there is, otherwise return false

/** ** @param cookiestr document.cookie Cookie * @param userName key * @returns */ function ifEditWhiteList(cookiestr: string,userName:string): boolean { const whiteList = [ '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', ]; // Cookie does not exist if (! cookiestr) { return false; } // Call cookieParse to get cookie const cookie = cookieParse(cookiestr); // The value of key does not exist if (! cookie[userName]) { return false; } const email = cookie[userName].replace(/"/g, ''); console.log('email', email); return whiteList.indexOf(email) ! = = 1;Copy the code

The result looks like this:

conclusion

Because whitelisting requirements are ubiquitous, encapsulating a set of methods can improve development efficiency