Skip to content

Added login/register in backend #8

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
628 changes: 628 additions & 0 deletions backend/package-lock.json

Large diffs are not rendered by default.

10 changes: 7 additions & 3 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ."
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.0.3"
"mongoose": "^7.0.3",
"jsonwebtoken": "^8.5.1",
"bcrypt": "^5.1.0"
}
}
45 changes: 0 additions & 45 deletions backend/server.js

This file was deleted.

169 changes: 169 additions & 0 deletions backend/src/controllers/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import User from '../schemas/user.js';

// Register
const registerUser = async (req, res) => {
const { username, email, password, profileImgUrl } = req.body;
const saltRounds = 10;
const passwordHash = await bcrypt.hash(password, saltRounds);

const userMatches = await User.find({ username: username});
if (username.length < 3 || username.length > 25) {
res.status(400).json({ error: 'Username must be between 3 and 25 characters long, inclusive.' });
return;
} else if (/^[a-zA-Z0-9!@\$\^\&*\)\(._-]+$/g.test(username) !== true) {
res.status(400).json({ error: 'Username contains an invalid character.' });
return;
} else if (userMatches.length !== 0) {
res.status(400).json({ error: 'Username is already taken.' });
return;
}

if (password.length < 3) {
res.status(400).json({ error: 'Password must be at least 3 characters long.' });
return;
}
if (username)

try {
const user = await User.create({
username,
email,
password: passwordHash,
profileImgUrl,
});
User.create

res.status(200).json({
uId: user._id,
username: user.username,
email: user.email,
profileImgUrl: user.profileImgUrl,
token: generateToken(user._id.toString())
});
} catch (err) {
res.status(400).json(err);
}
};


// Login
const loginUser = async (req, res) => {
const { email, password } = req.body;

const user = await User.findOne({ email });
if (user && (await bcrypt.compare(password, user.password))) {
res.json({
uId: user._id,
username: user.username,
email: user.email,
profileImgUrl: user.profileImgUrl,
token: generateToken(user._id.toString()),
});
} else {
res.status(400).json({ error: 'Could not login.' });
}
};


// Search users (for search bar)
const searchUsers = async (req, res) => {
const searchStr = req.query.searchStr;
try {
const userMatches = await User.find({username : new RegExp(searchStr, 'i')});
const usernames = userMatches.map(user => user.username);
res.status(200).json(usernames);
} catch (err) {
res.status(200).json([]);
}
};


// Update user details
const updateUser = async (req, res) => {
const { username, profileImgUrl } = req.body;
const user = req.user;

const userMatches = await User.find({ username: username});
if (username.length < 3 || username.length > 25) {
res.status(400).json({ error: 'Username must be between 3 and 25 characters long, inclusive.' });
return;
} else if (/^[a-zA-Z0-9!@\$\^\&*\)\(._-]+$/g.test(username) !== true) {
res.status(400).json({ error: 'Username contains an invalid character.' });
return;
} else if (userMatches.length !== 0 && username !== user.username) {
res.status(400).json({ error: 'Username is already taken.' });
return;
}

try {
const userDoc = await User.findByIdAndUpdate(user._id, { username: username, profileImgUrl: profileImgUrl });
if (userDoc) {
res.status(200).json({
username: userDoc.username,
profileImgUrl: userDoc.profileImgUrl
});
} else {
res.status(400).json({ error: 'Could not update user details.' });
}
} catch (err) {
res.status(400).json(err);
}
};


// Fetch details of user (for profile page)
const detailsUser = async (req, res) => {
const user = req.user;
try {
const userDoc = await User.findById(user._id);
if (userDoc) {
res.status(200).json(userDoc);
} else {
res.status(400).json({ error: 'Could not get user details' });
}
} catch (err) {
res.status(400).json(err);
}
};


// Token logic
const generateToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: '1h',
});
};

const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];

if (token == null) {
res.status(401).json({ error: 'No token' });
return;
}

jwt.verify(
token,
process.env.JWT_SECRET,
async (err, decoded) => {
if (err) {
res.status(403).json({ error: 'Invalid token' });
return;
}

const user = await User.findById(decoded.id);
if (!user) {
res.status(400).json({ error: 'Invalid id' });
return;
}
req.user = user;

next();
}
);
}

export { registerUser, loginUser, searchUsers, updateUser, detailsUser, authenticateToken };
11 changes: 11 additions & 0 deletions backend/src/routes/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import express from 'express';
import { registerUser, loginUser, searchUsers, updateUser, detailsUser, authenticateToken } from '../controllers/user.js';
const router = express.Router();

router.post('/register', registerUser);
router.post('/login', loginUser);
router.get('/search', searchUsers);
router.put('/update', authenticateToken, updateUser);
router.get('/get', authenticateToken, detailsUser)

export default router;
29 changes: 29 additions & 0 deletions backend/src/schemas/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Schema, model } from 'mongoose';

const userSchema = new Schema({
email: {
type: String,
trim: true,
lowercase: true,
unique: true,
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
'Invalid email address',
],
},
username: {
type: String,
minLength: [3, 'Username must be at least 3 characters long'],
maxLength: [25, 'Username cannot be over 25 characters long'],
unique: true
},
password: {
type: String,
},
profileImgUrl: {
type: String,
default: 'https://i.stack.imgur.com/l60Hf.png',
},
});

export default model('User', userSchema);
24 changes: 24 additions & 0 deletions backend/src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import userRoutes from './routes/user.js';
import express from 'express';
import mongoose from 'mongoose';
const app = express();
app.use(express.json());

const uri = "mongodb+srv://chrico:[email protected]/?retryWrites=true&w=majority"

async function connect() {
try {
await mongoose.connect(uri);
console.log("Connected to MongoDB");
} catch (error) {
console.error(error);
}
}

connect();

app.use('/users', userRoutes);

app.listen(8000, () => {
console.log("Server started on port 8000");
});
26 changes: 13 additions & 13 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-helmet": "^6.1.0",
"react-router-dom": "^6.10.0",
"react-router-dom": "^6.11.2",
"react-scripts": "5.0.1",
"reactjs-popup": "^2.0.5",
"web-vitals": "^2.1.4"
Expand Down
1 change: 1 addition & 0 deletions frontend/src/backend.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const URL_PORT = 8000;
Loading