User data isn't saving to mongo, I did this a while ago but I can't seem to get it to work now. I'm using "mongodb": "^3.5.9" so it's not a version error and I can also connect to the database outside of NextAuth, so it's not a connection issue from what I can see.
[...nextauth].js
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET
})
],
jwt: {
secret: process.env.JWT_SECRET,
},
database: process.env.DATABASE_URL,
})
.env
GOOGLE_CLIENT_ID =
GOOGLE_CLIENT_SECRET =
NEXTAUTH_URL = http://localhost:3000
JWT_SECRET =
DATABASE_URL = mongodb+srv://username:password#cluster0.klwliur.mongodb.net/?retryWrites=true&w=majority
Related
I am making a sign up page with 3 providers (Twitter, Facebook and Instagram) using next-auth and prisma with mongoDB. The issue appears when I try to sign up with any of the providers. Here is my nextauth.js file.
import NextAuth from "next-auth"
import { PrismaAdapter } from "#next-auth/prisma-adapter"
import { PrismaClient } from '#prisma/client';
import InstagramProvider from "next-auth/providers/instagram";
import TwitterProvider from "next-auth/providers/twitter";
import FacebookProvider from "next-auth/providers/facebook";
const prisma = new PrismaClient();
export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
InstagramProvider({
clientId: process.env.INSTAGRAM_CLIENT_ID,
clientSecret: process.env.INSTAGRAM_CLIENT_SECRET
}),
TwitterProvider({
clientId: process.env.TWITTER_CLIENT_ID,
clientSecret: process.env.TWITTER_CLIENT_SECRET,
version: "2.0",
}),
FacebookProvider({
clientId: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET
}),
],
session: {
strategy: 'jwt',
},
});
I have tried to reinstall all the dependencies, because I don't see what else could be the problem. At first I thought it was the dependencies so I reinstall all the dependencies.
The problem is in your adapter in the [nextauth].js file or wherever you are declaring the prisma instance.
Check out those similar discussions:
https://github.com/nextauthjs/next-auth/discussions/4152
Integrating Prisma Adapter with Next Auth - Unexpected token 'export'
The issue actually comes from the prisma schema. I fixed it after reading the next auth documentation about prisma and mongoDB.
Previously, typeorm seems to have allowed the use of a ConnectionManager that seems to have allowed to name a particular connection whilst creation and fetch/check the connection with the same name like this:
import { Connection, createConnection, getConnectionManager } from 'typeorm';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
import * as tenantsOrmconfig from '../../tenants-orm.config';
export function getTenantConnection(tenantId: string): Promise<Connection> {
const connectionName = `tenant_${tenantId}`;
const connectionManager = getConnectionManager();
if (connectionManager.has(connectionName)) {
const connection = connectionManager.get(connectionName);
return Promise.resolve(connection.isConnected ? connection : connection.connect());
}
return createConnection({
...(tenantsOrmconfig as PostgresConnectionOptions),
name: connectionName,
schema: connectionName,
});
}
But, I'm confused now as to how to achieve this when I'm using a Datasource using a factory to create dynamic connection:
#Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
const host = configService.get('MY_DB_HOST');
const port = parseInt(configService.get('MY_DB_PORT'));
const user = configService.get('MY_DB_USER');
const password = configService.get('MY_DB_PASSWORD');
const dbName = configService.get('MY_DB_NAME');
return {
type: 'postgres',
host: host,
port: port,
username: user,
password: password,
database: dbName,
entities: entities,
synchronize: true,
};
}
})
],
controllers: [AppController],
providers: [AppService],
})
I'm trying to fetch an existing connection from the connection pool which typeorm is supposed to manage by default if it already exists, and that connection is supposed to belong to a tenant if it exists, else it should create a new connection for the tenant. How do I do this with a Datasource?
I can see that there is a datasourceInstance.manager.find() method, but, that seems to take an Entity which seems to query the database, and I can't find anything more useful in the docs.
I'm using windows 10, Nest.js and typeORM.
Previously, I had to create a new user\role uder my windows user - but now the ORM don't seem to find my db (called steamClone) - and calls a db named after my user:
error: database "Itay" does not exist
typeORM is configured like such encapsulated in a module:
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import {ConfigModule, ConfigService} from '#nestjs/config';
#Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (ConfigService: ConfigService) => ({
type: 'postgres',
host: ConfigService.get('DB_HOST'),
port: ConfigService.get('DB_PORT'),
username: ConfigService.get('DB_USER'),
password: ConfigService.get('DB_PASSWORD'),
database: ConfigService.get('DB_DATABASE'),
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: true,
})
})
],
})
export class DatabaseModule {}
all of the parameters are stored in a .env file
running on localhost, default port and everything, postgres user etc.
would love to know how to solve this
I git clone & copy MUI Nextjs example project & start from there.
From NextAuth portal, they said I can just copy mongodb adapter setup here and basically it will work well out of the box. I placed this file in this path: /src/lib/mongodb.js
Here I'm using CredentialsProvider. Basically I'm using my own form for login & authentication process.
Here my /pages/api/auth/[...nextauth].js file:
import { MongoDBAdapter } from "#next-auth/mongodb-adapter";
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import clientPromise from "../../../src/lib/mongodb";
export default NextAuth({
secret: process.env.SECRET,
adapter: MongoDBAdapter(clientPromise),
providers: [
CredentialsProvider({
async authorize(credentials) {
const { email, password } = credentials
if(email !== 'test#test.com' || password !== 'password123') {
throw new Error('User does not exists. Please make sure you insert the correct email & password.')
}
return {
id: 1,
name: 'Tester',
email: 'test#test.com'
}
}
})
],
callbacks: {
redirect: async ({ url, baseUrl }) => {
return baseUrl
}
}
})
What I understood, I can just straight away use this adapter & it will create 4 models/tables (User, Session, Account, VerificationToken) by default. So I don't need to create them myself. Ref doc here
According to the NextAuth MongoDB Adapter documentation, I just need to specify the MONGODB_URI in .env.local.
so here my /.env.local file content:
NEXTAUTH_URL=http://localhost:3000
MONGODB_URI=mongodb+srv://<username>:<password>#rest.lvnpm.mongodb.net/<database_name>?retryWrites=true&w=majority
SECRET=someSecret
NODE_ENV=development
So currently, it does nothing at all. I don't need to specify session.strategy to database since by default NextAuth will recognized that if I use adapter option.
What do I need to do here to make this work? Any helps is appreciated. Here my github project
I just found out that in NextAuth, if I use CredentialsProvider. I won't be able to persist data using database strategy. You may go here to NextAuth documentation itself to know why
I am trying to connect with MongoDB by mongoose. Everything was ok, when I was connecting with my local db where there is no authentication.
When I've tried to connect to other DB with set admin user and credentials, I've got error and I've tried various different options but without any positive result.
I use these versions:
"mongodb": "^3.3.2",
"mongoose": "^5.7.1"
And my server side technology is node.js
I've tried these options:
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}?authSource=admin`,
{ useNewUrlParser: true, useUnifiedTopology: true });
then I've tried this:
let options = {
"auth": { "authSource":"admin"},
"user": "SVSAdmin",
"pass":"8&PG2DCUuDPvy$hx",
"useUnifiedTopology": true,
"useNewUrlParser": true
};
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}, options);
and this:
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=SCRAM-SHA-1')
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=MONGODB-CR')
and also this:
mongoose.connect('mongodb://user:password#host/yourDB?authSource=admin&w=1')
but it does not work. My credentials are ok.
The error message is:
{
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
}
Maybe important thing is that I'm connecting with db by ssh
I would be grateful for any help.
If u are using ur database remotly then u can use it via IP.
db = mongodb://52.221.52.32/DataBaseName