Skip to content

Commit

Permalink
Add comments to new-main branch for the files I have worked on, middl…
Browse files Browse the repository at this point in the history
…eware.js, passport.js, controller.js, routes.js, index.html, server.js, database.js
  • Loading branch information
thisiszaida committed Dec 13, 2024
1 parent edac0a6 commit 6359a4f
Show file tree
Hide file tree
Showing 7 changed files with 152 additions and 179 deletions.
1 change: 1 addition & 0 deletions backend/authentication/auth/middleware.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const factoryResponse = (status, message) => ({ status, message });

//middleware function to validate authorization
const isAuthenticated = (req, res, next) => {
return req.isAuthenticated()
? next()
Expand Down
55 changes: 26 additions & 29 deletions backend/authentication/auth/passport.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,43 @@
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const dotenv = require("dotenv");
const { User } = require("../../database.js");
const { User } = require("../../database.js");

// Load environment variables from a .env file
// dotenv.config();
dotenv.config();

console.log("CLIENT_ID:", process.env.CLIENT_ID); // Log to verify it's being loaded
console.log("CLIENT_ID:", process.env.CLIENT_ID); // Log to verify it's being loaded
console.log("CLIENT_SECRET:", process.env.CLIENT_SECRET);

passport.use(
new GoogleStrategy(
{
clientID:
" 943439459529-pi8k0nivh7mkgcod3v76phmh00kahqvd.apps.googleusercontent.com",
clientSecret: "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",
//google callback url must match
callbackURL: "http://127.0.0.1:4000/auth/google/callback",
scope: ["profile", "email"],
},

async (accessToken, refreshToken, profile, done) => {
try {
//set up google strategy
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
//google callback url must match
callbackURL: "http://127.0.0.1:4000/auth/google/callback",
scope: ["profile", "email"],
},
async (accessToken, refreshToken, profile, done) => {
try{
console.log(profile);
console.log(profile.emails);
//check if user already exists
let user = await User.findOne({ where: { user_id: profile.id } });

//if user does not already exist, create one
if (!user) {
user = await User.create({
username: profile.displayName, // You can adjust this to use Google profile data
username: profile.displayName,
name: profile.displayName,
email:
profile.emails && profile.emails[0]
? profile.emails[0].value
: "[email protected]", // Ensure email is available from the profile
password: "google_auth", // Use a default or generated password
email: profile.emails[0].value,
password: 'google_auth', // Use a default or generated password
user_id: profile.id,
created_events: "", // Set empty or default value if needed
interested_events: "",
upcoming_events: "",
past_events: "",
created_events: '', // Set empty
interested_events: '',
upcoming_events: '',
past_events: '',
});
console.log("User created:", user);
} else {
Expand All @@ -51,8 +48,8 @@ passport.use(
console.error("Error during user creation or retrieval:", error);
done(error, null);
}
}
)
}
)
);

passport.serializeUser((user, done) => done(null, user.user_id));
Expand All @@ -62,4 +59,4 @@ passport.deserializeUser(async (user_id, done) => {
done(null, user);
});

module.exports = passport;
module.exports = passport;
130 changes: 50 additions & 80 deletions backend/authentication/controller.js
Original file line number Diff line number Diff line change
@@ -1,92 +1,62 @@
const bcrypt = require("bcryptjs");
const dotenv = require("dotenv");
const User = require("../database");
const { User } = require("../database");

//Initialize dotenv
dotenv.config();

// Helper functions
// This function creates a response object with a status and a message.
const factoryResponse = (status, message) => ({ status, message });

const existsUser = async (username) => {
const user = await User.findOne({ where: { username } });
return user;
};

// Registration route.
// This route creates a new user in the database.
const register = async (req, res) => {
const { username, password } = req.body;

// Check if the username is already taken
if (await existsUser(username))
return res.status(400).json(factoryResponse(400, "Username already taken"));

const hash = await bcrypt.hash(password, 10);
await User.create({ username, password: hash });
res.json(factoryResponse(200, "Registration successful"));
console.log("User registered successfully");
};

// Login route.
// This route checks the user's credentials and logs them in.
const login = async (req, res, next) => {
const { username, password } = req.body;
const user = await User.findOne({ where: { username } });
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json(factoryResponse(401, "Invalid credentials"));
}

// Log the user in using the req.login() function provided by Passport.
// This function establishes a login session for the user. The user object
// is serialized and stored in the session. It can be accessed in subsequent
// requests using req.user.
req.login(user, (err) =>
err ? next(err) : res.json(factoryResponse(200, "Login successful"))
);
};
// Register function
async function register(req, res) {
const { email, username, password } = req.body;
try {
//Check if user already exists
const existingUser = await User.findOne({ where: { username } });
if (existingUser) {
return res.status(400).json({ message: 'Username already exists' });
}
//Create new user if not
const newUser = await User.create({ email, username, password});
res.status(201).json({ message: 'User registered successfully' });
} catch (error){
res.status(500).json({ message: 'Error during registration' });
}
}

//Login function
async function login(req, res) {
const { username, password } = req.body;
try {
//Check if user exists
const user = await User.findOne({ where: { username } });
if (!user) {
return res.status(400).json({ message: 'User not found' });
}

//Verify password
if (user.password !== password) {
return res.status(400).json({ message: 'Incorrect password' });
}

//Login successful
res.status(200).json({ message: 'Login successful' });
} catch (error) {
res.status(500).json({ message: 'Error during login' });
}
}

// Logout route.
// Logout route
// This route logs the user out.
// The req.logout() function is provided by Passport. It removes the user's
// session and logs them out.
const logout = (req, res) => {
req.logout(function (err) {
if (err) {
res.json(factoryResponse(500, "Logout failed"));
return;
}
res.redirect("/login");
});
req.logout(function (err) {
if (err) {
res.json(factoryResponse(500, "Logout failed"));
return;
}
res.redirect("/login");
});
};

// Google Authentication callback route.
// This route is called by Google after the user has authenticated.
// It redirects the user to the home page.
const googleAuthCallback = (req, res) => {
//res.redirect("../frontend/source/index.html");
res.send("this would be the home page after successful login");
};

// Profile route.
// This route is protected by the isAuthenticated middleware.
// It returns a welcome message to the user.
const getProfile = (req, res) => {
res.json(factoryResponse(200, `Welcome, ${req.user.username}`));
};

// Home page route.
// Protected by isAuthenticated middleware.
// Brings user to the home page which is index.html
const bringHome = (req, res) => {
res.send("hello");
};

module.exports = {
register,
login,
logout,
googleAuthCallback,
getProfile,
bringHome,
};
//Export modules
module.exports = { register, login, logout };
Loading

0 comments on commit 6359a4f

Please sign in to comment.