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

739 notification apis #742

Merged
merged 4 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
190 changes: 184 additions & 6 deletions packages/backend/src/notifications.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import express from 'express';
import auth from './auth';
import request from 'supertest';
import notifications from './notifications';
import { NotificationChannelType } from '@dm3-org/dm3-lib-delivery';

const keysA = {
encryptionKeyPair: {
Expand All @@ -20,7 +21,7 @@ const keysA = {

describe('Notifications', () => {
describe('get NotificationChannels', () => {
it('Returns 200 and an empty array when the user has no chanels set up', async () => {
it('Returns empty array as global notification is turned off', async () => {
const app = express();
app.use(bodyParser.json());
app.use(notifications());
Expand All @@ -46,6 +47,8 @@ describe('Notifications', () => {
return {};
},
getIdEnsName: async (ensName: string) => ensName,
getGlobalNotification: async (ensName: string) =>
Promise.resolve({ isEnabled: false }),
getUsersNotificationChannels: async (ensName: string) =>
Promise.resolve([]),
};
Expand All @@ -59,22 +62,151 @@ describe('Notifications', () => {
.set({
authorization: `Bearer ${token}`,
})
.send();

expect(status).toBe(200);
expect(body).toEqual({
notificationChannels: [],
});
});

it('Returns 200 with empty notification channels as global notification is turned on', async () => {
const app = express();
app.use(bodyParser.json());
app.use(notifications());

const token = await createAuthToken();

app.locals.db = {
getSession: async (ensName: string) =>
Promise.resolve({
challenge: '123',
token,
signedUserProfile: {
profile: {
publicSigningKey:
keysA.signingKeyPair.publicKey,
},
},
}),
setSession: async (_: string, __: any) => {
return (_: any, __: any, ___: any) => {};
},
getUserStorage: async (addr: string) => {
return {};
},
getIdEnsName: async (ensName: string) => ensName,
getUsersNotificationChannels: async (ensName: string) =>
Promise.resolve([]),
getGlobalNotification: async (ensName: string) =>
Promise.resolve({ isEnabled: true }),
};

app.locals.web3Provider = {
resolveName: async () =>
'0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1',
};
const { status, body } = await request(app)
.get(`/bob.eth`)
.set({
authorization: `Bearer ${token}`,
})
.send();

expect(status).toBe(200);
expect(body).toEqual([]);
expect(body).toEqual({
notificationChannels: [],
});
});
});

describe('setUserStorage', () => {
it('User can setup email notifications', async () => {
it('Returns 400 on setup email notifications as email ID is invalid', async () => {
const app = express();
app.use(bodyParser.json());
app.use(notifications());

const token = await createAuthToken();
const addUsersNotificationChannelMock = jest.fn();

app.locals.db = {
getSession: async (ensName: string) =>
Promise.resolve({
challenge: '123',
token,
}),
setSession: async (_: string, __: any) => {
return (_: any, __: any, ___: any) => {};
},
setUserStorage: (_: string, __: string) => {},
getIdEnsName: async (ensName: string) => ensName,
addUsersNotificationChannel: addUsersNotificationChannelMock,
};

app.locals.web3Provider = {
resolveName: async () =>
'0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1',
};

const { status } = await request(app)
.post(`/bob.eth`)
.set({
authorization: `Bearer ${token}`,
})
.send({
recipientValue: 'bob.eth',
notificationChannelType: NotificationChannelType.EMAIL,
});

expect(status).toBe(400);
});

it('Returns 400 on setup email notifications as notificationChannelType is invalid', async () => {
const app = express();
app.use(bodyParser.json());
app.use(notifications());

const token = await createAuthToken();
const addUsersNotificationChannelMock = jest.fn();

app.locals.db = {
getSession: async (ensName: string) =>
Promise.resolve({
challenge: '123',
token,
}),
setSession: async (_: string, __: any) => {
return (_: any, __: any, ___: any) => {};
},
setUserStorage: (_: string, __: string) => {},
getIdEnsName: async (ensName: string) => ensName,
addUsersNotificationChannel: addUsersNotificationChannelMock,
};

app.locals.web3Provider = {
resolveName: async () =>
'0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1',
};

const { status } = await request(app)
.post(`/bob.eth`)
.set({
authorization: `Bearer ${token}`,
})
.send({
recipientValue: '[email protected]',
notificationChannelType: '',
});

expect(status).toBe(400);
});

it('Returns 400 on setup email notifications as globalNotifications is turned off', async () => {
const app = express();
app.use(bodyParser.json());
app.use(notifications());

const token = await createAuthToken();
const addUsersNotificationChannelMock = jest.fn();

app.locals.db = {
Expand All @@ -88,20 +220,66 @@ describe('Notifications', () => {
},
setUserStorage: (_: string, __: string) => {},
getIdEnsName: async (ensName: string) => ensName,
getGlobalNotification: async (ensName: string) =>
Promise.resolve({ isEnabled: false }),
addUsersNotificationChannel: addUsersNotificationChannelMock,
};

app.locals.web3Provider = {
resolveName: async () =>
'0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1',
};

const { status } = await request(app)
.post(`/email/bob.eth`)
.post(`/bob.eth`)
.set({
authorization: `Bearer ${token}`,
})
.send({
recipientValue: '[email protected]',
notificationChannelType: NotificationChannelType.EMAIL,
});

expect(status).toBe(400);
});

it('User can setup email notifications', async () => {
const app = express();
app.use(bodyParser.json());
app.use(notifications());

const token = await createAuthToken();

const addUsersNotificationChannelMock = jest.fn();

app.locals.db = {
getSession: async (ensName: string) =>
Promise.resolve({
challenge: '123',
token,
}),
setSession: async (_: string, __: any) => {
return (_: any, __: any, ___: any) => {};
},
setUserStorage: (_: string, __: string) => {},
getIdEnsName: async (ensName: string) => ensName,
getGlobalNotification: async (ensName: string) =>
Promise.resolve({ isEnabled: true }),
addUsersNotificationChannel: addUsersNotificationChannelMock,
};
app.locals.web3Provider = {
resolveName: async () =>
'0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1',
};

const { status, body } = await request(app)
.post(`/bob.eth`)
.set({
authorization: `Bearer ${token}`,
})
.send({
recipientAddress: 'bob.eth',
recipientValue: '[email protected]',
notificationChannelType: NotificationChannelType.EMAIL,
});

expect(status).toBe(200);
Expand All @@ -110,7 +288,7 @@ describe('Notifications', () => {
{
type: 'EMAIL',
config: {
recipientValue: 'bob.eth',
recipientValue: 'bob@gmail.com',
},
},
);
Expand Down
77 changes: 55 additions & 22 deletions packages/backend/src/notifications.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Importing the necessary modules and functions
import cors from 'cors';
import { NotificationChannelType } from '@dm3-org/dm3-lib-delivery';
import { normalizeEnsName } from '@dm3-org/dm3-lib-profile';
import express from 'express';
import { auth } from './utils';
import { validateNotificationChannel } from './validation/notification/notificationChannelValidation';

// Exporting a function that returns an Express router
export default () => {
Expand Down Expand Up @@ -60,26 +60,48 @@ export default () => {
}
});

// Defining a route to handle POST requests for adding an email notification channel
router.post('/email/:ensName', async (req, res, next) => {
// Defining a route to handle POST requests for adding an notification channel
router.post('/:ensName', async (req, res, next) => {
try {
const account = normalizeEnsName(req.params.ensName);

// Extracting recipientAddress from the request body
const { recipientAddress } = req.body;

// Adding a user's notification channel to the database
await req.app.locals.db.addUsersNotificationChannel(account, {
type: NotificationChannelType.EMAIL,
config: {
// TODO: This endpoint will be modified as generic,
// not specific to email ID
recipientValue: recipientAddress,
},
});
// Extracting recipientValue & notificationChannelType from the request body
const { recipientValue, notificationChannelType } = req.body;

// Sending a success response
res.sendStatus(200);
// Validate req.body data
const { isValid, errorMessage } = validateNotificationChannel(
notificationChannelType,
recipientValue,
);

// Return if invalid data found
if (!isValid) {
res.sendStatus(400).json({
error: errorMessage,
});
}

// Fetch global notification data of user from database
const globalNotification =
await req.app.locals.db.getGlobalNotification(account);

// Throw error if global notification is turned off
if (!globalNotification.isEnabled) {
res.sendStatus(400).json({
error: 'Global notifications is off',
});
} else {
// Adding a user's notification channel to the database
await req.app.locals.db.addUsersNotificationChannel(account, {
type: notificationChannelType,
config: {
recipientValue: recipientValue,
},
});

// Sending a success response
res.sendStatus(200);
}
} catch (e) {
// Passing the error to the next middleware
next(e);
Expand All @@ -91,12 +113,23 @@ export default () => {
try {
const account = normalizeEnsName(req.params.ensName);

// Getting notification channels for a user from the database
const notificationChannels =
await req.app.locals.db.getUsersNotificationChannels(account);
// Fetch global notification data of user from database
const globalNotification =
await req.app.locals.db.getGlobalNotification(account);

// Sending the fetched notification channels as a JSON response
res.json(notificationChannels);
// if global notification is turned off
if (!globalNotification.isEnabled) {
res.status(200).json({ notificationChannels: [] });
} else {
// Getting notification channels for a user from the database
const notificationChannels =
await req.app.locals.db.getUsersNotificationChannels(
account,
);

// Sending the fetched notification channels as a JSON response
res.status(200).json({ notificationChannels });
}
} catch (e) {
// Passing the error to the next middleware
next(e);
Expand Down
Loading