check required auth in vue beforeEach method with firebase v9 - firebase

i want to check if user exist before go to some pages in beforeEach method
i export the user state i use firebase v9
export const userAuthState = ()=>{
let currentUser = null;
onAuthStateChanged(auth, (user) => {
if (user) {
currentUser = user;
}
});
return currentUser;
}
here where i use it
import {userAuthState} from 'src/backend/firebase-config';
...
console.log("before route");
Router.beforeEach(async (to,from,next)=>{
if(await !userAuthState() && to.meta.requiresAuth){
next({path: 'login', query:{ redirect: to.fullPath }})
}else if(await userAuthState() && to.meta.requiresAuth == 'login'){
next({path:'/'})
}else{
next()
}
})
here the problem cant navigate to any page and print the console.log many times
how i can check the user before route in correct way
thank you.

I'll give you a simple example of how can you make some decision based on user authentication.
For this, I'll use Vuex as a central store since you'll commonly use user information across all your app. I'll assume that you're building an SPA with Vue and Firebase V9.
This is a simple store for users. Register this store with Vue (with .use()) in your main.js file (your entry point file).
import { createStore } from 'vuex'
const Store = createStore({
state() {
return {
user: {
uid: '',
email: ''
}
}
},
mutations: {
setUser (state, payload) {
if (payload) {
state.user.uid = payload.uid
state.user.email = payload.email
return
}
state.user.uid = ''
state.user.email = ''
}
}
})
export Store
Now, at your App.vue (or your root component) you simple call onAuthStateChanged and run commits depending on User's state:
<template>
<div>Your wonderful template...</div>
</template>
<script>
import { onAuthStateChanged } from "firebase/auth";
import { yourAuthService } from 'yourFirebaseInit'
export default {
name: 'App',
created () {
onAuthStateChanged(yourAuthService, (user) => {
if (user) {
this.$store.commit('setUser', { uid: user.uid, email: user.email })
} else {
this.$store.commit('setUser', null)
}
})
}
}
</script>
Finally, in your routes, you could do something like:
// we import the Store that we've created above.
import { Store } from 'your-store-path'
Router.beforeEach((to,from,next)=>{
if(to.meta.requiresAuth && Store.state.user.uid === ''){
next({path: 'login', query:{ redirect: to.fullPath }})
} else{
next()
}
})
This is a simple example of how can you implement an Authentication flow with Vue and Firebase V9.

Related

How to get stripe customers in next js

I am using Stripe in my NextJs project and have tried to get customers list in my app but have not succeeded. If anyone knows how to get it, please instruct me on how to do that.
This is my code:
import { loadStripe } from "#stripe/stripe-js";
async function getStripeCustomers(){
const stripe = await loadStripe(
process.env.key
);
if (stripe) {
// there was a toturail for node.js like this.
console.log(stripe.customers.list())
}
}
useEffect(() => {
getStripeCustomers()
}, []);
I think you should do this logic in backend so create a route in api folder then try this code.
// api/payment/get-all-customers.js
import Stripe from "stripe";
export default async function handler(req, res) {
if (req.method === "POST") {
const { token } = JSON.parse(req.body);
if (!token) {
return res.status(403).json({ msg: "Forbidden" });
}
const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET, {
apiVersion: "2020-08-27",
});
try {
const customers = await stripe.customers.list(); // returns all customers sorted by createdDate
res.status(200).json(customers);
} catch (err) {
console.log(err);
res.status(500).json({ error: true });
}
}
}
Now from frontend send a POST request to newly created route.

Get supabase `user` server side in next.js

I am attempting to get the current logged in supabase user while server side.
I have attempted to use const user = supabase.auth.user(); but I always get a null response.
I have also attempted const user = supabase.auth.getUserByCookie(req) but it also returns null. I think because I am not sending a cookie to the api when calling it from the hook.
I have tried passing the user.id from the hook to the api but the api is not receiving the parameters.
I also attempted this approach but the token is never fetched. It seems to not exist in req.cookies.
let supabase = createClient(supabaseUrl, supabaseKey);
let token = req.cookies['sb:token'];
if (!token) {
return
}
let authRequestResult = await fetch(`${supabaseUrl}/auth/v1/user`, {
headers: {
'Authorization': `Bearer ${token}`,
'APIKey': supabaseKey
}
});
`
Does anyone know how to get the current logged in user in server side code?
If you need to get the user in server-side, you need to set the Auth Cookie in the server using the given Next.js API.
// pages/api/auth.js
import { supabase } from "../path/to/supabaseClient/definition";
export default function handler(req, res) {
if (req.method === "POST") {
supabase.auth.api.setAuthCookie(req, res);
} else {
res.setHeader("Allow", ["POST"]);
res.status(405).json({
message: `Method ${req.method} not allowed`,
});
}
}
This endpoint needs to be called every time the state of the user is changed, i.e. the events SIGNED_IN and SIGNED_OUT
You can set up a useEffect in _app.js or probably in a User Context file.
// _app.js
import "../styles/globals.css";
import { supabase } from '../path/to/supabaseClient/def'
function MyApp({ Component, pageProps }) {
useEffect(() => {
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
handleAuthChange(event, session)
if (event === 'SIGNED_IN') {
// TODO: Actions to Perform on Sign In
}
if (event === 'SIGNED_OUT') {
// TODO: Actions to Perform on Logout
}
})
checkUser()
return () => {
authListener.unsubscribe()
}
}, [])
return <Component {...pageProps} />;
}
async function handleAuthChange(event, session) {
await fetch('/api/auth', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
credentials: 'same-origin',
body: JSON.stringify({ event, session }),
})
}
export default MyApp;
You can now handle this user with a state and pass it to the app or whichever way you'd like to.
You can get the user in the server-side in any Next.js Page
// pages/user_route.js
import { supabase } from '../path/to/supabaseClient/def'
export default function UserPage ({ user }) {
return (
<h1>Email: {user.email}</h1>
)
}
export async function getServerSideProps({ req }) {
const { user } = await supabase.auth.api.getUserByCookie(req)
if (!user) {
return { props: {}, redirect: { destination: '/sign-in' } }
}
return { props: { user } }
}
Here's a YouTube Tutorial from Nader Dabit - https://www.youtube.com/watch?v=oXWImFqsQF4
And his GitHub Repository - https://github.com/dabit3/supabase-nextjs-auth
supabase have a library of helpers for managing auth for both client- and server-side auth and fetching in a couple of frameworks including Next.js: https://github.com/supabase/auth-helpers and appears to be the recommended solution for similar problems based on this thread: https://github.com/supabase/supabase/issues/3783
This is how I'm using it in an API handler, but provided you have access to req, you can access the user object this way:
import { supabaseServerClient } from '#supabase/auth-helpers-nextjs';
const { user } = await supabaseServerClient({ req, res }).auth.api.getUser(req.cookies["sb-access-token"]);
Note that you will need to use the helper library supabaseClient and supabaseServerClient on the client and server side respectively for this to work as intended.
I was following a tutorial today and was having a similar issue and the below is how i managed to fix it.
I've got this package installed github.com/jshttp/cookie which is why i'm calling cookie.parse.
Supabase Instance:
`//../../../utils/supabase`
import { createClient } from "#supabase/supabase-js";
export const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_KEY
);
In my case this was my API page:
import { supabase } from "../../../utils/supabase";
import cookie from "cookie";
import initStripe from "stripe";
const handler = async (req, res) => {
const { user } = await supabase.auth.api.getUserByCookie(req);
if (!user) {
return res.status(401).send("Unathorized");
}
const token = cookie.parse(req.headers.cookie)["sb-access-token"];
supabase.auth.session = () => ({
access_token: token,
});`
const {
data: { stripe_customer },
} = await supabase
.from("profile")
.select("stripe_customer")
.eq("id", user.id)
.single();
For anyone who tries to figure out how to get the user server side with the new #supabase/auth-helpers-nextjs, Michele gave the answer.
Just a note: If you're trying to get the user on nextJs's Middleware, instead of:
... req.cookies["sb-access-token"]
You have to use: req.cookies.get('sb-access-token')
For example:
import { supabaseServerClient } from '#supabase/auth-helpers-nextjs';
const { user } = await supabaseServerClient({ req, res }).auth.api.getUser(req.cookies.get('sb-access-token'))
UPDATE: 2023. Available now on Supabase Docs here
import { createServerSupabaseClient } from '#supabase/auth-helpers-nextjs'
export default function Profile({ user }) {
return <div>Hello {user.name}</div>
}
export const getServerSideProps = async (ctx) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient(ctx)
// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession()
if (!session)
return {
redirect: {
destination: '/',
permanent: false,
},
}
return {
props: {
initialSession: session,
user: session.user,
},
}
}

Protect pages from not logged in user in Nextjs

I am creating a login page and dashboard for the admin panel using NExtjS and react-redux. Below is the code I have tried. If I login using Id and password I can login and get all the values from the state and everything works fine.
The problem is if I tried to access the dashboard URL directly it says
Cannot read properties of null (reading 'name') how can I redirect the user to the login page instead of getting up to return statement ???
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';
const Dashboard = () => {
const { auth } = useSelector((state) => state);
const router = useRouter();
console.log(auth)
// I can get all the objects from state and cookies are set as state for browser reload so everything is fine here.
useEffect(() => {
if (!auth.userInfo && auth.userInfo.role == 'user') {
router.push('/admin');
console.log('I am here');
}
}, []);
return <h1>{auth.userInfo.name}</h1>;
};
export default dynamic(() => Promise.resolve(Dashboard), { ssr: false });
Finally I find the correct way of solving this issue. The correct way was:
export const getServerSideProps = async (context) => {
const session = await getSession({ req: context.req });
if (session) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
return {
props: {
session,
},
};
};

How to store firebase token in Vuex store

I'm trying to store the accessToken that comes back from Firebase into the Vuex store in my Vue project when I run the code I get the following error:
Uncaught TypeError: Cannot read property '$store' of undefined
It looks like it's not picking up store.js in the code below, any ideas why that might be?
Thanks
Login.vue
mounted: function() {
Firebase.auth.onAuthStateChanged( user => {
if (user) {
user.getIdToken().then(function(idToken) {
this.$store.commit('setStoreToken', idToken)
return idToken
});
}
else {
.
.
.
}
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
loggedIn: false,
accessToken: '',
},
mutations: {
loggedIn () {
this.state.loggedIn = true
},
loggedOut () {
this.state.loggedIn = false
},
setStoreToken(state, accessToken) {
state.accessToken = accessToken
},
},
getters: {
getAccessToken: state => {
return state.accessToken
}
},
})
main.js
import store from './store.js'
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
My guess:
user.getIdToken().then(function(idToken) {
this.$store.commit('setStoreToken', idToken)
return idToken
});
You dont use an arrow function, that means that this is binded to the function itself you can either use an arrow function or you create a variable infront of it like this const self = this
user.getIdToken().then((idToken)=>{
this.$store.commit('setStoreToken', idToken)
return idToken
});
Or you do it like this:
const self = this;
user.getIdToken().then(function(idToken) {
self.$store.commit('setStoreToken', idToken)
return idToken
});

vue js router + firebase authentication

I use vue js 2.4.2 , vue router 2.7.0 , and firebase 4.3.0. I can't get the route authentication stuff to work. This is my current route.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import Firebase from './firebase'
import Dashboard from './components/Dashboard.vue'
import Auth from './components/Auth.vue'
let router = new Router({
mode: 'history',
routes: [
{
path: '/',
component: Dashboard,
meta: {
auth: true
}
},
{
path: '/login',
component: Auth
}
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.auth)) {
if (!Firebase.auth().currentUser) {
next({
path: '/login'
})
} else {
next()
}
} else {
next()
}
})
export default router
But now everytime I go to / it redirects me back to /login, probably because the Firebase.auth().currentUser is null, even though I am in fact logged in. How do I fix this?
try using Firebase.auth().onAuthStateChanged instead of Firebase.auth().currentUser; it is the recommended way to get the current user.
Getting the user by currentUser may cause a problem similar to what you are seeing. This is from the official doc of firebase.
Note: currentUser might also be null because the auth object has not finished initializing. If you use an observer to keep track of the user's sign-in status, you don't need to handle this case.
Try to set you authentication logic like this:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.auth)) {
Firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
next({
path: '/login'
})
} else {
next()
}
}
} else {
next()
}
})

Resources