npm package: @mccowngordon/vue-secure-token
Description: ## Description
Latest version: 0.5.111

# McCownGordon Construction Vue Secure Token

## Description

Securely handles API authentication between **Vue.js** / **Sharepoint Framework Extensions projects (_SPFX_)** and Azure Functions using Active Directory Provider tokens.

<br>

-   Dynamically adds a vuex module to your store called **SecureToken**
-   Provides Vue.axios() and Vue.apiHandler() methods
-   Includes wrapper component `<RenderComponent>` that displays loading indicator and friendly error message

<br>

## SecureToken store

| Getter            | Description                                                                                                                                            |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| sharepointContext | spfx this\.context                                                                                                                                     |
| apiBaseUrl        | Depending on the environment, for example: http://localhost:7071/api/RewardsRecognition or https://mgcforms\.azurewebsites\.net/api/RewardsRecognition |
| environment       | 'local' or 'production'                                                                                                                                |
| token             | jwt encoded token                                                                                                                                      |
| serverError       | true or false \- the apiHandler\(\) method will update this if an error occurs                                                                         |
| unauthorized      | true or false \- the apiHandler\(\) method will update this if the server returns a 401 response                                                       |
| waitingOnServer   | true or false \- starts out as true and gets updated to false after apiHandler\(\) method finishes with either status 200 or an error                  |

## Setup

install:

```bash
    # NPM
    npm install @mccowngordon/vue-secure-token --save

```

Import the package:

In [_projectName_]WebParts.ts

```javascript
import VueSecureToken, { VueSecureTokenConfig } from '@mccowngordon/vue-secure-token';
```

And initialize inside the `render()` method:

```javascript
    const vueSecureTokenConfig: VueSecureTokenConfig = {
      store,
      spContext: this.context,
      localFunctionAppRoot: "http://localhost:7071/api/RewardsRecognition"
      azureFunctionAppRoot: "https://mgcforms.azurewebsites.net/api/RewardsRecognition"
    };
    Vue.use(VueSecureToken, vueSecureTokenConfig);

```

# Update types in your project

types/vue/shims-vue.d.ts:

```javascript
import { AxiosStatic } from "axios";
import { ApiHandler } from '@mccowngordon/vue-secure-token';

declare module 'vue/types/vue' {
    interface VueConstructor {
        axios: AxiosStatic,
        apiHandler: ApiHandler
    }
}
```

## Usage

Anytime you want to call the MGC Function api:

```javascript
// If first request is an error because of an expired token,
// retryFunc is called after retrieving a new valid token
const retryFunc = () => this.context.dispatch('fetchInitData');

Vue.apiHandler({
    method: 'get',
    url: 'giftsAndCards',
    waitingIndicator: true,
})
    .then((response) => {
        this.context.commit('SET_GIFTS_AND_CARDS', response.data);
    })
    .catch((err) => {
        if (err.message.includes(401)) {
            this.context.commit('SET_UNAUTHORIZED');
        } else {
            this.context.commit('SET_SERVER_ERROR');
        }
    });
```

## How to use custom errors

```javascript
if (typeof response === 'object' && response.toString().includes('403')) {
    // this is a forbidden response/error
    this.context.dispatch(
        'SecureToken/setCustomError',
        {
            set: true,
            message: 'Sorry you are not authorized to access this application.',
            type: 'Error',
        },
        {
            root: true,
        },
    );
} else {
    this.context.commit('SET_SUBMISSIONS', response.data);
    this.context.commit('SET_FETCHED');
    if (!this._statusFilter) {
        this.context.commit('SET_FILTER_SUBMISSIONS', this._filters[0]);
    }
    return true;
}
```

Display an error (from a Vue Component)

```javascript
this.$store.dispatch(
    'SecureToken/setCustomError',
    {
        set: true,
        message: 'Error loading calendar.  Please contact the IT Department with this error message. 87400.',
        type: 'Error',
    },
    {
        root: true,
    },
);
```

Clear errors (from a Vue Component)

```javascript
this.$store.dispatch(
    'SecureToken/setCustomError',
    {
        set: false,
        message: null,
        type: null,
    },
    {
        root: true,
    },
);
```

How to manually toggle the waiting indicator

```javascript
  // loading indicator from separate module
  @secureToken.Action
  public setWaitingOnServer;


 this.setWaitingOnServer(true);
```

## To Publish An Update

Currently this project is not in its own git repo. @TODO Save it as its own repo
run `npm run build ; npm publish`