nuxt-community / auth-module

Zero-boilerplate authentication support for Nuxt 2
https://auth.nuxtjs.org
MIT License
1.93k stars 927 forks source link

How to set a different URL for laravel passport userInfo endpoints #1710

Open truesteps opened 2 years ago

truesteps commented 2 years ago

Heya!

I'm in a pickle! I was developing my site locally, so It all worked since all my endpoints start with http://localhost, so the assignAbsoluteEndpoints function in provider.ts was working properly, and didn't join both of my URLs into one.

Is it possible to exclude userInfo from the influence of the assignAbsoluteEndpoints function? My url is different than the URL I fetch userInfo from...

Down to the domain... the domain is different too.

Thanks!

truesteps commented 2 years ago

Found a way to go around it... I keep the userInfo as is, than I just overwrite the fetchUser method of the scheme with this ugly hack, where I set the baseURL to empty and combine it with the axios proxy...

Any better solutions are welcome.

the get function from lodash-es is a substitute for getProp from utils

The only reason this could work is 'cause I proxy the url where the userInfo exists... Otherwise I couldn't reliably get a env variable in this schema.

~/nuxt.config.js

...
    auth: {
        redirect: {
            home: '/<redacted>',
        },
        strategies: {
            laravelPassport: {
                provider: 'laravel/passport',
                scheme: '~/schemes/CustomOAuth2Scheme',
                endpoints: {
                    userInfo: `/server/sessions/me`
                },
                url: '<redacted>',
                clientId: '<redacted>',
                clientSecret: '<redacted>',
            },
        },
    },
...

~/schemes/CustomOAuth2Scheme.js

import { Oauth2Scheme } from '@nuxtjs/auth-next/dist/runtime';
import { get } from 'lodash-es';

export default class CustomOAuth2Scheme extends Oauth2Scheme {
    async fetchUser() {
        if (!this.check().valid) {
            return;
        }

        if (!this.options.endpoints.userInfo) {
            this.$auth.setUser({});
            return;
        }

        const { data } = await this.$auth.requestWith(this.name, {
            url: this.options.endpoints.userInfo.replace(this.options.url, ''),
            baseURL: '',
        });

        if (!this.options.user.property) {
            this.$auth.setUser(data);
            return;
        }

        this.$auth.setUser(get(data, this.options.user.property));
    }
}
truesteps commented 2 years ago

Maybe the solution could be so that the assignAbsoluteEndpoints function checks whether the endpoint starts with a https:// or http:// protocol and decide whether to pluck the strategy url if it doesn't start with a protocol?