chore: migrate to composition API and auth0-spa
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
import { ApolloClient } from 'apollo-client'
|
||||
import { createHttpLink } from 'apollo-link-http'
|
||||
import { InMemoryCache } from 'apollo-cache-inmemory';
|
||||
import { setContext } from 'apollo-link-context'
|
||||
import { useAuth } from './auth'
|
||||
import { reactive, toRefs } from '@vue/composition-api'
|
||||
|
||||
let instance = null
|
||||
|
||||
const apiUrl = process.env.graphqlApi || '/query'
|
||||
|
||||
const httpLink = createHttpLink({
|
||||
uri: apiUrl
|
||||
})
|
||||
|
||||
const getToken = async (options) => {
|
||||
const { getTokenSilently, isAuthenticated } = useAuth()
|
||||
if (isAuthenticated.value) {
|
||||
return await getTokenSilently.value(options)
|
||||
} else {
|
||||
return options
|
||||
}
|
||||
};
|
||||
|
||||
const authLink = setContext(async (_, { headers }) => {
|
||||
const token = await getToken()
|
||||
return {
|
||||
headers: {
|
||||
...headers,
|
||||
authorization: token ? `Bearer ${token}` : '',
|
||||
}
|
||||
};
|
||||
})
|
||||
|
||||
const client = new ApolloClient({
|
||||
link: authLink.concat(httpLink),
|
||||
cache: new InMemoryCache(),
|
||||
defaultOptions: {
|
||||
watchQuery: {
|
||||
fetchPolicy: 'cache-and-network',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
instance = client
|
||||
|
||||
export const useMutation = (mutation, options) => {
|
||||
const opts = options;
|
||||
const doMutate = options => new Promise((resolve, reject) => {
|
||||
out.loading = true
|
||||
instance.mutate({
|
||||
mutation,
|
||||
...opts,
|
||||
...options
|
||||
})
|
||||
.then(result => {
|
||||
out.loading = false
|
||||
out.data = result.data
|
||||
resolve(result)
|
||||
})
|
||||
.catch(e => {
|
||||
out.loading = false
|
||||
out.error = e
|
||||
reject(e)
|
||||
})
|
||||
})
|
||||
const out = reactive({
|
||||
data: {},
|
||||
error: null,
|
||||
loading: false,
|
||||
})
|
||||
return [doMutate, toRefs(out)]
|
||||
}
|
||||
|
||||
export const useLazyQuery = (query, options) => {
|
||||
const opts = options
|
||||
let watchedQuery = null
|
||||
const doQuery = options => new Promise((resolve, reject) => {
|
||||
out.loading = true
|
||||
let effectiveOptions = {
|
||||
query,
|
||||
...(opts || {}),
|
||||
...(options || {})
|
||||
}
|
||||
watchedQuery = instance.watchQuery(effectiveOptions)
|
||||
watchedQuery.subscribe(({loading, data}) => {
|
||||
out.loading = loading
|
||||
out.data = data || {}
|
||||
out.error = null
|
||||
resolve(data)
|
||||
}, error => {
|
||||
out.loading = false
|
||||
out.error = error
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
const refetch = variables => {
|
||||
const opts = {}
|
||||
if (variables) (
|
||||
opts.variables = variables
|
||||
)
|
||||
doQuery(opts)
|
||||
}
|
||||
const startPolling = interval => doQuery({pollInterval: interval})
|
||||
const stopPolling = () => {
|
||||
if (watchedQuery) {
|
||||
watchedQuery.stopPolling()
|
||||
}
|
||||
}
|
||||
const out = reactive({
|
||||
data: {},
|
||||
error: null,
|
||||
loading: false,
|
||||
refetch,
|
||||
startPolling,
|
||||
stopPolling
|
||||
})
|
||||
return [doQuery, toRefs(out)]
|
||||
}
|
||||
|
||||
export const useQuery = (query, options) => {
|
||||
const [doQuery, out] = useLazyQuery(query, options)
|
||||
doQuery()
|
||||
return out
|
||||
}
|
||||
|
||||
// import { execute, makePromise, ApolloLink, Observable } from 'apollo-link';
|
||||
// import { HttpLink } from 'apollo-link-http';
|
||||
// const { includeCredentials } = require('./middleware');
|
||||
// import { onError } from 'apollo-link-error';
|
||||
//
|
||||
// const defaultGraphUri = process.env.graphqlApi || 'https://shiny-gateway.unbound.se';
|
||||
// const httpLink = new HttpLink({ uri: defaultGraphUri, fetch: includeCredentials, credentials: 'same-origin' });
|
||||
// const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
|
||||
// if (graphQLErrors) {
|
||||
// console.log('GraphQL errors:', graphQLErrors);
|
||||
// // for (let err of graphQLErrors) {
|
||||
// // switch (err.extensions.code) {
|
||||
// // case 'UNAUTHENTICATED':
|
||||
// // // error code is set to UNAUTHENTICATED
|
||||
// // // when AuthenticationError thrown in resolver
|
||||
// //
|
||||
// // // modify the operation context with a new token
|
||||
// // }
|
||||
// // }
|
||||
// }
|
||||
// if (networkError) {
|
||||
// if (networkError.statusCode === 401) {
|
||||
// return new Observable(observer => {
|
||||
// // webAuth.checkSession(() => {
|
||||
// const subscriber = {
|
||||
// next: observer.next.bind(observer),
|
||||
// error: observer.error.bind(observer),
|
||||
// complete: observer.complete.bind(observer)
|
||||
// };
|
||||
//
|
||||
// // Retry last failed request
|
||||
// forward(operation).subscribe(subscriber);
|
||||
// // }, (err) => {
|
||||
// // console.log(err);
|
||||
// // observer.error(err)
|
||||
// // });
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// );
|
||||
@@ -1,8 +0,0 @@
|
||||
import Vue from 'vue';
|
||||
import AppLoader from '~/components/common/app-loader';
|
||||
import AppMessage from '~/components/common/app-message';
|
||||
import AppLazyBackground from '~/components/common/app-lazy-background';
|
||||
|
||||
Vue.component('app-loader', AppLoader);
|
||||
Vue.component('app-message', AppMessage);
|
||||
Vue.component('app-lazy-background', AppLazyBackground);
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
import createAuth0Client from '@auth0/auth0-spa-js'
|
||||
import { reactive, toRefs } from '@vue/composition-api'
|
||||
|
||||
/** Define a default action to perform after authentication */
|
||||
const DEFAULT_REDIRECT_CALLBACK = () =>
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
|
||||
let instance;
|
||||
|
||||
const params = (new URL(window.location)).searchParams
|
||||
const domain = params.get('domain') || 'unbound.eu.auth0.com'
|
||||
|
||||
export const useAuth = (onRedirectCallback = DEFAULT_REDIRECT_CALLBACK) => {
|
||||
if (instance) {
|
||||
return toRefs(instance)
|
||||
}
|
||||
|
||||
const options = {
|
||||
domain: domain,
|
||||
client_id: 'orQfnvCPUR5C3mJkKoiWLQHOVQsBn60e',
|
||||
audience: 'http://dancefinder.unbound.se',
|
||||
redirect_uri: window.location.origin,
|
||||
}
|
||||
|
||||
instance = reactive({
|
||||
loading: false,
|
||||
isAuthenticated: false,
|
||||
user: {},
|
||||
auth0Client: null,
|
||||
popupOpen: false,
|
||||
error: null,
|
||||
/** Authenticates the user using a popup window */
|
||||
loginWithPopup: async o => {
|
||||
this.popupOpen = true;
|
||||
|
||||
try {
|
||||
await instance.auth0Client.loginWithPopup(o);
|
||||
} catch (e) {
|
||||
// eslint-disable-next-line
|
||||
console.error(e);
|
||||
} finally {
|
||||
instance.popupOpen = false;
|
||||
}
|
||||
|
||||
instance.user = await instance.auth0Client.getUser();
|
||||
instance.isAuthenticated = true;
|
||||
},
|
||||
/** Handles the callback when logging in using a redirect */
|
||||
handleRedirectCallback: async () => {
|
||||
instance.loading = true;
|
||||
try {
|
||||
await instance.auth0Client.handleRedirectCallback();
|
||||
instance.user = await instance.auth0Client.getUser();
|
||||
instance.isAuthenticated = true;
|
||||
} catch (e) {
|
||||
instance.error = e;
|
||||
} finally {
|
||||
instance.loading = false;
|
||||
}
|
||||
},
|
||||
/** Authenticates the user using the redirect method */
|
||||
loginWithRedirect: o => {
|
||||
return instance.auth0Client.loginWithRedirect(o);
|
||||
},
|
||||
/** Returns all the claims present in the ID token */
|
||||
getIdTokenClaims: o => {
|
||||
return instance.auth0Client.getIdTokenClaims(o);
|
||||
},
|
||||
/** Returns the access token. If the token is invalid or missing, a new one is retrieved */
|
||||
getTokenSilently: o => {
|
||||
return instance.auth0Client.getTokenSilently(o);
|
||||
},
|
||||
/** Gets the access token using a popup window */
|
||||
getTokenWithPopup: o => {
|
||||
return instance.auth0Client.getTokenWithPopup(o);
|
||||
},
|
||||
/** Logs the user out and removes their session on the authorization server */
|
||||
logout: o => {
|
||||
return instance.auth0Client.logout(o);
|
||||
}
|
||||
})
|
||||
|
||||
const fetchUser = () => {
|
||||
instance.auth0Client.isAuthenticated()
|
||||
.then(a => {
|
||||
instance.isAuthenticated = a
|
||||
instance.auth0Client.getUser()
|
||||
.then(u => {
|
||||
instance.user = u
|
||||
instance.loading = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
// Create a new instance of the SDK client using members of the given options object
|
||||
createAuth0Client(options)
|
||||
.then(client => {
|
||||
instance.loading = true
|
||||
instance.auth0Client = client
|
||||
try {
|
||||
// If the user is returning to the app after authentication..
|
||||
if (
|
||||
window.location.search.includes('code=') &&
|
||||
window.location.search.includes('state=')
|
||||
) {
|
||||
// handle the redirect and retrieve tokens
|
||||
instance.auth0Client.handleRedirectCallback()
|
||||
.then(appState => {
|
||||
// Notify subscribers that the redirect callback has happened, passing the appState
|
||||
// (useful for retrieving any pre-authentication state)
|
||||
onRedirectCallback(appState);
|
||||
// Initialize our internal authentication state
|
||||
fetchUser()
|
||||
})
|
||||
} else {
|
||||
fetchUser()
|
||||
}
|
||||
} catch (e) {
|
||||
instance.error = e;
|
||||
} finally {
|
||||
instance.loading = false
|
||||
}
|
||||
})
|
||||
|
||||
return toRefs(instance)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import Vue from 'vue';
|
||||
import VueCompositionApi from '@vue/composition-api';
|
||||
|
||||
Vue.use(VueCompositionApi);
|
||||
@@ -1,15 +0,0 @@
|
||||
export default ({ app }) => {
|
||||
app.router.beforeEach((to, from, next) => {
|
||||
// keep the graphql api url variable on all navigation,
|
||||
// if it is actually present.
|
||||
let target;
|
||||
|
||||
if (!to.query.graph && from.query.graph) {
|
||||
target = {
|
||||
path: to.path,
|
||||
query: { ...to.query, graph: from.query.graph },
|
||||
};
|
||||
}
|
||||
next(target);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import Vue from 'vue';
|
||||
import hooks from '@u3u/vue-hooks';
|
||||
|
||||
Vue.use(hooks);
|
||||
@@ -0,0 +1,14 @@
|
||||
let i18n = null
|
||||
let localePath = null
|
||||
|
||||
export const useTranslation = () => {
|
||||
return {
|
||||
t: i18n.t.bind(i18n),
|
||||
localePath
|
||||
}
|
||||
}
|
||||
|
||||
export default ({app}) => {
|
||||
i18n = app.i18n
|
||||
localePath = app.localePath
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import Vue from 'vue';
|
||||
import VueLazyload from 'vue-lazyload';
|
||||
|
||||
Vue.use(VueLazyload, {
|
||||
lazyComponent: true,
|
||||
});
|
||||
Reference in New Issue
Block a user