Skip to content

Commit

Permalink
fixed-401
Browse files Browse the repository at this point in the history
  • Loading branch information
Vahdet Parlak committed Jul 21, 2024
1 parent 31dab14 commit 9baef20
Show file tree
Hide file tree
Showing 16 changed files with 247 additions and 150 deletions.
2 changes: 1 addition & 1 deletion authservice/src/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def generate_access_token(user_id, jti):
payload = {
'user_id': user_id,
'jti': jti, # unique identifier for the token pair.
'exp': datetime.now(tz=timezone.utc) + timedelta(minutes=45),
'exp': datetime.now(tz=timezone.utc) + timedelta(seconds=5),
'iat': datetime.now(tz=timezone.utc)
}
access_token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
Expand Down
Binary file added bucketservice/media/images/avatar7_1ERBFAb.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 4 additions & 37 deletions frontend/src/routes/ai/Ai.js
Original file line number Diff line number Diff line change
@@ -1,81 +1,68 @@
import { navigateTo } from "../../utils/navTo.js";
import { navigateTo as originalNavigateTo } from "../../utils/navTo.js";

export async function fetchAi() {
if (!localStorage.getItem("access_token")) {
const access_token = localStorage.getItem("access_token");
if (!access_token) {
console.log("No access token found");
navigateTo("/login");
} else {
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreBoard = document.getElementById('scoreBoard');
const startButton = document.getElementById('startButton');

const paddleHeight = 100;
const paddleWidth = 10;
const ballSize = 10;

let leftPaddleY = canvas.height / 2 - paddleHeight / 2;
let rightPaddleY = canvas.height / 2 - paddleHeight / 2;
let ballX = canvas.width / 2;
let ballY = canvas.height / 2;
let ballSpeedX = 5;
let ballSpeedY = 5;

let leftScore = 0;
let rightScore = 0;

let gameRunning = false;

function drawRect(x, y, width, height, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, width, height);
}

function drawCircle(x, y, radius, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
ctx.fill();
}

function drawNet() {
for (let i = 0; i < canvas.height; i += 40) {
drawRect(canvas.width / 2 - 1, i, 2, 20, '#fff');
}
}

function draw() {
// Clear canvas
drawRect(0, 0, canvas.width, canvas.height, '#000');

// Draw paddles
drawRect(0, leftPaddleY, paddleWidth, paddleHeight, '#fff');
drawRect(canvas.width - paddleWidth, rightPaddleY, paddleWidth, paddleHeight, '#fff');

// Draw ball
drawCircle(ballX, ballY, ballSize, '#fff');

// Draw net
drawNet();
}

function update() {
// Move ball
ballX += ballSpeedX;
ballY += ballSpeedY;

// Ball collision with top and bottom walls
if (ballY - ballSize < 0 || ballY + ballSize > canvas.height) {
ballSpeedY = -ballSpeedY * 1.05;
}

// Ball collision with paddles
if (
(ballX - ballSize < paddleWidth && ballY > leftPaddleY && ballY < leftPaddleY + paddleHeight) ||
(ballX + ballSize > canvas.width - paddleWidth && ballY > rightPaddleY && ballY < rightPaddleY + paddleHeight)
) {
ballSpeedX = -ballSpeedX * 1.05;
}

// Score points
if (ballX < 0) {
rightScore++;
Expand All @@ -84,10 +71,8 @@ export async function fetchAi() {
leftScore++;
resetBall();
}

// Update score display
scoreBoard.textContent = `Player 1: ${leftScore} | AI: ${rightScore}`;

// Check for game over
if (leftScore === 5 || rightScore === 5) {
const winner = leftScore === 5 ? "Player 1" : "AI";
Expand All @@ -99,15 +84,12 @@ export async function fetchAi() {
navigateTo("/ai");
}
}

function resetBall() {
ballX = canvas.width / 2;
ballY = canvas.height / 2;
ballSpeedX = -ballSpeedX;
ballSpeedY = Math.random() > 0.5 ? 5 : -5;
}


function gameLoop() {
if (gameRunning) {
handleInput();
Expand All @@ -116,18 +98,14 @@ export async function fetchAi() {
requestAnimationFrame(gameLoop);
}
}

// Keyboard controls
const keys = {};

document.addEventListener('keydown', (e) => {
keys[e.key] = true;
});

document.addEventListener('keyup', (e) => {
keys[e.key] = false;
});

function handleInput() {
// Left paddle
if (keys['w'] && leftPaddleY > 0) {
Expand All @@ -136,23 +114,20 @@ export async function fetchAi() {
if (keys['s'] && leftPaddleY < canvas.height - paddleHeight) {
leftPaddleY += 5;
}

// AI controlled right paddle
const aiSpeed = 5 + Math.random() * 2; // AI speed varies between 3 and 5
if (rightPaddleY + paddleHeight / 2 < ballY) {
rightPaddleY += aiSpeed;
} else if (rightPaddleY + paddleHeight / 2 > ballY) {
rightPaddleY -= aiSpeed;
}

// Ensure AI paddle stays within canvas bounds
if (rightPaddleY < 0) {
rightPaddleY = 0;
} else if (rightPaddleY > canvas.height - paddleHeight) {
rightPaddleY = canvas.height - paddleHeight;
}
}

startButton.addEventListener('click', () => {
if (!gameRunning) {
gameRunning = true;
Expand All @@ -164,45 +139,37 @@ export async function fetchAi() {
gameLoop();
}
});

function finishGame() {
gameRunning = false;
startButton.style.display = 'block';
alert("VS AI is aborted!");
}

// Listen for navigation events
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;

history.pushState = function () {
if (gameRunning) {
finishGame();
}
return originalPushState.apply(history, arguments);
};

history.replaceState = function () {
if (gameRunning) {
finishGame();
}
return originalReplaceState.apply(history, arguments);
};

window.addEventListener('popstate', () => {
if (gameRunning) {
finishGame();
}
});

function navigateTo(url) {
if (gameRunning) {
finishGame();
}
originalNavigateTo(url);
}

draw();
}
}

6 changes: 6 additions & 0 deletions frontend/src/routes/changepassword/Changepassword.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export async function fetchChangepassword() {
return RefreshToken().then(() => {
return postChangePasswordRequest().then(handleResponse);
});
} else if (response.status === 401 && errorData.error) {
document.getElementById("logout-button").click();
} else {
throw errorData;
}
Expand All @@ -61,6 +63,10 @@ export async function fetchChangepassword() {
postChangePasswordRequest()
.then(handleResponse)
.then(data => {
if (data.error) {
insertIntoElement('fields-warning', "Error: " + data.error);
return;
}
setTimeout(() => {
alert("Password changed successfully");
navigateTo("/");
Expand Down
64 changes: 47 additions & 17 deletions frontend/src/routes/edit/Edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@ export async function fetchEdit() {

if (!response.ok) {
const errorData = await response.json();
if (response.status === 401) {
if (errorData.error === "Token has expired") {
await RefreshToken();
return fetchEdit();
}
document.getElementById("logout-button").click();
return;
}
if (response.status === 500) {
let message = "error: " + errorData.error;
alert(message);
navigateTo("/"); // redirect to home page
return;
}
throw new Error(errorData.error);
}

Expand Down Expand Up @@ -62,16 +76,21 @@ export async function fetchEdit() {
const handleResponse = response => {
if (!response.ok) {
return response.json().then(errorData => {
if (response.status === 401 && errorData.error === "Token has expired") {
return RefreshToken().then(() => {
return postUpdateUserRequest().then(handleResponse);
});
if (response.status === 401) {
if (errorData.error === "Token has expired") {
return RefreshToken().then(() => {
return postUpdateUserRequest().then(handleResponse);
});
}
document.getElementById("logout-button").click();
return;
} else if (response.status === 207) {
alert("Email updated successfully, please verify your email");
document.getElementById("logout-button").click();
return;
}
else {
} else if (response.status === 500) {
throw errorData;
} else {
throw errorData;
}
});
Expand All @@ -81,9 +100,12 @@ export async function fetchEdit() {

postUpdateUserRequest()
.then(handleResponse)
.then(() => {
alert("Profile updated successfully");
navigateTo("/profile");
.then((data) => {
if (!data.error) {
alert("Profile updated successfully");
navigateTo("/profile");
return;
}
})
.catch(err => {
if (err.error) {
Expand Down Expand Up @@ -133,12 +155,16 @@ export async function fetchEdit() {
const handleResponse = response => {
if (!response.ok) {
return response.json().then(errorData => {
if (response.status === 401 && errorData.error === "Token has expired") {
return RefreshToken().then(() => {
return postAvatarUpdate().then(handleResponse);
});
if (response.status === 401) {
if (errorData.error === "Token has expired") {
return RefreshToken().then(() => {
return postAvatarUpdate().then(handleResponse);
});
}
document.getElementById("logout-button").click();
return;
} else {
throw new Error("Couldn't update avatar");
throw errorData;
}
});
}
Expand All @@ -147,11 +173,15 @@ export async function fetchEdit() {
postAvatarUpdate()
.then(handleResponse)
.then(data => {
alert("Avatar updated successfully");
navigateTo("/profile");
if (!data.error) {
alert("Avatar updated successfully");
navigateTo("/profile");
}
})
.catch(error => {
console.error(error);
if (error.error) {
insertIntoElement('fields-warning', "Error: " + error.error);
}
});
});

Expand Down
32 changes: 24 additions & 8 deletions frontend/src/routes/friendrequests/Friendrequests.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,26 @@ export async function fetchFriendrequests() {
});
if (!response_user.ok) {
const errorData = await response_user.json();
if (errorData.error === 'Token has expired') {
await RefreshToken();
return fetchFriendrequests(); // Retry fetching after token refresh
} else {
throw new Error(errorData.error);
if (response_user.status === 401) {
if (errorData.error === "Token has expired") {
await RefreshToken();
return fetchFriendrequests();
}
document.getElementById("logout-button").click();
return;
}
if (response_user.status === 500) {
let message = "error: " + errorData.error;
alert(message);
navigateTo("/"); // redirect to home page
return;
}
throw new Error(errorData.error);
}
const data = await response_user.json();
const user = data.data[0];


const response = await fetch(requestsList + "?page=" + currentPage + "&limit=5", {
method: "GET",
headers: {
Expand All @@ -39,14 +49,20 @@ export async function fetchFriendrequests() {
});
if (!response.ok) {
const errorData = await response.json();
if (errorData.error === 'Token has expired') {
await RefreshToken();
return fetchFriendrequests(); // Retry fetching after token refresh
if (response.status === 401) {
if (errorData.error === "Token has expired") {
await RefreshToken();
return fetchFriendrequests();
}
document.getElementById("logout-button").click();
return;
} else {
throw new Error(errorData.error);
}
}



const requests_res = await response.json();
const requests = requests_res.data;
let paginate_data = requests_res.pagination;
Expand Down
Loading

0 comments on commit 9baef20

Please sign in to comment.