res locals being wiped from _app.tsx in NextJS - express

I am working on a NextJS app that integrates with passport for authentication. I have it configured so that on login it links to a 3rd party auth service (keycloak - shouldn't be important) and then on success back to a callback url.
The session exists on req.session and I have a root level middleware ('/') to append the req.session.user to res.locals.user
In the custom _app.tsx file I have a getInitialProps that I can extract out ctx.res.locals.user and logging it to console all data is as expected.
The problem is when I pass it as part of pageProps returned from getInitialProps, the same user data is undefined when console logged within JSX.
Here's how the code looks:
function MyApp({Component, pageProps}: AppProps<{user: any}>) {
const { user } = pageProps;
return (
<div>
{console.log(user)} // this is 'undefined' in browser console
{/* ... */}
</div>
);
}
MyApp.getInitialProps = async (appContext: AppContext) => {
const pageProps = await App.getInitialProps(appContext);
const user = appContext.ctx.res.locals.user;
console.log(user) // logs the correct user information in the terminal
return {
pageProps: {
...pageProps,
user,
}
}
};
I am checking the logs on the home-page of app (pages/index.tsx), which has its own getServerSideProps call so I am wondering if this is the point where the res.locals is being cleared?
Questions:
Should I be able to pass res.locals from server to client like this?
If yes, can you see what I'm doing wrong
If not, how should user data returned in req.session be made available from server to client in NextJS?

Related

FirebaseAuth with SvelteKit on +page.ts load

I have a SvelteKit app and am using Firebase and Node to do simple Google SSO auth. I am using an API that requires the IDToken of the currently signed in user to authenticate requests. Ideally I'd like to use the +page.ts load function to load in the data, something like this:
export const load = (async () => {
// Get user, token
const auth = getAuth();
const user = auth.currentUser;
const token = await user?.getIDToken();
if (!token) throw error(401, "Could not authenticate");
// Use token to get data needed to load page
const data = api.requestData(token);
return { data };
}) satisfies PageLoad;
export const ssr = false;
The issue is that user is always null when this function executes. I imagine this is because this is called before the page loads and Firebase hasn't had a way to access the session and get the current user.
My question is, what approach do I take to solve this without simply requesting the data after the page is rendered? Is there a way to authenticate the user server side? Thanks so much.

404 error calling GET API from a shopify theme-extension

I'm new to shopify development, and can't figure out how to call an authenticated API from a shopify theme-extension. Essentially, I'm trying to make a theme extension, where one of the functionalities is that when a checkbox is clicked, an API that counts the number of products is called.
I have a working api that gets the product count, and in web>index.js, I have set-up the end-point:
app.get("/api/products/count", async (_req, res) => {
const countData = await shopify.api.rest.Product.count({
session: res.locals.shopify.session,
});
res.status(200).send(countData);
});
Under web>frontend>hooks, I have the authenticated hooks set-up as shown below. I've tested that if I call the "api/products/count" API from one of the web pages using useAppQuery, it works as expected, and returns the product count.
import { useAuthenticatedFetch } from "./useAuthenticatedFetch";
import { useMemo } from "react";
import { useQuery } from "react-query";
export const useAppQuery = ({ url, fetchInit = {}, reactQueryOptions }) => {
const authenticatedFetch = useAuthenticatedFetch();
const fetch = useMemo(() => {
return async () => {
const response = await authenticatedFetch(url, fetchInit);
return response.json();
};
}, [url, JSON.stringify(fetchInit)]);
return useQuery(url, fetch, {
...reactQueryOptions,
refetchOnWindowFocus: false,
});
};
In my theme extension code, I've added an event listener to the checkbox which calls getProductCount. In getProductCount, I want to call /api/products/count:
import { useAppQuery } from "../../../web/frontend/hooks";
export const getProductCount = (product) => {
const {
data,
refetch: refetchProductCount,
isLoading: isLoadingCount,
isRefetching: isRefetchingCount,
} = useAppQuery({
url: "/api/products/count",
reactQueryOptions: {
onSuccess: () => {
setIsLoading(false);
},
},
});
}
However, when I run locally and click the checkbox, it returns a 404 error trying to find useAppQuery. The request URL is https://cdn.shopify.com/web/frontend/hooks. It seems like the authentication isn't working because that URL looks incorrect.
Am I missing a step that I need to do in order to call an authenticated API from a theme-extension?
I thought the issue was just the import path for useAppQuery but I've tried different paths, and they all return the same 404 issue.
If you want a hot tip here. In your theme App extension, you do not actually need to make an API call to get a product count. In your theme app extension, you can just use Liquid, and dump the product count out to a variable of your choice, and use the count, display the count, do whatever.
{{ shop.product_count }}
Of course, this does not help you if you need other storefront API calls in your theme App extension, but whatever. In my experience, I render the API Access Token I need in my theme app extension, and then making my Storefront API calls is just a fetch().
The only time I would use authenticated fetch, is when I am doing embedded App API calls, but that is a different beast from a theme app extension. In there, you do not get to make authenticated calls as the front-end is verboten for those of course. Instead you'd use App Proxy for security.
TL:DR; Storefront API calls with a token should not fail with a 404 if you call the right endpoint. You can use Storefront API inside a theme app extension. Inside a theme app extension, if you need backend Admin API access, you can use App Proxy calls.

Nuxt don't see a authenticated user

I am doing user authentication, but I ran into a problem. First, when loading, the middleware is loaded, it does not see the authorized user through $fire.auth.onAuthStateChanged. And if you go to another page (without reloading page), user is appear. How to make him see it at the first boot?
Here is my middleware
export default function ({app, route, redirect}) {
console.log('middleware')
app.$fire.auth.onAuthStateChanged(user => {
if (user) {
console.log('user+')
if (route.path === perm.signin || route.path === perm.signup) {
return redirect('/')
}
} else {
console.log('user-')
if (route.path !== perm.signin || route.path !== perm.signup) {
return redirect(perm.signin)
}
}
})
}
and what I received (1st pic) when first enter to app in console.log(middleware, user-). But if I go to another page I receive middleware, user+.
I need user + to be on the first start
onAuthStateChanged fires the callback you provided as argument after the middleware has run.
In other words the callback's return statements are not being run when the middleware runs.
You could either ensure the middleware is called after the first authentication attempt, but this would slow down the initial startup of the application. So you could expose the nuxt router to the onAuthStateChanged handler and router.push('/login') or router.push('/somewhere') from there.

Running Nuxt middleware client side after static rendering

We're switching from SPA to statically generated, and are running into a problem with middleware.
Basically, when Nuxt is statically rendered, middleware is run on the build server first, and then is run after each page navigation client side. The important point is that middleware is not run client side on first page load. This is discussed here
We work around this for some use cases by creating a plugin that uses the same code, since plugins are run on the first client load.
However, this pattern doesn't work well for this use case. The following is an example of the middleware that we want to use:
// middleware/authenticated.js
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.authenticated) {
return redirect('/login')
}
}
// Inside a component
<template>
<h1>Secret page</h1>
</template>
<script>
export default {
middleware: 'authenticated'
}
</script>
This example is taken directly from the Nuxt docs.
When rendered statically, this middleware is not called on first page load, so a user might end up hitting their dashboard before they've logged in, which causes problems.
To add this to a plugin, the only way I can think to do this is by adding a list of authenticated_routes, which the plugin could compare to and see if the user needs to be authed.
The problem with that solution though is that we'd then need to maintain a relatively complex list of authed pages, and it's made worse by having dynamic routes, which you'd need to match a regex to.
So my question is: How can we run our authenticated middleware, which is page specific, without needing to maintain some list of routes that need to be authenticated? Is there a way to actually get the middleware associated to a route inside a plugin?
To me it is not clear how to solve it the right way. We are just using the static site generation approach. We are not able to run a nuxt middleware for the moment. If we detect further issues with the following approach we have to switch.
One challenge is to login the user on hot reload for protected and unprotected routes. As well as checking the login state when the user switches the tabs. Maybe session has expired while he was on another tab.
We are using two plugins for that. Please, let me know what you think.
authRouteBeforeEnter.js
The plugin handles the initial page load for protected routes and checks if the user can access a specific route while navigating around.
import { PROTECTED_ROUTES } from "~/constants/protectedRoutes"
export default ({ app, store }) => {
app.router.beforeEach(async (to, from, next) => {
if(to.name === 'logout'){
await store.dispatch('app/shutdown', {userLogout:true})
return next('/')
}
if(PROTECTED_ROUTES.includes(to.name)){
if(document.cookie.indexOf('PHPSESSID') === -1){
await store.dispatch('app/shutdown')
}
if(!store.getters['user/isLoggedIn']){
await store.dispatch('user/isAuthenticated', {msg: 'from before enter plugin'})
console.log('user is logged 2nd try: ' + store.getters['user/isLoggedIn'])
return next()
}
else {
/**
* All fine, let him enter
*/
return next()
}
}
return next()
})
}
authRouterReady.js
This plugin ment for auto login the user on unprotected routes on initial page load dnd check if there is another authRequest required to the backend.
import { PROTECTED_ROUTES } from "~/constants/protectedRoutes";
export default function ({ app, store }) {
app.router.onReady(async (route) => {
if(PROTECTED_ROUTES.includes(route.name)){
// Let authRouterBeforeEnter.js do the job
// to avoid two isAuthorized requests to the backend
await store.dispatch('app/createVisibilityChangedEvent')
}
else {
// If this route is public do the full init process
await store.dispatch('app/init')
}
})
}
Additionally i have added an app module to the store. It does a full init process with auth request and adding a visibility changed event or just adds the event.
export default {
async init({ dispatch }) {
dispatch('user/isAuthenticated', {}, {root:true})
dispatch('createVisibilityChangedEvent')
},
async shutdown({ dispatch }, {userLogout}) {
dispatch('user/logout', {userLogout}, {root:true})
},
async createVisibilityChangedEvent({ dispatch }) {
window.addEventListener('visibilitychange', async () => {
if (document.visibilityState === 'visible') {
console.log('visible changed');
await dispatch('user/isAuthenticated', {}, {root:true})
}
})
},
}

Implementing Google One Tap Login using angular

navbar.template.html
<div id="g_id_onload"
data-client_id="832#################m921.apps.googleusercontent.com"
data-cancel_on_tap_outside="false"
data-login_uri="http://localhost:3010/auth/g-one-tap"
data-callback="handleCredentialResponse">
</div>
The API get the response I am able to validate the user and return the validated JWT token, how can I capture the response and avoid the redirection of the page to http://localhost:3010/auth/g-one-tap
How can I us some click function to be used in typsecript file which can help in following the normal login flow which I am using earlier with google login button.
public socialSignIn(responseData) {
this.googleSubscription = this._globalService.googleLogin(responseData)
.subscribe(
data => {
if (data['success']) {
const token = data['data']['token'];
if (this.platformId === 'browser') {
// login to save the token
}
}
},
error => {
console.log('error');
}
);
}
As mentioned here, you should not use both data-login_uri and data-callbck attributes at the same time.
You need to remove the data-login_uri attribute in you code.
And povide an implementation for the callback function (whose name is handleCredentialResponse in your code) if not yet.