push service
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import express from "express";
|
||||
import { Body, Controller, Post, Query, Request, Route, Security, SuccessResponse } from "tsoa";
|
||||
import type { PushSubscriptionCreateArgs as PushSubscriptionCreateArgsDto } from "../dtos/pushSubscription.js";
|
||||
import { inject } from "../infrastructure/di/injector.js";
|
||||
import { KC_SECURITY_NAME } from "../services/keycloak/user/keycloak-user.js";
|
||||
import { PushService } from "../services/push/pushService.js";
|
||||
|
||||
@Route("push")
|
||||
export class PushContoller extends Controller {
|
||||
private readonly pushService = inject(PushService);
|
||||
|
||||
@Post("add")
|
||||
@Security(KC_SECURITY_NAME)
|
||||
@SuccessResponse("200", "OK")
|
||||
public async addSubscription(
|
||||
@Body() subscription: PushSubscriptionCreateArgsDto,
|
||||
@Request() request: express.Request,
|
||||
): Promise<void> {
|
||||
return await this.pushService.storeSubscription(subscription, request, request.res);
|
||||
}
|
||||
|
||||
@Post('reset')
|
||||
@Security(KC_SECURITY_NAME)
|
||||
@SuccessResponse('200', 'OK')
|
||||
public async resetSubscriptions(
|
||||
@Request() request: express.Request
|
||||
): Promise<void>{
|
||||
return await this.pushService.reset(request);
|
||||
}
|
||||
|
||||
@Post('clearSingle')
|
||||
@Security(KC_SECURITY_NAME)
|
||||
@SuccessResponse("200", 'OK')
|
||||
public async clearSubscription(
|
||||
@Request() request: express.Request,
|
||||
@Query() clientId: string
|
||||
):Promise<void>{
|
||||
await this.pushService.clearSubscription(clientId, request);
|
||||
}
|
||||
|
||||
@Post('test-publish')
|
||||
@Security(KC_SECURITY_NAME)
|
||||
@SuccessResponse("200", "OK")
|
||||
public async publishTestMessage(
|
||||
@Request() request: express.Request
|
||||
): Promise<void>{
|
||||
this.pushService.sendtestNotification(request);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,11 +13,11 @@ import { Claim } from "../dtos/claim.js";
|
||||
import { type User } from "../dtos/user.js";
|
||||
import { inject } from "../infrastructure/di/index.js";
|
||||
import { KC_SECURITY_NAME } from "../services/keycloak/user/index.js";
|
||||
import { UserService } from "../services/userService.js";
|
||||
import { UserAdminService } from "../services/userAdminService.js";
|
||||
|
||||
@Route("users")
|
||||
export class UsersController extends Controller {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly userService = inject(UserAdminService);
|
||||
|
||||
@Security(KC_SECURITY_NAME, [Claim.UserAdmin])
|
||||
@SuccessResponse("200", "OK")
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { JsonValue } from "@prisma/client/runtime/client";
|
||||
|
||||
export class PushSubscriptionDto{
|
||||
id!: string;
|
||||
endpoint!: string;
|
||||
expirationTime!: number | null;
|
||||
keys!: {
|
||||
p256dh: string;
|
||||
auth: string;
|
||||
};
|
||||
topic!: "TEST";
|
||||
topicConfiguration!: JsonValue | null;
|
||||
clientId!: string;
|
||||
}
|
||||
|
||||
export class PushSubscriptionCreateArgs/* implements Omit<PushSubscriptionDto, "id">*/{
|
||||
endpoint!: string;
|
||||
expirationTime!: number | null;
|
||||
keys!: { p256dh: string; auth: string; };
|
||||
topic!: "TEST";
|
||||
topicConfiguration!: string | null;
|
||||
clientId!: string;
|
||||
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { type Request } from "express";
|
||||
import { PrismaClient } from "../../generated/prisma/client.js";
|
||||
import type { UserModel } from "../../generated/prisma/models.js";
|
||||
import { Injectable } from "../../infrastructure/di/injectable-decorator.js";
|
||||
|
||||
type ExtendedClient = ReturnType<typeof createExtendedClient>;
|
||||
@@ -23,7 +24,17 @@ export type SafeClient = Omit<
|
||||
>;
|
||||
|
||||
function createExtendedClient(client: PrismaClient) {
|
||||
return client;
|
||||
return client.$extends({
|
||||
client: {
|
||||
async ensureUserKnown(userId: string): Promise<UserModel>{
|
||||
let user = await client.user.findUnique({where: {id: userId}});
|
||||
if(user==null){
|
||||
user = await client.user.create({data:{id: userId}});
|
||||
}
|
||||
return user
|
||||
}
|
||||
}
|
||||
});
|
||||
// .$extends({
|
||||
// name: "testExtension",
|
||||
// model: {
|
||||
|
||||
@@ -31,6 +31,9 @@ export class KeycloakUser {
|
||||
this.keycloakConnect = new Promise(async resolve => {
|
||||
const config = await this.getConfig();
|
||||
const client = new KeycloakConnect({ store: sessionStore }, config);
|
||||
client.authenticated=(r)=>{
|
||||
console.dir(r);
|
||||
};
|
||||
resolve(client);
|
||||
});
|
||||
}
|
||||
@@ -49,4 +52,10 @@ export class KeycloakUser {
|
||||
const client = await this.keycloakConnect;
|
||||
return client.middleware();
|
||||
}
|
||||
|
||||
public async getUid(request: Request, response?: Response): Promise<string>{
|
||||
const client = await this.keycloakConnect;
|
||||
const grant = await client.getGrant(request, response ?? ({} as any));
|
||||
return (grant.access_token as any)?.content?.sub;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { DbNull } from "@prisma/client/runtime/client";
|
||||
import type { Request, Response } from "express";
|
||||
import webpush from "web-push";
|
||||
import type { PushSubscriptionCreateArgs } from "../../dtos/pushSubscription.js";
|
||||
import { Topic } from "../../generated/prisma/enums.js";
|
||||
import { inject } from "../../infrastructure/di/index.js";
|
||||
import { Injectable } from "../../infrastructure/di/injectable-decorator.js";
|
||||
import { DatabaseService } from "../db/prisma.js";
|
||||
import { KeycloakUser } from "../keycloak/user/keycloak-user.js";
|
||||
import VAPID from './vapid.json' with { type: "json" };
|
||||
|
||||
@Injectable()
|
||||
export class PushService{
|
||||
private readonly db = inject(DatabaseService);
|
||||
private readonly userService = inject(KeycloakUser);
|
||||
|
||||
public constructor(){
|
||||
webpush.setVapidDetails("mailto:toniwalter.blue@gmail.com", VAPID.publicKey, VAPID.privateKey);
|
||||
}
|
||||
|
||||
public async storeSubscription(subscription: PushSubscriptionCreateArgs, request: Request, response?: Response): Promise<void>{
|
||||
const userId= await this.userService.getUid(request, response);
|
||||
await this.db.doRequest(async prisma=>{
|
||||
await prisma.ensureUserKnown(userId);
|
||||
return await prisma.pushSubscription.create({
|
||||
data: {
|
||||
auth: subscription.keys.auth,
|
||||
endpoint: subscription.endpoint,
|
||||
p256dh: subscription.keys.p256dh,
|
||||
expirationTime: subscription.expirationTime ?? null,
|
||||
userId: userId,
|
||||
clientId: subscription.clientId,
|
||||
topic: subscription.topic,
|
||||
topicConfiguration: subscription.topicConfiguration ? JSON.parse(subscription.topicConfiguration) : DbNull,
|
||||
}
|
||||
});
|
||||
}, request);
|
||||
}
|
||||
|
||||
public async sendtestNotification(request: Request){
|
||||
const subscriptions = await this.db.doRequest(async prisma=>prisma.pushSubscription.findMany({where:{topic: "TEST"}}), request);
|
||||
|
||||
const payload = {
|
||||
notification: {
|
||||
title: "ATitle",
|
||||
body: "DatBod",
|
||||
icon: "assets/some-icon.png",
|
||||
vibrate: [100, 50, 100],
|
||||
data: {
|
||||
dateOfArrival: Date.now(),
|
||||
primaryKey: 1
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
action: "explode",
|
||||
title: "Make Boom"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`sending ${subscriptions.length} test messages`);
|
||||
for(const s of subscriptions){
|
||||
const subscription: webpush.PushSubscription={
|
||||
endpoint: s.endpoint,
|
||||
keys: {
|
||||
auth: s.auth,
|
||||
p256dh: s.p256dh
|
||||
},
|
||||
expirationTime: s.expirationTime
|
||||
};
|
||||
try{
|
||||
const result = await webpush.sendNotification(subscription, JSON.stringify(payload), {
|
||||
topic: Topic.TEST,
|
||||
});
|
||||
console.log("success");
|
||||
console.dir(result);
|
||||
}catch(error){
|
||||
console.error("Cannot send notification: ", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async reset(request: Request): Promise<void> {
|
||||
const userId=await this.userService.getUid(request, request.res);
|
||||
const subscriptions = await this.db.doRequest(async prisma=>await prisma.pushSubscription.deleteMany({
|
||||
where:{userId: userId}
|
||||
}), request);
|
||||
|
||||
console.log(`deleted ${subscriptions.count} subs for ${userId}`);
|
||||
}
|
||||
|
||||
public async clearSubscription(clientId: string, request: Request): Promise<number> {
|
||||
const userId =await this.userService.getUid(request, request.res);
|
||||
const batchResult =await this.db.doRequest(async prisma=>await prisma.pushSubscription.deleteMany({
|
||||
where: {
|
||||
userId: userId,
|
||||
AND: {
|
||||
clientId: clientId
|
||||
}
|
||||
}
|
||||
}), request);
|
||||
return batchResult.count;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { type User } from "../dtos/user.js";
|
||||
import { inject } from "../infrastructure/di/index.js";
|
||||
import { KeycloakAdmin } from "./keycloak/admin/index.js";
|
||||
|
||||
export class UserService {
|
||||
export class UserAdminService {
|
||||
private readonly keycloakAdmin = inject(KeycloakAdmin);
|
||||
public async setClaim(
|
||||
uid: string,
|
||||
Reference in New Issue
Block a user