2023-01-21 21:36:22 +01:00
|
|
|
import { db } from '../utils/firebase'
|
|
|
|
import { getAuth } from 'firebase-admin/auth'
|
|
|
|
import { getMessaging } from 'firebase-admin/messaging'
|
|
|
|
|
|
|
|
export default defineEventHandler(async event => {
|
2023-01-22 15:42:45 +01:00
|
|
|
const { token, body, title, topic } = await readBody(event);
|
2023-01-21 21:36:22 +01:00
|
|
|
|
|
|
|
if (!token) throw createError({ statusCode: 400, statusMessage: 'no-token'})
|
|
|
|
if (!body) throw createError({ statusCode: 400, statusMessage: 'no-body'})
|
|
|
|
if (!title) throw createError({ statusCode: 400, statusMessage: 'no-title'})
|
2023-01-22 15:42:45 +01:00
|
|
|
if (!topic) throw createError({ statusCode: 400, statusMessage: 'no-topic'})
|
|
|
|
|
2023-01-21 21:36:22 +01:00
|
|
|
|
|
|
|
let decodedToken = null;
|
|
|
|
|
|
|
|
try {
|
|
|
|
decodedToken = await getAuth().verifyIdToken(token)
|
|
|
|
} catch (e) {
|
|
|
|
console.log(e)
|
|
|
|
throw createError({ statusCode: 500, statusMessage: 'error-verify-id'})
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!decodedToken) throw createError({ statusCode: 500, statusMessage: 'error-verify-id-test'})
|
|
|
|
|
|
|
|
try {
|
|
|
|
const uid = decodedToken.uid;
|
|
|
|
|
|
|
|
const docRef = db.collection('users').doc(uid);
|
|
|
|
const doc = await docRef.get();
|
|
|
|
|
|
|
|
if (!doc.exists) throw createError({ statusCode: 500, statusMessage: 'doc-not-found'})
|
|
|
|
|
|
|
|
const data = doc.data()
|
|
|
|
|
|
|
|
if (!data.sendNews) throw createError({ statusCode: 500, statusMessage: 'no-permissions'})
|
|
|
|
|
|
|
|
const message = {
|
|
|
|
notification: {
|
|
|
|
title: title,
|
|
|
|
body: body,
|
|
|
|
},
|
|
|
|
webpush: {
|
|
|
|
notification: {
|
|
|
|
icon: '/ios/256.png'
|
|
|
|
}
|
|
|
|
},
|
2023-01-22 15:42:45 +01:00
|
|
|
topic: topic,
|
2023-01-21 21:36:22 +01:00
|
|
|
apns: {
|
|
|
|
payload: {
|
|
|
|
aps: {
|
|
|
|
sound: 'default'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
const response = await getMessaging().send(message)
|
|
|
|
|
|
|
|
console.log('Successfully sent message:', response);
|
|
|
|
|
|
|
|
return { code: 'success', response: response }
|
|
|
|
|
|
|
|
} catch (e) {
|
|
|
|
throw createError({ statusCode: 500, statusMessage: e.message })
|
|
|
|
}
|
|
|
|
})
|