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
44 changes: 11 additions & 33 deletions script.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// scripts.js
document.addEventListener('DOMContentLoaded', () => {
const registerForm = document.getElementById('register-form');
const loginForm = document.getElementById('login-form');
Expand Down Expand Up @@ -44,6 +43,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
if (response.ok) {
alert('Login successful');
window.location.href = '/dashboard';
} else {
alert('Invalid username or password');
}
Expand All @@ -60,6 +60,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
if (response.ok) {
alert('Logout successful');
window.location.href = '/';
} else {
alert('Logout failed');
}
Expand All @@ -68,31 +69,26 @@ document.addEventListener('DOMContentLoaded', () => {
}
});

// Check if the current page is the course content page
if (window.location.pathname === '/course-content') {
// Call the fetchCourseContent function
fetchCourseContent();
const urlParams = new URLSearchParams(window.location.search);
const courseId = urlParams.get('id');
if (courseId) {
fetchCourseContent(courseId);
} else {
console.error('Course ID not provided');
}
}

// Check if the current page is the course content page
if (window.location.pathname === '/leader-board') {
// Fetch course content from server
if (window.location.pathname === '/leaderboard') {
fetchLeaderboardData();
}

// Check if the current page is the course content page
if (window.location.pathname === '/dashboard') {
//fetch Logged in user's full name
fetchFullName();
}
});

function fetchCourseContent() {
// Get course ID from URL parameter (assuming course ID is passed in the URL)
const urlParams = new URLSearchParams(window.location.search);
const courseId = urlParams.get('id');

// Make AJAX request to fetch course content from server
function fetchCourseContent(courseId) {
fetch(`/course/${courseId}`)
.then(response => {
if (!response.ok) {
Expand All @@ -101,7 +97,6 @@ function fetchCourseContent() {
return response.json();
})
.then(data => {
// Display course content on the page
displayCourseContent(data);
})
.catch(error => {
Expand All @@ -110,30 +105,23 @@ function fetchCourseContent() {
}

function displayCourseContent(courseContent) {
// Get the course name element
const courseNameElement = document.getElementById('course-name');
// Set the course name
courseNameElement.textContent = courseContent.name;

// Get the course content element
const courseContentElement = document.getElementById('course-content');
// Clear previous content
courseContentElement.innerHTML = '';

// Loop through the modules and display them
courseContent.modules.forEach(module => {
const moduleSection = document.createElement('section');
moduleSection.innerHTML = `
<h2>${module.title}</h2>
<p>${module.description}</p>
<!-- Add more elements as needed (e.g., videos, quizzes) -->
`;
courseContentElement.appendChild(moduleSection);
});
}

function fetchLeaderboardData() {
// Make AJAX request to fetch leaderboard data from server
fetch('/leaderboard')
.then(response => {
if (!response.ok) {
Expand All @@ -142,7 +130,6 @@ function fetchLeaderboardData() {
return response.json();
})
.then(data => {
// Display leaderboard data on the page
displayLeaderboardData(data);
})
.catch(error => {
Expand All @@ -151,12 +138,9 @@ function fetchLeaderboardData() {
}

function displayLeaderboardData(leaderboardData) {
// Get the leaderboard element
const leaderboardElement = document.getElementById('leaderboard');
// Clear previous content
leaderboardElement.innerHTML = '';

// Create a table to display leaderboard data
const table = document.createElement('table');
table.innerHTML = `
<tr>
Expand All @@ -166,7 +150,6 @@ function displayLeaderboardData(leaderboardData) {
</tr>
`;

// Loop through the leaderboard data and add rows to the table
leaderboardData.forEach((entry, index) => {
const row = document.createElement('tr');
row.innerHTML = `
Expand All @@ -177,12 +160,10 @@ function displayLeaderboardData(leaderboardData) {
table.appendChild(row);
});

// Append the table to the leaderboard element
leaderboardElement.appendChild(table);
}

function fetchFullName() {
// Make AJAX request to fetch the user's full name from the server
fetch('/get-fullname')
.then(response => {
if (!response.ok) {
Expand All @@ -191,7 +172,6 @@ function fetchFullName() {
return response.json();
})
.then(data => {
// Display the user's full name on the dashboard
displayFullName(data.fullName);
})
.catch(error => {
Expand All @@ -200,8 +180,6 @@ function fetchFullName() {
}

function displayFullName(fullName) {
// Get the element where the full name will be displayed
const fullNameElement = document.getElementById('user-fullname');
// Set the inner HTML of the element to the user's full name
fullNameElement.textContent = fullName;
}
141 changes: 106 additions & 35 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// server.js
const express = require('express');
const session = require('express-session');
const bcrypt = require('bcryptjs');
Expand All @@ -17,9 +16,9 @@ app.use(session({
// Create MySQL connection
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'learning_management'
user: 'admin',
password: 'CHidozie12@',
database: 'LMS'
});

// Connect to MySQL
Expand All @@ -41,18 +40,18 @@ app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));

// Define routes

// Root route
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});



// Define a User representation for clarity
const User = {
tableName: 'users',
tableName: 'users',
createUser: function(newUser, callback) {
connection.query('INSERT INTO ' + this.tableName + ' SET ?', newUser, callback);
},
},
getUserByEmail: function(email, callback) {
connection.query('SELECT * FROM ' + this.tableName + ' WHERE email = ?', email, callback);
},
Expand All @@ -63,68 +62,68 @@ const User = {

// Registration route
app.post('/register', [
// Validate email and username fields
check('email').isEmail(),
check('username').isAlphanumeric().withMessage('Username must be alphanumeric'),

// Custom validation to check if email and username are unique
check('email').custom(async (value) => {
const user = await User.getUserByEmail(value);
const user = await new Promise((resolve, reject) => {
User.getUserByEmail(value, (err, results) => {
if (err) reject(err);
resolve(results[0]);
});
});
if (user) {
throw new Error('Email already exists');
}
}),
check('username').custom(async (value) => {
const user = await User.getUserByUsername(value);
const user = await new Promise((resolve, reject) => {
User.getUserByUsername(value, (err, results) => {
if (err) reject(err);
resolve(results[0]);
});
});
if (user) {
throw new Error('Username already exists');
}
}),
], async (req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

// Hash the password
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(req.body.password, saltRounds);

// Create a new user object
const newUser = {
email: req.body.email,
username: req.body.username,
password: hashedPassword,
full_name: req.body.full_name
};

// Insert user into MySQL
User.createUser(newUser, (error, results, fields) => {
if (error) {
console.error('Error inserting user: ' + error.message);
return res.status(500).json({ error: error.message });
console.error('Error inserting user: ' + error.message);
return res.status(500).json({ error: error.message });
}
console.log('Inserted a new user with id ' + results.insertId);
res.status(201).json(newUser);
});
});
});

// Login route
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Retrieve user from database
connection.query('SELECT * FROM users WHERE username = ?', [username], (err, results) => {
if (err) throw err;
if (results.length === 0) {
res.status(401).send('Invalid username or password');
} else {
const user = results[0];
// Compare passwords
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
// Store user in session
req.session.user = user;
res.send('Login successful');
} else {
Expand All @@ -141,28 +140,100 @@ app.post('/logout', (req, res) => {
res.send('Logout successful');
});

//Dashboard route
// Route to serve the dashboard HTML file
app.get('/dashboard', (req, res) => {
// Assuming you have middleware to handle user authentication and store user information in req.user
const userFullName = req.user.full_name;
res.render('dashboard', { fullName: userFullName });
if (!req.session.user) {
return res.status(401).send('You must log in to view this page.');
}
res.sendFile(__dirname + '/dashboard.html');
});

// Route to serve the course content HTML file
app.get('/course-content', (req, res) => {
if (!req.session.user) {
return res.status(401).send('You must log in to view this page.');
}
res.sendFile(__dirname + '/course-content.html');
});

// Route to retrieve course content
app.get('/course/:id', (req, res) => {
const courseId = req.params.id;
const sql = 'SELECT * FROM courses WHERE id = ?';
db.query(sql, [courseId], (err, result) => {
if (err) {
throw err;
}
// Send course content as JSON response
res.json(result);
connection.query(sql, [courseId], (err, result) => {
if (err) {
throw err;
}
res.json(result[0]); // Assuming courses table has a single row per ID
});
});
});

// Route to fetch leaderboard data
app.get('/leaderboard', (req, res) => {
// Replace with actual leaderboard fetching logic
const leaderboardData = [
{ name: 'John Doe', score: 100 },
{ name: 'Jane Smith', score: 95 },
{ name: 'Michael Johnson', score: 90 }
];
res.json(leaderboardData);
});

// Route to fetch user's full name
app.get('/get-fullname', (req, res) => {
if (!req.session.user) {
return res.status(401).send('You must log in to view this page.');
}
const fullName = req.session.user.full_name;
res.json({ fullName });
});

// Route to handle user course selection
app.post('/select-course', (req, res) => {
if (!req.session.user) {
return res.status(401).send('You must log in to select a course.');
}

const { courseId } = req.body;
const userId = req.session.user.id;

// Assuming a table `user_courses` with columns `user_id` and `course_id`
const sql = 'INSERT INTO user_courses (user_id, course_id) VALUES (?, ?)';
connection.query(sql, [userId, courseId], (err, result) => {
if (err) {
console.error('Error selecting course:', err);
return res.status(500).send('Failed to select course.');
}
res.send('Course selected successfully.');
});
});

// Route to fetch user's selected courses
app.get('/my-courses', (req, res) => {
if (!req.session.user) {
return res.status(401).send('You must log in to view your courses.');
}

const userId = req.session.user.id;

// Assuming a join between `user_courses` and `courses` tables to fetch course details
const sql = `
SELECT courses.*
FROM courses
INNER JOIN user_courses ON user_courses.course_id = courses.id
WHERE user_courses.user_id = ?
`;
connection.query(sql, [userId], (err, results) => {
if (err) {
console.error('Error fetching user courses:', err);
return res.status(500).send('Failed to fetch user courses.');
}
res.json(results);
});
});

// Start server
const PORT = process.env.PORT || 3000;
const PORT = process.env.PORT || 30011;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});