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 3 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
185 changes: 179 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 500 as global notification is turned off', async () => {
const app = express();
app.use(bodyParser.json());
app.use(notifications());
Expand Down Expand Up @@ -59,22 +60,108 @@ describe('Notifications', () => {
.set({
authorization: `Bearer ${token}`,
})
.send();

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

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 = {
Expand All @@ -90,18 +177,104 @@ describe('Notifications', () => {
getIdEnsName: async (ensName: string) => ensName,
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: '',
});

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

it('Returns 500 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 = {
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: false }),
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: NotificationChannelType.EMAIL,
});

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

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 +283,7 @@ describe('Notifications', () => {
{
type: 'EMAIL',
config: {
recipientValue: 'bob.eth',
recipientValue: 'bob@gmail.com',
},
},
);
Expand Down
49 changes: 39 additions & 10 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,21 +60,41 @@ 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;
// Extracting recipientValue & notificationChannelType from the request body
const { recipientValue, notificationChannelType } = req.body;

// 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) {
throw new Error('Global notifications is off');
}

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

Expand All @@ -91,12 +111,21 @@ export default () => {
try {
const account = normalizeEnsName(req.params.ensName);

// 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) {
throw new Error('Global notifications is off');
}

// 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.json(notificationChannels);
res.json({ notificationChannels });
} catch (e) {
// Passing the error to the next middleware
next(e);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { NotificationChannelType } from '@dm3-org/dm3-lib-delivery';
import { checkRegexPattern } from './regexValidation';

// validates notification channel type & recipient value
export const validateNotificationChannel = (
notificationChannelType: string,
recipientValue: string,
): {
isValid: boolean;
errorMessage?: string;
} => {
try {
// throw error if recipient value not found
if (!recipientValue) {
throw new Error('Recipient value is missing');
}

// throw error if notification channel type not found
if (!notificationChannelType) {
throw new Error('Notification Channel Type is missing');
}

// fetch supported notification channel types
const channelTypeCheck = Object.values(
NotificationChannelType,
).includes(notificationChannelType as NotificationChannelType);

// throw error if notification channel type is invalid
if (!channelTypeCheck) {
throw new Error('Invalid notification channel type');
}

// check regex pattern of provided value
const regexCheck = checkRegexPattern(
notificationChannelType,
recipientValue,
);

// throw error if value is invalid
if (!regexCheck) {
throw new Error(
`Invalid ${notificationChannelType.toLowerCase()} value`,
);
}

return {
isValid: true,
};
} catch (error: any) {
// return with error message
return {
isValid: false,
errorMessage: error.message,
};
}
};
Loading