Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Want to Add Backend for SignUp/Login #102 #117

Closed
wants to merge 4 commits into from
Closed
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
Binary file modified .gitignore
Binary file not shown.
Binary file added backend/.gitignore
Binary file not shown.
5 changes: 5 additions & 0 deletions backend/env-example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PORT=4000
MONGO_URI=your_mongo_uri
JWT_SECRET=your_jwt_secret
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
24 changes: 24 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "backend",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"bcrypt": "^5.1.1",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-session": "^1.18.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.4.1",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0"
}
}
140 changes: 140 additions & 0 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Import necessary modules
require('dotenv').config(); // Add this line at the top

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const session = require('express-session');

const app = express();
const port = process.env.PORT || 4000;
const mongoURI = process.env.MONGO_URI;
const jwtSecret = process.env.JWT_SECRET;
const googleClientID = process.env.GOOGLE_CLIENT_ID;
const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET;

// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(session({ secret: 'your_session_secret', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

// MongoDB Models
const UserSchema = new mongoose.Schema({
username: { type: String },
email: { type: String, required: true, unique: true },
password: { type: String },
googleId: { type: String, unique: true },
});

const User = mongoose.model('User', UserSchema);

// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));

// Passport Google OAuth Strategy
passport.use(new GoogleStrategy({
clientID: googleClientID,
clientSecret: googleClientSecret,
callbackURL: 'http://localhost:4000/auth/google/callback'
},
async (token, tokenSecret, profile, done) => {
try {
let user = await User.findOne({ googleId: profile.id });
if (user) {
return done(null, user);
} else {
user = new User({ googleId: profile.id, email: profile.emails[0].value, username: profile.displayName });
await user.save();
return done(null, user);
}
} catch (error) {
return done(error, null);
}
}));

passport.serializeUser((user, done) => {
done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err, null);
}
});

// Root route
app.get('/', (req, res) => {
res.redirect('http://localhost:3000/');
});

// Routes
app.post('/signup', async (req, res) => {
const { username, email, password } = req.body;

try {
let user = await User.findOne({ email });
if (user) {
return res.status(400).json({ success: false, errors: 'User already exists' });
}

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

user = new User({ username, email, password: hashedPassword });
await user.save();

const token = jwt.sign({ userId: user._id }, jwtSecret, { expiresIn: '1h' });

res.json({ success: true, token });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, errors: 'Server error' });
}
});

app.post('/login', async (req, res) => {
const { email, password } = req.body;

try {
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ success: false, errors: 'Invalid credentials' });
}

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ success: false, errors: 'Invalid credentials' });
}

const token = jwt.sign({ userId: user._id }, jwtSecret, { expiresIn: '1h' });

res.json({ success: true, token });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, errors: 'Server error' });
}
});

app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/');
});

app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Binary file added frontend/.gitignore
Binary file not shown.
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const LoginSignup = () => {
});

const handleSignInWithGoogle = () => {
window.location.href = 'http://localhost:4000/auth/google'; // Redirect to the server route for Google OAuth login
window.location.href = 'https://seven5per-backend-1.onrender.com/auth/google'; // Redirect to the server route for Google OAuth login
};

const ChangeHandler = (e) => {
Expand Down Expand Up @@ -58,7 +58,7 @@ const LoginSignup = () => {
if (!validate()) return;
console.log("login");
let responseData;
await fetch("http://localhost:4000/login", {
await fetch("https://seven5per-backend-1.onrender.com/login", {
method: "POST",
headers: {
Accept: 'application/form-data',
Expand All @@ -78,7 +78,7 @@ const LoginSignup = () => {
if (!validate()) return;
console.log("Sign up");
let responseData;
await fetch("http://localhost:4000/signup", {
await fetch("https://seven5per-backend-1.onrender.com/signup", {
method: "POST",
headers: {
Accept: 'application/form-data',
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Empty file removed server.js
Empty file.
94 changes: 0 additions & 94 deletions src/components/about/About.jsx

This file was deleted.

Loading