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

ERROR: The following fields are invalid: Email, Username #36

Open
engin-can opened this issue Feb 25, 2025 · 8 comments · May be fixed by #38
Open

ERROR: The following fields are invalid: Email, Username #36

engin-can opened this issue Feb 25, 2025 · 8 comments · May be fixed by #38

Comments

@engin-can
Copy link

engin-can commented Feb 25, 2025

I am using your example with local-users and users and I keep getting this every time I load the admin panel. Any idea why?

[14:54:16] ERROR: The following fields are invalid: Email, Username
    err: {
      "type": "ValidationError",
      "message": "The following fields are invalid: Email, Username",
      "stack":
          ValidationError: The following fields are invalid: Email, Username
              at beforeChange (webpack-internal:///(rsc)/./node_modules/payload/dist/fields/hooks/beforeChange/index.js:44:15)
              at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
              at async createOperation (webpack-internal:///(rsc)/./node_modules/payload/dist/collections/operations/create.js:152:35)
              at async Object.authenticate (webpack-internal:///(rsc)/./node_modules/payload-oauth2/dist/auth-strategy.js:56:33)
              at async args.payload.authStrategies.reduce.Promise.resolve.user (webpack-internal:///(rsc)/./node_modules/payload/dist/auth/executeAuthStrategies.js:7:24)
              at async eval (webpack-internal:///(rsc)/./node_modules/@payloadcms/next/dist/utilities/initReq.js:44:7)
              at async initPage (webpack-internal:///(rsc)/./node_modules/@payloadcms/next/dist/utilities/initPage/index.js:52:7)
              at async RootPage (webpack-internal:///(rsc)/./node_modules/@payloadcms/next/dist/views/Root/index.js:69:26)
      "data": {
        "collection": "local-users",
        "errors": [
          {
            "label": "Email",
            "message": "Please enter a valid email address.",
            "path": "email"
          },
          {
            "label": "Username",
            "message": "This field is required.",
            "path": "username"
          }
        ]
      },
      "isOperational": true,
      "isPublic": false,
      "status": 400,
      "name": "ValidationError"
    }

LocalUsers.ts

import type { CollectionConfig } from 'payload';
import { LocalUser } from '@/payload-types';
import { admins } from '../utils/isAdmin';

export const LocalUsers: CollectionConfig = {
  slug: 'local-users',
  // defaultPopulate: {
  //   username: true,
  // },
  admin: {
    useAsTitle: 'email',
  },
  auth: {
    maxLoginAttempts: 5,
    lockTime: 600 * 1000,
    loginWithUsername: {
      allowEmailLogin: true,
      requireEmail: true,
    },
    verify: {
      generateEmailHTML: ({ token, user }) => {
        const url = `${process.env.NEXT_PUBLIC_URL}/account/activate?token=${token}`;
        return `Hey ${user.email}, activate your account by clicking here: ${url}`;
      },
    },
    forgotPassword: {
      generateEmailHTML: ({ token, user } = {}) => {
        const url = `${process.env.NEXT_PUBLIC_URL}/account/password/reset?token=${token}`;
        return `Hey ${user?.email}, reset your password by clicking here: ${url}`;
      },
    },
  },
  access: {
    admin: admins,
    read: () => true,
    create: () => true,
  },
  fields: [
    {
      name: 'isAdmin',
      type: 'checkbox',
      label: 'Admin',
      defaultValue: false,
      access: {
        read: ({ req: { user } }) => Boolean((user as LocalUser).isAdmin),
      },
    },
  ],
};

Users.ts

import { CollectionConfig } from 'payload';

export const Users: CollectionConfig = {
  slug: 'users',
  auth: { disableLocalStrategy: true },
  admin: { useAsTitle: 'email' },
  fields: [{ name: 'email', type: 'email', required: true }],
};
@engin-can
Copy link
Author

engin-can commented Feb 25, 2025

I found what's causing it. Code below doesn't seem to work with loginWithUsername: {allowEmailLogin: true, requireEmail: true}. When I am logged in as a 'local user' it tries to create a LocalUser without email and username.

Logging

jwtUser {
  id: '258300ac-497b-4abc-8142-832410448c6a',
  collection: 'local-users',
  email: '',
  iat: 1740493072,
  exp: 1740500272
}

Code

user = (await payload.create({
                            collection: userCollection,
                            data: jwtUser,
                        }));

@engin-can
Copy link
Author

@WilsonLe do you know why authenticate from auth-strategy is called when I am logged in as a 'local' user? Shouldn't it just call payload's default authentication function?

@WilsonLe
Copy link
Owner

WilsonLe commented Feb 25, 2025

Payload's executeAuthStrategies runs all auth strategies until there is one returned that contains a user.

https://github.com/payloadcms/payload/blob/main/packages/payload/src/auth/executeAuthStrategies.ts

The plugin might have prepended the strategy before payload's local strategy.

@engin-can
Copy link
Author

engin-can commented Feb 25, 2025

Should we perhaps add something like this to auth-strategy then? Not sure how else to solve this...

  if (typeof jwtUser.email !== "string" || !jwtUser.email) {
                        payload.logger.warn("Using email as identity but no email is found in jwt token");
                        return { user: null };
                    }

@WilsonLe
Copy link
Owner

That makes sense. Can you create a PR for that?

@engin-can
Copy link
Author

engin-can commented Feb 25, 2025

Sure, is it expected that it calls this authenticate several times when I visit a page on admin panel? I noticed it calls authenticate 4 times when I open Users page for example....

Image

@WilsonLe
Copy link
Owner

Not sure if it's expected, but you can find the answer in seeing if the executeAuthStrategy function is being called that many times in Payload's code base.

@engin-can
Copy link
Author

engin-can commented Feb 25, 2025

PR here: #38

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants