Account Vuex Module Example

This Vuex module will do all the heavy lifting so your components deal with an easy API and you can easily check on the users’ authenticated state.

account.vue

When a user logs in, a timer is set to automatically refresh the token when it expires.

Vuex Module Explained

State Variables:

authorized A boolean you can check if a user is authorized ( $store.state.account.authorized )

A boolean you can check if a user is authorized ( ) user An object of the user's information

An object of the user's information loginError A string containing the Cognito response on an invalid login attempt

A string containing the Cognito response on an invalid attempt signupError A string containing the Cognito response on an invalid signup attempt

A string containing the Cognito response on an invalid attempt confirm Boolean indicating if the user wants to confirm their email address. This can happen right after signup or if a user comes back later.

Boolean indicating if the user wants to confirm their email address. This can happen right after signup or if a user comes back later. confirmError A string containing the Cognito response on an invalid email confirmation

Module Usage:

These 3 module actions trigger the AWS Amplify Authentication/Cognito Service.

Other Actions

fetchUser attempts to refresh the user state from Cognito. Should only call once on application initialize, or if you want to refresh the token

attempts to refresh the state from Cognito. Should only call once on application initialize, or if you want to refresh the token logout will ensure the user has logged out

Handling Authentication Changes:

Most cases will require logic run when a user gets logged in or out. You can add this to main.js or app.vue then choose to redirect the user, load components, etc on change.

Fetching the JWT (JSON Web Token)

You may need to obtain the JWT for interacting with a server or API. Here is some example code to fetch it:

The state is passed to the method purely to check if the user is currently authorized, this can be handled differently.

Extending Authentication to a Server API

Very soon I will release an article on: