Skip to content

Commit

Permalink
Merge pull request #109 from Arquisoft/develop-users
Browse files Browse the repository at this point in the history
Adding session
  • Loading branch information
PBC003 authored Mar 7, 2024
2 parents c59ac81 + 3fc618e commit c90d9a6
Show file tree
Hide file tree
Showing 10 changed files with 189 additions and 95 deletions.
18 changes: 17 additions & 1 deletion gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,23 @@ app.post('/user/edit', async (req, res) => {

app.get('/group/list', async (req, res) => {
try {
const userResponse = await axios.get(userServiceUrl + '/group/list');
const userResponse = await axios.get(userServiceUrl + '/group/api/list');
res.json(userResponse.data);
} catch (error) {
if (error.response && error.response.status) {
res.status(error.response.status).json({ error: error.response.data.error });
} else if (error.message) {
res.status(500).json({ error: error.message });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
}
});

app.post('/user/edit', async (req, res) => {
try {
// Forward the add user request to the user service
const userResponse = await axios.post(userServiceUrl + '/user/edit', req.body);
res.json(userResponse.data);
} catch (error) {
if (error.response && error.response.status) {
Expand Down
6 changes: 6 additions & 0 deletions users/models/user-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
primaryKey: true,
notEmpty: true,
},
password: {
type: DataTypes.STRING,
Expand All @@ -24,10 +25,12 @@ const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false,
notEmpty: true,
},
surname: {
type: DataTypes.STRING,
allowNull: false,
notEmpty: true,
},
createdAt: {
type: DataTypes.DATE,
Expand Down Expand Up @@ -64,6 +67,9 @@ const Group = sequelize.define('Group', {
type: DataTypes.STRING,
primaryKey: true
},
creator: {
type: DataTypes.STRING,
},
createdAt: {
type: DataTypes.DATE,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
Expand Down
9 changes: 5 additions & 4 deletions users/routes/group-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ const apiRoutes = require('../services/group-api');
// Adding a group to the database
router.post('/add', async (req, res) => {
try {
const { name } = req.body;
const { name,username } = req.body;

// To be changed when more fileds are added
const newGroup = await Group.create({
name: name,
creator: username,
createdAt: new Date()
});

Expand All @@ -27,11 +27,12 @@ router.post('/add', async (req, res) => {
router.post('/:name/join', async (req, res) => {
try {
const groupName = req.params.name;
const { username } = req.body;

// Need to get the logged in user for the username
// Need to be tested
const newUserGroup = await UserGroup.create({
name: groupName,
// username: username,
username: username,
createdAt: new Date()
});

Expand Down
11 changes: 6 additions & 5 deletions users/routes/user-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ router.post('/add', async (req, res) => {
// Route for edit a user
router.post('/edit', async (req, res) => {
try {

const { username, total_score, correctly_answered_questions, incorrectly_answered_questions, total_time_played, games_played } = req.body;

// Find the user in the database by their username
Expand All @@ -67,11 +68,11 @@ router.post('/edit', async (req, res) => {
}

// Update the user's fields with the provided values
userToUpdate.total_score = total_score;
userToUpdate.correctly_answered_questions = correctly_answered_questions;
userToUpdate.incorrectly_answered_questions = incorrectly_answered_questions;
userToUpdate.total_time_played = total_time_played;
userToUpdate.games_played = games_played;
userToUpdate.total_score = userToUpdate.total_score + total_score;
userToUpdate.correctly_answered_questions = userToUpdate.correctly_answered_questions + correctly_answered_questions;
userToUpdate.incorrectly_answered_questions = userToUpdate.incorrectly_answered_questions + incorrectly_answered_questions;
userToUpdate.total_time_played = userToUpdate.total_time_played + total_time_played;
userToUpdate.games_played = userToUpdate.games_played + games_played;

// Save the changes to the database
await userToUpdate.save();
Expand Down
30 changes: 15 additions & 15 deletions webapp/src/SessionContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,35 @@ const SessionProvider = ({ children }) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);

// This hook recovers user data if available in localstorage when the sessprovider is created
useEffect(() => {
const storedSessionId = localStorage.getItem('sessionId');
if (storedSessionId) {
setSessionId(storedSessionId);
setIsLoggedIn(true);
// useEffect(() => {
// const storedSessionId = localStorage.getItem('sessionId');
// if (storedSessionId) {
// setSessionId(storedSessionId);
// setIsLoggedIn(true);

// Here you can get the username using the sessionID
const storedUsername = localStorage.getItem('username');
if (storedUsername) {
setUsername(storedUsername);
}
}
}, []);
// // Here you can get the username using the sessionID
// const storedUsername = localStorage.getItem('username');
// if (storedUsername) {
// setUsername(storedUsername);
// }
// }
// }, []);

const createSession = (username) => {
const newSessionId = uuidv4();
setSessionId(newSessionId);
setUsername(username);
setIsLoggedIn(true);
localStorage.setItem('sessionId', newSessionId);
localStorage.setItem('username', username);
setUsername(username);
};

const destroySession = () => {
localStorage.removeItem('sessionId');
localStorage.removeItem('username');
setSessionId('');
setIsLoggedIn(false);
setUsername('');
localStorage.removeItem('sessionId');
localStorage.removeItem('username');
};

return (
Expand Down
105 changes: 83 additions & 22 deletions webapp/src/components/NavBar.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,17 @@ const pages = [
// Add an object for each new page
];

// Provisional settings menu for a logged user
const settings = [
{ path: '/profile', text: 'Perfil' },
{ path: '/', text: 'Cerrar Sesión' }
]

function NavBar() {
// Width for the nav menu element (?) Is it used later as a boolean ??????
const [anchorElNav, setAnchorElNav] = React.useState(null);
const [anchorElUser, setAnchorElUser] = React.useState(null);
const { username, isLoggedIn, destroySession } = useContext(SessionContext);

const handleOpenNavMenu = (event) => {
setAnchorElNav(event.currentTarget);
Expand All @@ -29,13 +37,22 @@ function NavBar() {
setAnchorElNav(null);
};

const { sessionId, username, isLoggedIn, createSession, destroySession } = useContext(SessionContext);
const handleOpenUserMenu = (event) => {
setAnchorElUser(event.currentTarget);
};

const handleCloseUserMenu = () => {
setAnchorElUser(null);
};

const handleLogout = () => {
handleCloseUserMenu();
destroySession();
};

return (
// position="static" => Barra se desplaza con scroll down
<AppBar position="static" >
{/* The Container component is used to limit the maximum width of the content inside the AppBar. It ensures that the content doesn't extend too far horizontally. */}
{/* <Container maxWidth="xl"> */}
{/* disableGutters -> Remove toolbar's padding */}
<Toolbar sx={{ alignItems: 'center', justifyContent: 'space-between' }}>
{/* Menú de Navegación, sólo se muestra en dispositivos móviles */}
Expand Down Expand Up @@ -77,29 +94,73 @@ function NavBar() {
))}
</Menu>
</Box>
<Button component={Link} to="/" sx={{'&:hover': { backgroundColor: '#5f7e94'},}}>
<Button component={Link} to="/" sx={{'&:hover': { backgroundColor: '#5f7e94' },}}>
<img src="/white_logo.png" alt="Logo" style={{ height: 40 }} />
</Button>
{/* Pages list in NavBar, only displayed when menu button is not, i.e., in larger devices */}
<Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}>
{pages.map((page) => (
<Button component={Link} to={page.path} key={page.path} sx={{ color: 'white', display: 'block','&:hover': { backgroundColor: '#5f7e94', },}}>
{page.text}
</Button>
))}
</Box>
{/* Pending: auth depending: if not auth: log in else: menu */}

<Button component={Link} to={'/login'} sx={{ p: 0, display: 'flex', alignItems: 'center', flexGrow: 0, '&:hover': { backgroundColor: '#5f7e94', }}} >
<Typography variant="body2" sx={{ color: 'white', textDecoration: 'none' }}>
{isLoggedIn ? `${username}` : "Log In"}
</Typography>
<IconButton >
<Avatar src="/default_user.jpg" alt="Profile pic" sx={{ width: 33, height: 33 }} />
</IconButton>
</Button>

{/* Pages list in NavBar, only displayed when menu button is not, i.e., in larger devices */}
{isLoggedIn ? (
<Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}>
{pages.map((page) => (
<Button component={Link} to={page.path} key={page.path} sx={{ color: 'white', display: 'block','&:hover': { backgroundColor: '#5f7e94' },}}>
{page.text}
</Button>
))}
</Box>
):(
<Box></Box>
)}


{isLoggedIn ? (
<Box>
<Button onClick={handleOpenUserMenu} sx={{ p: 0, display: 'flex', alignItems: 'center', flexGrow: 0, '&:hover': { backgroundColor: '#5f7e94' }}} >
<Typography variant="body2" sx={{ color: 'white', textDecoration: 'none' }}>
{username}
</Typography>
<IconButton >
{/* Need to change the image for the user profile one */}
<Avatar src="/default_user.jpg" alt="Profile pic" sx={{ width: 33, height: 33 }} />
</IconButton>
</Button>
<Menu
sx={{ mt: '45px' }}
id="menu-appbar"
anchorEl={anchorElUser}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={Boolean(anchorElUser)}
onClose={handleCloseUserMenu}
>
{settings.map((setting) => (

<MenuItem key={setting.path} onClick={setting.path==='/'? handleLogout:handleCloseUserMenu}>
<Link to={setting.path} style={{ textDecoration:'none', color:'inherit' }}>
<Typography textAlign="center">{setting.text}</Typography>
</Link>
</MenuItem>
))}
</Menu>
</Box>
):(
<Button component={Link} to={'/login'} sx={{ p: 0, display: 'flex', alignItems: 'center', flexGrow: 0, '&:hover': { backgroundColor: '#5f7e94' }}} >
<Typography variant="body2" sx={{ color: 'white', textDecoration: 'none' }}>
Log In
</Typography>
<IconButton >
<Avatar src="/default_user.jpg" alt="Profile pic" sx={{ width: 33, height: 33 }} />
</IconButton>
</Button>
)}
</Toolbar>
{/* </Container> */}
</AppBar>
);
}
Expand Down
Loading

0 comments on commit c90d9a6

Please sign in to comment.