API서버 - 특정 데이터에 소유권 지정하기(글 쓰기, 수정하기 기능)

이번 포스팅은 DB와 연결하여 클라이언트 자신이 넣은 값을 식별하여 수정하는 방법을 설명합니다.

즉, 자신이 쓴 글만 수정 가능하며, 자신이 쓰지 않은 글은 수정 할 수 없는 기능을 말합니다.

 

  • DB 연동 과정은 이전 포스팅을 참고해주세요.

https://luvris2.tistory.com/182

 

API서버 - DB 연동하기

API서버 DB연동하기 DB : MySQL Programming language : Python IDE : Visual Studio Code MySQL DB 생성 (recipe) Table 생성 (recipe, user) DB를 관리 할 수 있는 권한 설정하기 (MySQL) SQL 쿼리 use mysql;..

luvris2.tistory.com

 

DB에 값을 넣는 코드는 아래 포스팅을 참고해주세요.

해당 포스팅은 자신이 쓴 글의 소유권을 지정하는 코드가 추가 되었습니다.

https://luvris2.tistory.com/185

 

API서버 - 클라이언트로부터 입력받은 값 DB에 넣기 (POST)

이번 포스팅은 DB와 연결하여 클라이언트가 값을 넣는 방법을 설명합니다. DB 연동 과정은 이전 포스팅을 참고해주세요. https://luvris2.tistory.com/182 API서버 - DB 연동하기 API서버 DB연동하기 DB : MySQL P

luvris2.tistory.com


MySQL - 관계 테이블 설정

  • 유저의 정보가 담겨있는 user 테이블의 의 식별 정보(user_id)를 글의 정보가 담겨있는 recipe 테이블과 연결
    • 각각의 테이블에 연결점을 만들어서 유저의 식별 정보(id)로 두 개의 테이블 접근
  • recipe 테이블에 user_id 항목 추가

 

  • Foreign Key 설정
    • Foreign Key Name : r_user_id
    • Referenced Table : recipe 테이블의 user_id 컬럼을 user 테이블의 id 컬럼과 연결


Visual Studio Code

API 서버 구축

  • 메인 파일 : app.py
  • 자신이 작성한 글의 식별 번호 지정하기
    • 서버 URL : 로컬호스트/recipes
  • 자신의 글만 수정 할 수 있게 하기
    • 서버 URL : 로컬호스트/recipes/숫자(작성된 데이터)
  • 식별 정보(id)는 보안을 위해 토큰화
from flask import Flask
from flask_jwt_extended import JWTManager
from flask_restful import Api

from config import Config
from resources.recipe import RecipeListResource
from resources.recipe_info import RecipeResource

# API 서버를 구축하기 위한 기본 구조
app = Flask(__name__)

# 환경변수 셋팅
app.config.from_object(Config) # 만들었던 Config.py의 Config 클래스 호출

# JWT 토큰 생성
jwt = JWTManager(app)

# restfulAPI 생성
api = Api(app)

# 경로와 리소스(api코드) 연결
api.add_resource(RecipeListResource, '/recipes') # 목록 보기
api.add_resource(RecipeResource, '/recipes/<int:recipe_id>') # 특정 값 불러오기

if __name__ == '__main__' :
    app.run()

기능 설계 - 글을 작성하면 자신의 글로 소유권 지정하기

  • 추가 리소스 파일 : recipe.py
  • 클래스 RecipeListResource를 자원화
  • 토큰화된 식별 정보(id)의 데이터를 원복하여 DB에서 신원 확인
  • 글 작성시 식별 정보(id)를 지정하여 누구의 글인지 확인 가능
from flask import request
from flask_restful import Resource

import mysql.connector
from mysql_connection import get_connection

from flask_jwt_extended import get_jwt_identity, jwt_required

class RecipeListResource(Resource) :
    # 헤더 부분에 jwt_required()가 존재하지 않으면 get_jwt_identity가 작동하지 않음
    @jwt_required()
    def post(self) :
        data = request.get_json()

        # user_id의 토큰화 된 데이터를 다시 원복
        user_id = get_jwt_identity()
        try :
            connection = get_connection()
            query = '''
                    insert into recipe
                        (name, description, cook_time, direction, user_id)
                    values
                        (%s, %s, %s, %s, %s);
                    '''
            # 토큰화 원복한 데이터 값은 user_id, data로 받아오지 않았으므로 그대로 기재
            record = (data['name'], data['description'], data['cook_time'], data['direction'], user_id)
            cursor = connection.cursor()
            cursor.execute(query, record)
            connection.commit()
            cursor.close()
            connection.close()

        except mysql.connector.Error as e :
            print(e)
            cursor.close()
            connection.close()
            return {"error" : str(e)}, 503 #HTTPStatus.SERVICE_UNAVAILABLE

        return {"result" : "success"}, 200

POSTMAN - 글을 작성하면 자신의 글로 소유권 지정 테스트

API 서버 구축

  • POST- 로컬호스트/recipes
  • Authorization - 토큰 입력 (id)
    • 자신의 식별 아이디 (user_id) 기입(토큰화 된 데이터)하여 소유권을 지정
  • 로그인시 자신의 토큰을 이용하여 토큰으로 데이터 접근
  • 로그인의 토큰 설정은 아래의 포스팅에서 확인 가능
  • https://luvris2.tistory.com/196
 

API서버 - 회원을 DB에 등록하고 로그인을 할 수 있는 기능 구현하기

이번 포스팅은 DB의 user table을 이용하여 로그인을 위한 회원 등록을 하고, 로그인하는 기능을 서술합니다. 보안을 위해 유저의 식별 가능한 id는 토큰화하며 입력한 비밀번호는 암호화하여 DB에

luvris2.tistory.com

 

  • 자신의 식별 id와 함께 작성한 글을 DB에 저장
    • Authorization 토큰 지정 : Bearer 토큰 / Body :생성할 값 입력


MySQL

  • 값을 넣기 이전의 DB

 

  • user_id의 값이 1인 유저의 데이터 입력
    • user_id 가 1임을 확인


Visual Studio Code

기능 설계 - 자신이 작성한 글 수정하기

  • 추가 리소스 파일 : recipe_info.py
  • 클래스 RecipeResource를 자원화
  • 회원 식별 ID 토큰화된 데이터 원복하여 DB에서 신원 확인
  • 식별 ID를 이용하여 자신의 글인지 확인하여 맞을 경우 수정하는 기능
from flask import request
from flask_restful import Resource
from flask_jwt_extended import get_jwt_identity, jwt_required

import mysql.connector
from mysql_connection import get_connection


class RecipeResource(Resource) :
	@jwt_required()
    def put(self, recipe_id) :
        data = request.get_json()
        
        try :
            connection = get_connection()
            user_id = get_jwt_identity()

            # recipe_id = user_id 확인
            query = '''select user_id from recipe where id = %s;'''
            record = (recipe_id, )
            cursor = connection.cursor(dictionary = True)
            cursor.execute(query, record)
            result_list = cursor.fetchall()
            recipe = result_list[0]
            
            # user_id가 다를 경우 수정 불가
            if recipe['user_id'] != user_id :
                cursor.close()
                connection.close()
                return { "error" : "님의 레시피를 수정할 수 없습니다."}

            query = '''
                    update recipe set
                        name=%s, description=%s, cook_time=%s, direction=%s
                    where id = %s;
                    '''
            record = (data['name'], data['description'], data['cook_time'], data['direction'], recipe_id)
            cursor = connection.cursor()
            cursor.execute(query, record)
            connection.commit()
            cursor.close()
            connection.close()

        except mysql.connector.Error as e :
            print(e)
            cursor.close()
            connection.close()
            return {"error" : str(e)}, 503 #HTTPStatus.SERVICE_UNAVAILABLE

        return {"result" : "success"}, 200

POSTMAN - 자신의 글 수정하기 테스트

API 서버 구축

  • POST- 로컬호스트/recipes/작성된 데이터 번호
  • Authorization - 토큰 입력 (id)
    • 자신의 식별 아이디 (user_id)를 기입(토큰화 된 데이터)하여 자신의 글인지 확인
  • 로그인시 자신의 토큰을 이용하여 토큰으로 데이터 접근
  • 로그인의 토큰 설정은 아래의 포스팅에서 확인 가능
  • 자신의 식별 id를 이용하여 DB의 글 수정
    • Authorization 토큰 지정 : Bearer 토큰 / Body :수정 할 값 입력

 

다른 유저(토큰 변경)가 글을 수정시 에러 문구 출력

  • 다른 유저로 로그인 후 토큰 확인

 

  • 작성자 소유권 확인

 

  • 다른 유저의 식별 id를 이용하여 DB의 글 수정
    • Authorization 토큰 지정 : Bearer 토큰 / Body :수정 할 값 입력
    • 에러 출력


MySQL 토큰으로 식별(user_id)하여 데이터 수정하기

  • 수정 전

 

  • 토큰으로 user_id 식별하여 수정