Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
17 changes: 4 additions & 13 deletions .env_sample
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
# VARIABLES PARA LA BASE DE datos
# ENVIROMENT VARIABLES FOR DATABASE

DB_PORT = puerto
DB_NAME = nombre de la base de datos
DB_USER = nombre del usuario
DB_PASSWORD = contraseña
DB_HOST = host en el cual esta corriendo
CONNECT_PORT = puerto el cual se conecta la base de datos

CONNECT_PORT = puerto de conexión de node
# ENVIROMENT VARIABLES FOR FIREBASE

# VARIABLES PARA FIREBASE
DIR_FIREBASE_KEY = direccion de archivo con la clave

DIR_FIREBASE_KEY = dirección de la clave de firebase en formato .json

# JOSONWEBTOKEN

SECRET_KEY = palabra secreta para crear el token
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
package-lock.json
.env
keys/
firebaseKey.json
build
16 changes: 8 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"dotenv": "16.0.3",
"express": "4.18.2",
"firebase-admin": "^11.3.0",
"helmet": "^6.0.0",
"helmet": "^6.0.1",
"jsonwebtoken": "^8.5.1",
"morgan": "^1.10.0",
"node-cron": "^3.0.2",
Expand All @@ -27,25 +27,25 @@
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.12",
"@types/cors": "^2.8.13",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.14",
"@types/jsonwebtoken": "^8.5.9",
"@types/morgan": "^1.9.3",
"@types/node": "^18.11.9",
"@types/node": "^18.11.13",
"@types/node-cron": "^3.0.6",
"@types/swagger-jsdoc": "^6.0.1",
"@types/swagger-ui-express": "^4.1.3",
"@types/yamljs": "^0.2.31",
"@typescript-eslint/eslint-plugin": "^5.44.0",
"eslint": "^8.28.0",
"@typescript-eslint/eslint-plugin": "^5.46.1",
"eslint": "^8.29.0",
"eslint-config-prettier": "8.5.0",
"eslint-config-standard-with-typescript": "^23.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-n": "^15.5.1",
"eslint-plugin-n": "^15.6.0",
"eslint-plugin-promise": "^6.1.1",
"prettier": "2.8.0",
"prettier": "2.8.1",
"ts-node-dev": "^2.0.0",
"typescript": "^4.9.3"
"typescript": "^4.9.4"
}
}
2 changes: 1 addition & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ app.use(helmet());
app.use(authRouter);
app.use(notificationRouter);

const swaggerJsDocs = YAML.load('./docs/docs.yaml');
const swaggerJsDocs = YAML.load('./docs/doc.yaml');
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerJsDocs));

app.use(handleError);
Expand Down
14 changes: 10 additions & 4 deletions src/controllers/auth.controllers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NextFunction, Request, Response } from 'express';
import * as bcrypt from 'bcryptjs';
import { createError } from '../middleware/errorHandle';
import { db, dbAuth } from '..';
import { db, dbAuth, dbCheck } from '..';

interface IUser {
name: string;
Expand Down Expand Up @@ -66,12 +66,18 @@ export async function login(req: Request, res: Response, next: NextFunction) {
if (!passwordCorrect)
return next(new createError(400, 'correo o contraseña no es correcta'));

const token = await dbAuth.createCustomToken(userExist.uid);
console.log(userExist.uid);

// const token = await dbAuth.createCustomToken(userExist.uid);

const token = await dbCheck.createToken(userExist.uid);

console.log(token);

return res
.status(200)
.header({ auth: token, user: userExist.uid })
.json(`bienvenido ${userExist.displayName}, token`);
.header({ user: userExist.uid })
.json(`bienvenido ${userExist.displayName}`);
} catch (err: any) {
next(new createError(404, err.message));
}
Expand Down
4 changes: 0 additions & 4 deletions src/controllers/notification.controllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ export async function getNotifications(

const listNotification = await notificationRef.get().then(listItem);

console.log(listNotification);
console.log(!listNotification);
console.log(!!listNotification);

if (!listNotification)
return next(new createError(202, 'no hay notificación'));

Expand Down
12 changes: 0 additions & 12 deletions src/firebase/key/firebase.json

This file was deleted.

1 change: 0 additions & 1 deletion src/firebase/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ const message = {
},
condition: condition,
};

export function sendMessage(message: Message) {
admin
.messaging()
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const service = require(`${__dirname}${process.env.DIR_FIREBASE_KEY}`);

admin.initializeApp({
credential: admin.credential.cert(service),
projectId: 'my-second-project-3113f',
});

async function connect() {
Expand All @@ -31,3 +32,4 @@ connect();
export const db = admin.firestore();
export const dbAuth = admin.auth();
export const dbMessage = admin.messaging();
export const dbCheck = admin.appCheck();
48 changes: 21 additions & 27 deletions src/middleware/notification/configNotification.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,53 @@
import { Message } from 'firebase-admin/lib/messaging/messaging-api';

export function configurationNotification(
time: Date,
title: string,
body: string,
orientation: string,
image?: string
imageUrl?: string
) {
let config: Message = {
notification: { title, body, imageUrl: image },
webpush: { notification: { title, body, image } },
android: { notification: { title, body, imageUrl } },
apns: { payload:{aps:{}}},
};
let config = {};

const notification = {};
const webpush = {};
const android = {};
const apns = {};
const notification = {
title,
body,
imageUrl,
};

if (image) {
if (imageUrl) {
if (orientation) {
config = {
webpush: { notification: { title, body, image } },
webpush: { notification },
};
} else if (orientation) {
config = {
android: { notification: { title, body, image } },
android: { notification },
};
} else if (orientation) {
config = {
appnl: { notification: { title, body, image } },
};
config: {
apns: {
payload: notification;
}
}
} else {
config = {
webpush: { notification: { title, body, image } },
};
config = { notification };
}
} else {
if (orientation) {
config = {
webpush: { notification: { title, body, image } },
webpush: { notification: { title, body } },
};
} else if (orientation) {
config = {
webpush: { notification: { title, body, image } },
android: { notification: { title, body } },
};
} else if (orientation) {
config = {
webpush: { notification: { title, body, image } },
apns: { payload: { title, body } },
};
} else {
config = {
webpush: { notification: { title, body, image } },
notification: { notification: { title, body } },
};
}
}
return config;
}
65 changes: 10 additions & 55 deletions src/middleware/notification/notificationProgrammer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Message } from 'firebase-admin/lib/messaging/messaging-api';
import cron from 'node-cron';
import { sendMessage } from './sendNotification';
import { configurationNotification } from './configNotification';

export function sendNow(
time: Date,
Expand All @@ -9,91 +10,45 @@ export function sendNow(
orientation: string,
img?: string
) {
let message;
if (img) {
message = {
notification: {
title,
body,
imageUrl: img,
},
};
} else {
message = {
notification: {
title,
body,
},
};
}

const message = configurationNotification(title, body, orientation, img);
sendMessage(message);
}

export function sendProgrammer(
time: Date,
title: string,
description: string,
body: string,
orientation: string,
img?: string
) {
console.log('se enviaron la notificaciones');
const message = {
notification: {
title,
body: description,
},
};
const message = configurationNotification(title, body, orientation, img);

const dayMonth: number | string = time.getDate() || '*';
const dayWeek: number | string = time.getDate() || '*';
const minute: number | string = time.getSeconds() || '*';
const month: number | string = time.getMonth() || '*';
const hour: number | string = time.getHours() || '*';
cron.schedule(`${minute} ${hour} ${dayMonth} ${month} ${dayWeek}`, () => {
const message = {};
sendMessage(message);
});
}

export function sendRecurrent(
time: Date,
dayWeek: number[],
title: string,
description: string,
body: string,
orientation: string,
img?: string
) {
console.log('se enviaron la notificaciones');
const message: Message = {
condition: '',
token: '',
topic: '',
android: {
collapseKey: '',
data: {},
fcmOptions: { analyticsLabel: '' },
notification: {
body: '',
bodyLocArgs: [''],
bodyLocKey: '',
imageUrl: '.... hay mas configuraciones',
},
priority: 'high',
ttl: 1000,
restrictedPackageName: '',
},
apns: { fcmOptions: { imageUrl: '' } },
data: {},
fcmOptions: { analyticsLabel: '' },
notification: { body: '', title, imageUrl: '' },
webpush: { data: {}, notification: {}, fcmOptions: {} },
};
const message = configurationNotification(title, body, orientation, img);

const dayMonth: number | string = time.getDate() || '*';
const dayWeek: number | string = time.getDate() || '*';
const minute: number | string = time.getSeconds() || '*';
const month: number | string = time.getMonth() || '*';
const hour: number | string = time.getHours() || '*';

cron.schedule(`${minute} ${hour} ${dayMonth} ${month} ${dayWeek}`, () => {
const message = {};
sendMessage(message);
});
}
2 changes: 1 addition & 1 deletion src/middleware/notification/sendNotification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Message } from 'firebase-admin/lib/messaging/messaging-api';
export async function sendMessage(message: any) {
await admin
.messaging()
.send(message, true)
.send(message)
.then(() => console.log(message))
.then(() => console.log({ message: 'mensaje enviado correctamente' }))
.catch(error => {
Expand Down
13 changes: 11 additions & 2 deletions src/middleware/token.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NextFunction, Request, Response } from 'express';
import { dbAuth } from '..';
import { db, dbAuth, dbCheck } from '..';
import { createError } from './errorHandle';

export async function isAuthenticate(
Expand All @@ -10,11 +10,20 @@ export async function isAuthenticate(
try {
const authenticate: any = req.headers['auth'];

if (!authenticate) next(new createError(403, 'usuario no autenticado'));
if (!authenticate)
return next(new createError(403, 'usuario no autenticado'));

const isAuth = await dbAuth.verifyIdToken(authenticate);

if (!isAuth) return next(new createError(404, 'no esta autorizado'));

const appCheakToken = req.header('X-Firebase-AppCheck');

if (!appCheakToken)
return next(new createError(401, 'no tiene autorizacion'));

const appCheckClaim = await dbCheck.verifyToken(appCheakToken)

} catch (err: any) {
next(new createError(0, err.message));
}
Expand Down