Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Users unable to login on production build #710

Closed
2 of 4 tasks
GhS88 opened this issue Sep 24, 2020 · 20 comments
Closed
2 of 4 tasks

Users unable to login on production build #710

GhS88 opened this issue Sep 24, 2020 · 20 comments
Labels
help-needed The maintainer needs help due to time constraint/missing knowledge question Ask how to do something or how something works

Comments

@GhS88
Copy link

GhS88 commented Sep 24, 2020

Your question
First of all, i am really sorry but I am bit new to next/nextauth. I started by cloning the example project and went from there. I have one enabled provider (discord). My issue is that everything works fine when i am running the dev build but as soon as I am running the production build (next start using npm or yarn build then start), users cannot login. I am getting "QueryFailedError: relation "account__accounts" does not exist"

What are you trying to do
Here's a snippet from my simple config:

import Models from "../../../models";
import Adapters from "next-auth/adapters"


const options = {
  providers: [
    Providers.Discord({
      clientId: process.env.DISCORD_CLIENT_ID,
      clientSecret: process.env.DISCORD_CLIENT_SECRET,
      scope: 'identify email guilds',
    }),
  ],
  adapter: Adapters.TypeORM.Adapter(
    // The first argument should be a database connection string or TypeORM config object
    process.env.DATABASE_URL,
    // The second argument can be used to pass custom models and schemas
    {
      models: {
        User: Models.User,
        Account: Models.Account,
      },
    }
  )


When I am running yarn dev, everything is working as expected.

When I am switching to yarn build & yarn start using the same .env from the same machine, i am getting the following exception:

[next-auth][error][get_user_by_provider_account_id_error] QueryFailedError: relation "account__accounts" does not exist
    at new QueryFailedError (/Users/user/Downloads/project/node_modules/typeorm/error/QueryFailedError.js:11:28)
    at Query.callback (/Users/user/Downloads/project/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:184:38)
    at Query.handleError (/Users/user/Downloads/project/node_modules/pg/lib/query.js:139:19)
    at Client._handleErrorMessage (/Users/user/Downloads/project/node_modules/pg/lib/client.js:326:17)
    at Connection.emit (events.js:315:20)
    at /Users/user/Downloads/project/node_modules/pg/lib/connection.js:109:12
    at Parser.parse (/Users/user/Downloads/project/node_modules/pg-protocol/dist/parser.js:40:17)
    at Socket.<anonymous> (/Users/user/Downloads/project/node_modules/pg-protocol/dist/index.js:8:42)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12) {
  length: 117,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '752',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '1194',
  routine: 'parserOpenTable',
  query: 'SELECT "Account_Account"."id" AS "Account_Account_id", "Account_Account"."compound_id" AS "Account_Account_compound_id", "Account_Account"."user_id" AS "Account_Account_user_id", "Account_Account"."provider_type" AS "Account_Account_provider_type", "Account_Account"."provider_id" AS "Account_Account_provider_id", "Account_Account"."provider_account_id" AS "Account_Account_provider_account_id", "Account_Account"."refresh_token" AS "Account_Account_refresh_token", "Account_Account"."access_token" AS "Account_Account_access_token", "Account_Account"."access_token_expires" AS "Account_Account_access_token_expires", "Account_Account"."created_at" AS "Account_Account_created_at", "Account_Account"."updated_at" AS "Account_Account_updated_at" FROM "account__accounts" "Account_Account" WHERE "Account_Account"."provider_id" = $1 AND "Account_Account"."provider_account_id" = $2 LIMIT 1',
  parameters: [ 'discord', '210621734712377344' ]
} 
https://next-auth.js.org/errors#get_user_by_provider_account_id_error
[next-auth][error][oauth_callback_handler_error] Error: GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR
    at /Users/user/Downloads/project/node_modules/next-auth/dist/adapters/typeorm/index.js:224:35
    at Generator.throw (<anonymous>)
    at asyncGeneratorStep (/Users/user/Downloads/project/node_modules/next-auth/dist/adapters/typeorm/index.js:28:103)
    at _throw (/Users/user/Downloads/project/node_modules/next-auth/dist/adapters/typeorm/index.js:30:291)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) 
https://next-auth.js.org/errors#oauth_callback_handler_error

Now i understand from https://next-auth.js.org/errors that GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR means a DB interaction error but what I am failing to understand is why I am getting this error if I am running the build using the same .env and using the same db instance. I am using a postgres instance if that helps. I appreciate any assistance.

Feedback
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

  • [] Found the documentation helpful
  • Found documentation but was incomplete
  • Could not find relevant documentation
  • Found the example project helpful
  • Did not find the example project helpful
@GhS88 GhS88 added the question Ask how to do something or how something works label Sep 24, 2020
@iaincollins
Copy link
Member

Hi there!

Hmm I wonder if you have a slightly different schema on production database than in development database (assuming you have more than one database)?

If you are able to login in with a tool you can use to view and compare schemas on each database that might highlight any discrepancies.

If you only have one database and are connecting to it in both development and production modes I'd be surprised to see this, but do let me know if that's the case!

@GhS88
Copy link
Author

GhS88 commented Sep 28, 2020

Hi ian,

Indeed i tested by connecting the production build to the same DB i am using in the dev environment and I was still facing this issue. As a workaround I created two new views account_accounts and user_users in the db. For some reason in the production build, next-auth is trying to query account_accounts and user_users instead of accounts and users when using custom models.

@iaincollins
Copy link
Member

Thanks for the response! Hmm that is odd and I don't know why that is happening.

It seems like it would be helpful to have this open to look at and for us to try and work out what is going on.

@iaincollins iaincollins added the help-needed The maintainer needs help due to time constraint/missing knowledge label Sep 28, 2020
@glenarama
Copy link

glenarama commented Oct 1, 2020

Im seeing the same issue: //Simplifying

class User extends Adapters.TypeORM.Models.User.model {
  constructor(name, email, image, emailVerified) {
    super(name, email, image, emailVerified)
  }
}

Running yarn dev gets:

User = [Function: User]

Running with build / start (OR deploying to Vercel) gets:

User = [Function: User_User]

@fedekau
Copy link
Contributor

fedekau commented Oct 3, 2020

We have the exact same issue, in dev mode it works perfectly, but on production mode it duplicates the table and you get users_users, etc.

@fedekau
Copy link
Contributor

fedekau commented Oct 3, 2020

Looking very quickly to the code, why is https://github.com/nextauthjs/next-auth/blob/main/src/adapters/typeorm/index.js#L72 needed on non production envs only? I think it might be related to the issue 🤔

Edit

I just tried removing the environment check locally and that worked perfectly

if (process.env.NODE_ENV !== 'production') {
  await updateConnectionEntities(connection, config.entities)
}

@fedekau
Copy link
Contributor

fedekau commented Oct 3, 2020

Since synchronising the schema is dangerous and removing that if statement is not possible without forking the library I tried simply writing the model/schema from scratch instead of extending the provided model. This works for me and it is the only workaround I could find.

Workaround

If you have a custom model, for example you add a role column to the users table

import Adapters from 'next-auth/adapters';

// Extend the built-in models using class inheritance
export default class User extends Adapters.TypeORM.Models.User.model {
  // You can extend the options in a model but you should not remove the base
  // properties or change the order of the built-in options on the constructor
  constructor(name, email, image, emailVerified) {
    super(name, email, image, emailVerified);
  }
}

export const UserSchema = {
  name: 'User',
  target: User,
  columns: {
    ...Adapters.TypeORM.Models.User.schema.columns,
    role: {
      type: 'varchar',
      nullable: true,
    },
  },
};

instead do it without extending the class

export default class User {
  constructor(name, email, image, emailVerified) {
    if (name) {
      this.name = name;
    }
    if (email) {
      this.email = email;
    }
    if (image) {
      this.image = image;
    }
    if (emailVerified) {
      const currentDate = new Date();
      this.emailVerified = currentDate;
    }
  }
}

export const UserSchema = {
  name: 'User',
  target: User,
  columns: {
    id: {
      primary: true,
      type: 'int',
      generated: true,
    },
    name: {
      type: 'varchar',
      nullable: true,
    },
    email: {
      type: 'varchar',
      unique: true,
      nullable: true,
    },
    emailVerified: {
      type: 'timestamp',
      nullable: true,
    },
    image: {
      type: 'varchar',
      nullable: true,
    },
    createdAt: {
      type: 'timestamp',
      createDate: true,
    },
    updatedAt: {
      type: 'timestamp',
      updateDate: true,
    },
    role: {
      type: 'varchar',
      nullable: true,
    },
  },
};

this "solves" the problem.

@zdne
Copy link

zdne commented Oct 12, 2020

I can confirm I have the same issue and @fedekau "solution" works

@archywillhe
Copy link

archywillhe commented Oct 16, 2020

got into this too; I think @fedekau's hot fix work for many cases! But in my case I have another couple of api calls using the TypeORM adaptor to perform CURD operations with custom models, and I'm inconsistently getting some weird EntityMetadataNotFoundError (only in serverless setting; works perfectly locally & on heroku! ) : - /

could be related to this:

typeorm/typeorm#1327

maybe something to do with the constraint in a serverless setting and some of the stuff in typeORM weren't implemented with serverless in mind?

Hmm or could also be due to some optimsiation done in Vercel for the functional calls I guess. just opened a discussion here: vercel/vercel#5299 Really hoping to get this fixed before we launch our app : 0

@glenarama
Copy link

@archywillhe Another way around this for now if your having problems is to manually rename it:

class User extends Adapters.TypeORM.Models.User.model {
  // You can extend the options in a model but you should not remove the base
  // properties or change the order of the built-in options on the constructor
  constructor(name, email, image, emailVerified) {
    super(name, email, image, emailVerified)
  }
}

Object.defineProperty(User, "name", { value: "User" })

@archywillhe
Copy link

archywillhe commented Oct 17, 2020

@glenames ohh interesting! I will give it a try! thanks mate!

also: dou you know where can i read more about using .defineProperty on Classes?

update: unforuntaely still getting Error?error=EntityMetadataNotFound%3A%20No%20metadata%20for%20"User"%20was%20found.

@stale
Copy link

stale bot commented Dec 16, 2020

Hi there! It looks like this issue hasn't had any activity for a while. It will be closed if no further activity occurs. If you think your issue is still relevant, feel free to comment on it to keep it open. (Read more at #912) Thanks!

@stale stale bot added the stale Did not receive any activity for 60 days label Dec 16, 2020
@stale
Copy link

stale bot commented Dec 23, 2020

Hi there! It looks like this issue hasn't had any activity for a while. To keep things tidy, I am going to close this issue for now. If you think your issue is still relevant, just leave a comment and I will reopen it. (Read more at #912) Thanks!

@stale stale bot closed this as completed Dec 23, 2020
@Xodarap
Copy link
Contributor

Xodarap commented Jan 9, 2021

Can we reopen this? It just happened to me on my production site; I redeployed and the issue went away, but it's kind of worrying that this can happen.

@balazsorban44 balazsorban44 reopened this Jan 9, 2021
@stale stale bot removed the stale Did not receive any activity for 60 days label Jan 9, 2021
@jmaister
Copy link

I can't extend the User model to make it available. It seems to work for others in this issue.

imagen

jordi@jordi-ssd-t5:~/workspace/furgos$ yarn typeorm migration:show
yarn run v1.22.5
$ TYPEORM=true yarn local ./node_modules/typeorm/cli.js --config ormconfig.ts migration:show
$ DOTENV_CONFIG_PATH=./.env ts-node -P ./tsconfig.typeorm.json -r dotenv/config ./node_modules/typeorm/cli.js --config ormconfig.ts migration:show
Error during migration show:
TypeError: Cannot read property 'TypeORM' of undefined
    at Object.<anonymous> (/home/jordi/workspace/furgos/src/entity/User.ts:3:25)

@deep-c
Copy link
Contributor

deep-c commented Feb 10, 2021

Im having the same problem as @jmaister above trying to create a migration via typeorm. All models etc are in typescript and I am invoking the following

"typeorm": "cross-env TS_NODE_PROJECT=tsconfig.typeorm.json TS_NODE_TRANSPILE_ONLY=true ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js"
npm run typeorm migration:generate -- -n Initial

I get the following error:

Error during migration generation:
TypeError: Cannot read property 'TypeORM' of undefined
    at Object.<anonymous> (/usr/src/app/src/models/User.ts:3:45)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module.m._compile (/usr/src/app/node_modules/ts-node/src/index.ts:1056:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/src/app/node_modules/ts-node/src/index.ts:1059:12)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> **(/usr/src/app/src/models/index.ts:1:1)**

tsconfig file used

{
    "compilerOptions": {
        "lib": ["es5", "es6"],
        "target": "es6",
        "module": "commonjs",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true,
        "baseUrl": "src",
        "paths": {
            "@/*": ["*"]
        }
    },
    "exclude": ["node_modules"]
}

custom user model:

import Adapters, { TypeORMUserModel } from 'next-auth/adapters';

export default class User extends (Adapters.TypeORM.Models.User.model as typeof TypeORMUserModel) {
    constructor(name?: string, email?: string, image?: string, emailVerified?: Date) {
        super(name, email, image, emailVerified);
    }
}

export const UserSchema = {
    name: 'User',
    target: User,
    columns: {
        ...Adapters.TypeORM.Models.User.schema.columns,
        dob: {
            type: Date,
            nullable: true,
        },
    },
};

@jmaister
Copy link

jmaister commented Feb 10, 2021

Im having the same problem as @jmaister above trying to create a migration via typeorm. All models etc are in typescript and I am invoking the following

"typeorm": "cross-env TS_NODE_PROJECT=tsconfig.typeorm.json TS_NODE_TRANSPILE_ONLY=true ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js"
npm run typeorm migration:generate -- -n Initial

Fixed by moving to Passport.js
It took 2 hours to remove next-auth and implement it with Passport.js, however I lost the email confirmations. But users can create their accounts and login.

@deep-c
Copy link
Contributor

deep-c commented Feb 10, 2021

@jmaister so looks like their might be some issues with the new typescript work. After changing it to the following i was able to generate an initial typeorm migration.

import { EntitySchema } from 'typeorm';
import { TypeORMUserModel } from 'next-auth/adapters';
import Adapters from 'next-auth/dist/adapters/index';

export default class User extends (Adapters.TypeORM.Models.User.model as typeof TypeORMUserModel) {
    constructor(name?: string, email?: string, image?: string, emailVerified?: Date) {
        super(name, email, image, emailVerified);
    }
}

export const UserSchema = new EntitySchema<User>({
    name: 'User',
    target: User,
    columns: {
        ...Adapters.TypeORM.Models.User.schema.columns,
        dob: {
            type: Date,
            nullable: true,
        },
    },
});

@iaincollins
Copy link
Member

Some of the replies ere are really helpful, especially this one from @fedekau which I think is a good one that should be followed up:

Looking very quickly to the code, why is https://github.com/nextauthjs/next-auth/blob/main/src/adapters/typeorm/index.js#L72 needed on non production envs only? I think it might be related to the issue thinking

The comments above from @deep-c and the issues @archywillhe has linked to are also helpful and interesting.

As this discussion seems to have become quite broad (and is about more than one specific thing; with no single action that seems obvious arising from this) I'm going to mark this issue as closed now and suggest that anyone with issues related to migration raise them in the Discussions area that we have now.

Please do also raise a feature request if you can identify ways we could make changes (in code and/or documentation) to help folks avoid doing whatever they are doing that is triggering problems with table names.

Likewise if we think there is a race condition or behaviour that is explicitly incorrect please do raise a bug about that behaviour.

A critical thing we need to be able to understand why these are happening is code to replicate any problems - in particular we need to understand how folks are building and compiling their apps to see where the problem is.

To confirm, I do not see these issues myself with either TypeORM or Prisma adapters on production sites, including in cases with custom models.

Specific challenges I think we have include that the guidance we have on how to use custom models is sparse, it may need to be reviewed and I suspect there are some issues specific to folks using TypeScript run into too.

There are also issues with different version of TypeORM from time to time, so understand what versions of libraries people are suing is also helpful when it comes to replicating problems.

We do have working schema creation tests for a range of databases with the default adapter (Postgres, MySQL, MSSQL, MongoDB...) and they test table/collection creation/column types/indexes/etc. IIRC they do not current include examples of custom models but those should be easy to extend.

We may wish to do that and then go back and see if we can improve some of the examples/tutorials for the default adapter.

Feel free to create feature request to extend those example and link back to this issue.

h4yha pushed a commit to nextjs-opinionated/nextjs-opinionated-hasura that referenced this issue Jun 14, 2021
@sourabhmahato
Copy link

I am having an issue with next auth in production whenever I clink in sign in it shows /api/auth/signin?=true and reloads the page never signs in

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help-needed The maintainer needs help due to time constraint/missing knowledge question Ask how to do something or how something works
Projects
None yet
Development

No branches or pull requests