Skip to content

Commit

Permalink
[service] merge push subscription into api handler
Browse files Browse the repository at this point in the history
Co-authored-by: elf Pavlik <elf-pavlik@hackers4peace.net>
  • Loading branch information
samurex and elf-pavlik committed Jan 8, 2024
1 parent c4663a4 commit 53c6501
Show file tree
Hide file tree
Showing 11 changed files with 49 additions and 185 deletions.
4 changes: 4 additions & 0 deletions packages/api-messages/src/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ abstract class MessageBase {

export class HelloRequest extends MessageBase {
public type = RequestMessageTypes.HELLO_REQUEST;

constructor(public subscription?: PushSubscription) {
super();
}
}

export class ApplicationsRequest extends MessageBase {
Expand Down
41 changes: 0 additions & 41 deletions packages/service/config/controllers/push-subscription.json

This file was deleted.

2 changes: 0 additions & 2 deletions packages/service/config/service.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"./controllers/agents.json",
"./controllers/login-redirect.json",
"./controllers/api.json",
"./controllers/push-subscription.json",
"./controllers/webhooks.json",
"./controllers/invitations.json"
],
Expand All @@ -33,7 +32,6 @@
{ "@id": "urn:solid:authorization-agent:controller:Agents" },
{ "@id": "urn:solid:authorization-agent:controller:LoginRedirect" },
{ "@id": "urn:solid:authorization-agent:controller:API" },
{ "@id": "urn:solid:authorization-agent:controller:PushSubscription" },
{ "@id": "urn:solid:authorization-agent:controller:Webhooks" },
{ "@id": "urn:solid:authorization-agent:controller:Invitations" }
]
Expand Down
4 changes: 4 additions & 0 deletions packages/service/src/handlers/api-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export class ApiHandler extends HttpHandler {
throw new BadRequestHttpError('body is required');
}
if (body.type === RequestMessageTypes.HELLO_REQUEST) {
if (body.subscription) {
await this.sessionManager.addPushSubscription(context.authn.webId, body.subscription);
}

const oidcSession = await this.sessionManager.getOidcSession(context.authn.webId);
let loginStatus: LoginStatus;

Expand Down
33 changes: 0 additions & 33 deletions packages/service/src/handlers/push-subscription-handler.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ export * from './handlers/agents-handler';
export * from './handlers/middleware-http-handler';
export * from './handlers/authn-context-handler';
export * from './handlers/api-handler';
export * from './handlers/push-subscription-handler';
export * from './handlers/webhooks-handler';
export * from './handlers/invitations-handler';

Expand Down
23 changes: 22 additions & 1 deletion packages/service/test/unit/handlers/api-handler-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ const logger = getLogger();
const saiSession: AuthorizationAgent = {} as AuthorizationAgent;
const manager = {
getSaiSession: jest.fn(() => saiSession),
getOidcSession: jest.fn()
getOidcSession: jest.fn(),
addPushSubscription: jest.fn()
} as unknown as jest.Mocked<SessionManager>;

let apiHandler: ApiHandler;
Expand All @@ -67,6 +68,7 @@ const headers = { 'content-type': 'application/json' };
beforeEach(() => {
manager.getSaiSession.mockClear();
manager.getOidcSession.mockReset();
manager.addPushSubscription.mockReset();
queue = new MockedQueue('grants');
apiHandler = new ApiHandler(manager, queue);
});
Expand Down Expand Up @@ -121,6 +123,25 @@ describe('hello', () => {
}
});
});
test('should add the subscription', (done) => {
const oidcSession = {
info: { isLoggedIn: false }
} as unknown as Session;
manager.getOidcSession.mockResolvedValueOnce(oidcSession);
const request = {
headers: { 'content-type': 'application/json' },
body: {
type: RequestMessageTypes.HELLO_REQUEST,
subscription: { endpoint: 'https://endpoint.example' } as PushSubscription
}
} as unknown as HttpHandlerRequest;
const ctx = { request, authn } as AuthenticatedAuthnContext;

apiHandler.handle(ctx).subscribe(() => {
expect(manager.addPushSubscription).toBeCalledWith(webId, request.body.subscription);
done();
});
});
});

describe('incorrect request', () => {
Expand Down

This file was deleted.

19 changes: 3 additions & 16 deletions ui/authorization/src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ async function getDataFromApi<T extends ResponseMessage>(request: Request): Prom
return (await response.json()) as T;
}

async function checkServerSession(): Promise<LoginStatus> {
const request = new HelloRequest();
async function checkServerSession(subscription?: PushSubscription): Promise<LoginStatus> {
const request = new HelloRequest(subscription);
const data = await getDataFromApi<HelloResponseMessage>(request);
const response = new HelloResponse(data);
return response.payload;
Expand Down Expand Up @@ -171,18 +171,6 @@ async function acceptInvitation(capabilityUrl: string, label: string, note?: str
return response.payload;
}

// TODO: use api messages
async function subscribeToPushNotifications(subscription: PushSubscription) {
const options = {
method: 'POST',
body: JSON.stringify(subscription),
headers: {
'Content-Type': 'application/json'
}
};
await authnFetch(`${backendBaseUrl}/push-subscribe`, options);
}

export function useBackend() {
return {
checkServerSession,
Expand All @@ -198,7 +186,6 @@ export function useBackend() {
listDataRegistires,
createInvitation,
listSocialAgentInvitations,
acceptInvitation,
subscribeToPushNotifications
acceptInvitation
};
}
25 changes: 12 additions & 13 deletions ui/authorization/src/store/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ export const useCoreStore = defineStore('core', () => {
await oidcLogin(options);
}

async function getPushSubscription() {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (subscription) {
pushSubscription.value = subscription;
}
return backend.checkServerSession(subscription ?? undefined);
}

async function handleRedirect(url: string) {
const oidcInfo = await handleIncomingRedirect(url);
if (!oidcInfo?.webId) {
Expand All @@ -42,7 +51,7 @@ export const useCoreStore = defineStore('core', () => {
userId.value = oidcInfo.webId;

// TODO check if backend authenticated
const loginStatus = await backend.checkServerSession();
const loginStatus = await getPushSubscription();
isBackendLoggedIn.value = loginStatus.isLoggedIn;
redirectUrlForBackend.value = loginStatus.completeRedirectUrl ?? '';
}
Expand All @@ -60,17 +69,6 @@ export const useCoreStore = defineStore('core', () => {
}
}

async function getPushSubscription() {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.getSubscription();
if (subscription) {
pushSubscription.value = subscription;
await backend.subscribeToPushNotifications(subscription);
}
}

/* TODO: DRY ⬆️⬇️ */

async function enableNotifications() {
const result = await Notification.requestPermission();
if (result === 'granted') {
Expand All @@ -83,8 +81,9 @@ export const useCoreStore = defineStore('core', () => {
});
}
pushSubscription.value = subscription;
await backend.subscribeToPushNotifications(subscription);
await backend.checkServerSession(subscription);
}
return result;
}

return {
Expand Down
7 changes: 4 additions & 3 deletions ui/authorization/src/views/Dashboard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,13 @@ import { useAppStore } from '@/store/app';
const coreStore = useCoreStore()
const appStore = useAppStore()
coreStore.getPushSubscription()
const enableNotificationsLoading = ref(false)
function enableNotifications() {
async function enableNotifications() {
enableNotificationsLoading.value = true
coreStore.enableNotifications()
await coreStore.enableNotifications()
enableNotificationsLoading.value = false
}
// TODO: act differently depending on message.data
Expand Down

0 comments on commit 53c6501

Please sign in to comment.