.env
1 2 |
GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= |
views/index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google Drive Clone</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <div class="container mt-5"> <h1 class="mb-4">Google Drive Mini Clone</h1> <a href="<%= authUrl %>" class="btn btn-primary">Login with Google</a> </div> </body> </html> |
views/dashboard.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google Drive File Viewer</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container my-4"> <h1 class="text-center">Google Drive File Viewer</h1> <div class="d-flex justify-content-between mb-3"> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file" class="form-control" required /> <button type="submit" class="btn btn-success mt-3">Upload File</button> </form> </div> <h5>Files in Google Drive</h5> <table class="table table-striped"> <thead> <tr> <th>File Name</th> <th>Actions</th> </tr> </thead> <tbody> <% files.forEach((file) => { %> <tr> <td> <a href="https://drive.google.com/file/d/<%= file.id %>/view" target="_blank"> <%= file.name %> </a> </td> <td> <a href="/download/<%= file.id %>" class="btn btn-primary">Download</a> <form action="/delete/<%= file.id %>" method="POST" style="display:inline;"> <button type="submit" class="btn btn-danger">Delete</button> </form> </td> </tr> <% }); %> </tbody> </table> </div> </body> </html> |
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
const express = require("express"); const { google } = require("googleapis"); const fs = require('fs') const session = require("express-session"); // Import express-session const multer = require("multer"); const dotenv = require("dotenv"); dotenv.config(); const app = express(); const port = 5000; app.use( session({ secret: "secretkey", // Replace with a secure key resave: false, saveUninitialized: true, cookie: { secure: false }, // Set to true if using HTTPS }) ); // Google OAuth setup const CLIENT_ID = process.env.GOOGLE_CLIENT_ID; const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET; const REDIRECT_URI = "http://localhost:5000/oauth2callback"; // Middleware to serve static files app.use(express.static("public")); app.use(express.urlencoded({ extended: false })); app.use(express.json()); // Set up EJS as the view engine app.set("view engine", "ejs"); // Google OAuth2 client const oauth2Client = new google.auth.OAuth2( CLIENT_ID, CLIENT_SECRET, REDIRECT_URI ); // Middleware to check if user is authenticated const isAuthenticated = (req, res, next) => { if (req.session.token) { oauth2Client.setCredentials(req.session.token); next(); } else { res.redirect("/"); } }; // Route to login page app.get("/", (req, res) => { const authUrl = oauth2Client.generateAuthUrl({ access_type: "offline", scope: "https://www.googleapis.com/auth/drive", }); res.render('index',{authUrl}) }); // OAuth2 callback route app.get("/oauth2callback", (req, res) => { const code = req.query.code; oauth2Client.getToken(code, (err, tokens) => { if (err) { console.log("Error getting OAuth tokens: ", err); return res.send("Error authenticating with Google"); } req.session.token = tokens; res.redirect("/dashboard"); }); }); // Route to display files after authentication app.get("/dashboard", isAuthenticated, (req, res) => { const drive = google.drive({ version: "v3", auth: oauth2Client }); drive.files.list({ pageSize: 20, fields: "files(id, name, mimeType)" }, (err, response) => { if (err) { return res.send("Error fetching files from Google Drive"); } console.log(response.data.files) res.render("dashboard", { files: response.data.files }); }); }); // File upload endpoint using multer const upload = multer({ dest: "uploads/" }); app.post("/upload", isAuthenticated, upload.single("file"), (req, res) => { const drive = google.drive({ version: "v3", auth: oauth2Client }); const fileMetadata = { name: req.file.originalname, }; const media = { body: fs.createReadStream(req.file.path), }; drive.files.create( { resource: fileMetadata, media: media, fields: "id", }, (err, file) => { if (err) { return res.send("Error uploading the file."); } res.redirect("/dashboard"); } ); }); app.post("/delete/:fileId", isAuthenticated, (req, res) => { const fileId = req.params.fileId; const drive = google.drive({ version: "v3", auth: oauth2Client }); drive.files.delete({ fileId: fileId }, (err) => { if (err) { console.error("Error deleting the file:", err); return res.status(500).send("Error deleting the file."); } console.log(`File with ID ${fileId} deleted successfully.`); res.redirect("/dashboard"); // Redirect to dashboard after deletion }); }); // File download endpoint app.get("/download/:fileId", isAuthenticated, (req, res) => { const fileId = req.params.fileId; const drive = google.drive({ version: "v3", auth: oauth2Client }); // First, retrieve the file metadata to get its name and extension drive.files.get( { fileId: fileId, fields: "name" }, // Fetch only the 'name' field (err, metadataResponse) => { if (err) { console.error("Error fetching file metadata:", err); return res.send("Error fetching file metadata."); } const fileName = metadataResponse.data.name; // Get the file's name // Then, fetch the file content drive.files.get( { fileId: fileId, alt: "media" }, { responseType: "stream" }, (err, fileResponse) => { if (err) { console.error("Error downloading the file:", err); return res.send("Error downloading the file."); } // Set the appropriate headers for file download res.setHeader( "Content-Disposition", `attachment; filename="${fileName}"` ); // Pipe the file content to the response fileResponse.data.pipe(res); } ); } ); }); // Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); }); |