how can I use 'vue3-google-oauth' with boot files in Quasar? - vuejs3

I am trying to implement Google OAuth2 using 'vue3-google-oauth'.
I tried the method below, but the signIn() function returned false.
Please tell me how to use 'vue3-google-oauth' with boot files in Quasar.
this is my code.
googleoauth.js
import { boot } from 'quasar/wrappers';
import GAuth from 'vue3-google-oauth2';
let app;
export default boot(({ app }) => {
const gAuthOption = {
clientId: '835170725866-nt6qibip4tb7jafav2k20j83ipso67mo.apps.googleusercontent.com',
scope: 'profile email',
prompt: 'select_account',
};
app.use(GAuth, gAuthOption);
app = app;
});
export { app };
quasar.config.js
...
boot: ['googleoauth'],
...
LoginPage.vue ----- I want to use Google OAuth2 in this file
import { getCurrentInstance } from 'vue';
const app = getCurrentInstance();
app.appContext.config.globalProperties.$gAuth.signIn(); // return false (not working)

Related

Quasar v2 Vue-Apollo Setup

I've recent switched over to Quasar v2 and I'm having trouble getting the info I need for the vue apollo setup. I am using https://apollo.vuejs.org/guide/installation.html#_1-apollo-client to try and install vue apollo into the framework using the boot file.
This is my boot/apollo.ts file
import { boot } from 'quasar/wrappers';
import ApolloClient from 'apollo-boost';
import VueApollo from 'vue-apollo';
const apollo = new ApolloClient({
uri: 'https://api.graphcms.com/simple/v1/awesomeTalksClone',
});
const apolloProvider = new VueApollo({
defaultClient: apollo,
});
export default boot(({ app }) => {
// for use inside Vue files (Options API) through this.$apollo
app.config.globalProperties.$apollo = apollo;
// ^ ^ ^ this will allow you to use this.$apollo (for Vue Options API form)
// so you won't necessarily have to import apollo in each vue file
});
export { apollo, VueApollo, apolloProvider };
And this is where I am trying to use it:
import { Vue } from 'vue-class-component';
export default class LoginPage extends Vue {
public login() {
console.log(this.$apollo);
}
}
The error I'm getting is
Property '$apollo' does not exist on type 'LoginPage'.
I can see in the comment for the globalProperties it mentions the vue options api. Not sure if this is happening because I use vue-class-component.
I ended up added this below the export
declare module '#vue/runtime-core' {
interface ComponentCustomProperties {
$apollo: FunctionConstructor;
}
}

How to access boot file configured axios from Quasar V2 Composition API setup function?

How to access boot file configured axios from Quasar V2 Composition API setup function, without importing axios in every file?
Since this.$axios can be used only for Options API, I tried to access through the context parameter of setup function.
Even though it works, context.root is now deprecated in Vue 3.
I do not want to import axios in every file as shown in the example at https://next.quasar.dev/quasar-cli/ajax-requests
For setup method access, I think it is still not implemented since mentioned as a TODO activity at https://next.quasar.dev/quasar-cli/boot-files#examples-of-appropriate-usage-of-boot-files
Similar to axios, usage of vue-i18n also from boot file is an issue for me.
setup (props, context) {
context.root.$axios({
method: 'get',
url: 'http://localhost:8080/storemgr/item/3',
}).then((response: any) => {
console.log(response)
}).catch((error: any) => {
console.log(error)
})
...
}
Below is my axios boot file contents generated by Quasar V2 CLI
import axios, { AxiosInstance } from 'axios'
import { boot } from 'quasar/wrappers'
declare module 'vue/types/vue' {
interface Vue {
$axios: AxiosInstance;
}
}
export default boot(({ Vue }) => {
// eslint-disable-next-line #typescript-eslint/no-unsafe-member-access
Vue.prototype.$axios = axios
})
The only other way I found is to use Provide/Inject.
In my boot file, I use it like this:
export default boot(({ app }) => {
app.config.globalProperties.$axios = axios
app.provide('axios', app.config.globalProperties.$axios)
})
In any component:
setup() {
const axios: AxiosInstance = inject('axios') as AxiosInstance
[...]
}
In hindsight, I'm not quite sure if this is better than importing it.
For This worked
import {api} from 'boot/axios'
setup() {
return{
api.post('shop/', data, { #api imported that works in setup quasar
headers: {
Authorization: `token ${JSON.parse(localStorage.getItem("userData")).token}`,
'Content-Type': 'multipart/form-data'
},
onUploadProgress: function (progressEvent) {
console.log((progressEvent.loaded / progressEvent.total) * 100);
dialog.update({
message: `${(progressEvent.loaded / progressEvent.total) * 100}%`
})
}
})
}
}

firebase.auth.GoogleAuthProvider is not a constructor

I'm trying to use google sign using firebase in the Vue framework. I don't know what the error is this can anyone help me with this.
vue.runtime.esm.js?2b0e:1888 TypeError: _firebase_js__WEBPACK_IMPORTED_MODULE_2__.fb.auth.GoogleAuthProvider is not a constructor
at VueComponent.socialLogin (Signin.vue?3d55:76)
at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1854)
at HTMLButtonElement.invoker (vue.runtime.esm.js?2b0e:2179)
at HTMLButtonElement.original._wrapper (vue.runtime.esm.js?2b0e:6917)
this is my code
firebase.js
import firebase from "firebase";
var firebaseConfig = {
config
};
const fb=firebase.initializeApp(firebaseConfig);
export { fb };
Sign in.vue
<script>
import { fb } from "../firebase.js";
export default {
name: "Signin",
components: {},
data() {
return {
};
},
methods: {
socialLogin() {
const provider = new fb.auth.GoogleAuthProvider();
fb.auth().signInWithPopup(provider).then((result) => {
this.$router.replace('home');
}).catch((err) => {
alert('Oops. ' + err.message)
});
}
}
};
</script>
The auth property (not the auth() function) is available on the static firebase object, not your firebase app.
You want something more like this
import firebase from "firebase/app"
import "firebase/auth" // 👈 this could also be in your `firebase.js` file
const provider = new firebase.auth.GoogleAuthProvider()

How to import Firebase only on client in Sapper?

I'm importing Firebase into my Sapper application, I do not want the imports to be evaluated on the server. How do I make sure imports are only on the client-side?
I am using Sapper to run sapper export which generates the static files. I have tried:
Creating the firebase instance in it's own file and exported the firebase.auth() and firebase.firestore() modules.
Trying to adjust the rollup.config.js to resolve the dependencies differently, as suggested from the error message below. This brings more headaches.
Creating the Firebase instance in client.js. Unsuccessful.
Creating the instance in stores.js. Unsuccessful.
Declaring the variable and assigning it in onMount(). This causes me to have to work in different block scopes. And feels a bit hacky.
The initialization of the app, works fine:
import firebase from 'firebase/app'
const config = {...}
firebase.initializeApp(config);
I have also discovered that if I change the import to just import firebase from 'firebase' I do not get this server error:
#firebase/app:
Warning: This is a browser-targeted Firebase bundle but it appears it is being run in a Node environment. If running in a Node environment, make sure you are using the bundle specified by the "main" field in package.json.
If you are using Webpack, you can specify "main" as the first item in
"resolve.mainFields": https://webpack.js.org/configuration/resolve/#resolvemainfields
If using Rollup, use the rollup-plugin-node-resolve plugin and set "module" to false and "main" to true: https://github.com/rollup/rollup-plugin-node-resolve
I expected to just export these firebase functionalities from a file and import them into my components like:
<script>
import { auth } from "../firebase";
</script>
But as soon as that import is include, the dev server crashes. I don't want to use it on the server, since I'm just generating the static files.
Does anyone have some ideas on how to achieve importing only on client side?
So I have spent too much time on this. There isn't really a more elegant solution than onMOunt.
However, I did realize that sapper really should be used for it's SSR capabilities. And I wrote an article about how to get set up on Firebase with Sapper SSR and Cloud Functions:
https://dev.to/eckhardtd/how-to-host-a-sapper-js-ssr-app-on-firebase-hmb
Another solution to original question is to put the Firebase CDN's in the global scope via the src/template.html file.
<body>
<!-- The application will be rendered inside this element,
because `app/client.js` references it -->
<div id='sapper'>%sapper.html%</div>
<!-- Sapper creates a <script> tag containing `app/client.js`
and anything else it needs to hydrate the app and
initialise the router -->
%sapper.scripts%
<!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-firestore.js"></script>
</body>
</html>
and in the component:
<script>
import { onMount } from 'svelte';
let database, authentication;
onMount(() => {
database = firebase.firestore();
authentication = firebase.auth();
});
const authHandler = () => {
if (process.browser) {
authentication
.createUserWithEmailAndPassword()
.catch(e => console.error(e));
}
}
</script>
<button on:click={authHandler}>Sign up</button>
I was able to import firebase using ES6. If you are using rollup you need to consfigure namedExports in commonjs plugin:
//--- rollup.config.js ---
...
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'node_modules/idb/build/idb.js': ['openDb'],
'node_modules/firebase/dist/index.cjs.js': ['initializeApp', 'firestore'],
},
}),
The you can use it like this:
//--- db.js ---
import * as firebase from 'firebase';
import 'firebase/database';
import { firebaseConfig } from '../config'; //<-- Firebase initialization config json
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export { firebase };
// Initialize db
export const db = firebase.firestore();
and maybe use it in a service like such:
// --- userService.js ----
import { db } from './common';
const usersCol = db.collection('users');
export default {
async login(username, password) {
const userDoc = await usersCol.doc(username).get();
const user = userDoc.data();
if (user && user.password === password) {
return user;
}
return null;
},
};
EDITED
Full rollup config
/* eslint-disable global-require */
import resolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import commonjs from 'rollup-plugin-commonjs';
import svelte from 'rollup-plugin-svelte';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import config from 'sapper/config/rollup';
import { sass } from 'svelte-preprocess-sass';
import pkg from './package.json';
const mode = process.env.NODE_ENV;
const dev = mode === 'development';
const legacy = !!process.env.SAPPER_LEGACY_BUILD;
// eslint-disable-next-line no-shadow
const onwarn = (warning, onwarn) =>
(warning.code === 'CIRCULAR_DEPENDENCY' && warning.message.includes('/#sapper/')) || onwarn(warning);
export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
svelte({
dev,
hydratable: true,
emitCss: true,
preprocess: {
style: sass(),
},
}),
resolve({
browser: true,
}),
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'node_modules/idb/build/idb.js': ['openDb'],
'node_modules/firebase/dist/index.cjs.js': ['initializeApp', 'firestore'],
},
}),
legacy &&
babel({
extensions: ['.js', '.mjs', '.html', '.svelte'],
runtimeHelpers: true,
exclude: ['node_modules/#babel/**'],
presets: [
[
'#babel/preset-env',
{
targets: '> 0.25%, not dead',
},
],
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
[
'#babel/plugin-transform-runtime',
{
useESModules: true,
},
],
],
}),
!dev &&
terser({
module: true,
}),
],
onwarn,
},
server: {
input: config.server.input(),
output: config.server.output(),
plugins: [
replace({
'process.browser': false,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
svelte({
generate: 'ssr',
dev,
}),
resolve(),
commonjs(),
],
external: Object.keys(pkg.dependencies).concat(require('module').builtinModules || Object.keys(process.binding('natives'))),
onwarn,
},
serviceworker: {
input: config.serviceworker.input(),
output: config.serviceworker.output(),
plugins: [
resolve(),
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
commonjs(),
!dev && terser(),
],
onwarn,
},
};
The clean way is to use the Dynamic Import as the documentation said: Making a component SSR compatible
The way to get around this is to use a dynamic import for your component, from within the onMount function (which is only called on the client), so that your import code is never called on the server.
So here for example we want to import the core of firebase and the authentication package too.
<script>
let firebase;
onMount(async () => {
const module = await import("firebase/app");
await import("firebase/auth");
firebase = module.default;
firebase.initializeApp(firebaseConfig);
});
<script>
And now you can use firebase object as you can, for example we want to login with email and password:
let email;
let password;
async function login() {
try {
let result = await firebase.auth().signInWithEmailAndPassword(
email,
password
);
console.log(result.user);
} catch (error) {
console.log(error.code, error.message);
}
}
In order to use Firebase with Sapper, you have to import firebase not firebase/app. You do want firebase to be able to load correctly with SSR on the backend, not just the frontend. If you have some metatags, for example, that would be stored in the database, you want them to load on the backend (UNTESTED).
You could just use firebase, but then you get the annoying console warning. Remember also firebase loads ALL firebase dependencies while firebase/app does not, that is why you don't want to use it on the frontend. There is probably a way with admin-firebase, but we want to have less dependencies.
Do not use rxfire at all. You don't need it. It causes errors with Sapper. Just plain Firebase.
firebase.ts
import firebase from 'firebase/app';
import "firebase/auth";
import "firebase/firestore";
import * as config from "./config.json";
const fb = (process as any).browser ? firebase : require('firebase');
fb.initializeApp(config);
export const auth = fb.auth();
export const googleProvider = new fb.auth.GoogleAuthProvider();
export const db = fb.firestore();
Firebase functions require an extra step and you must enable dynamic imports. (UNTESTED)
export const functions = (process as any).browser ? async () => {
await import("firebase/functions");
return fb.functions()
} : fb.functions();
While this compiles, I have not tried to run httpsCallable or confirmed it will load from the database on the backend for seo ssr from the db. Let me know if it works.
I suspect all of this will work with the new SvelteKit now that Sapper is dead.

vuex not loading module decorated with vuex-module-decorators

I get this error when trying to load a store module with the vuex-module-decorators into the initialiser:
vuex.esm.js?2f62:261 Uncaught TypeError: Cannot read property
'getters' of undefined at eval (vuex.esm.js?2f62:261) at Array.forEach
() at assertRawModule (vuex.esm.js?2f62:260) at
ModuleCollection.register (vuex.esm.js?2f62:186) at eval
(vuex.esm.js?2f62:200) at eval (vuex.esm.js?2f62:75) at Array.forEach
() at forEachValue (vuex.esm.js?2f62:75) at ModuleCollection.register
(vuex.esm.js?2f62:199) at new ModuleCollection (vuex.esm.js?2f62:160)
The index.ts file is quite simple and all works until i introduce the modules to the initialiser:
import Vue from 'vue';
import Vuex from 'vuex';
import { AuthenticationModule, IAuthenticationState } from './modules/authentication';
import VuexPersistence from 'vuex-persist';
Vue.use(Vuex);
export interface IRootState {
authentication: IAuthenticationState;
}
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
const store = new Vuex.Store<IRootState>({
modules: {
authentication: AuthenticationModule, // if this is not here it works but this will mean the vuex-persist will not work
},
plugins: [vuexLocal.plugin],
});
export default store;
Here is the authentication module i believe is throwing the error:
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import { Generic422, LoginEmailPost, RegisterPost, TokenRenewPost, User, UserEmailPut, UserPasswordPut, UserPut } from '#/api/ms-authentication/model/models';
import { Api } from '#/services/ApiHelper';
import Auth from '#/services/Auth';
import store from '#/store';
export interface IAuthenticationState {
user: User;
authenticated: boolean;
prompt: {
login: boolean,
};
errorRegister: Generic422;
errorLogin: Generic422;
}
const moduleName = 'authentication';
#Module({dynamic: true, store, name: moduleName})
class Authentication extends VuexModule implements IAuthenticationState
{
public authenticated: boolean = false;
public errorRegister: Generic422 = {};
public errorLogin: Generic422 = {};
public prompt = {
login: false,
};
public user: User = {
email: '',
firstName: '',
lastName: '',
birthday: '',
verified: false,
};
#Action({commit: 'SET_USER'})
public async login(data: LoginEmailPost) {
try {
const resp = await Api.authenticationApi.v1LoginEmailPost(data);
Auth.injectAccessJWT(resp.data.tokenAccess.value);
Auth.injectRenewalJWT(resp.data.tokenRenewal.value);
return resp.data.user;
} catch (e) {
return e.statusCode;
}
}
#Mutation
public SET_USER(user: User) {
this.authenticated = true;
this.user = {...this.user, ...user};
}
}
export const AuthenticationModule = getModule(Authentication);
I took this setup from: https://github.com/calvin008/vue3-admin
I don't know if this is a bug or if this is a setup issue but completely stuck here as I intend to use the vuex-persist here to "rehydrate" the store after page reload.
Another completely different way of declaring the stores with this lib was here: https://github.com/eladcandroid/typescript-vuex-example/blob/master/src/components/Profile.vue but the syntax seems it would get wildly verbose when in the vue3-admin it is alll neatly in the store opposed to the component.
Currently I have all the state nicely persisted to local storage but I have no idea due to this error or and lack of exmaple how rehydrate the store with this stored data :/
It seems there are two ways to use the decorators but both are quite different. I like the method i have found from the vie admin as the components are nice and clean, but i cannot inject the modules as https://www.npmjs.com/package/vuex-persist#detailed states should be done :/
I found the answer to be the example vue admin app was not structured quite correctly.
Instead to export the class from the module:
#Module({ name: 'authentication' })
export default class Authentication extends VuexModule implements IAuthenticationState {
Then inject the class as a module into the index and export the module via the decorator but also inject the store into the said decorator:
import Vue from 'vue';
import Vuex from 'vuex';
import Authentication from './modules/authentication';
import VuexPersistence from 'vuex-persist';
import { getModule } from 'vuex-module-decorators';
Vue.use(Vuex);
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
const store = new Vuex.Store({
modules: {
authentication: Authentication,
},
plugins: [vuexLocal.plugin],
});
export default store;
export const AuthenticationModule = getModule(Authentication, store);
The result is it all works.

Resources