Skip to content

Commit fc19c9d

Browse files
committed
the login is made according to what has been learned in the classroom
1 parent b355132 commit fc19c9d

File tree

15 files changed

+262
-37
lines changed

15 files changed

+262
-37
lines changed

index.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99

1010
</head>
1111
<body>
12+
<h1>Posts</h1>
13+
14+
<div class="session"></div>
1215
<div class="notifications"></div>
1316
<div class="loader hidden"></div> <!-- by defaul "loader" is hidden -->
1417
<div class="posts-container"></div>

src/js/main.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
import { loaderController } from "./components/loader/loaderController.js";
22
import { notificationsController } from "./components/notifications/notificationsController.js";
3+
34
import { showPostsController } from "./modules/show-posts/showPostsController.js";
5+
import { loginController } from "../js/modules/login/loginController.js";
46

57

68
// Get the DOM nodes we need to interact with.
79
document.addEventListener("DOMContentLoaded", () => {
810

911
// Here I go to the DOM and select the nodes I need to manage in my code and I manage them in my controllers.
10-
const container = document.querySelector(".posts-container") // ".posts-container" is a Node
11-
const loader = document.querySelector(".loader") // ".loader" is a Node
12+
const container = document.querySelector(".posts-container")
13+
const loader = document.querySelector(".loader")
1214
const notifications = document.querySelector(".notifications")
13-
15+
const session = document.querySelector(".session")
1416

1517
const { show, hide } = loaderController(loader);
1618
const { showNotification } = notificationsController(notifications)
@@ -36,7 +38,6 @@ document.addEventListener("DOMContentLoaded", () => {
3638
showNotification(errorMessage) // <-- Here we do not add the type “success” so it will be “error”.
3739
})
3840

39-
// Then this next code happens in showPostsController.js
40-
showPostsController(container)
41-
41+
showPostsController(container) // This line happens in showPostsController.js
42+
loginController(session)
4243
})

src/js/modules/create-post/createPostController.js

Whitespace-only changes.

src/js/modules/create-post/createPostModel.js

Whitespace-only changes.

src/js/modules/login/login.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { loginController } from "./loginController.js"
2+
import {notificationsController} from "../../components/notifications/notificationsController.js"
3+
4+
document.addEventListener("DOMContentLoaded", () => {
5+
6+
const loginForm = document.querySelector("#loginForm")
7+
const notifications = document.querySelector("#notifications");
8+
9+
const { showNotification } = notificationsController(notifications)
10+
11+
loginForm.addEventListener("login-error", (event) => {
12+
const message = event.detail;
13+
showNotification(message)
14+
})
15+
16+
loginForm.addEventListener("login-ok", (event) => {
17+
const message = event.detail.message;
18+
const type = event.detail.type;
19+
showNotification(message, type)
20+
})
21+
22+
loginController(loginForm)
23+
})
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { REGEXP } from "../../utils/constants.js";
2+
import { loginUser } from "./loginModel.js";
3+
4+
export function loginController(loginForm) {
5+
6+
loginForm.addEventListener("submit", (event) => {
7+
event.preventDefault();
8+
9+
const userEmailElement = loginForm.querySelector("#mail");
10+
const userEmail = userEmailElement.value;
11+
12+
const passwordElement = loginForm.querySelector("#password");
13+
const password = passwordElement.value;
14+
15+
const emailRegExp = new RegExp(REGEXP.mail);
16+
17+
if (emailRegExp.test(userEmail)) {
18+
19+
handleLoginUser(userEmail, password, loginForm)
20+
21+
} else {
22+
23+
dispatchLoginError(loginForm, 'Incorrect mail format');
24+
}
25+
})
26+
27+
async function handleLoginUser(userEmail, password, loginForm) {
28+
29+
try {
30+
31+
const existingToken = localStorage.getItem("accessToken");
32+
33+
if (existingToken) {
34+
throw new Error("There is already an active session. Log out before logging in with another user.");
35+
}
36+
37+
const token = await loginUser(userEmail, password);
38+
39+
dispatchLoginSuccess(loginForm, 'You have successfully logged in.');
40+
41+
localStorage.setItem("accessToken", token)
42+
43+
setTimeout(() => {
44+
window.location = '/index.html'
45+
}, 500);
46+
47+
48+
} catch (error) {
49+
50+
dispatchLoginError(loginForm, error.message);
51+
52+
}
53+
}
54+
55+
function dispatchLoginSuccess(loginForm, successMessage) {
56+
const event = new CustomEvent("login-ok", {
57+
detail: {
58+
message: successMessage,
59+
type: 'success'
60+
}
61+
});
62+
loginForm.dispatchEvent(event);
63+
}
64+
65+
function dispatchLoginError(loginForm, errorMessage) {
66+
const event = new CustomEvent("login-error", {
67+
detail: errorMessage
68+
});
69+
loginForm.dispatchEvent(event);
70+
}
71+
}
72+

src/js/modules/login/loginModel.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
export async function loginUser(email, password) {
2+
3+
try {
4+
const response = await fetch("http://localhost:8000/auth/login", {
5+
method: "POST",
6+
body: JSON.stringify({
7+
username: email,
8+
password
9+
}),
10+
headers: {
11+
"Content-type": "application/json"
12+
}
13+
});
14+
15+
const data = await response.json();
16+
17+
if (!response.ok) {
18+
const errorMessage = data.message;
19+
console.error(`Error: ${response.status} (${response.statusText}) --> ${errorMessage}`);
20+
throw new Error(errorMessage);
21+
}
22+
23+
/* if (!response.ok) {
24+
throw new Error("error iniciando sesión")
25+
} */
26+
27+
const { accessToken } = data;
28+
29+
if (!accessToken) {
30+
throw new Error("No se recibió el token de acceso");
31+
}
32+
33+
return accessToken;
34+
35+
} catch (error) {
36+
throw error;
37+
}
38+
}

src/js/modules/show-posts/showPostsModel.js

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,22 @@ export async function getPosts() {
55
try {
66
const response = await fetch('http://localhost:8000/api/posts')
77

8+
const data = await response.json();
9+
810
if (!response.ok) {
9-
// It will occur when there is a connection to the server and to the database, but the server responds with an error.
10-
throw new Error("Server error: " + response.status + " - " + response.statusText);
11+
const errorMessage = data.message || 'Error desconocido';
12+
console.error(`Error: ${response.status} (${response.statusText}): ${errorMessage}`);
13+
throw new Error(errorMessage);
1114
}
1215

13-
posts = await response.json();
16+
if (data.length === 0) {
17+
const apiMessage = 'No posts to fetch in the API';
18+
console.error(`Response: ${response.status} (${response.statusText}) --> ${apiMessage}`);
19+
throw new Error(apiMessage);
20+
}
1421

1522
} catch (error) {
16-
17-
// It will occur when you cannot connect to the server or database at all.
18-
console.error("Fetch error:", error);
19-
throw new Error("It was not possible to get the posts. Please try again later.");
23+
throw error;
2024
}
2125

2226
return posts;
Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
import { REGEXP } from "../../utils/constants.js";
22
import { createUser } from "../signup/signUpModel.js";
33

4-
export const signUpController = (form) => {
4+
export const signUpController = (signupForm) => {
55

6-
form.addEventListener("submit", (event) => {
6+
signupForm.addEventListener("submit", (event) => {
77

88
/* By default, when a form is submitted the browser reloads the page and
99
all JavaScript and current app state information is lost. */
1010
event.preventDefault();
1111

12-
const nameElement = form.querySelector('#name');
12+
const nameElement = signupForm.querySelector('#name');
1313
const name = nameElement.value;
1414

15-
const emailElement = form.querySelector('#email');
15+
const emailElement = signupForm.querySelector('#email');
1616
const email = emailElement.value;
1717

18-
const passwordElement = form.querySelector('#password');
18+
const passwordElement = signupForm.querySelector('#password');
1919
const password = passwordElement.value;
2020

21-
const passwordConfirmElement = form.querySelector('#password-confirm');
21+
const passwordConfirmElement = signupForm.querySelector('#password-confirm');
2222
const passwordConfirm = passwordConfirmElement.value;
2323

2424
const errors = []
@@ -36,49 +36,49 @@ export const signUpController = (form) => {
3636
errors.push('The email format is incorrect.')
3737
}
3838

39-
// check that the passwords are the same
39+
// check that the passwords are the sameH
4040
if (password !== passwordConfirm) {
4141
errors.push('Passwords are not the same.')
4242
}
4343

4444
if (errors.length === 0) {
45-
handleCreateUser(name, email, password, form)
45+
handleCreateUser(name, email, password, signupForm)
4646
} else {
4747
errors.forEach(error => {
48-
const event = new CustomEvent("register-error", {
49-
detail: error
48+
const event = new CustomEvent("sigup-error", {
49+
detail: error // <-- "error" are actually theh
5050
});
51-
form.dispatchEvent(event)
51+
signupForm.dispatchEvent(event)
5252
})
5353
}
5454
})
5555

56-
const handleCreateUser = async (name, email, password, form) => {
56+
const handleCreateUser = async (name, email, password, signupForm) => {
5757
try {
5858

5959
/* Insert User to API REST VVVVVVVVVVVVVVVVVVV */
6060
await createUser(name, email, password);
61-
const event = new CustomEvent("register-ok", {
61+
const event = new CustomEvent("sigup-ok", {
6262
detail: {
6363
message: 'You have successfully registered.',
6464
type: 'success'
6565
}
6666
});
6767
/* AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA */
6868

69-
form.dispatchEvent(event)
69+
signupForm.dispatchEvent(event)
7070
setTimeout(() => {
7171
window.location = '/'
7272
}, 5000);
7373

7474
} catch (error) {
7575

76-
const event = new CustomEvent("register-error", {
76+
const event = new CustomEvent("sigup-error", {
7777
detail: error.message
7878
});
7979

8080
// This event is sent to "signup" as it is being listened to.
81-
form.dispatchEvent(event)
81+
signupForm.dispatchEvent(event)
8282
}
8383
}
8484
}

0 commit comments

Comments
 (0)