chore: merge from 2.0

This commit is contained in:
Elliot DeNolf
2023-09-14 12:10:36 -04:00
2597 changed files with 96505 additions and 105649 deletions

View File

@@ -1,29 +1,27 @@
import React, { useEffect, useState } from 'react';
import { useAuth } from '../../src/admin/components/utilities/Auth';
import { User } from '../../src/auth';
import { UIField } from '../../src/fields/config/types';
import React, { useEffect, useState } from 'react'
import type { User } from '../../packages/payload/src/auth'
import type { UIField } from '../../packages/payload/src/fields/config/types'
import { useAuth } from '../../packages/payload/src/admin/components/utilities/Auth'
export const AuthDebug: React.FC<UIField> = () => {
const [state, setState] = useState<User | null | undefined>();
const { user } = useAuth();
const [state, setState] = useState<User | null | undefined>()
const { user } = useAuth()
useEffect(() => {
const fetchUser = async () => {
const userRes = await fetch(`/api/users/${user?.id}`)?.then((res) => res.json());
setState(userRes);
};
const userRes = await fetch(`/api/users/${user?.id}`)?.then((res) => res.json())
setState(userRes)
}
fetchUser();
}, [user]);
fetchUser()
}, [user])
return (
<div id="auth-debug">
<div id="use-auth-result">
{user?.custom as string}
</div>
<div id="users-api-result">
{state?.custom as string}
</div>
<div id="use-auth-result">{user?.custom as string}</div>
<div id="users-api-result">{state?.custom as string}</div>
</div>
);
};
)
}

View File

@@ -1,21 +1,17 @@
import { v4 as uuid } from 'uuid';
import { mapAsync } from '../../src/utilities/mapAsync';
import { buildConfigWithDefaults } from '../buildConfigWithDefaults';
import { devUser } from '../credentials';
import { AuthDebug } from './AuthDebug';
import { v4 as uuid } from 'uuid'
export const slug = 'users';
export const namedSaveToJWTValue = 'namedSaveToJWT value';
export const saveToJWTKey = 'x-custom-jwt-property-name';
import { mapAsync } from '../../packages/payload/src/utilities/mapAsync'
import { buildConfigWithDefaults } from '../buildConfigWithDefaults'
import { devUser } from '../credentials'
import { AuthDebug } from './AuthDebug'
import { namedSaveToJWTValue, saveToJWTKey, slug } from './shared'
export default buildConfigWithDefaults({
admin: {
user: 'users',
autoLogin: {
email: 'test@example.com',
password: 'test',
email: devUser.email,
password: devUser.password,
prefillOnly: true,
},
},
@@ -160,9 +156,9 @@ export default buildConfigWithDefaults({
id: {
equals: user.id,
},
};
}
}
return true;
return true
},
},
auth: {
@@ -187,7 +183,7 @@ export default buildConfigWithDefaults({
password: devUser.password,
custom: 'Hello, world!',
},
});
})
await mapAsync([...Array(2)], async () => {
await payload.create({
@@ -196,7 +192,7 @@ export default buildConfigWithDefaults({
apiKey: uuid(),
enableAPIKey: true,
},
});
});
})
})
},
});
})

View File

@@ -1,43 +1,48 @@
import { Request } from 'express';
import { Strategy } from 'passport-strategy';
import { Payload } from '../../../src/payload';
import { buildConfigWithDefaults } from '../../buildConfigWithDefaults';
import type { Request } from 'express'
export const slug = 'users';
export const strategyName = 'test-local';
import { Strategy } from 'passport-strategy'
import type { Payload } from '../../../packages/payload/src/payload'
import { buildConfigWithDefaults } from '../../buildConfigWithDefaults'
export const slug = 'users'
export const strategyName = 'test-local'
export class CustomStrategy extends Strategy {
ctx: Payload;
ctx: Payload
constructor(ctx: Payload) {
super();
this.ctx = ctx;
super()
this.ctx = ctx
}
authenticate(req: Request, options?: any): void {
if (!req.headers.code && !req.headers.secret) {
return this.success(null);
return this.success(null)
}
this.ctx.find({
collection: slug,
where: {
code: {
equals: req.headers.code,
this.ctx
.find({
collection: slug,
where: {
code: {
equals: req.headers.code,
},
secret: {
equals: req.headers.secret,
},
},
secret: {
equals: req.headers.secret,
},
},
}).then((users) => {
if (users.docs && users.docs.length) {
const user = users.docs[0];
user.collection = slug;
user._strategy = `${slug}-${strategyName}`;
this.success(user);
} else {
this.error(null);
}
});
})
.then((users) => {
if (users.docs && users.docs.length) {
const user = users.docs[0]
user.collection = slug
user._strategy = `${slug}-${strategyName}`
this.success(user)
} else {
this.error(null)
}
})
}
}
@@ -88,8 +93,7 @@ export default buildConfigWithDefaults({
saveToJWT: true,
hasMany: true,
},
],
},
],
});
})

View File

@@ -1,28 +1,28 @@
import payload from '../../../src';
import { initPayloadTest } from '../../helpers/configHelpers';
import { slug } from './config';
import payload from '../../../packages/payload/src'
import { initPayloadTest } from '../../helpers/configHelpers'
import { slug } from './config'
require('isomorphic-fetch');
require('isomorphic-fetch')
let apiUrl;
let apiUrl
const [code, secret, name] = ['test', 'strategy', 'Tester'];
const [code, secret, name] = ['test', 'strategy', 'Tester']
const headers = {
'Content-Type': 'application/json',
};
}
describe('AuthStrategies', () => {
beforeAll(async () => {
const { serverURL } = await initPayloadTest({ __dirname, init: { local: false } });
apiUrl = `${serverURL}/api`;
});
const { serverURL } = await initPayloadTest({ __dirname, init: { local: false } })
apiUrl = `${serverURL}/api`
})
afterAll(async () => {
if (typeof payload.db.destroy === 'function') {
await payload.db.destroy(payload);
await payload.db.destroy(payload)
}
});
})
describe('create user', () => {
beforeAll(async () => {
@@ -34,8 +34,8 @@ describe('AuthStrategies', () => {
}),
headers,
method: 'post',
});
});
})
})
it('should return a logged in user from /me', async () => {
const response = await fetch(`${apiUrl}/${slug}/me`, {
@@ -44,12 +44,12 @@ describe('AuthStrategies', () => {
code,
secret,
},
});
})
const data = await response.json();
const data = await response.json()
expect(response.status).toBe(200);
expect(data.user.name).toBe(name);
});
});
});
expect(response.status).toBe(200)
expect(data.user.name).toBe(name)
})
})
})

View File

@@ -1,9 +1,11 @@
import type { Page } from '@playwright/test';
import { test, expect } from '@playwright/test';
import { AdminUrlUtil } from '../helpers/adminUrlUtil';
import { initPayloadE2E } from '../helpers/configHelpers';
import { login, saveDocAndAssert } from '../helpers';
import { slug } from './config';
import type { Page } from '@playwright/test'
import { expect, test } from '@playwright/test'
import { login, saveDocAndAssert } from '../helpers'
import { AdminUrlUtil } from '../helpers/adminUrlUtil'
import { initPayloadE2E } from '../helpers/configHelpers'
import { slug } from './shared'
/**
* TODO: Auth
@@ -13,48 +15,48 @@ import { slug } from './config';
* log out
*/
const { beforeAll, describe } = test;
let url: AdminUrlUtil;
const { beforeAll, describe } = test
let url: AdminUrlUtil
describe('auth', () => {
let page: Page;
let page: Page
beforeAll(async ({ browser }) => {
const { serverURL } = await initPayloadE2E(__dirname);
url = new AdminUrlUtil(serverURL, slug);
const { serverURL } = await initPayloadE2E(__dirname)
url = new AdminUrlUtil(serverURL, slug)
const context = await browser.newContext();
page = await context.newPage();
const context = await browser.newContext()
page = await context.newPage()
await login({
page,
serverURL,
});
});
})
})
describe('authenticated users', () => {
test('should allow change password', async () => {
await page.goto(url.account);
await page.goto(url.account)
await page.locator('#change-password').click();
await page.locator('#field-password').fill('password');
await page.locator('#field-confirm-password').fill('password');
await page.locator('#change-password').click()
await page.locator('#field-password').fill('password')
await page.locator('#field-confirm-password').fill('password')
await saveDocAndAssert(page);
});
await saveDocAndAssert(page)
})
test('should have up-to-date user in `useAuth` hook', async () => {
await page.goto(url.account);
await page.goto(url.account)
await expect(await page.locator('#users-api-result')).toHaveText('Hello, world!');
await expect(await page.locator('#use-auth-result')).toHaveText('Hello, world!');
await expect(page.locator('#users-api-result')).toHaveText('Hello, world!')
await expect(page.locator('#use-auth-result')).toHaveText('Hello, world!')
const field = await page.locator('#field-custom');
await field.fill('Goodbye, world!');
await saveDocAndAssert(page);
const field = page.locator('#field-custom')
await field.fill('Goodbye, world!')
await saveDocAndAssert(page)
await expect(await page.locator('#users-api-result')).toHaveText('Goodbye, world!');
await expect(await page.locator('#use-auth-result')).toHaveText('Goodbye, world!');
});
});
});
await expect(page.locator('#users-api-result')).toHaveText('Goodbye, world!')
await expect(page.locator('#use-auth-result')).toHaveText('Goodbye, world!')
})
})
})

View File

@@ -1,41 +1,43 @@
import jwtDecode from 'jwt-decode';
import { GraphQLClient } from 'graphql-request';
import payload from '../../src';
import { initPayloadTest } from '../helpers/configHelpers';
import { namedSaveToJWTValue, saveToJWTKey, slug } from './config';
import { devUser } from '../credentials';
import type { User } from '../../src/auth';
import configPromise from '../collections-graphql/config';
require('isomorphic-fetch');
import type { User } from '../../packages/payload/src/auth'
let apiUrl;
let client: GraphQLClient;
import payload from '../../packages/payload/src'
import configPromise from '../collections-graphql/config'
import { devUser } from '../credentials'
import { initPayloadTest } from '../helpers/configHelpers'
import { namedSaveToJWTValue, saveToJWTKey, slug } from './shared'
require('isomorphic-fetch')
let apiUrl
let client: GraphQLClient
const headers = {
'Content-Type': 'application/json',
};
}
const { email, password } = devUser;
const { email, password } = devUser
describe('Auth', () => {
beforeAll(async () => {
const { serverURL } = await initPayloadTest({ __dirname, init: { local: false } });
apiUrl = `${serverURL}/api`;
const config = await configPromise;
const url = `${serverURL}${config.routes.api}${config.routes.graphQL}`;
client = new GraphQLClient(url);
});
const { serverURL } = await initPayloadTest({ __dirname, init: { local: false } })
apiUrl = `${serverURL}/api`
const config = await configPromise
const url = `${serverURL}${config.routes.api}${config.routes.graphQL}`
client = new GraphQLClient(url)
})
afterAll(async () => {
if (typeof payload.db.destroy === 'function') {
await payload.db.destroy(payload);
await payload.db.destroy(payload)
}
});
})
describe('GraphQL - admin user', () => {
let token;
let user;
let token
let user
beforeAll(async () => {
// language=graphQL
const query = `mutation {
@@ -46,35 +48,29 @@ describe('Auth', () => {
email
}
}
}`;
const response = await client.request(query);
user = response.loginUser.user;
token = response.loginUser.token;
});
}`
const response = await client.request(query)
user = response.loginUser.user
token = response.loginUser.token
})
it('should login', async () => {
expect(user.id).toBeDefined();
expect(user.email).toEqual(devUser.email);
expect(token).toBeDefined();
});
expect(user.id).toBeDefined()
expect(user.email).toEqual(devUser.email)
expect(token).toBeDefined()
})
it('should have fields saved to JWT', async () => {
const decoded = jwtDecode<User>(token);
const {
email: jwtEmail,
collection,
roles,
iat,
exp,
} = decoded;
const decoded = jwtDecode<User>(token)
const { email: jwtEmail, collection, roles, iat, exp } = decoded
expect(jwtEmail).toBeDefined();
expect(collection).toEqual('users');
expect(Array.isArray(roles)).toBeTruthy();
expect(iat).toBeDefined();
expect(exp).toBeDefined();
});
});
expect(jwtEmail).toBeDefined()
expect(collection).toEqual('users')
expect(Array.isArray(roles)).toBeTruthy()
expect(iat).toBeDefined()
expect(exp).toBeDefined()
})
})
describe('REST - admin user', () => {
beforeAll(async () => {
@@ -85,8 +81,8 @@ describe('Auth', () => {
}),
headers,
method: 'post',
});
});
})
})
it('should prevent registering a new first user', async () => {
const response = await fetch(`${apiUrl}/${slug}/first-register`, {
@@ -96,10 +92,10 @@ describe('Auth', () => {
}),
headers,
method: 'post',
});
})
expect(response.status).toBe(403);
});
expect(response.status).toBe(403)
})
it('should login a user successfully', async () => {
const response = await fetch(`${apiUrl}/${slug}/login`, {
@@ -109,17 +105,17 @@ describe('Auth', () => {
}),
headers,
method: 'post',
});
})
const data = await response.json();
const data = await response.json()
expect(response.status).toBe(200);
expect(data.token).toBeDefined();
});
expect(response.status).toBe(200)
expect(data.token).toBeDefined()
})
describe('logged in', () => {
let token: string | undefined;
let loggedInUser: User | undefined;
let token: string | undefined
let loggedInUser: User | undefined
beforeAll(async () => {
const response = await fetch(`${apiUrl}/${slug}/login`, {
@@ -129,12 +125,12 @@ describe('Auth', () => {
}),
headers,
method: 'post',
});
})
const data = await response.json();
token = data.token;
loggedInUser = data.user;
});
const data = await response.json()
token = data.token
loggedInUser = data.user
})
it('should return a logged in user from /me', async () => {
const response = await fetch(`${apiUrl}/${slug}/me`, {
@@ -142,16 +138,16 @@ describe('Auth', () => {
...headers,
Authorization: `JWT ${token}`,
},
});
})
const data = await response.json();
const data = await response.json()
expect(response.status).toBe(200);
expect(data.user.email).toBeDefined();
});
expect(response.status).toBe(200)
expect(data.user.email).toBeDefined()
})
it('should have fields saved to JWT', async () => {
const decoded = jwtDecode<User>(token);
const decoded = jwtDecode<User>(token)
const {
email: jwtEmail,
collection,
@@ -163,33 +159,33 @@ describe('Auth', () => {
unnamedTabSaveToJWTFalse,
iat,
exp,
} = decoded;
} = decoded
const group = decoded['x-group'] as Record<string, unknown>;
const tab = decoded.saveToJWTTab as Record<string, unknown>;
const tabString = decoded['tab-test'] as Record<string, unknown>;
const group = decoded['x-group'] as Record<string, unknown>
const tab = decoded.saveToJWTTab as Record<string, unknown>
const tabString = decoded['tab-test'] as Record<string, unknown>
expect(jwtEmail).toBeDefined();
expect(collection).toEqual('users');
expect(collection).toEqual('users');
expect(Array.isArray(roles)).toBeTruthy();
expect(jwtEmail).toBeDefined()
expect(collection).toEqual('users')
expect(collection).toEqual('users')
expect(Array.isArray(roles)).toBeTruthy()
// 'x-custom-jwt-property-name': 'namedSaveToJWT value'
expect(customJWTPropertyKey).toEqual(namedSaveToJWTValue);
expect(group).toBeDefined();
expect(group['x-test']).toEqual('nested property');
expect(group.saveToJWTFalse).toBeUndefined();
expect(liftedFromGroup).toEqual('lifted from group');
expect(tabLiftedSaveToJWT).toEqual('lifted from unnamed tab');
expect(tab['x-field']).toEqual('yes');
expect(tabString.includedByDefault).toEqual('yes');
expect(unnamedTabSaveToJWTString).toEqual('text');
expect(unnamedTabSaveToJWTFalse).toBeUndefined();
expect(iat).toBeDefined();
expect(exp).toBeDefined();
});
expect(customJWTPropertyKey).toEqual(namedSaveToJWTValue)
expect(group).toBeDefined()
expect(group['x-test']).toEqual('nested property')
expect(group.saveToJWTFalse).toBeUndefined()
expect(liftedFromGroup).toEqual('lifted from group')
expect(tabLiftedSaveToJWT).toEqual('lifted from unnamed tab')
expect(tab['x-field']).toEqual('yes')
expect(tabString.includedByDefault).toEqual('yes')
expect(unnamedTabSaveToJWTString).toEqual('text')
expect(unnamedTabSaveToJWTFalse).toBeUndefined()
expect(iat).toBeDefined()
expect(exp).toBeDefined()
})
it('should allow authentication with an API key with useAPIKey', async () => {
const apiKey = '0123456789ABCDEFGH';
const apiKey = '0123456789ABCDEFGH'
const user = await payload.create({
collection: slug,
@@ -198,21 +194,21 @@ describe('Auth', () => {
password: 'test',
apiKey,
},
});
})
const response = await fetch(`${apiUrl}/${slug}/me`, {
headers: {
...headers,
Authorization: `${slug} API-Key ${user?.apiKey}`,
},
});
})
const data = await response.json();
const data = await response.json()
expect(response.status).toBe(200);
expect(data.user.email).toBeDefined();
expect(data.user.apiKey).toStrictEqual(apiKey);
});
expect(response.status).toBe(200)
expect(data.user.email).toBeDefined()
expect(data.user.apiKey).toStrictEqual(apiKey)
})
it('should refresh a token and reset its expiration', async () => {
const response = await fetch(`${apiUrl}/${slug}/refresh-token`, {
@@ -220,16 +216,16 @@ describe('Auth', () => {
headers: {
Authorization: `JWT ${token}`,
},
});
})
const data = await response.json();
const data = await response.json()
expect(response.status).toBe(200);
expect(data.refreshedToken).toBeDefined();
});
expect(response.status).toBe(200)
expect(data.refreshedToken).toBeDefined()
})
it('should refresh a token and receive an up-to-date user', async () => {
expect(loggedInUser?.custom).toBe('Hello, world!');
expect(loggedInUser?.custom).toBe('Hello, world!')
await payload.update({
collection: slug,
@@ -237,20 +233,20 @@ describe('Auth', () => {
data: {
custom: 'Goodbye, world!',
},
});
})
const response = await fetch(`${apiUrl}/${slug}/refresh-token`, {
method: 'post',
headers: {
Authorization: `JWT ${token}`,
},
});
})
const data = await response.json();
const data = await response.json()
expect(response.status).toBe(200);
expect(data.user.custom).toBe('Goodbye, world!');
});
expect(response.status).toBe(200)
expect(data.user.custom).toBe('Goodbye, world!')
})
it('should allow a user to be created', async () => {
const response = await fetch(`${apiUrl}/${slug}`, {
@@ -264,23 +260,23 @@ describe('Auth', () => {
'Content-Type': 'application/json',
},
method: 'post',
});
})
const data = await response.json();
const data = await response.json()
expect(response.status).toBe(201);
expect(data).toHaveProperty('message');
expect(data).toHaveProperty('doc');
expect(response.status).toBe(201)
expect(data).toHaveProperty('message')
expect(data).toHaveProperty('doc')
const { doc } = data;
const { doc } = data
expect(doc).toHaveProperty('email');
expect(doc).toHaveProperty('createdAt');
expect(doc).toHaveProperty('roles');
});
expect(doc).toHaveProperty('email')
expect(doc).toHaveProperty('createdAt')
expect(doc).toHaveProperty('roles')
})
it('should allow verification of a user', async () => {
const emailToVerify = 'verify@me.com';
const emailToVerify = 'verify@me.com'
const response = await fetch(`${apiUrl}/public-users`, {
body: JSON.stringify({
email: emailToVerify,
@@ -292,9 +288,9 @@ describe('Auth', () => {
'Content-Type': 'application/json',
},
method: 'post',
});
})
expect(response.status).toBe(201);
expect(response.status).toBe(201)
const userResult = await payload.find({
collection: 'public-users',
@@ -305,21 +301,24 @@ describe('Auth', () => {
equals: emailToVerify,
},
},
});
})
const { _verified, _verificationToken } = userResult.docs[0];
const { _verified, _verificationToken } = userResult.docs[0]
expect(_verified).toBe(false);
expect(_verificationToken).toBeDefined();
expect(_verified).toBe(false)
expect(_verificationToken).toBeDefined()
const verificationResponse = await fetch(`${apiUrl}/public-users/verify/${_verificationToken}`, {
headers: {
'Content-Type': 'application/json',
const verificationResponse = await fetch(
`${apiUrl}/public-users/verify/${_verificationToken}`,
{
headers: {
'Content-Type': 'application/json',
},
method: 'post',
},
method: 'post',
});
)
expect(verificationResponse.status).toBe(200);
expect(verificationResponse.status).toBe(200)
const afterVerifyResult = await payload.find({
collection: 'public-users',
@@ -330,15 +329,16 @@ describe('Auth', () => {
equals: emailToVerify,
},
},
});
})
const { _verified: afterVerified, _verificationToken: afterToken } = afterVerifyResult.docs[0];
expect(afterVerified).toBe(true);
expect(afterToken).toBeNull();
});
const { _verified: afterVerified, _verificationToken: afterToken } =
afterVerifyResult.docs[0]
expect(afterVerified).toBe(true)
expect(afterToken).toBeNull()
})
describe('Account Locking', () => {
const userEmail = 'lock@me.com';
const userEmail = 'lock@me.com'
const tryLogin = async () => {
await fetch(`${apiUrl}/${slug}/login`, {
@@ -350,9 +350,9 @@ describe('Auth', () => {
'Content-Type': 'application/json',
},
method: 'post',
});
})
// expect(loginRes.status).toEqual(401);
};
}
beforeAll(async () => {
const response = await fetch(`${apiUrl}/${slug}/login`, {
@@ -362,10 +362,10 @@ describe('Auth', () => {
}),
headers,
method: 'post',
});
})
const data = await response.json();
token = data.token;
const data = await response.json()
token = data.token
// New user to lock
await fetch(`${apiUrl}/${slug}`, {
@@ -378,12 +378,12 @@ describe('Auth', () => {
Authorization: `JWT ${token}`,
},
method: 'post',
});
});
})
})
it('should lock the user after too many attempts', async () => {
await tryLogin();
await tryLogin();
await tryLogin()
await tryLogin()
const userResult = await payload.find({
collection: slug,
@@ -394,18 +394,18 @@ describe('Auth', () => {
equals: userEmail,
},
},
});
})
const { loginAttempts, lockUntil } = userResult.docs[0];
const { loginAttempts, lockUntil } = userResult.docs[0]
expect(loginAttempts).toBe(2);
expect(lockUntil).toBeDefined();
});
expect(loginAttempts).toBe(2)
expect(lockUntil).toBeDefined()
})
it('should unlock account once lockUntil period is over', async () => {
// Lock user
await tryLogin();
await tryLogin();
await tryLogin()
await tryLogin()
await payload.update({
collection: slug,
@@ -417,7 +417,7 @@ describe('Auth', () => {
data: {
lockUntil: Date.now() - 605 * 1000,
},
});
})
// login
await fetch(`${apiUrl}/${slug}/login`, {
@@ -430,7 +430,7 @@ describe('Auth', () => {
'Content-Type': 'application/json',
},
method: 'post',
});
})
const userResult = await payload.find({
collection: slug,
@@ -441,15 +441,15 @@ describe('Auth', () => {
equals: userEmail,
},
},
});
})
const { loginAttempts, lockUntil } = userResult.docs[0];
const { loginAttempts, lockUntil } = userResult.docs[0]
expect(loginAttempts).toBe(0);
expect(lockUntil).toBeNull();
});
});
});
expect(loginAttempts).toBe(0)
expect(lockUntil).toBeNull()
})
})
})
it('should allow forgot-password by email', async () => {
// TODO: Spy on payload sendEmail function
@@ -461,12 +461,12 @@ describe('Auth', () => {
headers: {
'Content-Type': 'application/json',
},
});
})
// expect(mailSpy).toHaveBeenCalled();
expect(response.status).toBe(200);
});
expect(response.status).toBe(200)
})
it('should allow reset password', async () => {
const token = await payload.forgotPassword({
@@ -475,46 +475,48 @@ describe('Auth', () => {
email: devUser.email,
},
disableEmail: true,
});
})
const result = await payload.resetPassword({
collection: 'users',
data: {
password: devUser.password,
token,
},
overrideAccess: true,
}).catch((e) => console.error(e));
const result = await payload
.resetPassword({
collection: 'users',
data: {
password: devUser.password,
token,
},
overrideAccess: true,
})
.catch((e) => console.error(e))
expect(result).toBeTruthy();
});
});
expect(result).toBeTruthy()
})
})
describe('API Key', () => {
it('should authenticate via the correct API key user', async () => {
const usersQuery = await payload.find({
collection: 'api-keys',
});
})
const [user1, user2] = usersQuery.docs;
const [user1, user2] = usersQuery.docs
const success = await fetch(`${apiUrl}/api-keys/${user2.id}`, {
headers: {
'Content-Type': 'application/json',
Authorization: `api-keys API-Key ${user2.apiKey}`,
},
}).then((res) => res.json());
}).then((res) => res.json())
expect(success.apiKey).toStrictEqual(user2.apiKey);
expect(success.apiKey).toStrictEqual(user2.apiKey)
const fail = await fetch(`${apiUrl}/api-keys/${user1.id}`, {
headers: {
'Content-Type': 'application/json',
Authorization: `api-keys API-Key ${user2.apiKey}`,
},
});
})
expect(fail.status).toStrictEqual(404);
});
});
});
expect(fail.status).toStrictEqual(404)
})
})
})

View File

@@ -8,96 +8,96 @@
export interface Config {
collections: {
users: User;
'api-keys': ApiKey;
'public-users': PublicUser;
'payload-preferences': PayloadPreference;
'payload-migrations': PayloadMigration;
};
globals: {};
users: User
'api-keys': ApiKey
'public-users': PublicUser
'payload-preferences': PayloadPreference
'payload-migrations': PayloadMigration
}
globals: {}
}
export interface User {
id: string;
roles: ('admin' | 'editor' | 'moderator' | 'user' | 'viewer')[];
custom?: string;
updatedAt: string;
createdAt: string;
enableAPIKey?: boolean;
apiKey?: string;
apiKeyIndex?: string;
email: string;
resetPasswordToken?: string;
resetPasswordExpiration?: string;
salt?: string;
hash?: string;
loginAttempts?: number;
lockUntil?: string;
password?: string;
id: string
roles: ('admin' | 'editor' | 'moderator' | 'user' | 'viewer')[]
custom?: string
updatedAt: string
createdAt: string
enableAPIKey?: boolean
apiKey?: string
apiKeyIndex?: string
email: string
resetPasswordToken?: string
resetPasswordExpiration?: string
salt?: string
hash?: string
loginAttempts?: number
lockUntil?: string
password?: string
}
export interface ApiKey {
id: string;
updatedAt: string;
createdAt: string;
enableAPIKey?: boolean;
apiKey?: string;
apiKeyIndex?: string;
id: string
updatedAt: string
createdAt: string
enableAPIKey?: boolean
apiKey?: string
apiKeyIndex?: string
}
export interface PublicUser {
id: string;
updatedAt: string;
createdAt: string;
email: string;
resetPasswordToken?: string;
resetPasswordExpiration?: string;
salt?: string;
hash?: string;
_verified?: boolean;
_verificationToken?: string;
loginAttempts?: number;
lockUntil?: string;
password?: string;
id: string
updatedAt: string
createdAt: string
email: string
resetPasswordToken?: string
resetPasswordExpiration?: string
salt?: string
hash?: string
_verified?: boolean
_verificationToken?: string
loginAttempts?: number
lockUntil?: string
password?: string
}
export interface PayloadPreference {
id: string;
id: string
user:
| {
value: string | User;
relationTo: 'users';
value: string | User
relationTo: 'users'
}
| {
value: string | ApiKey;
relationTo: 'api-keys';
value: string | ApiKey
relationTo: 'api-keys'
}
| {
value: string | PublicUser;
relationTo: 'public-users';
};
key?: string;
value: string | PublicUser
relationTo: 'public-users'
}
key?: string
value?:
| {
[k: string]: unknown;
[k: string]: unknown
}
| unknown[]
| string
| number
| boolean
| null;
updatedAt: string;
createdAt: string;
| null
updatedAt: string
createdAt: string
}
export interface PayloadMigration {
id: string;
name?: string;
batch?: number;
id: string
name?: string
batch?: number
schema?:
| {
[k: string]: unknown;
[k: string]: unknown
}
| unknown[]
| string
| number
| boolean
| null;
updatedAt: string;
createdAt: string;
| null
updatedAt: string
createdAt: string
}

View File

@@ -0,0 +1,30 @@
import { buildConfigWithDefaults } from '../../buildConfigWithDefaults'
export const collectionSlug = 'users'
export default buildConfigWithDefaults({
debug: true,
admin: {
user: 'users',
},
collections: [
{
slug: collectionSlug,
auth: {
removeTokenFromResponses: true,
},
fields: [
{
name: 'roles',
label: 'Role',
type: 'select',
options: ['admin', 'editor', 'moderator', 'user', 'viewer'],
defaultValue: 'user',
required: true,
saveToJWT: true,
hasMany: true,
},
],
},
],
})

View File

@@ -0,0 +1,73 @@
import mongoose from 'mongoose'
import payload from '../../../packages/payload/src'
import { devUser } from '../../credentials'
import { initPayloadTest } from '../../helpers/configHelpers'
import { RESTClient } from '../../helpers/rest'
import { collectionSlug } from './config'
require('isomorphic-fetch')
let client: RESTClient
describe('Remove token from auth responses', () => {
beforeAll(async () => {
const config = await initPayloadTest({ __dirname, init: { local: false } })
const { serverURL } = config
client = new RESTClient(config, { serverURL, defaultSlug: collectionSlug })
await client.endpoint(`/api/${collectionSlug}/first-register`, 'post', devUser)
await client.login()
})
afterAll(async () => {
await mongoose.connection.dropDatabase()
await mongoose.connection.close()
await payload.mongoMemoryServer.stop()
})
it('should not include token in response from /login', async () => {
const { status, data } = await client.endpoint(`/api/${collectionSlug}/login`, 'post', devUser)
expect(status).toBe(200)
expect(data.token).not.toBeDefined()
expect(data.user.email).toBeDefined()
})
it('should not include token in response from /me', async () => {
const { status, data } = await client.endpointWithAuth(`/api/${collectionSlug}/me`)
expect(status).toBe(200)
expect(data.token).not.toBeDefined()
expect(data.user.email).toBeDefined()
})
it('should not include token in response from /refresh-token', async () => {
const { status, data } = await client.endpointWithAuth(
`/api/${collectionSlug}/refresh-token`,
'post',
)
expect(status).toBe(200)
expect(data.refreshedToken).not.toBeDefined()
expect(data.user.email).toBeDefined()
})
it('should not include token in response from /reset-password', async () => {
const token = await payload.forgotPassword({
collection: collectionSlug,
data: { email: devUser.email },
disableEmail: true,
})
const { status, data } = await client.endpoint(
`/api/${collectionSlug}/reset-password`,
'post',
{
token,
password: devUser.password,
},
)
expect(status).toBe(200)
expect(data.token).not.toBeDefined()
expect(data.user.email).toBeDefined()
})
})

5
test/auth/shared.ts Normal file
View File

@@ -0,0 +1,5 @@
export const slug = 'users'
export const namedSaveToJWTValue = 'namedSaveToJWT value'
export const saveToJWTKey = 'x-custom-jwt-property-name'

View File

@@ -1,28 +1,28 @@
import React, { useEffect, useState } from 'react';
import { useAuth } from '../../../src/admin/components/utilities/Auth';
import { UIField } from '../../../src/fields/config/types';
import { User } from '../../../src/auth';
import React, { useEffect, useState } from 'react'
import type { User } from '../../../packages/payload/src/auth'
import type { UIField } from '../../../packages/payload/src/fields/config/types'
import { useAuth } from '../../../packages/payload/src/admin/components/utilities/Auth'
export const AuthDebug: React.FC<UIField> = () => {
const [state, setState] = useState<User | null | undefined>();
const { user } = useAuth();
const [state, setState] = useState<User | null | undefined>()
const { user } = useAuth()
useEffect(() => {
if (user) {
fetch(`/api/users/${user.id}`).then((r) => r.json()).then((newUser) => {
setState(newUser);
});
fetch(`/api/users/${user.id}`)
.then((r) => r.json())
.then((newUser) => {
setState(newUser)
})
}
}, [user]);
}, [user])
return (
<div id="auth-debug-ui-field">
<div id="users-api-result">
{state?.custom as string}
</div>
<div id="use-auth-result">
{user?.custom as string}
</div>
<div id="users-api-result">{state?.custom as string}</div>
<div id="use-auth-result">{user?.custom as string}</div>
</div>
);
};
)
}