Meteor loading Firebase Admin on Server Side - firebase

I am working on a React Native / Meteor combo, Where Meteor is my server. I need to set up a Firebase admin instance to send an API request for triggering push notifications for my React Native app.
I have installed the Firebase NPM SDK, when I go to import and/or require the firebase.admin object instance is empty or incomplete. Works fine if I load it into a normal node app setup.
I am assuming there is a latency with the import/require. I looked at some wrapper packages but they are outdated and unmaintained.
import * as admin from 'firebase-admin'
console.log(admin)
Should print
FirebaseNamespace {
__esModule: true,
credential:
{ cert: [Function: cert],
refreshToken: [Function: refreshToken],
applicationDefault: [Function: applicationDefault] },
SDK_VERSION: '6.2.0',
Promise: [Function: Promise],
INTERNAL:
FirebaseNamespaceInternals {
firebase_: [Circular],
serviceFactories: {},
apps_: {},
appHooks_: {} },
default: [Circular] }
But instead prints
{ default: {}, [Symbol(__esModule)]: true }

Related

next-auth: Why occurs 'OAuthCallback' error only in production?

I want add signin features using 'GoogleProvider' in next-auth.
I finished google cloud and firebase settings
OAuth 2.0 client ID in Credentials
App domain, Authorized domains in OAuth consent screen
create web app in firebase project settings
and [...nextauth].ts code is below:
import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import KakaoProvider from "next-auth/providers/kakao"
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { db } from "../../../firebase.config";
const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID_DEV as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET_DEV as string
})
],
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: "jwt",
maxAge: 3 * 60 * 60
},
adapter: FirestoreAdapter(db.app.options),
pages: {
signIn: '/login'
},
callbacks: {
async session({ session, user, token }) {
return session;
}
},
debug: true
}
export default NextAuth(authOptions);
This project is deploying with Github Actions, Cloud Run, Firebase Hosting.
It works very well in local but not works in production.
Interestingly, It works well in Cloud Run project service URL.
Only not works in domain web page that used Firebase Hosting.
so, I tried these
change Authorized redirect URIs in OAuth 2.0 client ID
Edit app registration in OAuth consent screen
callbackUrl property in signIn function
Is this problem caused by Firebase Hosting?
How can I solve this problem?
Thanks.
+add
When I was looking log in Cloud Run, I found these logs:
https://next-auth.js.org/errors#oauth_callback_error checks.state argument is missing.
error: TypeError: checks.state argument is missing.
name: 'OAuthCallbackError'

getting error when using nuxt 3 with nuxt auth module

I am using nuxt 3 + nuxt auth module
getting this error :
this is my nuxt config
export default defineNuxtConfig({
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth-next'
],
auth: {
strategies: {
cookie: {
cookie: {
// (optional) If set, we check this cookie existence for loggedIn check
name: 'XSRF-TOKEN',
},
endpoints: {
// (optional) If set, we send a get request to this endpoint before login
csrf: {
url: ''
}
}
},
}
}
})
what is the problem ?
The auth module is currently not supported by Nuxt3 but it is planned on the roadmap.
https://v3.nuxtjs.org/community/roadmap#%EF%B8%8F-roadmap
Latest official update: https://twitter.com/Atinux/status/1570317156033642496?t=YNN0iWL6M5l3Z0xm_ernCg&s=19

Identifier 'module' has already been declared - amplify and nuxt 3

I am getting an error in nuxt3 then setting up this amplify plugin. I am trying to add auth to nuxt3 via plugins
plugins/amplify.js
import Amplify, {withSSRContext} from 'aws-amplify';
export default defineNuxtPlugin((ctx) => {
const awsConfig = {
Auth: {
region: "ap-south-1",
userPoolId: "ap-south-1_#########",
userPoolWebClientId: "#####################",
authenticationFlowType: "USER_SRP_AUTH",
},
};
Amplify.configure({ ...awsConfig, ssr: true });
if (process.server) {
const { Auth } = withSSRContext(ctx.req);
return {
provide: {
auth: Auth,
},
};
}
return {
provide: {
auth: Auth,
},
};
}
[nuxt] [request error] Identifier 'module' has already been declared
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
at async link (internal/modules/esm/module_job.js:67:21)
Does anyone know what's going on?
Been facing this myself... I don't think its a nuxt problem but rather Vite.
I gave up on running the app on dev mode and just resorted to building the app and launching it. Also, in order to use aws-amplify with vite you need to apply some workarounds:
https://ui.docs.amplify.aws/vue/getting-started/troubleshooting
For the window statement (which only makes sense on the browser) you'll need to wrap that with an if statement. Added this to my plugin file
if (process.client) {
window.global = window;
var exports = {};
}
This will let you build the project and run it with npm run build . Far from ideal but unless someone knows how to fix that issue with dev in vite...
BTW, you can also just switch to webpack builder on nuxt settings and the issue goes away.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
builder: "webpack"
});
I think this might be a problem with auto imports of nuxt.
I added a ~/composables/useBucket.ts file which I used in ~/api. Same error started popping up the next day. After I moved ~/composables/useBucket.ts to ~/composablesServer/useBucket.ts issue disappeared.

Amplify CDK with Next.js SSR

I am trying to deploy a next.js (ssr) application in AWS' Amplify using the CDK but Amplify fails to identify the app as next.js ssr. When I do it manually though, using AWS UI, app is identified as SSR and works as expected.
This is generated by aws-cdk/aws-amplify v118 as:
import * as cdk from '#aws-cdk/core';
import * as amplify from '#aws-cdk/aws-amplify';
import codebuild = require('#aws-cdk/aws-codebuild');
export class AmplifyStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: cdk.StackProps) {
super(scope, id, props);
const sourceCodeProvider = new amplify.GitHubSourceCodeProvider({
owner: '.....',
repository: '....',
oauthToken: cdk.SecretValue.secretsManager('github-token'),
});
const buildSpec = codebuild.BuildSpec.fromObjectToYaml(
{
version: 1,
applications: [
{
frontend: {
phases: {
preBuild: {
commands: [
"npm install"
]
},
build: {
commands: [
"npm run build"
]
}
},
artifacts: {
baseDirectory: ".next",
files: [
"**/*"
]
},
cache: {
paths: [
"node_modules/**/*"
]
}
}
}
]
}
);
const amplifyApp = new amplify.App(this, "cdk-nf-web-app", {
sourceCodeProvider: sourceCodeProvider,
buildSpec: buildSpec
});
amplifyApp.addBranch('develop', {
basicAuth: amplify.BasicAuth.fromGeneratedPassword('dev')
});
amplifyApp.addCustomRule({
source: "</^[^.]+$|\\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>",
target: "/index.html",
status: amplify.RedirectStatus.REWRITE
});
}
}
Which is identical to what AWS has generated when I do it manually from UI. The difference here is the lack of Framework identification as shown in picture. Any ideas?
To answer my own question, I was missing the role as without it aws won't create the necessary resources. (role: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-iam-readme.html)
Edit to elaborate on how i fixed it:
Added a new role that can be used by amplify
const role = new iam.Role(this, 'amplify-role-webapp-'+props.environment, {
assumedBy: new iam.ServicePrincipal('amplify.amazonaws.com'),
description: 'Custom role permitting resources creation from Amplify',
});
and assigned a policy (AdministratorAccess) that role
let iManagedPolicy = iam.ManagedPolicy.fromAwsManagedPolicyName(
'AdministratorAccess',
);
role.addManagedPolicy(iManagedPolicy)
Then upon creating the app, i assigned the role to the app:
const amplifyApp = new amplify.App(this, "cdk-nf-web-app", {
sourceCodeProvider: sourceCodeProvider,
buildSpec: buildSpec,
role: role <--- this line here
});
The amplify app requires authorisation to create the relevant resources:
// This is for demonstrations purposes only; Do not give full access for production usage!
amplifyApp.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({
resources: ["*"],
actions: ['*'],
}))
Source Code Showcase

Meteor + Apollo Subscription: Websocket connection closed

I'm using meteor and trying to make Apollo Subscriptions to work, but I'm getting
WebSocket connection to 'ws://127.0.0.1:3000/sockjs/401/m892wugm/websocket' failed: Connection closed before receiving a handshake response in the client.
I followed apollographql.com guide for Server Configuration and Client Configuration but I'm not quite sure how to connection the client to the server yet.
In the client, I'm using ApolloClient and ApolloLink to pass the Meteor auth to GraphQL.
Here's the code:
Client
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
const httpLink = new createHttpLink()
const authLink = new ApolloLink((operation, forward) => {
operation.setContext(() => ({
headers: { 'meteor-login-token': Accounts._storedLoginToken() },
}))
return forward(operation)
})
export default ApolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
})
Server
createApolloServer({
schema,
tracing: true,
cacheControl: true,
})
new SubscriptionServer({
schema,
execute,
subscribe,
}, {
server: WebApp.httpServer,
path: '/subscriptions',
})
Package.json (not everything, of course)
Meteor 1.6.1.1
...
"apollo-client": "^2.2.5",
"apollo-link": "^1.2.1",
"apollo-link-context": "^1.0.7",
"apollo-link-http": "^1.5.3",
"apollo-link-ws": "^1.0.8",
"subscriptions-transport-ws": "^0.9.9",
...
I read somewhere that passing noServer: true to the SubscriptionServer() resolve the conflict. The error indeed goes away, but the subscription doesnt seem to work either.
And yes, I have followed the Meteor Integration guide from apollographql, but the info there is outdated and does not work.

Resources