GithubHelp home page GithubHelp logo

d0whc3r / vue-auth-plugin Goto Github PK

View Code? Open in Web Editor NEW
58.0 6.0 13.0 5.04 MB

Vue auth plugin with typescript

Home Page: https://vue-auth-plugin.netlify.app

License: MIT License

JavaScript 2.47% TypeScript 97.53%
vue vue-plugin vue-cli vue-2 authorization authentication typescript

vue-auth-plugin's Introduction

πŸ”‘ Vue Auth Plugin

A simple authentication and authorization library for Vue.js using typescript

Inspired in @websanova/vue-auth

Pull requests and issues are welcome

πŸ‘€ Project status

@d0whc3r/vue-auth-plugin Dev Token Netlify Status pipeline status codecov Codacy Badge Quality Gate Status Maintainability Rating Security Rating Bugs Vulnerabilities dependencies npm version FOSSA Status

πŸš€ Install

yarn add @d0whc3r/vue-auth-plugin

πŸ““ Documentation and Usage

https://vue-auth-plugin.netlify.app

https://d0whc3r.github.io/vue-auth-plugin

πŸ”§ Project demo

git clone https://github.com/d0whc3r/vue-auth-plugin.git
cd vue-auth-plugin
yarn install
cd demo
yarn install
yarn start

πŸ“Š Project tests

yarn test

Plugin created using vue-cli 3 and p11n plugin

©️ License

MIT

FOSSA Status

πŸ”– Keywords

vue, plugin, auth, authorization, authentication, login, roles, vuejs, vue2, typescript

vue-auth-plugin's People

Contributors

arthurpai avatar d0whc3r avatar dependabot[bot] avatar fossabot avatar glandos avatar jfornies avatar renovate-bot avatar semantic-release-bot avatar themaxaboy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

vue-auth-plugin's Issues

Uncaught (in promise) Error: Avoided redundant navigation to current location: "/login".

Describe the bug
I have my login form on the authRedirect page (/login). After my API server returns failed login (code 401), the plugin attempts to redirect to the same page which results into uncaught error.

To Reproduce
Steps to reproduce the behavior:
Call this.$auth.login({ ... }) on the authRedirect page (/login).

Expected behavior
I'd expect no redirect if login request failed and the user is already on the authRedirect page.

login() and fetchData() return incomplete promises

Describe the bug
Calling $auth.login() returns a promise that will resolve right after login, but before the call (and the result) of fetchData.

To Reproduce

  • Call await Vue.$auth.login(…)
  • Call Vue.$auth.user() right after
  • The returned value is null.

https://codepen.io/glandos/pen/YzQNjeB?editors=1112
You can see that loginNotOK follow the pattern of the current code, while loginOK returns the result of the promise.then call.

Expected behavior
login returned promise should resolve when all information are there. Especially, this code should be valid:

await Vue.$auth.login({username, password})
assert Vue.$auth.user() !== null

This is not the case today.

Is this a wanted behavior? Should I opened a PR to fix that?

Support for Axios >= 0.23 & Typescript with common headers

Describe the bug
Since Axios 0.23 and the inclusion of axios/axios#4140 types have changed for global headers.

It is now forbidden to set axios.defaults.headers.Authorization = 'Bearer {auth_token}' and it must be set in axios.defaults.headers.common instead.

However vue-auth-plugin skip non-strings value in

&& this.options.headerTokenReplace

Header is not replaced, and authenticated requests failed.

Expected behavior
Header should be replaced.

Additional context
Maybe the test should go deeper to handle common, get, post, etc, headers.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://[secure]@github.com/d0whc3r/vue-auth-plugin.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://[secure]@github.com/d0whc3r/vue-auth-plugin.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://github.com/d0whc3r/vue-auth-plugin.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

2FA two-factor authentication support

Are there any plans to integrate multi factor authentication, this will usually defer the retrieval of the token to a second login request of some sort, the first is a email + password auth, followed by a single use password check.

Avoided redundant navigation in afterLogin

Describe the bug
Similar to #265, there can be a redundant navigation in the afterLogin method.

To Reproduce
Steps to reproduce the behavior:

  1. Add a form onto the / path
  2. Log in
  3. See the error:
 Uncaught (in promise) Error: Avoided redundant navigation to current location: "/".
    createRouterError http://localhost:8080/js/chunk-vendors.js:76180
    createNavigationDuplicatedError http://localhost:8080/js/chunk-vendors.js:76153
    confirmTransition http://localhost:8080/js/chunk-vendors.js:76313
    transitionTo http://localhost:8080/js/chunk-vendors.js:76243
    push http://localhost:8080/js/chunk-vendors.js:76610
    push http://localhost:8080/js/chunk-vendors.js:77031
    push http://localhost:8080/js/chunk-vendors.js:77030

Expected behavior
No error

Additional context
This could use the new push method introduced in d538f17. I didn't want to propose a PR, because I don't really know if I can just replace this.router.push by this.push in afterLogin.

[QUESTION] - HTTP Error Response Handling

I would just like to check something regarding handling of HTTP error codes: when I pass invalid credentials to the /login endpoint of my API, it will respond with a 401 response.

In my front-end app, I have this code to attempt a user login:

          this.$auth.login({
            email: this.loginForm.email,
            password: this.loginForm.password
          })
            .then((response) => {
              this.$Notice.success({
                title: `logged onto console`
              })
            })
            .catch((err) => {
              this.$Notice.error({
                title: `could not log on`,
                desc: err
              })
            })

I was expecting the notification in the catch block to fire on the 401, but it goes into the then block.

Am I doing something wrong? Or, is this something that I need to configure on either the vue-auth-plugin config, or the global axios config?

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://[secure]@github.com/d0whc3r/vue-auth-plugin.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://github.com/d0whc3r/vue-auth-plugin.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Override default options in loginData or subojects.

Describe the bug
I'd like to override only one of the loginData options, e.g.:

Vue.use(VueAuth, {
  loginData: {
    redirect: '/home',
  }
})

Expected behavior
All options described in docs should be set, like method: 'POST'

Instead, all loginData object is erased, and default options from axios are used.

Maybe I missed something?

vue-router is a required dependency

I get the "vue-router is a required dependency" error when starting my vue app, but the vue-router has been installed.

plugins/index.js:

import './iview'
import './form-create'
import './vuex-orm'
import './vue-orgchart'
import './vue-axios'
import './vue-auth'

vue-auth plugin file:

import Vue from 'vue'
import VueAuth from '@d0whc3r/vue-auth-plugin'

const options = {
  authMeta: 'auth',
  rolesVar: 'roles',
  tokenDefaultName: 'default_auth_token',
  userDefaultName: 'default_auth_user',
  tokenStore: ['localStorage'],
  headerTokenReplace: '{auth_token}',
  tokenType: 'Bearer',
  vuexStoreSpace: 'vue-auth',
  authRedirect: '/login',
  loginData: {
    url: '/auth/login',
    method: 'POST',
    redirect: '/user',
    headerToken: 'Authorization',
    fetchUser: false
  },
  logoutData: {
    url: '/auth/logout',
    method: 'POST',
    redirect: '/login',
    makeRequest: false
  },
  fetchData: {
    url: '/auth/user',
    method: 'GET',
    interval: 30,
    enabled: false
  }
}

Vue.use(VueAuth, options)

router.js:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
     ...
  ]
})

main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router'

import store from './store'
import './plugins'
import './filters'

require('@/assets/style.css')

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

[FEATURE REQUEST] - Refresh Token

It would be great if one could get a refresh token together with the initial access token in the login response payload - an enhancement to #80.

Example:

{
  "token": "eyJ************KJU",
  "refreshToken": "ed******************WjT",
  "type": "bearer"
}

The refreshToken is then stored in a separate key in localstorge (or cookie/vuex).

If the refreshData option fires, or with $auth.refresh() method, the API call will then include the refreshToken in the Authorization header or the request body.

Your thoughts?

FetchData interval not start when refresh page

Describe the bug
If user is logged in, and then press F5 to refresh page.
The fetchData will not working.

Solution
May be on AuthVueHttp.configureHttp,
Checking token is exist, then call AuthVueHttp.startIntervals

Like this

  private configureHttp() {
    var token = this.storeManager.getToken()
    if (!!token) {
      this.startIntervals();
    }

    ....
  }

Support oauth2

Support oauth2 using providers like facebook, github or google

vuex is a required dependency if you want to use "vuex" as storage

Bug
Getting this error that vuex is a required dependency, even if Vuex is installed explicitly. I use the JS version of Vue, and not the TS one.

main.js file

import Vue from 'vue'
import './plugins/vuetify'
import './plugins/axios'
import './plugins/vue-auth-plugin'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import pathify from 'vuex-pathify'

Vue.use(Vuex)

const store = new Vuex.Store({
plugins: [ pathify.plugin ]
})

Vue.store = store

export default store

vue-auth-plugin.js

import Vue from 'vue'
import VueAuth from '@d0whc3r/vue-auth-plugin'

const options = {
authMeta: 'auth',
rolesVar: 'roles',
tokenDefaultName: 'auth_token',
userDefaultName: 'auth_user',
tokenStore: ['vuex', 'cookie'],
headerTokenReplace: '{auth_token}',
tokenType: 'Bearer',
vuexStoreSpace: 'auth',

authRedirect: '/login',

loginData: {
  url: '/auth/login',
  method: 'POST',
  redirect: '/user',
  headerToken: 'Authorization',
  fetchUser: false,
},
logoutData: {
  url: '/auth/logout',
  method: 'POST',
  redirect: '/login',
  makeRequest: false,
},

}

Vue.use(VueAuth, options)

What should i do ? been trying to find a solution for a quite a while, nothing helpful found.
Only one thing to mention, as in the documentation it is indeed state that you have to explicitly declare the store and the router - only exception being in my code, is that i cannot use (Vue as any).store = store as i am not using Typescript.

Thank you in advance !

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @types/express-jwt Unavailable
npm codacy-coverage Unavailable
npm codecov Unavailable
npm npm-run-all Available

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): replace dependency npm-run-all with npm-run-all2 5.0.0
  • chore(deps): update dependency @types/cors to v2.8.17
  • chore(deps): update dependency @types/express to v4.17.21
  • chore(deps): update dependency express-jwt to v6.1.2 (express-jwt, @types/express-jwt)
  • chore(deps): update vue-cli monorepo to v4.5.19 (@vue/cli-plugin-babel, @vue/cli-plugin-pwa, @vue/cli-plugin-typescript, @vue/cli-plugin-unit-jest, @vue/cli-plugin-vuex, @vue/cli-service)
  • chore(deps): update dependency @types/jest to v27.5.2
  • chore(deps): update dependency @vue/test-utils to v1.3.6
  • chore(deps): update dependency axios-mock-adapter to v1.22.0
  • chore(deps): update dependency body-parser to v1.20.2
  • chore(deps): update dependency commitizen to v4.3.0
  • chore(deps): update octokit monorepo (@octokit/core, @octokit/plugin-paginate-rest)
  • fix(deps): update dependency vue-router to v3.6.5
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update dependency @types/express-jwt to v7
  • chore(deps): update dependency @types/jsonwebtoken to v9
  • chore(deps): update dependency @vue/test-utils to v2
  • chore(deps): update dependency express-jwt to v8
  • chore(deps): update dependency jest-junit to v16
  • chore(deps): update dependency typescript to v5
  • chore(deps): update dependency vue to v3
  • chore(deps): update dependency vuex to v4
  • chore(deps): update node.js to v20 (node, @types/node)
  • chore(deps): update octokit monorepo (major) (@octokit/core, @octokit/plugin-paginate-rest)
  • chore(deps): update vue-cli monorepo to v5 (major) (@vue/cli-plugin-babel, @vue/cli-plugin-pwa, @vue/cli-plugin-typescript, @vue/cli-plugin-unit-jest, @vue/cli-plugin-vuex, @vue/cli-service)
  • fix(deps): update dependency vue-router to v4
  • πŸ” Create all rate-limited PRs at once πŸ”

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/nodejs.yml
  • actions/checkout v1
  • actions/setup-node v1
gitlabci
.gitlab-ci.yml
  • node 12
npm
demo/package.json
  • core-js 3.16.2
  • vue 2.6.14
  • vue-axios 3.2.5
  • vue-class-component 7.2.6
  • vue-property-decorator 9.1.2
  • vue-router 3.5.2
  • vuex 3.6.2
  • vuex-class 0.3.2
  • @types/cors 2.8.12
  • @types/express 4.17.13
  • @types/express-jwt 6.0.2
  • @types/jsonwebtoken 8.5.4
  • @types/node 16.6.1
  • @vue/cli-plugin-babel 4.5.13
  • @vue/cli-plugin-pwa 4.5.13
  • @vue/cli-plugin-typescript 4.5.13
  • @vue/cli-service 4.5.13
  • body-parser 1.19.0
  • cors 2.8.5
  • express 4.17.1
  • express-jwt 6.1.0
  • jsonwebtoken 8.5.1
  • npm-run-all 4.1.5
  • ts-node 10.2.0
  • typescript 4.3.5
  • vue-template-compiler 2.6.14
package.json
  • vue-router 3.5.2
  • @octokit/core 3.5.1
  • @octokit/plugin-paginate-rest 2.15.1
  • @semantic-release/changelog 5.0.1
  • @semantic-release/commit-analyzer 8.0.1
  • @semantic-release/git 9.0.0
  • @semantic-release/github 7.2.3
  • @semantic-release/npm 7.1.3
  • @semantic-release/release-notes-generator 9.0.3
  • @types/jest 27.0.1
  • @vue/cli-plugin-babel 4.5.13
  • @vue/cli-plugin-typescript 4.5.13
  • @vue/cli-plugin-unit-jest 4.5.13
  • @vue/cli-plugin-vuex 4.5.13
  • @vue/cli-service 4.5.13
  • @vue/test-utils 1.2.2
  • axios 0.21.1
  • axios-mock-adapter 1.20.0
  • babel-core 7.0.0-bridge.0
  • codacy-coverage 3.4.0
  • codecov 3.8.3
  • commitizen 4.2.4
  • coveralls 3.1.1
  • cross-env 7.0.3
  • gh-pages 3.2.3
  • jest 26.6.3
  • jest-junit 12.2.0
  • jest-sonar-reporter 2.0.0
  • js-cookie 3.0.0
  • semantic-release 17.4.5
  • sonar-scanner 3.1.0
  • ts-jest 26.5.6
  • ts-node 10.2.0
  • typescript 4.3.5
  • vue 2.6.14
  • vue-axios 3.2.5
  • vue-cli-plugin-p11n 0.4.0
  • vue-server-renderer 2.6.14
  • vue-template-compiler 2.6.14
  • vuex 3.6.2

  • Check this box to trigger a request for Renovate to run again on this repository

Logout function clears the store before executing the http call

Describe the bug
When triggering this.$auth.logout() while having the option makeRequest: true makes the request to the backend with the Authorization token set to Bearer null.

After reading the code, in case makeRequest is true, after leaving the if condition, it will clear the store data before the timing that the promise resolves, leading to the token to used be null.

To Reproduce

  1. Create a basic example
  2. Set the logoutData option makeRequest to true in order to call the backend
  3. Execute $auth.logout()
  4. In the headers the request Authorization header will be: Bearer null

Expected behavior

  • In case makeRequest is enabled for logout the store should only be clean on resolve of the promise

Multiple vue.js app instance support

  1. this approach:
    https://d0whc3r.github.io/vue-auth-plugin/installation.html#use-vue-router-and-vuex
const store = new Vuex.Store({ ... });
(Vue as any).store = store;
      if (!_this.Vue.store) {
526:        throw Error('[vue-auth-plugin] vuex is a required dependency if you want to use "vuex" as storage');
      }

vue-auth-plugin.umd.js:526 Uncaught Error: [vue-auth-plugin] vuex is a required dependency if you want to use "vuex" as storage
    at new StoreVuex (vue-auth-plugin.umd.js:526)
    at vue-auth-plugin.umd.js:650
    at Array.map (<anonymous>)
    at AuthStoreManager.setStores (vue-auth-plugin.umd.js:640)
    at new AuthStoreManager (vue-auth-plugin.umd.js:622)
    at new Auth (vue-auth-plugin.umd.js:1833)
    at Object.install (vue-auth-plugin.umd.js:1893)
    at Function.Vue.use (vue.js:5094)
    at vue-auth-plugin.umd.js:1910
    at vue-auth-plugin.umd.js:9
  1. prevents using multiple vue.js app instances:
    https://vuex.vuejs.org/guide/state.html
    when store is injected per-instance:
const app = new Vue({
  el: '#app',
  // provide the store using the "store" option.
  // this will inject the store instance to all child components.
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
  1. instead, VueAuthPlugin should behave as store-attached plugin:
    https://vuex.vuejs.org/guide/plugins.html
const store = new Vuex.Store({
  // ...
  plugins: [VueAuthPlugin] // can be class or instance
})

Support privileges

Enable meta to support roles and redirect to a configurable forbidden page

[Documentation] False information in the Default Options section

Branch: master
Documentation provides false information about the default options.

The Default options section in the Guide
suggests that the
customToken: (response) => response.data['token']
this is false in my opinion because this is not implemented anywhere.
The only place where is this implemented, is in the test :
vue-auth-plugin/tests/integration/customToken.spec.ts
but this mentioned test
test if is it possible to pass custom token getter,
not the existence of the default one.

Expected behavior

  • Remove the misleading doc part
  • OR Implement the missing part
  • OR explain in docs that by default the token is taken from the Header not from the response body

[QUESTION] - User Data Object

My options:

const options = {
  ...
  tokenStore: ['localStorage'],
  loginData: {
    url: '/auth/login',
    method: 'POST',
    redirect: '/',
    headerToken: 'Authorization',
    fetchUser: true
  },
  fetchData: {
    url: '/auth/me',
    method: 'GET',
    interval: 30,
    enabled: false
  }
}

Sample response from /auth/me:

{
    "id": 1,
    "name": "My Name",
    "jobTitle": {
        "id": 1,
        "title": "Dev"
    },
    "status": {
        "id": 1,
        "title": "active",
    },
    "user": {
        "id": 19,
        "email": "[email protected]"
    }
}

When I call const user = this.$auth.user(), I get the following in the user object:

{
        "id": 19,
        "email": "[email protected]"
 }

How do i get the entire payload from the API call into user, and not just the user node?

Get vue-auth to work with my current vue-router configuration

Hello,

I'm having trouble extending my app with your vue-auth plugin. I'm quite new to Vue.JS, and your plugin is the first one that gives me headaches. When I try to include your plugin according to your documentation, it throws me the error:

Uncaught Error: [vue-auth-plugin] vue-router is a required dependency

I started with a SSR-starter package and I'm extending it for the last couple of weeks. This SSR package had a router predefined, and it exports the new Router() directly, so I'm not able to bind it to the Vue instance in the way vue-auth requires.

This is my current router configuration:

`import Vue from 'vue';
import Router from 'vue-router';
import VueAuth from '@d0whc3r/vue-auth-plugin';
import { filenameToCamelCase, requireAll } from 'src/utils';
import { prefetchMixin } from 'src/utils/ssr';

const auth_options = {
authMeta: 'auth',
rolesVar: 'roles',
tokenDefaultName: 'default_auth_token',
userDefaultName: 'default_auth_user',
tokenStore: ['cookie'],
headerTokenReplace: '{auth_token}',
tokenType: 'Bearer',
vuexStoreSpace: 'vue-auth',

authRedirect: '/login',

loginData: {
	url: '/auth/login',
	method: 'POST',
	redirect: '/user',
	headerToken: 'Authorization',
	fetchUser: false,
	customToken: (response) => response.data['token'],
},
logoutData: {
	url: '/auth/logout',
	method: 'POST',
	redirect: '/login',
	makeRequest: false,
},
fetchItem: '',
fetchData: {
	url: '/auth/user',
	method: 'GET',
	interval: 30,
	enabled: false,
},
refreshData: {
	url: '/auth/refresh',
	method: 'GET',
	interval: 30,
	enabled: false,
},

};

Vue.use(Router);
Vue.use(VueAuth, auth_options);

const routes = [];
let route404, pathMap;

if (process.env.NODE_ENV !== 'production') pathMap = {};

// register all components in directory as routes (excepting files/folders starting from "")
requireAll(require.context('src/pages/', true, /^(?:(?!/?
).)+.(vue|js)$/), (component, name) => {
const route = {
component,
// generate route path based on file path
// remove file extension and '/index'
path: name.substr(1).replace(/(/index)?.[a-zA-Z0-9]+$/, '') +
// allow components adding their own route parameters
(component.routePath ? ('/' + component.routePath) : ''),
// add meta fields if there are any
meta: component.routeMeta,
// sub routes
children: component.routes
};

// prefetch data for all route components
if (!component.mixins) component.mixins = [];
component.mixins.push(prefetchMixin);

if (route.path === '/404') {
	// generate component name automatically
	if (!component.name) component.name = 'NotFoundPage';

	route.path = '*';
	if (!route.meta) route.meta = { statusCode: 404 };
	else if (!route.meta.statusCode) route.meta.statusCode = 404;
	route404 = route;
}
else {
	if (route.path === '') route.path = '/';
	// generate component name automatically
	if (!component.name) component.name = filenameToCamelCase(name) + 'Page';

	// let components create their own sub routes
	if (component.routes) route.children = component.routes;
	// map route parameters to component props by default
	route.props = component.routeProps === undefined ? true : component.routeProps;

	if (process.env.NODE_ENV !== 'production') {
		if (pathMap[route.path])
			throw new Error(`Duplicate path in vue-router: ${route.path}, components are: ${pathMap[route.path]}, ${name}`);
		pathMap[route.path] = name;
	}
	routes.push(route);
}

});

// catch-all route (404)
if (route404) routes.push(route404);

// we should return factory for SSR (runInNewContext: false)
export default router => new Router({
routes,
linkExactActiveClass: "is-active",
mode: 'history',
scrollBehavior(to, from, saved) {
if (to.path === from.path || to.meta && to.meta.keepScrollPosition) return saved;
// use to restore scroll position after prefetching within component code
if (saved) to.meta.scrollPosition = saved;
return saved || { x: 0, y: 0 };
}
});

Vue.router = router; <-----`

Could you give me a hint or example how I have to define my constant, without breaking the SSR-adjusted export? (export default router => new Router)

Kind Regards,
Dennis

Getting User from authentication request body

Is your feature request related to a problem? Please describe.
This is related to: #118

Describe the solution you'd like
Similarly, my user object is passed in the response body from the authentication endpoint. So I'm using customToken: (response) => response.data['token'], in the loginData options. Is it possible to create a customUser that is also in the response like customUser: (response) => response.data['user'], ?

Or is there another way to set the user within loginData?

Authenticated request without override header

Is your feature request related to a problem? Please describe.
It is not a problem, but I would like to not override the header on every HTTP request, I mean... this package is about authentication.
Describe the solution you'd like
When the login is successful, the header on every request needs to be authenticated. With the option to be non-authenticated.

Getting the Token from body and not from header

Hello,

I would like to use your plugin in my next personal project, as it simplifies things by a lot.
Yet i am curious, how could i achieve that once the Response message from the API server is sent, that i could grab the Token from the body? Currently having some issues in providing custom headers as response, which include the access token generated.

If i wasn't clear enough, please let me know and i will further explain!

Thank you in advance !

Support return path

Is your feature request related to a problem? Please describe.
When navigating to an authenticated route, the /login route is activated, and the desired route is lost.

Describe the solution you'd like
We should be able to re-route the application to the desired route before login. E.g. using :

            next({
                path: '/login',
                params: { nextUrl: to.fullPath }
            })

In the beforeEach hook. And then, the login component can re-route using the nextUrl params after successful login.

Is 1.9.0 really published?

I see that 1.9.0 is referenced on NPM, but neither in changelog, nor git tag, nor GitHub release.

Is this "normal"? I guess I have nothing to worry about, but I just want to be sure before updating this code :)

[feature] update demo

Build demo in pipeline and create a separated package.json only for demo and its dependencies.
Remove not needed dependencies from main package.json

error vue-axios is a required dependency

For @vue/cli v3
When installing the vue-auth-plugin it marks a dependency on the module "vue-axios is a required dependency" when it is already installed

 "dependencies": {
    "@d0whc3r/vue-auth-plugin": "^1.5.2",
    "@fortawesome/fontawesome-svg-core": "^1.2.25",
    "@fortawesome/free-regular-svg-icons": "^5.11.2",
    "@fortawesome/free-solid-svg-icons": "^5.11.2",
    "@fortawesome/vue-fontawesome": "^0.1.7",
    "axios": "^0.19.0",
    "core-js": "^2.6.5",
    "element-ui": "^2.4.5",
    "js-cookie": "^2.2.1",
    "normalize.css": "^8.0.1",
    "nprogress": "^0.2.0",
    "path-to-regexp": "^3.1.0",
    "vee-validate": "^3.0.10",
    "vue": "^2.6.10",
    "vue-axios": "^2.1.4",
    "vue-router": "^3.0.3",
    "vuex": "^3.0.1"
  },

imagen

[FEATURE REQUEST] - Check for expired token

Firstly ... I really enjoy the simplicity of this plugin!! Quick and easy to use!

From what I can see, $auth.check() currently only checks for the existence of the token in storage.

Tokens may expire after a period time. In this scenario, if one clicks on a route (just an example) that requires auth, the check will pass because the token is in localstorage, but when a request is sent to the API, a 401 is returned.

So, it would be great if the $auth.check() could include a check for expiry - maybe using the exp from the token?

More strict?

Hello! Are you planning to make your ts-code more strict?
"strictNullChecks": true,
"noImplicitAny": true,

Option rolesVar to support a response role type object.

When I use vue-auth-plugin with strapi headless cms, the login api gets a role response as a object type.

user: {
    blocked: false,
    confirmed: false,
    created_at: "2020-09-25T20:58:22.478Z",
    email: "[email protected]",
    id: 1,
    provider: "local",
    role: {
        description: "Default role given to authenticated user.",
        id: 1,
        name: "Authenticated",
        type: "authenticated",
    },
    updated_at: "2020-09-25T20:58:22.487Z",
    username: "user"
}

I think the rolesVar option should be set to a string with dot for access the object like lodash get.

_.get(object, 'a.b.c', 'default');

For me rolesVar is "role.type"

An alternative is to add a customRole like customToken.

customToken: (response) => response.data['token']
customRole: (response) => response.data['user']['role']['type']

Please consider thank you and sorry for my writing.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Unify options.loginData.fetchData and options.fetchData

Is your feature request related to a problem? Please describe.
I want to transform the received object from the profile URL defined in options.fetchData.url before storing it as a user. This is currently not possible, since only options.fetchItem is used as key to transform the received object.

This is a bit confusing with options.loginData.fetchData that is a function that transform the response from the login URL only.

Describe the solution you'd like
options.fetchData could use options.fetchItem as a function and call it.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://github.com/d0whc3r/vue-auth-plugin.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.