Skip to content

Commit

Permalink
fetchusers implemented
Browse files Browse the repository at this point in the history
authorization using jwt token
  • Loading branch information
sankhadip-roy committed Aug 29, 2024
1 parent 532fd9d commit 14c5595
Show file tree
Hide file tree
Showing 10 changed files with 122 additions and 13 deletions.
15 changes: 14 additions & 1 deletion backend/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,17 @@ const registerController = asyncHandler(async (req, res) => {
}
});

module.exports = { loginController, registerController };
const fetchAllUsersController = asyncHandler(async (req, res) => {
const keyword = req.query.search ? {
$or: [
{ name: { $regex: req.query.search, $options: 'i' } },
{ email: { $regex: req.query.search, $options: 'i' } },
],
} : {};
const users = await User.find(keyword).find({
_id: { $ne: req.user._id },
});
res.send(users);
});

module.exports = { loginController, registerController, fetchAllUsersController };
25 changes: 25 additions & 0 deletions backend/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const asyncHandler = require('express-async-handler');

const protect = asyncHandler(async (req, res, next) => {
let token;

if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, 'sankha'); // process.env.JWT_SECRET later
req.user = await User.findById(decoded.id).select('-password');
next();
} catch (error) {
console.error(error);
res.status(401);
throw new Error('Not authorized, token failed');
}
}
if (!token) {
res.status(401);
throw new Error('Not authorized, no token');
}
});
module.exports = { protect };
6 changes: 3 additions & 3 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
"name": "backend",
"version": "1.0.0",
"description": "chat room app backend",
"main": "index.js",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
"dev": "nodemon"
},
"author": "sankhadip roy",
"license": "ISC",
Expand All @@ -19,4 +19,4 @@
"mongoose": "^8.5.4",
"socket.io": "^4.7.5"
}
}
}
4 changes: 3 additions & 1 deletion backend/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
const express = require('express');
const Router = express.Router();
const { loginController, registerController } = require("../controllers/userController");
const { loginController, registerController, fetchAllUsersController } = require("../controllers/userController");
const { protect } = require('../middleware/authMiddleware');

Router.post("/login", loginController);
Router.post("/register", registerController);
Router.get("/fetchusers", protect, fetchAllUsersController);

module.exports = Router;
6 changes: 3 additions & 3 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ app.use(cors());

const connectDb = async () => {
try {
mongoose.connect("mongodb+srv://sankhadiproy23:[email protected]/?retryWrites=true&w=majority"); //will use env variable later
await mongoose.connect("mongodb+srv://sankhadiproy23:[email protected]/?retryWrites=true&w=majority"); //will use env variable later
console.log("Database connected"); //log
}
catch (err) {
Expand Down Expand Up @@ -46,7 +46,7 @@ const onlineUsers = new Set();
io.on("connection", (socket) => {
onlineUsers.add(socket.id);
const usersList = Array.from(onlineUsers);
console.log(`✔ ${socket.id} :` + usersList); //log
// console.log(`✔ ${socket.id} :` + usersList); //log
io.emit('online-users', usersList);
socket.on('send_message', (data) => {
// console.log("Data:", data); //log
Expand All @@ -56,7 +56,7 @@ io.on("connection", (socket) => {
socket.on('disconnect', () => {
onlineUsers.delete(socket.id);
const usersList = Array.from(onlineUsers);
console.log(`✘ ${socket.id} :` + usersList) //log
// console.log(`✘ ${socket.id} :` + usersList) //log
io.emit('online-users', usersList);
});
});
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Signup from './components/Signup'
import Login from './components/Login'
import MessageRoom from "./components/MessageRoom"
import Users from './components/Users'


function App() {
Expand All @@ -16,6 +17,7 @@ function App() {
<Routes>
<Route path='/register' element={<Signup />} />
<Route path='/login' element={<Login />} />
<Route path='/fetchusers' element={<Users />} />
<Route path='' element={<MessageRoom />} />
</Routes>
</BrowserRouter>
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ export default function Login() {
const [user, setUser] = useRecoilState(userloggedin);
const navigate = useNavigate();

const handleSubmit = (e) => {
const handleSubmit = async (e) => {
e.preventDefault();
axios.post("http://localhost:3001/login", { name, password })
await axios.post("http://localhost:3001/login", { name, password })
.then(result => {
if (result.data.stat === "Success") {
// console.log(result); //log
Expand Down
11 changes: 11 additions & 0 deletions frontend/src/components/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,18 @@ function NavList() {
const loggedUser = useRecoilValue(userloggedin);
return (
loggedUser == 'anonymous-not-loggedin' ? (

< ul className="my-2 flex flex-col gap-2 lg:mb-0 lg:mt-0 lg:flex-row lg:items-center lg:gap-6" >
<Typography
as="li"
variant="small"
color="blue-gray"
className="p-1 font-medium"
>
<a href="http://localhost:5173/fetchusers" className="flex items-center hover:text-blue-500 transition-colors">
Allusers
</a>
</Typography>
<Typography
as="li"
variant="small"
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/components/Signup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@ export default function Signup() {
const [password, setPassword] = useState("");
const navigate = useNavigate();

const handleSubmit = (e) => {
const handleSubmit = async (e) => {
e.preventDefault();
axios.post("http://localhost:3001/register", { name, email, password })
const response = await axios.post("http://localhost:3001/register", { name, email, password })
.then(result => {
console.log(result);
navigate("/login");
localStorage.setItem('userData', JSON.stringify(result.data));
// navigate("/login");
})
.catch(err => {
console.error(err);
alert("An error occurred. Please try again." + err);
});
// localStorage.setItem('userData', JSON.stringify(response));

}

return (
Expand Down
53 changes: 53 additions & 0 deletions frontend/src/components/Users.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from 'axios';

function Users() {
const [users, setUsers] = useState([]);
const navigate = useNavigate();

useEffect(() => {
const userData = JSON.parse(localStorage.getItem('userData'));
console.log("User data from local storage", userData);//log
if (!userData) {
navigate(-1);
return;
}

const fetchUsers = async () => {
try {
const config = {
headers: {
Authorization: `Bearer ${userData.token}`,
},
};
const response = await axios.get('http://localhost:3001/fetchusers', config);
console.log("User data from API", response.data);
setUsers(response.data);
} catch (error) {
console.error("Error fetching users:", error);
}
};

fetchUsers();
}, []);

return (
<>
<div className="flex items-center justify-center min-h-screen bg-gray-100">
<div className="px-8 py-6 mt-4 text-left bg-white shadow-lg rounded-lg w-full max-w-md">
<h3 className="text-2xl font-bold text-center text-gray-800 mb-4">Users</h3>
<div className="mt-4">
{users.map(user => (
<div key={user._id} className="mb-4">
<p className="text-sm font-medium text-gray-700">Name: {user.name}</p>
<p className="text-sm font-medium text-gray-700">Email: {user.email}</p>
</div>
))}
</div>
</div>
</div>
</>
);
}
export default Users;

0 comments on commit 14c5595

Please sign in to comment.