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
164 changes: 157 additions & 7 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -508,11 +508,19 @@ const courseid = '9'; // Replace with the actual Course ID
// });

// const upload = multer({ storage: storage })
app.get("/data", verifyToken, (req, res) => {
res.render("data");
app.get("/data", function(req, res) {
const pageTitle = 'Upload your Documents here';
const metaRobots = 'follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large';
const metaKeywords = 'medical instructor, medical teacher, apply for medical instructor';
const ogDescription = 'Medical Academic Instructor - Apply for medical teacher and shine your career with us.';
const canonicalLink = 'https://globalmedacademy.com/become-teacher';
const username = req.session.username || null;
res.render('data', { pageTitle, metaRobots, metaKeywords, ogDescription, canonicalLink ,isUserLoggedIn: req.isUserLoggedIn,
username: username });
});



//multer db config starts

// const { ObjectID } = require('mongodb');
Expand Down Expand Up @@ -693,22 +701,162 @@ app.get('/cancel', (req, res) => {
// new latest logic

// const storage = new GridFsStorage({
const url = process.env.MONGODB_URI;

// file: (req, file) => {
// return {
// filename: `${crypto.randomBytes(16).toString('hex')}${path.extname(file.originalname)}`,
// };
// },
// });

const url = process.env.MONGODB_URI;
const storage = new GridFsStorage({ url });

const upload = multer({ storage });

// Define a route to handle file uploads
app.post('/data', upload.array('file',4), (req, res) => {
return res.json({ message: 'File uploaded successfully to the database' });
// app.post('/data', upload.array('AadharCard',4), (req, res) => {
// // return res.json({ message: 'File uploaded successfully to the database' });

// const { originalname, filename, path, size } = req.file;

// // taking jws token as user id


// const token = req.cookies.authToken;

// if (!token) {
// return res.status(401).send('Unauthorized: No token provided');
// }

// let userId;
// try {
// // Verify and decode the token to get the user's ID
// const decoded = jwt.verify(token, JWT_SECRET);
// userId = decoded.userId;
// } catch (error) {
// return res.status(401).send('Unauthorized: Invalid token');
// }

// // end 1

// console.log('User ID:', req.user._id);

// // Create a GridFS stream to store the file
// const writestream = gfs.createWriteStream({
// filename: originalname,
// metadata: {
// userId: req.user._id, // Assuming you have user data in the request
// },
// });

// fs.createReadStream(path).pipe(writestream);

// writestream.on('close', (file) => {

// User.findByIdAndUpdate(
// req.user._id,
// { $push: { files: file._id } },
// { new: true },
// (err, updatedUser) => {
// if (err) {
// // Handle the error
// console.error('Error updating user:', err);
// return res.status(500).send('File upload failed');
// }

// res.status(200).send('File uploaded and associated with the user');
// }
// );
// });

// });

app.post('/data', upload.array('AadharCard',4), async (req, res) => {
// return res.json({ message: 'File uploaded successfully to the database' });

});
// const { originalname, filename, path, size } = req.file;

// taking jws token as user id

const token = req.cookies.authToken;

if (!token) {
return res.status(401).send('Unauthorized: No token provided');
}

let userId;
try {
// Verify and decode the token to get the user's ID
const decoded = jwt.verify(token, JWT_SECRET);
userId = decoded.userId;
} catch (error) {
return res.status(401).send('Unauthorized: Invalid token');
}

const file = new File({
originalname,
filename,
path,
size,
contentType,
userId: req.user._id,
});

// Save the file to the database
await file.save();

// Update the user's files array to include the new file ID
req.user.files.push(file._id);

// Save the user to the database
await req.user.save();

// Create a GridFS stream to store the file
const writestream = gfs.createWriteStream({
filename: originalname,
metadata: {
userId: userId, // Assuming you have user data in the request
},
});

// Pipe the file buffer to the GridFS stream
await fs.promises.pipeline(fs.createReadStream(path), writestream);

// Get the file ID from the GridFS stream
const fileId = writestream.id;

// Update the user's files array to include the new file ID
const updatedUser = await User.findByIdAndUpdate(
userId,
{ $push: { files: fileId } },
{ new: true }
);

// Return a success response to the user
res.status(200).send('File uploaded and associated with the user');
});


// User.findById(userId)
// .populate('files')
// .exec((err, user) => {
// if (err) {
// // Handle the error
// console.error('Error fetching user:', err);
// return res.status(500).send('Failed to retrieve user data');
// }

// // Log the user object to the console for inspection
// console.log('User:', user);

// // User and associated files retrieved successfully
// res.json(user);
// });





app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.redirect('/auth_email');
Expand All @@ -718,6 +866,8 @@ app.use((err, req, res, next) => {





app.listen(3000, function () {
console.log("Server started successfully!");
});
Expand Down
17 changes: 13 additions & 4 deletions utils/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const UserSchema = new Schema({
email: String,
course: String,
coursesPurchased: [String],
files: [{ type: Schema.Types.ObjectId, ref: 'File' }],

});

Expand All @@ -43,14 +44,22 @@ const requestSchema = new mongoose.Schema({
const User = mongoose.model('User', UserSchema);


const FileSchema = new Schema({
// const FileSchema = new Schema({
// originalname: String,
// name: String,
// path: String,
// size: Number,
// })
const FileSchema = new mongoose.Schema({
originalname: String,
name: String,
filename: String,
path: String,
size: Number,
})
contentType: String,
userId: { type: Schema.Types.ObjectId, ref: 'User' },
});

const File = mongoose.model('File',FileSchema);
const Request = mongoose.model('Request', requestSchema);

module.exports = { mongoose, User,File,Request, Course};
module.exports = { mongoose,File,User,Request, Course};
6 changes: 3 additions & 3 deletions utils/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ function checkEmailVerified(req, res, next) {
}


app.get("/data", (req,res) => {
res.render("data");
})
// app.get("/data", (req,res) => {
// res.render("data");
// })
app.get("/course-masonry", async function(req, res) {
const pageTitle = 'Professional, Advanced, Fellowship courses';
const metaRobots = 'follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -577,10 +577,10 @@
</div>
</div>
<div class="buy-now-btn mt--15">
<form action="/checkout/64b977cffa47d3d1072b49b7" method="get">
<!-- <form action="/data" method="get"> -->

<button type="submit">Pay Now</button>
</form>
<a href="/data"><button type="submit">Pay Now</button></a>
<!-- </form> -->
</div>


Expand Down
34 changes: 19 additions & 15 deletions views/data.ejs
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>hey welcome to globalmedacademy</h1>
<% if (isUserLoggedIn) { %>
<!-- Include auth_header -->
<%- include('auth_header') %>
<% } else { %>
<!-- Include regular header -->
<%- include('header') %>
<% } %>
<br>
<br>
<br>
<br>
<br>
<h1>Upload Your Files Here</h1>
<form action="/data" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="let's see">

<input name="file" type="file" multiple/>
<!-- <input name="PanCard" type="file" /> -->
<!-- <input type="certificate" name="file" /> -->
<input type="submit" value="SUBMIT DOC'S">
</form>
</body>
</html>

<%- include('footer') %>