From 6d6c7b3dcd9146fb8eb10daf27a20997fbc8c99c Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 2 Feb 2018 19:11:25 +0330 Subject: [PATCH] feat: $auth.hasScope --- example/api/auth.js | 6 +++++- example/pages/secure.vue | 5 +++++ lib/defaults.js | 1 + lib/templates/auth.class.js | 14 ++++++++++++++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/example/api/auth.js b/example/api/auth.js index a836ccba5..53f9e0778 100644 --- a/example/api/auth.js +++ b/example/api/auth.js @@ -32,7 +32,11 @@ app.post('/login', (req, res, next) => { } const accessToken = jsonwebtoken.sign( - { username, rand: Math.random() * 1000 }, + { + username, + rand: Math.random() * 1000, + scope: ['test', 'user'] + }, 'dummy' ) diff --git a/example/pages/secure.vue b/example/pages/secure.vue index c8b5ed088..ae9535b73 100644 --- a/example/pages/secure.vue +++ b/example/pages/secure.vue @@ -8,6 +8,11 @@ + + User: {{ $auth.hasScope('user') }} + Test: {{ $auth.hasScope('test') }} + Admin: {{ $auth.hasScope('admin') }} + {{ $auth.token || '-' }} diff --git a/lib/defaults.js b/lib/defaults.js index f6d13e8f3..94c842c73 100644 --- a/lib/defaults.js +++ b/lib/defaults.js @@ -3,6 +3,7 @@ module.exports = { resetOnError: true, rewriteRedirects: true, namespace: 'auth', + scopeKey: 'scope', endpoints: { login: { url: '/api/auth/login', method: 'post', propertyName: 'token' }, logout: { url: '/api/auth/logout', method: 'post' }, diff --git a/lib/templates/auth.class.js b/lib/templates/auth.class.js index 595f044d7..84a6ec1d1 100644 --- a/lib/templates/auth.class.js +++ b/lib/templates/auth.class.js @@ -306,4 +306,18 @@ export default class Auth { this.ctx.redirect(to) } + + hasScope (scope) { + const userScopes = getProp(this.state.user, this.options.scopeKey) + + if (!userScopes) { + return + } + + if (Array.isArray(userScopes)) { + return userScopes.includes(scope) + } + + return Boolean(getProp(userScopes, scope)) + } }