initial
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
require("dotenv").config();
|
||||
|
||||
const express = require("express");
|
||||
const cors = require("cors");
|
||||
const admin = require("firebase-admin");
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert(
|
||||
require("./serviceAccountKey.json")
|
||||
),
|
||||
});
|
||||
|
||||
const API_KEY = process.env.API_KEY;
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
return res.status(401).json({
|
||||
error: "Missing Authorization Header",
|
||||
});
|
||||
}
|
||||
|
||||
const token = authHeader.replace("Bearer ", "");
|
||||
|
||||
if (token !== API_KEY) {
|
||||
return res.status(403).json({
|
||||
error: "Invalid API Key",
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
app.post("/push", authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const {
|
||||
type = "none",
|
||||
title,
|
||||
message,
|
||||
} = req.body;
|
||||
|
||||
if (!title || !message) {
|
||||
return res.status(400).json({
|
||||
error: "title and message required",
|
||||
});
|
||||
}
|
||||
|
||||
let color = "#2196f3";
|
||||
|
||||
switch (type) {
|
||||
case "info":
|
||||
color = "#2196f3";
|
||||
break;
|
||||
|
||||
case "warning":
|
||||
color = "#ff9800";
|
||||
break;
|
||||
|
||||
case "danger":
|
||||
color = "#f44336";
|
||||
break;
|
||||
|
||||
case "none":
|
||||
default:
|
||||
color = "#9e9e9e";
|
||||
break;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
topic: "global",
|
||||
|
||||
notification: {
|
||||
title,
|
||||
body: message,
|
||||
},
|
||||
|
||||
data: {
|
||||
type,
|
||||
color,
|
||||
},
|
||||
|
||||
android: {
|
||||
priority: "high",
|
||||
notification: {
|
||||
color,
|
||||
},
|
||||
},
|
||||
|
||||
apns: {
|
||||
payload: {
|
||||
aps: {
|
||||
sound: "default",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
webpush: {
|
||||
notification: {
|
||||
icon: "/icon-192.png",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const response = await admin
|
||||
.messaging()
|
||||
.send(payload);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
firebaseResponse: response,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
res.status(500).json({
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server running on ${PORT}`);
|
||||
});
|
||||
Reference in New Issue
Block a user