Skip to content

Commit

Permalink
code developed during the lecture
Browse files Browse the repository at this point in the history
  • Loading branch information
luigidr committed May 27, 2021
1 parent 9afcdd7 commit 2e79af0
Show file tree
Hide file tree
Showing 8 changed files with 480 additions and 8 deletions.
30 changes: 29 additions & 1 deletion client/src/API.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,33 @@ async function getAllExams() {
}
}

const API = {getAllCourses, getAllExams};
async function login(credentials) {
let response = await fetch('/api/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
});
if(response.ok) {
const user = await response.json();
return user.name;
}
else {
const errDetails = await response.text();
throw errDetails;
}
}

async function getUserInfo() {
const response = await fetch(BASEURL + '/sessions/current');
const userInfo = await response.json();
if (response.ok) {
return userInfo;
} else {
throw userInfo; // an object with the error coming from the server
}
}

const API = {getAllCourses, getAllExams, login, getUserInfo};
export default API;
35 changes: 33 additions & 2 deletions client/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,38 @@ import { Container, Row, Alert } from 'react-bootstrap';
import { ExamScores } from './ExamComponents.js';
import AppTitle from './AppTitle.js';
import { useEffect, useState } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom';
import API from './API';
import { LoginForm } from './LoginComponents';

function App() {
const [exams, setExams] = useState([]);
const [courses, setCourses] = useState([]);
const [message, setMessage] = useState('');
const [loggedIn, setLoggedIn] = useState(false);

useEffect(() => {
const checkAuth = async () => {
// TODO: qui avremo le info sull'utente dal server, possiamo salvare da qualche parte
await API.getUserInfo();
setLoggedIn(true);
};
checkAuth();
}, []);

useEffect(()=> {
const getCourses = async () => {
if(loggedIn) {
const courses = await API.getAllCourses();
setCourses(courses);
}
};
getCourses()
.catch(err => {
setMessage({msg: "Impossible to load your exams! Please, try again later...", type: 'danger'});
console.error(err);
});
}, []);
}, [loggedIn]);

useEffect(()=> {
const getExams = async () => {
Expand All @@ -37,6 +50,17 @@ function App() {
}
}, [courses.length]);

const doLogin = async (credentials) => {
try {
const user = await API.login(credentials);
setLoggedIn(true);
setMessage({msg: `Welcome, ${user}!`, type: 'success'});
}catch(err) {
setMessage({msg: err, type: 'danger'});
}

}

return (<Router>
<Container className="App">
<Row>
Expand All @@ -47,10 +71,17 @@ function App() {
</Row> }

<Switch>
<Route path="/login" render={() =>
<>{loggedIn ? <Redirect to="/" /> : <LoginForm login={doLogin} /> }</>
} />
<Route path="/" render={() =>
<>
{loggedIn ?
<Row>
<ExamScores exams={exams} courses={courses} />
</Row>
: <Redirect to="/login" />}
</>
} />

</Switch>
Expand Down
45 changes: 45 additions & 0 deletions client/src/LoginComponents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useState } from "react";
import {Form, Button, Alert} from 'react-bootstrap';

function LoginForm(props) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [errorMessage, setErrorMessage] = useState('') ;

const handleSubmit = (event) => {
event.preventDefault();
setErrorMessage('');
const credentials = { username, password };

// SOME VALIDATION, ADD MORE!!!
let valid = true;
if(username === '' || password === '' || password < 6)
valid = false;

if(valid)
{
props.login(credentials);
}
else {
// show a better error message...
setErrorMessage('Error(s) in the form, please fix it.')
}
};

return (
<Form>
{errorMessage ? <Alert variant='danger'>{errorMessage}</Alert> : ''}
<Form.Group controlId='username'>
<Form.Label>email</Form.Label>
<Form.Control type='email' value={username} onChange={ev => setUsername(ev.target.value)} />
</Form.Group>
<Form.Group controlId='password'>
<Form.Label>Password</Form.Label>
<Form.Control type='password' value={password} onChange={ev => setPassword(ev.target.value)} />
</Form.Group>
<Button onClick={handleSubmit}>Login</Button>
</Form>
)
}

export { LoginForm };
6 changes: 3 additions & 3 deletions server/exam-dao.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ exports.listCourses = () => {
};

// get all exams
exports.listExams = () => {
exports.listExams = (id) => {
return new Promise((resolve, reject) => {
const sql = 'SELECT coursecode, score, date FROM exam';
const sql = 'SELECT coursecode, score, date FROM exam WHERE userId = ?';

db.all(sql, [], (err, rows) => {
db.all(sql, [id], (err, rows) => {
if (err) {
reject(err);
return;
Expand Down
Loading

0 comments on commit 2e79af0

Please sign in to comment.