Project

쿡핏_러너톤2

codingtori 2024. 12. 21. 21:43

sequelize 사용하기

 

npm i sequelize sequelize-cli mysql2

 

 

 

sequlize-cli 로부터 시퀄라이즈 명령어를 사용할 수 있도록 하는 것

  • sequelize-cli 는 시퀄라이즈 명령어 사용가능케 해주는 패키지
npx sequelize init

 

config.json 파일에 데이터베이스의 정보를 저장해주면, model 에서 데이터베이스 세팅을 할 때 정보를 일일이 써주지 않아도 된다.

 

그 후에 model 폴더에서 index.js 를 이렇게 수정하면 된다.

//model/index.js

import Sequelize from 'sequelize';
import configData from '../config/config.json' assert { type: 'json' };

const env = process.env.NODE_ENV || 'development';
const config = configData[env];
const db = {};

const sequelize = new Sequelize(config.database, config.username, config.password, config);

db.sequelize = sequelize;

export { sequelize };
export default db;

 

 

    그리고 app.js에 가서 디비와 연결하는 코드를 짠다.
import { sequelize } from './models/index.js';

sequelize.sync({ force: true })
    .then(() => {
        console.log("데이터 베이스 연결 성공")
    })
    .catch((err) => {
        console.log(err);
    });

 

그럼 연결 성공!


JWT

 

 

로그아웃

  //블랙리스트 이용한 구현
  const tokenBlacklist = [];
  
  try {
    // 토큰이 있는지 확인
    const { accessToken } = req.cookies;
    
    // 토큰이 있디면 유효성 검증
    if (accessToken) {
    	const decodedToken = jwt.verify(accessToken,"token-secret");
        const { id } = decodedToken;
        // 유효성 검증 통과시 해당 토큰 블랙리스트에 추가
    	if(id) {
      		tokenBlacklist.push(accessToken);
        }
    } else {
    throw new Error('로그인 정보가 없습니다.');
    }
  } catch (error) {
    throw new Error('유효하지 않은 토큰입니다.');
  }

 

다른 페이지로 넘어가면 계속 로그인이 풀리는 문제가 발생하였다
그 이유인 즉슨, 인증 미들웨어가 적용되지 않아 발생!!!! 로그인 상태를 유지하려면 authenticateToken 미들웨어를 라우트에 적용해야한다고 한다.

 

 

 

 


KAKAO login

 

카카오 로그인 구현시 access Token도 발급받았는데 계속 302 상태가 계속 된다면,,!!
auth route 카카오 로그인에서 json으로 반환하고 있는데 redirection uri가 서버쪽으로 되어있어서 서버로 가는데 client로 json응답 보내고 나서 client로 redirection하는 부분이 없어서 그렇다! 그래서 client로 redirection해줘야한다!!


데이터베이스 erd

 

Database ERD

Table users {
  id BIGINT [pk, increment] // Primary Key, Auto Increment
  loginId STRING [not null, unique] // Unique and not null
  nickname STRING
  password STRING [not null] // Not null
}

Table recipes {
  id BIGINT [pk, increment] // Primary Key, Auto Increment
  name STRING [not null] // Not null
  totalTime STRING [not null] // Not null
  difficulty STRING [not null] // Not null
  difficultyScore INTEGER [not null] // Not null
  ingredients TEXT [not null] // Stored as JSON
  steps TEXT [not null] // Stored as JSON
  userId BIGINT [not null] // Foreign Key to users table
}

Table saved_recipes {
  id BIGINT [pk, increment] // Primary Key, Auto Increment
  userId BIGINT [not null] // Foreign Key to users table
  recipeId BIGINT [not null] // Foreign Key to recipes table
}

// Relationships
Ref: recipes.userId > users.id [delete: cascade, update: cascade] // Recipes linked to Users
Ref: saved_recipes.recipeId > recipes.id [delete: cascade, update: cascade] // SavedRecipes linked to Recipes
Ref: saved_recipes.userId > users.id // SavedRecipes linked to Users