Skip to content

セッション管理をJWTに移行し、ユーザー認証のミドルウェアを追加。関連するルートとコントローラーを更新。#49

Open
Koseeee-27 wants to merge 5 commits into
developfrom
fix/be/auth
Open

Conversation

@Koseeee-27
Copy link
Copy Markdown
Collaborator

タスクに関しては一応切り出したけど、使わない想定。

@Koseeee-27 Koseeee-27 requested review from Copilot and ru-se October 30, 2025 05:50
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR migrates the authentication system from session-based to JWT (JSON Web Token) based authentication. The changes improve security and scalability by eliminating server-side session storage.

  • Introduces JWT authentication middleware to protect routes
  • Replaces session-based user retrieval with JWT token-based authentication
  • Refactors initial task creation logic into a dedicated model function

Reviewed Changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
backend/middleware/authMiddleware.js New authentication middleware that validates JWT tokens and attaches user info to requests
backend/routes/authRoutes.js Added protect middleware to the /me endpoint
backend/controllers/authController.js Removed session handling, simplified login/logout logic, and extracted initial task creation
backend/controllers/taskController.js Updated to use req.user instead of req.session.user
backend/controllers/letterController.js Updated to use req.user instead of req.session.user
backend/models/task.js Added createInitialTasks function to handle initial task setup
backend/app.js Removed express-session configuration

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/middleware/authMiddleware.js Outdated
Comment on lines +7 to +33
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
// 'Bearer <token>' からトークン部分を抽出
token = req.headers.authorization.split(' ')[1];

// トークンを検証
const decoded = jwt.verify(token, process.env.JWT_SECRET);

// ペイロードからユーザーIDを取得し、DBからユーザー情報を取得(パスワードは除く)
const [rows] = await pool.execute('SELECT user_id, username, email FROM users WHERE user_id = ?', [decoded.user_id]);

if (rows.length === 0) {
return res.status(401).json({ message: '認証に失敗しました: ユーザーが見つかりません' });
}

// reqオブジェクトにユーザー情報を格納
req.user = rows[0];

next();
} catch (error) {
console.error(error);
return res.status(401).json({ message: '認証に失敗しました: トークンが無効です' });
}
}

if (!token) {
return res.status(401).json({ message: '認証に失敗しました: トークンがありません' });
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

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

This token check is unreachable. If the authorization header is missing or doesn't start with 'Bearer', the code exits the outer if-block at line 30, but token remains undefined. This check should be moved outside the try-catch block but still within the outer if condition, or restructured to handle the case when the authorization header is absent before entering the if block at line 7.

Suggested change
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
// 'Bearer <token>' からトークン部分を抽出
token = req.headers.authorization.split(' ')[1];
// トークンを検証
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// ペイロードからユーザーIDを取得し、DBからユーザー情報を取得(パスワードは除く)
const [rows] = await pool.execute('SELECT user_id, username, email FROM users WHERE user_id = ?', [decoded.user_id]);
if (rows.length === 0) {
return res.status(401).json({ message: '認証に失敗しました: ユーザーが見つかりません' });
}
// reqオブジェクトにユーザー情報を格納
req.user = rows[0];
next();
} catch (error) {
console.error(error);
return res.status(401).json({ message: '認証に失敗しました: トークンが無効です' });
}
}
if (!token) {
return res.status(401).json({ message: '認証に失敗しました: トークンがありません' });
if (!(req.headers.authorization && req.headers.authorization.startsWith('Bearer'))) {
return res.status(401).json({ message: '認証に失敗しました: トークンがありません' });
}
try {
// 'Bearer <token>' からトークン部分を抽出
token = req.headers.authorization.split(' ')[1];
// トークンを検証
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// ペイロードからユーザーIDを取得し、DBからユーザー情報を取得(パスワードは除く)
const [rows] = await pool.execute('SELECT user_id, username, email FROM users WHERE user_id = ?', [decoded.user_id]);
if (rows.length === 0) {
return res.status(401).json({ message: '認証に失敗しました: ユーザーが見つかりません' });
}
// reqオブジェクトにユーザー情報を格納
req.user = rows[0];
next();
} catch (error) {
console.error(error);
return res.status(401).json({ message: '認証に失敗しました: トークンが無効です' });

Copilot uses AI. Check for mistakes.
Comment thread backend/controllers/letterController.js Outdated
const created_at = req.body.created_at;
const result = await Letter.selectLetter(user_id, created_at);

if (!letter) {
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

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

The variable letter is undefined. The query result is stored in result (line 43), so this condition should check if (!result) or if (result.length === 0) instead.

Suggested change
if (!letter) {
if (!result || result.length === 0) {

Copilot uses AI. Check for mistakes.
Comment thread backend/models/task.js Outdated

exports.createInitialTasks = async (userId) => {
const taskQuery =
"INSERT INTO tasks(task_title, task_name, task_type, status, user_id) VALUES ?";
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

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

The SQL query uses INSERT INTO tasks (lowercase), but other queries in this file use Tasks (capitalized). Ensure table name casing is consistent with your database schema to avoid potential query failures on case-sensitive database systems.

Suggested change
"INSERT INTO tasks(task_title, task_name, task_type, status, user_id) VALUES ?";
"INSERT INTO Tasks(task_title, task_name, task_type, status, user_id) VALUES ?";

Copilot uses AI. Check for mistakes.
Comment thread backend/app.js Outdated
"https://homemax-frontend.onrender.com",
],
credentials: true, // Cookie やセッションを許可
credentials: true, // Cookie やセッションを許可
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

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

The comment mentions 'Cookie やセッションを許可' (allowing cookies and sessions), but this PR removes session support. The comment should be updated to reflect that this is now only for allowing credentials like authorization headers.

Suggested change
credentials: true, // Cookie やセッションを許可
credentials: true, // 認証ヘッダーなどのクレデンシャルを許可

Copilot uses AI. Check for mistakes.
Comment thread backend/controllers/authController.js Outdated

// //JSONの受け取り
// app.use(express.json());
const Task = require("../models/task");
Copy link

Copilot AI Oct 30, 2025

Choose a reason for hiding this comment

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

Unused variable Task.

Suggested change
const Task = require("../models/task");

Copilot uses AI. Check for mistakes.
@Koseeee-27 Koseeee-27 requested a review from Copilot October 31, 2025 07:18
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/models/task.js
],
];
try {
await db.query(taskQuery, [initialTasks]);
Copy link

Copilot AI Oct 31, 2025

Choose a reason for hiding this comment

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

The db.query method is being called with await, but based on the db configuration (mysql2/promise pool) and other model patterns in this file, it should use db.execute for promise-based queries. Other methods in this file use new Promise wrappers around db.query for callback-based queries. Change to await db.execute(taskQuery, [initialTasks]) for consistency with the promise-based API.

Suggested change
await db.query(taskQuery, [initialTasks]);
await db.execute(taskQuery, [initialTasks]);

Copilot uses AI. Check for mistakes.
@@ -1,63 +1,55 @@
// サインアアップ、ログイン機能とか
Copy link

Copilot AI Oct 31, 2025

Choose a reason for hiding this comment

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

Corrected spelling of 'サインアアップ' to 'サインアップ' (removed duplicate 'ア').

Suggested change
// サインアアップ、ログイン機能とか
// サインアップ、ログイン機能とか

Copilot uses AI. Check for mistakes.
Comment thread backend/controllers/authController.js Outdated
@@ -1,136 +1,50 @@
// サインアアップ、ログイン機能とか
Copy link

Copilot AI Oct 31, 2025

Choose a reason for hiding this comment

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

Corrected spelling of 'サインアアップ' to 'サインアップ' (removed duplicate 'ア').

Suggested change
// サインアアップ、ログイン機能とか
// サインアップ、ログイン機能とか

Copilot uses AI. Check for mistakes.
Comment thread backend/controllers/letterController.js Outdated
addLetter: async function (req, res) {
try {
//ログインしていない場合ユーザーIDは0
let user_id = req.user ? req.user.user_id : 1;
Copy link

Copilot AI Oct 31, 2025

Choose a reason for hiding this comment

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

Defaulting to user_id = 1 when req.user is not present could assign letters to the wrong user. If authentication is required, this route should be protected with the protect middleware. If unauthenticated access is intentional, consider using a null/0 value or rejecting the request instead of defaulting to user ID 1.

Suggested change
let user_id = req.user ? req.user.user_id : 1;
let user_id = req.user ? req.user.user_id : 0;

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants