Skip to content

Commit

Permalink
feat(logging): use winston for logging
Browse files Browse the repository at this point in the history
- use winston for logging
  • Loading branch information
cgawron committed Nov 4, 2024
1 parent 272fdcb commit b1c8ac0
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 38 deletions.
5 changes: 3 additions & 2 deletions backend/src/config/dbConn.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import mongoose from "mongoose";

import { logger } from "../logging.js";
const mongo_url = process.env.MONGO_URI || "mongodb://localhost:27017/bookme"

/**
Expand All @@ -13,11 +14,11 @@ export const dataBaseConn = (): Promise<mongoose.Connection> => {
};
return mongoose.connect(mongo_url, connectOptions)
.then(connection => {
console.log(`MongoDB Connected: ${connection.connection.host}`);
logger.info(`MongoDB Connected: ${connection.connection.host}`);
return connection.connection;
})
.catch(err => {
console.log(`Error: ${err.message}`);
logger.error(`Error: ${err.message}`);
process.exit(1);
})
};
Expand Down
17 changes: 9 additions & 8 deletions backend/src/controller/authentication_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { createTransport } from "nodemailer";
import { OAuth2Client } from 'google-auth-library';
import { Request, Response } from "express";
import pkg, { JwtPayload } from 'jsonwebtoken';
import { logger } from "../logging.js";

// Dotenv Config
import dotenv from "dotenv";
Expand All @@ -20,15 +21,15 @@ const env = dotenv.config({
const { sign, verify } = pkg;

const REDIRECT_URI = `${process.env.API_URL}/google/oauthcallback`;
console.log("redirectUri: %s", REDIRECT_URI);
logger.debug("redirectUri: %s", REDIRECT_URI);
if (!process.env.CLIENT_SECRET) {
console.error("CLIENT_SECRET not set!")
logger.error("CLIENT_SECRET not set!")
}
if (!process.env.CLIENT_ID) {
console.error("CLIENT_ID not set!")
logger.error("CLIENT_ID not set!")
}
else {
console.log("clientId: %s", process.env.CLIENT_ID);
logger.debug("clientId: %s", process.env.CLIENT_ID);
}
const oAuth2Client = new OAuth2Client({
clientId: process.env.CLIENT_ID,
Expand Down Expand Up @@ -208,13 +209,13 @@ export const googleLoginController = (req: Request, res: Response): void => {
.verifyIdToken({ idToken, audience: process.env.CLIENT_ID })
.then(response => {
const { email_verified, name, email, picture, sub } = response.getAttributes().payload;
console.log('picture: %s', picture);
logger.debug('picture: %s', picture);
if (email_verified) {
const user_url = validateUrl(email);

const user = new UserModel({ name, email, picture_url: picture, user_url });
user._id = sub;
console.log('user: %o', user);
logger.debug('user: %o', user);
UserModel.findOneAndUpdate({ _id: sub }, { name, email, picture_url: picture, user_url }, { upsert: true })
.exec()
.then(user => {
Expand All @@ -239,7 +240,7 @@ export const googleLoginController = (req: Request, res: Response): void => {
});
})
.catch(error => {
console.error('Error saving user: %o', error);
logger.error('Error saving user: %o', error);
res.status(400).json({ message: "User signup failed with google", error })
});
} else {
Expand All @@ -249,7 +250,7 @@ export const googleLoginController = (req: Request, res: Response): void => {
}
})
.catch((err) => {
console.error('Error retrieving access token', err);
logger.error('Error retrieving access token', err);
res.status(400).json({
errors: "Google login failed. Try again",
});
Expand Down
30 changes: 16 additions & 14 deletions backend/src/controller/event_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@ import { errorHandler } from "../handlers/errorhandler.js";
import { addMinutes, addDays, startOfHour, startOfDay } from 'date-fns';
import { Request, Response } from "express";

import { logger } from "../logging.js";

//const DAYS = [Day.SUN, Day.MON, Day.TUE, Day.WED, Day.THU, Day.FRI, Day.SAT,]

function max<T>(a: T, b: T): T {
console.log('max: %o %o', a, b)
logger.debug('max: %o %o', a, b)
return a < b ? b : a;
}

function min<T>(a: T, b: T): T {
console.log('min: %o %o', a, b)
logger.debug('min: %o %o', a, b)
return a < b ? a : b;
}

Expand All @@ -34,7 +36,7 @@ export const getAvailableTimes = (req: Request, res: Response): void => {
let timeMax = new Date(<string>req.query.timeMax);
const url = <string>req.query.url;
const userid = <string>req.query.userid;
console.log('getAvailableTimes: %s %s %s %s', timeMin, timeMax, url, userid);
logger.debug('getAvailableTimes: %s %s %s %s', timeMin, timeMax, url, userid);
EventModel
.findOne({ url: url, user: userid })
.select("available bufferbefore duration bufferafter minFuture maxFuture maxPerDay -_id")
Expand All @@ -43,38 +45,38 @@ export const getAvailableTimes = (req: Request, res: Response): void => {
// Calculate intersection of requested and 'feasible' time interval
timeMin = max(timeMin, startOfHour(Date.now() + 1000 * event.minFuture));
timeMax = min(timeMax, startOfHour(Date.now() + 1000 * event.maxFuture));
console.log("Event: %o; timeMin: %s, timeMax: %s", event, timeMin, timeMax);
logger.debug("Event: %o; timeMin: %s, timeMax: %s", event, timeMin, timeMax);

// Request currently booked events. We need them for the maxPerDay restriction
return events(userid, timeMin.toISOString(), timeMax.toISOString())
.then(events => ({ events, event }));
})
.then(({ events, event }) => {
const blocked = calculateBlocked(events, event, timeMin, timeMax);
console.log("blocked: %o", blocked);
console.log("free: %o", blocked.inverse());
logger.debug("blocked: %o", blocked);
logger.debug("free: %o", blocked.inverse());

// Now query freeBusy service
return freeBusy(userid, timeMin.toISOString(), timeMax.toISOString())
.then(freeBusyResponse => ({ freeBusyResponse, event, blocked }));
})
.then(({ freeBusyResponse, event, blocked }) => {
let freeSlots = calculateFreeSlots(freeBusyResponse, event, timeMin, timeMax, blocked);
console.log('freeSlots before filtering: %j', freeSlots);
logger.debug('freeSlots before filtering: %j', freeSlots);
freeSlots = new IntervalSet(freeSlots.filter(slot => (slot.end.getTime() - slot.start.getTime()) > event.duration * 60 * 1000));
console.log('freeSlots after filtering: %j', freeSlots);
logger.debug('freeSlots after filtering: %j', freeSlots);
res.status(200).json(freeSlots);
})
.catch(err => {
console.error('getAvailableTime: event not found or freeBusy failed: %o', err);
logger.error('getAvailableTime: event not found or freeBusy failed: %o', err);
res.status(400).json({ error: err });
});

function calculateBlocked(events, event, timeMin, timeMax) {
const eventsPerDay = {};
const blocked = new IntervalSet([{ start: timeMin, end: timeMin }, { start: timeMax, end: timeMax }]);
events.forEach(evt => {
console.log('event: %o', evt);
logger.debug('event: %o', evt);
if (!evt.start.dateTime) {
return;
}
Expand All @@ -100,7 +102,7 @@ export const getAvailableTimes = (req: Request, res: Response): void => {
const calIntervals = new IntervalSet();
let current = timeMin;
for (const busy of response.data.calendars[key].busy) {
console.log('freeBusy: %o %o %d %d', busy.start, busy.end, event.bufferbefore, event.bufferafter);
logger.debug('freeBusy: %o %o %d %d', busy.start, busy.end, event.bufferbefore, event.bufferafter);
const _start = addMinutes(new Date(busy.start), -event.bufferbefore);
const _end = addMinutes(new Date(busy.end), event.bufferafter);
if (current < _start)
Expand All @@ -126,10 +128,10 @@ export const getAvailableTimes = (req: Request, res: Response): void => {
*/
export const addEventController = (req: Request, res: Response): void => {
const errors = validationResult(req);
console.log('errors: %j', errors);
logger.debug('errors: %j', errors);

const event: Event = req.body;
console.log('event: %j', event)
logger.debug('event: %j', event)

if (!errors.isEmpty()) {
const newError = errors.array().map<unknown>((error: ValidationError) => error.msg)[0];
Expand Down Expand Up @@ -221,7 +223,7 @@ export const getEventByIdController = (req: Request, res: Response): void => {
.findById({ _id: event_id })
.exec()
.then(event => {
console.log("getEvent: %s %o", event_id, event);
logger.debug("getEvent: %s %o", event_id, event);
res.status(200).json(event);
})
.catch(err => {
Expand Down
22 changes: 11 additions & 11 deletions backend/src/controller/google_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { Request, Response } from 'express';

import { Event, IntervalSet } from 'common';


import { logger } from '../logging.js';

// Dotenv Config
import dotenv from "dotenv";
Expand All @@ -30,7 +30,7 @@ const config = {
redirectUri: `${process.env.API_URL}/google/oauthcallback`,
}

console.log("google_controller: ", config);
logger.debug("google_controller: ", config);

const oAuth2Client = new OAuth2Client(config);
const SCOPES = [
Expand Down Expand Up @@ -133,7 +133,7 @@ async function checkFree(event: Event, userid: string, timeMin: Date, timeMax: D
export function insertEventToGoogleCal(req: Request, res: Response) {
const starttime = new Date(Number.parseInt(req.body.starttime));
const endtime = addMinutes(starttime, req.body.event.duration);
console.log("insertEvent: %s %o", req.body.starttime, starttime);
logger.debug("insertEvent: %s %o", req.body.starttime, starttime);

checkFree(req.body.event, req.params.user_id, starttime, endtime)
.then(free => {
Expand Down Expand Up @@ -183,7 +183,7 @@ export function insertEventToGoogleCal(req: Request, res: Response) {
};

oAuth2Client.setCredentials(user.google_tokens);
console.log('insert: event=%j', event)
logger.debug('insert: event=%j', event)
google.calendar({ version: "v3" }).events
.insert({
auth: oAuth2Client,
Expand All @@ -192,7 +192,7 @@ export function insertEventToGoogleCal(req: Request, res: Response) {
requestBody: event,
})
.then((evt: GaxiosResponse<Schema$Event>) => {
console.log('insert returned %j', evt)
logger.debug('insert returned %j', evt)
res.json({ success: true, message: "Event wurde gebucht", event: evt });
})
.catch(error => {
Expand Down Expand Up @@ -230,7 +230,7 @@ export const revokeScopes = (req: Request, res: Response): void => {
deleteTokens(userid);
})
.catch(err => {
console.log(err);
logger.error(err);
});
}
res.json({ msg: "ok" });
Expand Down Expand Up @@ -265,7 +265,7 @@ export function getCalendarList(req: Request, res: Response): void {
google.calendar({ version: "v3", auth })
.calendarList.list()
.then(list => {
console.log("calendarList: %j", list);
logger.debug("calendarList: %j", list);
res.json(list);
})
.catch(error => {
Expand Down Expand Up @@ -299,7 +299,7 @@ export const events = (user_id: string, timeMin: string, timeMax: string): Promi
return response.data.items
})
.catch(err => {
console.log('error in calendar.events.list: %o', err)
logger.debug('error in calendar.events.list: %o', err)
return []
})
})
Expand All @@ -310,7 +310,7 @@ function deleteTokens(userid: string) {
{ _id: userid },
{ $unset: { google_tokens: "" } }
).then(res => {
console.log(res);
logger.debug(res);
});
}

Expand All @@ -330,9 +330,9 @@ function saveTokens(user: string, token) {
});
UserModel.findOneAndUpdate({ _id: user }, { google_tokens }, { new: true })
.then(user => {
console.log('saveTokens: %o', user)
logger.debug('saveTokens: %o', user)
})
.catch(err => {
console.error('saveTokens: %o', err)
logger.error('saveTokens: %o', err)
});
}
8 changes: 5 additions & 3 deletions backend/src/handlers/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import { NextFunction, Request, Response } from "express";
import jwt_pkg from 'jsonwebtoken';
import { logger } from "../logging.js";

const { decode, sign, verify } = jwt_pkg;

export const middleware = {
Expand All @@ -18,7 +20,7 @@ export const middleware = {
const header = req.headers.authorization;
const cookie = req.cookies["access_token"];
if (!header && !cookie) {
console.log("No authorization header");
logger.debug("No authorization header");
res
.status(401)
.set("WWW-Authenticate", 'Bearer')
Expand All @@ -30,7 +32,7 @@ export const middleware = {
}
const token = cookie || header.split(" ")[1];
if (!token) {
console.log("No authorization token");
logger.debug("No authorization token");
res
.status(401)
.set("WWW-Authenticate", 'Bearer')
Expand All @@ -41,7 +43,7 @@ export const middleware = {
} else {
verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
console.log("Invalid token: ", err);
logger.error("Invalid token: ", err);
return res
.status(401)
.set("WWW-Authenticate", 'Bearer')
Expand Down

0 comments on commit b1c8ac0

Please sign in to comment.