Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements #11

Merged
merged 15 commits into from
Nov 9, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@
appendToken: false
},
storageTokenName: 'nuxt-auth-token',
tokenType: 'Bearer'
tokenType: 'Bearer',
notLoggedInRedirectTo: '/login',
loggedInRedirectTo: '/'
}
}
```
Expand Down Expand Up @@ -75,6 +77,12 @@ Set the token name in the local storage and in the cookie.
#### tokenType
Sets the token type of the authorization header.

#### notLoggedInRedirectTo
Sets the redirect URL default of the users not logged in. This is actived when 'auth' middeware is register.

#### loggedInRedirectTo
Sets the redirect URL default of the users logged in. This is actived when 'no-auth' middeware is register.

## Example usage

```js
Expand All @@ -99,6 +107,18 @@ store.state['auth']['user'] // get user data
store.getters['auth/loggedIn'] // get login status (true or false)
```

## Middleware

```js
// ... in nuxt.config.js ...
router: {
middleware: [
'auth', // If user not logged in, redirect to '/login' or to URL defined in notLoggedInRedirectTo property
'no-auth' // If user is already logged in, redirect to '/' or to URL defined in loggedInRedirectTo property
]
}
```

## License

[MIT License](./LICENSE)
Expand Down
8 changes: 5 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { resolve } = require('path')
const { merge } = require('lodash')

export default async function module (moduleOptions) {
export default function module (moduleOptions) {
// Apply defaults
const defaults = {
login: {
Expand All @@ -22,7 +22,9 @@ export default async function module (moduleOptions) {
appendToken: false
},
storageTokenName: 'nuxt-auth-token',
tokenType: 'Bearer'
tokenType: 'Bearer',
notLoggedInRedirectTo: '/login',
loggedInRedirectTo: '/'
}

const options = merge(defaults, moduleOptions, this.options.auth)
Expand All @@ -31,7 +33,7 @@ export default async function module (moduleOptions) {
this.addPlugin({ src: resolve(__dirname, '../templates/auth.plugin.js'), fileName: 'auth.plugin.js' })

// Middleware
this.addTemplate({ src: resolve(__dirname, '../templates/auth.middleware.js'), fileName: 'auth.middleware.js' })
this.addTemplate({ src: resolve(__dirname, '../templates/auth.middleware.js'), fileName: 'auth.middleware.js', options })

// Store
this.addTemplate({ src: resolve(__dirname, '../templates/auth.store.js'), fileName: 'auth.store.js', options })
Expand Down
6 changes: 4 additions & 2 deletions templates/auth.middleware.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import middleware from './middleware'

const options = <%= serialize(options) %>

middleware.auth = function authMiddleware ({ store, redirect }) {
// If user not logged in, redirect to /login
if (!store.getters['auth/loggedIn']) {
return redirect('/login')
return redirect(options.notLoggedInRedirectTo)
}
}

middleware['no-auth'] = function noAuthMiddleware ({ store, redirect }) {
// If user is already logged in, redirect to /
if (store.getters['auth/loggedIn']) {
return redirect('/')
return redirect(options.loggedInRedirectTo)
}
}
21 changes: 12 additions & 9 deletions templates/auth.store.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,22 +106,24 @@ export default {

// Append token
if (appendToken) {
paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/';
paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/'
endpoint = endpoint + paramTokenName + state.token
}

// Try to get user profile
try {
const headers = {'Authorization': options.tokenType + ' ' + state.token}
const userData = await this.$axios.$get(endpoint, {headers})
// Set Authorization Token in request
this.$axios.setToken(state.token, options.tokenType)

const userData = await this.$axios.$get(endpoint)

if (propertyName) {
commit('SET_USER', userData[propertyName])
} else {
commit('SET_USER', userData)
}
} catch (e) {
return dispatch('invalidate')
dispatch('invalidate')
}
},

Expand All @@ -137,7 +139,7 @@ export default {
dispatch('updateToken', token)

// Fetch authenticated user
dispatch('fetch')
await dispatch('fetch')
},

// Logout
Expand All @@ -146,18 +148,19 @@ export default {

// Append token
if (appendToken) {
paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/';
paramTokenName = (paramTokenName) ? ('?' + paramTokenName + '=') : '/'
endpoint = endpoint + paramTokenName + state.token
}

// Server side logout
try {
const headers = {'Authorization': options.tokenType + ' ' + state.token}
// Set Authorization Token in request
this.$axios.setToken(state.token, options.tokenType);

if (method.toUpperCase() === 'POST') {
await this.$axios.$post(endpoint, {}, {headers})
await this.$axios.$post(endpoint)
} else {
await this.$axios.$get(endpoint, {headers})
await this.$axios.$get(endpoint)
}
} catch (e) {
// eslint-disable-next-line no-console
Expand Down