Skip to content

Commit

Permalink
Add next auth sign up tests
Browse files Browse the repository at this point in the history
  • Loading branch information
cesarvarela committed Dec 16, 2024
1 parent f1da9ce commit 476bf88
Show file tree
Hide file tree
Showing 3 changed files with 215 additions and 55 deletions.
2 changes: 1 addition & 1 deletion site/gatsby-site/nextauth.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export const getAuthConfig = async (req: any): Promise<NextAuthOptions> => {
*/
async signIn({ user }) {

if (!(user as AdapterUser).emailVerified && req?.query?.operation == 'signin') {
if (!(user as AdapterUser).emailVerified && req?.query?.operation == 'login') {

return config.SITE_URL + '/api/auth/verify-request?provider=http-email&type=email'
}
Expand Down
266 changes: 213 additions & 53 deletions site/gatsby-site/server/tests/next-auth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,83 +34,243 @@ function mockAuthEvent(operation: string, email: string, callbackUrl: string): P

describe('Auth', () => {

test('Should not send an magic link email to unregistered users on sign in ', async () => {
describe('Login', () => {

test('Should not send an magic link email to unregistered users and to add them to the database', async () => {

await seedFixture({
auth: {
users: [],
},
});

await seedFixture({
auth: {
users: [],
},
});

const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();

const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();
const event = mockAuthEvent('login', '[email protected]', '/');

const event = mockAuthEvent('signin', '[email protected]', '/');
const response = await handler(event as HandlerEvent, {} as HandlerContext);

const response = await handler(event as HandlerEvent, {} as HandlerContext);
expect(sendEmailMock).not.toHaveBeenCalled();
expect(response).toMatchObject({
statusCode: 200,
headers: {
'Cache-Control': 'no-store, max-age=0',
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: config.SITE_URL + '/api/auth/verify-request?provider=http-email&type=email' }),
});

const users = await getCollection('auth', 'users').find({}).toArray();

expect(sendEmailMock).not.toHaveBeenCalled();
expect(response).toMatchObject({
statusCode: 200,
headers: {
'Cache-Control': 'no-store, max-age=0',
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: config.SITE_URL + '/api/auth/verify-request?provider=http-email&type=email' }),
expect(users).toHaveLength(0);
});

const users = await getCollection('auth', 'users').find({}).toArray();
test('Should send an magic link email to registered users', async () => {

expect(users).toHaveLength(0);
});
const email = "[email protected]";

test('Should send an magic link email to registered users on sign in ', async () => {
await seedFixture({
auth: {
users: [
{ email, emailVerified: new Date().toString() }
],
},
});

const email = "[email protected]";
const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();
const event = mockAuthEvent('login', email, '/');

await seedFixture({
auth: {
users: [
{ email, emailVerified: new Date().toString() }
const response = await handler(event as HandlerEvent, {} as HandlerContext);

expect(sendEmailMock).toHaveBeenCalledWith({
dynamicData: {
magicLink: expect.stringMatching(/^http:\/\/localhost:8000\/api\/auth\/callback\/http-email\?callbackUrl=http%3A%2F%2Flocalhost%3A8000%2F&token=.+&email=test.user%40incidentdatabase.ai$/),
},
recipients: [
{
email: "[email protected]",
},
],
},
});
subject: "Login link",
templateId: "Login",

const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();
const event = mockAuthEvent('signin', email, '/');
});

const response = await handler(event as HandlerEvent, {} as HandlerContext);
expect(response).toMatchObject({
statusCode: 200,
headers: {
'Cache-Control': 'no-store, max-age=0',
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: config.SITE_URL + '/api/auth/verify-request?provider=http-email&type=email' }),
});

expect(sendEmailMock).toHaveBeenCalledWith({
dynamicData: {
magicLink: expect.stringMatching(/^http:\/\/localhost:8000\/api\/auth\/callback\/http-email\?callbackUrl=http%3A%2F%2Flocalhost%3A8000%2F&token=.+&email=test.user%40incidentdatabase.ai$/),
},
recipients: [
const users = await getCollection('auth', 'users').find({}).toArray();

expect(users).toMatchObject([
{
email: "[email protected]",
emailVerified: expect.any(String),
}
]);
});

test('Should forward callbackUrl', async () => {

const email = "[email protected]";
const callbackUrl = '/some-path/some-page';

await seedFixture({
auth: {
users: [
{ email, emailVerified: new Date().toString() }
],
},
});

const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();
const event = mockAuthEvent('login', email, callbackUrl);

await handler(event as HandlerEvent, {} as HandlerContext);

expect(sendEmailMock).toHaveBeenCalledWith({
dynamicData: {
magicLink: expect.stringMatching(/^http:\/\/localhost:8000\/api\/auth\/callback\/http-email\?callbackUrl=http%3A%2F%2Flocalhost%3A8000%2Fsome-path%2Fsome-page&token=.+&email=test.user%40incidentdatabase.ai$/),
},
recipients: [
{
email: "[email protected]",
},
],
subject: "Login link",
templateId: "Login",

});
});
});

describe('Signup', () => {

test('Should send a Sig nup link email to unregistered users', async () => {

const email = "[email protected]";

await seedFixture({
auth: {
users: [],
verification_tokens: [],
},
});

const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();
const event = mockAuthEvent('signup', email, '/');

const response = await handler(event as HandlerEvent, {} as HandlerContext);

expect(sendEmailMock).toHaveBeenCalledWith({
dynamicData: {
magicLink: expect.stringMatching(/^http:\/\/localhost:8000\/api\/auth\/callback\/http-email\?callbackUrl=http%3A%2F%2Flocalhost%3A8000%2F&token=.+&email=test.user%40incidentdatabase.ai$/),
},
recipients: [
{
email: "[email protected]",
},
],
subject: "Signup link",
templateId: "Signup",
});

expect(response).toMatchObject({
statusCode: 200,
headers: {
'Cache-Control': 'no-store, max-age=0',
'Content-Type': 'application/json',
},
],
subject: "Login link",
templateId: "Login",
body: JSON.stringify({ url: config.SITE_URL + '/api/auth/verify-request?provider=http-email&type=email' }),
});

const users = await getCollection('auth', 'users').find({}).toArray();
expect(users).toMatchObject([]);

const tokens = await getCollection('auth', 'verification_tokens').find({}).toArray();
expect(tokens).toMatchObject([{ identifier: email, }]);
});

expect(response).toMatchObject({
statusCode: 200,
headers: {
'Cache-Control': 'no-store, max-age=0',
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: config.SITE_URL + '/api/auth/verify-request?provider=http-email&type=email' }),
test('Should send a Sig in link email to registered users', async () => {

const email = "[email protected]";

await seedFixture({
auth: {
users: [
{ email, emailVerified: new Date().toString() }
],
verification_tokens: [],
},
});

const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();
const event = mockAuthEvent('signup', email, '/');

const response = await handler(event as HandlerEvent, {} as HandlerContext);

expect(sendEmailMock).toHaveBeenCalledWith({
dynamicData: {
magicLink: expect.stringMatching(/^http:\/\/localhost:8000\/api\/auth\/callback\/http-email\?callbackUrl=http%3A%2F%2Flocalhost%3A8000%2F&token=.+&email=test.user%40incidentdatabase.ai$/),
},
recipients: [
{
email: "[email protected]",
},
],
subject: "Login link",
templateId: "Login",
});

expect(response).toMatchObject({
statusCode: 200,
headers: {
'Cache-Control': 'no-store, max-age=0',
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: config.SITE_URL + '/api/auth/verify-request?provider=http-email&type=email' }),
});

const tokens = await getCollection('auth', 'verification_tokens').find({}).toArray();
expect(tokens).toMatchObject([{ identifier: email, }]);
});

const users = await getCollection('auth', 'users').find({}).toArray();
test('Should forward callbackUrl', async () => {

const email = "[email protected]";
const callbackUrl = '/some-path/some-page';

await seedFixture({
auth: {
users: [
],
},
});

const sendEmailMock = jest.spyOn(emails, 'sendEmail').mockResolvedValue();
const event = mockAuthEvent('signup', email, callbackUrl);

await handler(event as HandlerEvent, {} as HandlerContext);

expect(sendEmailMock).toHaveBeenCalledWith({
dynamicData: {
magicLink: expect.stringMatching(/^http:\/\/localhost:8000\/api\/auth\/callback\/http-email\?callbackUrl=http%3A%2F%2Flocalhost%3A8000%2Fsome-path%2Fsome-page&token=.+&email=test.user%40incidentdatabase.ai$/),
},
recipients: [
{
email: "[email protected]",
},
],
subject: "Signup link",
templateId: "Signup",
});
});

expect(users).toMatchObject([
{
email: "[email protected]",
emailVerified: expect.any(String),
}
]);
});
});
2 changes: 1 addition & 1 deletion site/gatsby-site/src/contexts/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export const UserContextProvider: React.FC<UserContextProviderProps> = ({ childr
},
logIn: async (email: string, callbackUrl: string) => {

const result = await signIn('http-email', { email, redirect: false, callbackUrl }, { operation: 'signin' });
const result = await signIn('http-email', { email, redirect: false, callbackUrl }, { operation: 'login' });

return result;
},
Expand Down

0 comments on commit 476bf88

Please sign in to comment.