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

JWT Authentication - Log in #6

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
4 changes: 3 additions & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ PGDATABASE='TimeOffDB'
PGUSER='TimeOffDB_owner'
PGPASSWORD='wKT0JAWF6BqD'
ENDPOINT_ID='ep-empty-voice-a2dpidxi'
PORT=4050
PORT=4050

JWT_SECRET=a3b720d206c82f42da48594a96089e14acb3f7d62633af6d420de25526fe47c5
134 changes: 131 additions & 3 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,20 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.3",
"jsonwebtoken": "^9.0.2",
"knex": "^3.1.0",
"mysql2": "^3.9.2",
"pg": "^8.11.3",
"postgres": "^3.4.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start-server": "node src/backend/server.js",
"start-frontend": "react-scripts start --port 3003",
"start": "npm run start-server & npm run start-frontend",
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was there a specific reason for removing this? maybe we should update the readme for startup approach

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We tried to unify the frontend and the backend start and make it run in different ports, but talking with other of the mentors we decided to keep it separate

"start-server": "node src/backend/server.js",
"start-frontend": "react-scripts start "

"start-frontend": "react-scripts start ",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
Expand Down
19 changes: 14 additions & 5 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import './App.css';
import Navbar from './pages/Navbar';
import Main from './pages/main';

import Dashboard from './pages/dashboard';
import { UserProvider } from './UserContext';

function App() {
return (
<div className="App">
<Navbar/>
<Main/>
</div>
<Router>
<UserProvider>
<div className="App">
<Navbar />
<Routes>
<Route path="/" element={<Main />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</div>
</UserProvider>
</Router>
);
}

Expand Down
18 changes: 18 additions & 0 deletions src/UserContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { createContext, useContext, useState } from 'react';

const UserContext = createContext();

export const useUser = () => useContext(UserContext);

export const UserProvider = ({ children }) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);

const login = () => setIsLoggedIn(true);
const logout = () => setIsLoggedIn(false);

return (
<UserContext.Provider value={{ isLoggedIn, login, logout }}>
{children}
</UserContext.Provider>
);
};
25 changes: 25 additions & 0 deletions src/backend/API/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const express = require('express');
const jwt = require('jsonwebtoken');
const db = require('../database');
const router = express.Router();

router.post('/', async (req, res) => {
const { team_code } = req.body;

try {
const team = await db.select().from('teams').where('team_code', team_code).first();

if (!team) {
return res.status(401).json({ error: 'Invalid team code' });
}

const token = jwt.sign({ teamId: team.id }, process.env.JWT_SECRET, { expiresIn: '1h' });

res.json({ token });
} catch (error) {
console.error('Error logging in:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

module.exports = router;
24 changes: 7 additions & 17 deletions src/backend/API/teams.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,27 @@
const express = require('express');
const cors = require('cors');
const db = require('../database');
const router = express.Router();

const app = express();

app.use(cors({
origin: 'http://localhost:4051',
methods: ['GET', 'POST'],
credentials: true
}));

app.use(express.json());

app.get('/api/teams', async (req, res) => {
router.get('/', async (req, res) => {
try {
const teams = await db.select().from('team');
const teams = await db.select().from('teams');
res.json(teams);
} catch (error) {
console.error('Error fetching teams:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

app.post('/api/teams', async (req, res) => {
router.post('/', async (req, res) => {
try {
const { title, code } = req.body; // Aquí se espera que el campo se llame 'title'
const { team_name, team_code } = req.body;
const creationDate = new Date();
await db('team').insert({ title, code, created_date: creationDate }); // Insertar 'title' en lugar de 'name'
await db('teams').insert({ team_name, team_code, created_date: creationDate });
res.status(201).json({ message: 'Team created successfully' });
} catch (error) {
console.error('Error creating team:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

module.exports = app;
module.exports = router;
18 changes: 17 additions & 1 deletion src/backend/server.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
const app = require('./API/teams');
const express = require('express');
const cors = require('cors');
const loginRouter = require('./API/login');
const teamsRouter = require('./API/teams');

const app = express();

app.use(cors({
origin: 'http://localhost:4051',
methods: ['GET', 'POST'],
credentials: true
}));

app.use(express.json());

app.use('/api/login', loginRouter);
app.use('/api/teams', teamsRouter);

const PORT = process.env.PORT || 3030;
app.listen(PORT, () => {
Expand Down
Loading