Skip to content

Commit

Permalink
current-user
Browse files Browse the repository at this point in the history
  • Loading branch information
angelalvaigle committed Dec 9, 2024
1 parent 54298bb commit cd79527
Show file tree
Hide file tree
Showing 16 changed files with 213 additions and 28 deletions.
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ services:
image: ghcr.io/arquisoft/wiq_7/userservice:latest
profiles: ['dev', 'prod']
build: ./users/userservice
volumes:
- ./errors:/usr/src/userservice/errors
- ./middleware:/usr/src/userservice/middleware
- ./utils:/usr/src/userservice/utils
depends_on:
- mongodb
ports:
Expand Down
29 changes: 20 additions & 9 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ app.post('/login', async (req, res) => {
app.get('/logout', async (req, res) => {
try {
// Forward the login request to the authentication service
const authResponse = await axios.get(authServiceUrl + '/logout', req.body);
const authResponse = await axios.get(authServiceUrl + '/logout');
res.json(authResponse.data);
} catch (error) {
res
Expand All @@ -90,10 +90,25 @@ app.post('/adduser', async (req, res) => {
});

app.get('/users', async (req, res) => {
console.log(req);
try {
// Forward the get users request to the user service
const userResponse = await axios.get(userServiceUrl + '/users', req.body);
const userResponse = await axios.get(userServiceUrl + '/users');
res.json(userResponse.data);
} catch (error) {
res
.status(error.response.status)
.json({ error: error.response.data.error });
}
});

app.get('/current-user', async (req, res) => {
try {
// Forward the get users request to the user service
const userResponse = await axios.get(userServiceUrl + '/current-user', {
headers: {
Authorization: req.headers.authorization,
},
});
res.json(userResponse.data);
} catch (error) {
res
Expand Down Expand Up @@ -126,8 +141,7 @@ app.get('/questions', async (req, res) => {
try {
// Forward the get question request to the question asking service
const getQuestionResponse = await axios.get(
questionServiceUrl + '/questions',
req.body
questionServiceUrl + '/questions'
);
res.json(getQuestionResponse.data);
} catch (error) {
Expand Down Expand Up @@ -179,10 +193,7 @@ app.post('/addstat', async (req, res) => {
app.get('/stats', async (req, res) => {
try {
// Forward the get stats request to the stat service
const getStatsResponse = await axios.get(
statServiceUrl + '/stats',
req.body
);
const getStatsResponse = await axios.get(statServiceUrl + '/stats');
res.json(getStatsResponse.data);
} catch (error) {
res
Expand Down
4 changes: 4 additions & 0 deletions middleware/auth-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ export const authenticateUser = (req, res, next) => {

const { userId, role } = verifyJWT(token);
req.user = { userId, role };

console.log('auth mw req.user');
console.log(req.user);

next();
} catch (error) {
throw new UnauthenticatedError('Authentication invalid');
Expand Down
114 changes: 114 additions & 0 deletions users/userservice/package-lock.json

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

2 changes: 2 additions & 0 deletions users/userservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
"bcrypt": "^5.1.1",
"body-parser": "^1.20.2",
"express": "^4.18.2",
"http-status-codes": "^2.3.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.4"
},
"devDependencies": {
Expand Down
4 changes: 2 additions & 2 deletions users/userservice/user-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ export const getUsersController = async (req, res) => {

export const getCurrentUserController = async (req, res) => {
try {
console.log(req.user.userId);
const user = await User.findOne({ _id: req.user.userId }); // Fetch current user
const userWithoutPassword = user.toJSON;
res.json(userWithoutPassword);
res.json({ user: user });
} catch (error) {
res.status(500).json({ error: error.message });
}
Expand Down
8 changes: 7 additions & 1 deletion users/userservice/user-router.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
// userRouter.js
import express from 'express';
import { addUserController, getUsersController } from './user-controller.js';
import {
addUserController,
getUsersController,
getCurrentUserController,
} from './user-controller.js';
import { authenticateUser } from './middleware/auth-middleware.js';

const userRouter = express.Router();

// Define la ruta para el login y asocia el controlador
userRouter.post('/adduser', addUserController);
userRouter.get('/users', getUsersController);
userRouter.get('/current-user', authenticateUser, getCurrentUserController);

export default userRouter;
2 changes: 0 additions & 2 deletions utils/tokenUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ export const createJWT = (payload) => {
};

export const verifyJWT = (token) => {
console.log('verjwt');
console.log(token);
const decoded = jwt.verify(token, 'your-secret-key'); // process.env.JWT_SECRET);
return decoded;
};
5 changes: 5 additions & 0 deletions webapp/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import {
Admin,
} from './pages';

import { loader as dashboardLoader } from './pages/DashboardLayout';
import { loader as adminLoader } from './pages/Admin';

export const checkDefaultTheme = () => {
const isDarkTheme = localStorage.getItem('darkTheme') === 'true';
document.body.classList.toggle('dark-theme', isDarkTheme);
Expand Down Expand Up @@ -42,6 +45,7 @@ const router = createBrowserRouter([
{
path: 'dashboard',
element: <DashboardLayout />,
loader: dashboardLoader,
children: [
{
index: true,
Expand All @@ -62,6 +66,7 @@ const router = createBrowserRouter([
{
path: 'admin',
element: <Admin />,
loader: adminLoader,
},
],
},
Expand Down
8 changes: 8 additions & 0 deletions webapp/src/assets/wrappers/AddQuestionContainer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import styled from 'styled-components';

const Wrapper = styled.section`
background: var(--background-secondary-color);
border-radius: var(--border-radius);
display: grid;
grid-template-rows: 1fr auto;
grid-template-columns: repeat(3, 1fr);
row-gap: 2rem;
column-gap: 2rem;
margin: 0.5rem auto;
padding: 1rem;
@media (min-width: 768px) {
grid-template-columns: 1fr 1fr;
column-gap: 1rem;
Expand Down
2 changes: 1 addition & 1 deletion webapp/src/components/LogoutContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const LogoutContainer = () => {
onClick={() => setShowLogout(!showLogout)}
>
<FaUserCircle />
{user?.name}
{user?.username}
<FaCaretDown />
</button>
<div className={showLogout ? 'dropdown show-dropdown' : 'dropdown'}>
Expand Down
2 changes: 1 addition & 1 deletion webapp/src/pages/AddUser.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const AddUser = () => {
// Añadir un retardo antes de navegar
setTimeout(() => {
navigate('/login');
}, 2000); // 2000 ms = 2 segundos
}, 1000); // 1000 ms = 1 segundos
} catch (error) {
setError(error.response?.data?.error || 'An error occurred');
}
Expand Down
24 changes: 24 additions & 0 deletions webapp/src/pages/Admin.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
import { useLoaderData, redirect } from 'react-router-dom';
import axios from 'axios';
import Wrapper from '../assets/wrappers/StatsContainer';
import { AddQuestionContainer } from '../components';

const apiEndpoint =
process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

export const loader = async () => {
try {
const token = localStorage.getItem('token');
const response = await axios.get(`${apiEndpoint}/current-user`, {
headers: {
Authorization: `Bearer ${token}`,
},
});

return response.data;
} catch (error) {
console.log('You are not authorized to view this page');
return redirect('/dashboard');
}
};

const Admin = () => {
const { user } = useLoaderData();

return <AddQuestionContainer />;
};

Expand Down
Loading

0 comments on commit cd79527

Please sign in to comment.