preface

Recently, we sorted out the token auto-refresh process under the front and back end separation, and then there is the sharing of a nice tree shuttle box and further processing of the tree shuttle box request data. Here’s a brief description.

The body of the

Automatic Token Refresh

  1. Tokens are specially processed data that provides enough information to authorize the user to perform an operation. Or allow the client to obtain additional information about the authorization process (and then complete it). In other words, a token is information that allows the authorization process to be performed. Whether the client (or any party other than the authorization server) can read or parse this information is implementation-defined. The important thing is that the client takes this information and then uses it to access the resource. The JSON Web Token (JWT) specification defines a way in which common token information can be represented by an implementation.

  2. Two commonly used types are: access tokens and refresh tokens. The access token carries the necessary information to access the resource directly. In other words, when the client passes the access token to the server that manages the resource, the server can use the information contained in the token to determine whether the client is authorized. Access tokens usually have expiration dates and are transient.

    The refresh token contains the information needed to get a new access token. In other words, the client can use the refresh token to obtain a new access token issued by the authentication server whenever the access token requires access to a specific resource. Common use cases include obtaining a new access token after an old one has expired, or accessing a new resource for the first time. Refresh tokens can also expire, but with considerable longevity. Refresh tokens are usually subject to strict storage requirements to ensure that they do not leak. They can also be blacklisted by authorized servers.

  3. Function of the token During the generation of the token, the server has two phases: one is the token expiration time and the other is the token refresh time. The refresh time is definitely longer than the expiration time. When the user’s token expires, you can exchange the expired token for a new token to maintain the user’s login status. Of course, your token must expire within the refresh period. If it expires after the refresh period, the token will still return 401

  4. Token automatic life renewal implementation

    1. Add token flush logic to axios’ interceptor
    2. When a user’s token expires, the user requests a new token from the server
    3. Replace the old token with the new token
    4. The user’s current request is then continued
  5. The use of token automatic life renewal, the specific interpretation is written in the code

    1. First add token refresh logic to the response interceptor
     instance.interceptors.response.use(
             function(response) {// Do something about the response datareturn response.data
             },
             function (error) {
               console.log(error)
    
               if (error.response) {
                 if(error.response.status === 401) {// If the current route is not login and the user has the "remember password" operation // then request a new tokenif(router.currentRoute.name ! = ='login'{// If there are refreshTokens, and the token is expired,(locate 4010 here), judge the condition to change itselfif (sessionStorage.getItem('refreshToken') && code === '4010'{// refresh the token interface by using axios to skip the interceptor and replace the refreshToken const data = await axios({method:'post',
                         url: '/api/api/v1/access_token',
                         data: {
                           systemId: 10,
                           userCode: store.getters.code
                         },
                         headers: { Authorization: sessionStorage.getItem('refreshToken'}}) const token = data.data.data // After receiving the token, the token is saved as a new token to be carried in the subsequent requestsetToken(Token) // Then get the config information of the last request, Contains the last request parameters, address etc const config = error. The response. The config config. The headers. The Authorization = token / / use the request to request interface, after receiving the return value, Straight back out. Return data as first request const res = await axios.request(config)return res
                     } else{// If refreshToken expires, or some other condition, the login page message.error ('Login expired please login again! ')
                       setToken(' ')
                       router.push({
                         name: 'login'})}}}} // What to do about the response errorreturn Promise.reject(error.response)
             }
           )`
    Copy the code

    Tree shuttle box

    Select and delete tree data, such as permissions, departments, etc. You might use a tree structure to handle some interface operations.

    1. A practical tree shuttle box plugin, since there are wheels, there is no need to build. The actual effect

Use NPM to install el-tree-transfer –save

Then is the installation of the use, the specific can view its documentation, I will introduce the common here

<tree-transfer // title, that is, the left and right side of the title hint :title="data.options.title"// Data on the left :from_data="data.fromData"// Data on the right :to_data="data.toData"// Recognize the matching field by default :default-props="{label:'resourceName'}"// Shuttle box mode :mode="data.mode"// Click add method (move from left to right) @addbtn ="add"// Click the remove method (moving from right to left) @removebtn ="remove"/> 


            data() {
              return {
                data: {
                  fromData: [],
                  options: {
                    title: [
                      'Optional permissions'.'Selected permissions'
                    ]
                  },
                  toData: [],
                  mode: 'transfer', // transfer addressList}} // add(fromData, toData, Obj) {// Add, add all levels const arr = [... obj.halfnodes,...obj.nodes] console.log(arr,'Something added')
                  arr.forEach(item => {
                    item['option'] = '1'this.data.sendList = this.data.sendList.filter(e => e.id ! == item.id) this.data.sendList.push(item)})}, remove(fromData, toData, obj) { Move single const arr = [] obj.nodes. ForEach (item => {if(! item.childNodes) { arr.push(item) } }) // const arr = this.getTbs(obj.nodes) console.log(arr,'Reduced array')
                  arr.forEach(item => {
                    item['option'] = '0'this.data.sendList = this.data.sendList.filter(e => e.id ! == item.id) this.data.sendList.push(item) }) },Copy the code
  1. By analyzing its source code, a brief description of how it looks for and adds nodes as it moves left and right. When adding nodes, it looks at the right tree data as a string, and then gets the ID of the data currently added to the right, and then looks up whether the ID can be found in the current string. The add or not operation is the same as the remove operation, treating the left tree as a string

  2. If I want to use children, I will create a children property in the tree that will receive the value of childNodes. Okay, so that’s the problem, because we know that it does this by converting to a string, and then checking to see if the string contains this ID character, which is present in childNodes even though it looks like it’s not in children, So you’re going to have a situation where you pick a couple of them and move to the left and they’re gone. It is easy to delete childNode attributes. Of course, it is even easier to directly use childNode as an identifier. This problem will not occur

  3. Because, this plug-in has certain requirements for data format, so we need to do some processing for the ID of tree data, and Pid, the idea is to do some data modification and matching through recursion, here will not go into detail, directly on some of the code, can be directly converted to meet the requirements of tree data

// Use recursion to create the children property, not a concern if prop matchessetChidlren(item) {
            const that = this
            if (item.childNodes) {
              item['children'] = item.childNodes
              item.children.map(e => {
                that.setChidlren(e)
              })
            } else {
              return false}}, // Use recursion to add a tree PID for each item of background data requestedsetPid(item) {
            const that = this
            if(item.children) {item.children. Map (e => {// pid equals id e['pid'] = item.id
                that.setPid(e)
              })
            } else {
              return false}}, // Use recursion to set all ids, leaving the lowest id unchangedsetId(item) {
            const that = this
            if(item.children) {item.children. Map ((e, index) => {// Pid equals id e.id = item.id +The '-' + (index + 1)
                that.setId(e)
              })
            } else {
              return falseGetTarget (item, arr) {const that = this if there are children inside, recurse the current function, arr is the array of all the values that meet the criteriaif (item.children) {
              item.children.map(e => {
                that.getTarget(e, arr)
              })
            } else{// If not, prove that the current child is the element of the smallest node, i.e., arr.push(item)}}, GetTbs (toData) {const arr = [] todata.map (item => {getTbs(toData) {const arr = [] todata.map (item => {if (item.children) {
                this.getTarget(item, arr)
              } else {
                arr.push(item)
                return false}})returnGetMore (item, arr) {const that = this arr.push(item) // If there are children inside, recurse the current function. Arr is an array that stores all the eligible valuesif (item.children) {
              item.children.map(e => {
                that.getMore(e, arr)
              })
            }
Copy the code
  1. Use of specific processing data
    const res = await getallResuorce()
    const arr = res.data.data
    arr.map((item, index) => {
     item['pid'] = 0
     item.id = `${index + 1}`
     item['children'] = item.childNodes this.setChidlren(item) this.setId(item) this.setPid(item) }) const currentList = [] arr.forEach(item Const res2 = await getUserResuorce(row.rolecode, {this.getMore(item, currentList)}) // User's current permission'10')
    const arr2 = res2.data.data
    arr2.map((item, index) => {
     item['pid'] = 0
     item.id = `${index + 1}`
     item['children'] = item.childnodes this.setchidLren (item) this.setid (item) this.setpid (item)} // Save all lists this.data.fromdata = arrCopy the code

conclusion

Ok, this part is written here, it is not difficult, just some of the previous encountered, may be helpful to you to share with you, finally, come on, everyone!