Skip to content

Commit

Permalink
fixing database connection import
Browse files Browse the repository at this point in the history
  • Loading branch information
abedmohammed committed Nov 23, 2024
1 parent f4d03db commit 0661e36
Show file tree
Hide file tree
Showing 2 changed files with 119 additions and 121 deletions.
238 changes: 118 additions & 120 deletions backend/src/services/authService.js
Original file line number Diff line number Diff line change
@@ -1,148 +1,146 @@
const GoogleStrategy = require("passport-google-oidc");
const jwt = require("jsonwebtoken");
const connection = require("../database.js");
const { connection } = require("../database.js");
const { log, error } = require("../logger.js");

const generateUsername = (profile) => {
let username = profile.displayName ?? "";
let username = profile.displayName ?? "";

username.replace(" ", "-");
username.replace(" ", "-");

return username + Date.now().toString().slice(-7);
return username + Date.now().toString().slice(-7);
};

const addUser = (user) => {
return new Promise((resolve, reject) => {
connection.query(
"INSERT INTO `ai-journal`.`users` (id, name, email, created_at) VALUES (?, ?, ?, ?)",
[user.id, user.name, user.email, new Date()],
(err, results) => {
if (err) {
reject(err);
} else {
resolve(results);
}
}
);
return new Promise((resolve, reject) => {
connection.query(
"INSERT INTO `ai-journal`.`users` (id, name, email, created_at) VALUES (?, ?, ?, ?)",
[user.id, user.name, user.email, new Date()],
(err, results) => {
if (err) {
reject(err);
} else {
resolve(results);
}
}
);
})
.then((res) => {
log("Insertion request resulted in: " + res);
return true;
})
.then((res) => {
log("Insertion request resulted in: " + res);
return true;
})
.catch((err) => {
error(err);
return false;
});
.catch((err) => {
error(err);
return false;
});
};

const getUserByEmail = (email) => {
return new Promise((resolve, reject) => {
connection.query(
"SELECT * FROM `ai-journal`.`users` WHERE email = ?",
[email],
(err, results) => {
if (err) {
reject(err);
} else {
resolve(results);
}
}
);
return new Promise((resolve, reject) => {
connection.query(
"SELECT * FROM `ai-journal`.`users` WHERE email = ?",
[email],
(err, results) => {
if (err) {
reject(err);
} else {
resolve(results);
}
}
);
})
.then((results) => {
log("Selection request resulted in: " + results);

if (results.length > 1) {
throw "Multiple users with same ID!!";
}

if (results.length == 0) {
return undefined;
}

return {
username: "No usernames :(",
email: results[0]["email"],
name: results[0]["name"],
id: results[0]["id"],
};
})
.then((results) => {
log("Selection request resulted in: " + results);

if (results.length > 1) {
throw "Multiple users with same ID!!";
}

if (results.length == 0) {
return undefined;
}

return {
username: "No usernames :(",
email: results[0]["email"],
name: results[0]["name"],
id: results[0]["id"],
};
})
.catch((err) => {
error(err);
return undefined;
});
.catch((err) => {
error(err);
return undefined;
});
};

function initialize(passport) {
passport.use(
new GoogleStrategy(
{
clientID: process.env["GOOGLE_CLIENT_ID"],
clientSecret: process.env["GOOGLE_CLIENT_SECRET"],
callbackURL: "/api/auth/callback",
scope: ["profile", "email"],
},
async function dbCallback(issuer, profile, cb) {
log(
"In database check for " +
profile.emails[0].value +
" log in request"
);

let user = await getUserByEmail(profile.emails[0].value);

if (user == undefined) {
user = {
id: profile.id,
name: profile.displayName,
email: profile.emails[0].value,
username: generateUsername(profile),
};

addUser(user);
}

cb(null, user);
}
)
);
passport.use(
new GoogleStrategy(
{
clientID: process.env["GOOGLE_CLIENT_ID"],
clientSecret: process.env["GOOGLE_CLIENT_SECRET"],
callbackURL: "/api/auth/callback",
scope: ["profile", "email"],
},
async function dbCallback(issuer, profile, cb) {
log(
"In database check for " + profile.emails[0].value + " log in request"
);

passport.serializeUser(function (user, cb) {
process.nextTick(function () {
cb(null, {
id: user.id,
username: user.username,
name: user.name,
email: user.email,
});
});
let user = await getUserByEmail(profile.emails[0].value);

if (user == undefined) {
user = {
id: profile.id,
name: profile.displayName,
email: profile.emails[0].value,
username: generateUsername(profile),
};

addUser(user);
}

cb(null, user);
}
)
);

passport.serializeUser(function (user, cb) {
process.nextTick(function () {
cb(null, {
id: user.id,
username: user.username,
name: user.name,
email: user.email,
});
});
});

passport.deserializeUser(function (user, cb) {
process.nextTick(function () {
return cb(null, user);
});
passport.deserializeUser(function (user, cb) {
process.nextTick(function () {
return cb(null, user);
});
});
}

const jwtAuth = (req, res, next) => {
const token = req.header("Authorization");
if (!token) {
throw new Error("Authorization token is missing");
}
if (token.startsWith("Bearer ") == false) {
throw new Error("Authorization token should start with Bearer");
}
const jwtToken = token.substring(7, token.length);
try {
log("Recieved Token: " + jwtToken);
const decoded = jwt.verify(jwtToken, process.env.JWT_SECRET || "");
req.token = decoded;
} catch (err) {
throw new Error("Invalid token");
}

next();
const token = req.header("Authorization");
if (!token) {
throw new Error("Authorization token is missing");
}
if (token.startsWith("Bearer ") == false) {
throw new Error("Authorization token should start with Bearer");
}
const jwtToken = token.substring(7, token.length);
try {
log("Recieved Token: " + jwtToken);
const decoded = jwt.verify(jwtToken, process.env.JWT_SECRET || "");
req.token = decoded;
} catch (err) {
throw new Error("Invalid token");
}

next();
};

module.exports = { initialize, jwtAuth };
2 changes: 1 addition & 1 deletion backend/src/services/warehouseService.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// services/warehouseService.js
const connection = require("../database");
const { connection } = require("../database");

// Fetch all warehouses
const getAllWarehouses = () => {
Expand Down

0 comments on commit 0661e36

Please sign in to comment.