import bcrypt
import jwt

 

해시

import hashlib 
m = hashlib.sha256()
m.update(b"test password")
a = m.hexdigest()
print(a)
print(m)

 

jwt

import jwt
data_to_encode = {'some':'payload'}
encryption_secret = 'secrete'
algorithm = 'HS256'
encoded = jwt.encode(data_to_encode,encryption_secret,algorithm=algorithm)
print(encoded)

decode = jwt.decode(encoded,encryption_secret,algorithm=[algorithm])
print(decode)

 

구현

@app.route("/sign-up", methods=['POST'])
    def sign_up():
        new_user    = request.json
        # bcrypt
        new_user["password"] = bcrypt.hashpw(password=new_user["password"].encode("utf-8"), #2
                                             salt=bcrypt.gensalt())
        new_user_id = insert_user(new_user)
        new_user    = get_user(new_user_id)

        return jsonify(new_user)
        
        
  @app.route("/login", methods=["POST"])
    def login():
        credential = request.sjon
        email = credential["email"] 
        password = credential["password"] 
        user_credential = get_user_id_and_password(email) 
        

        if user_credential and bcrypt.checkpw(password=password.encode("utf-8"),
                                              hashed_password=user_credential["hashed_password"].encode("utf-8")): 
            user_id = user_credential["id"]
            payload = { 
                "user_id": user_id,
                "exp": datetime.utcnow() + timedelta(seconds = 60 * 60 * 24)
            }

            token = jwt.encode(payload=payload, 
                               key=app.config["JWT_SECRET_KEY"],
                               algorithm="HS256")

            return jsonify({ 
                "access_token": token.decode("utf-8") 
            }) 
        else:
            return "", 401 
#########################################################
#       Decorators
#########################################################
def login_required(f): 
    @wraps(f) 
    def decorated_function(*args, **kwargs):
        access_token = request.headers.get('Authorization') 
        if access_token is not None: 
            try:
                payload = jwt.decode(access_token, current_app.config['JWT_SECRET_KEY'], #5
                                     'HS256')
            except jwt.InvalidTokenError:
                 payload = None 

            if payload is None:
                return Response(status=401) 

            user_id = payload['user_id'] 
            g.user_id = user_id
            g.user = get_user(user_id) if user_id else None
        else:
            return Response(status=401) 
        return f(*args, **kwargs)
    return decorated_function

 

 

테스트

로그인

$ http -v POST http://localhost:5000/login email=test@naver.com password=123
POST /login HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 46
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "email": "test@naver.com",
    "password": "123"
}


HTTP/1.0 200 OK
Content-Length: 146
Content-Type: application/json
Date: Mon, 01 Mar 2021 05:08:12 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE2MTQ2NjE2OTJ9.JdL30bXdicc7dDDxJIfLfjSgRIqviCdHlRJxZt37A0o"
}

 

tweet

http -v POST http://localhost:5000/tweet tweet="heello" id=5 "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE2MTQ2NjEzMzJ9.Kb81rS_zD23f2PtIs27PVi5BVn5pwWvHkZx9e4ZDFi8"
POST /tweet HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE2MTQ2NjEzMzJ9.Kb81rS_zD23f2PtIs27PVi5BVn5pwWvHkZx9e4ZDFi8
Connection: keep-alive
Content-Length: 30
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "id": "5",
    "tweet": "heello"
}


HTTP/1.0 200 OK
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Mon, 01 Mar 2021 05:07:15 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

 

db

mysql> select * from users
    -> ;
+----+--------+---------------+-----------------+---------+---------------------+------------+
| id | name   | email         | hashed_password | profile | created_at          | updated_at |
+----+--------+---------------+-----------------+---------+---------------------+------------+
|  1 | 어피치 | 123@gmail.com | 1234            | HI~     | 2021-02-21 13:07:45 | NULL       |
|  4 | 라이언 | 456@gmail.com | 12345           | HI~     | 2021-02-21 13:09:09 | NULL       |
+----+--------+---------------+-----------------+---------+---------------------+------------+
2 rows in set (0.01 sec)

mysql> select * from users;
+----+--------+----------------+--------------------------------------------------------------+---------+---------------------+------------+
| id | name   | email          | hashed_password                                              | profile | created_at          | updated_at |
+----+--------+----------------+--------------------------------------------------------------+---------+---------------------+------------+
|  1 | 어피치 | 123@gmail.com  | 1234                                                         | HI~     | 2021-02-21 13:07:45 | NULL       |
|  4 | 라이언 | 456@gmail.com  | 12345                                                        | HI~     | 2021-02-21 13:09:09 | NULL       |
|  5 | 현욱   | test@naver.com | $2b$12$FRXLTbPVmqumaKtBHgRWbeNPkQx4V/Up1UcY0dxsjboaQMafK5iX6 | tester  | 2021-03-01 13:55:16 | NULL       |
+----+--------+----------------+--------------------------------------------------------------+---------+---------------------+------------+
3 rows in set (0.00 sec)

mysql> select * from tweets;
+----+---------+-----------------------------------------+---------------------+
| id | user_id | tweet                                   | created_at          |
+----+---------+-----------------------------------------+---------------------+
|  4 |       4 | My first tweet!                         | 2021-02-21 12:34:58 |
|  7 |       5 | Hello World                             | 2021-02-21 13:02:51 |
| 10 |       1 | Hello World                             | 2021-02-21 13:09:37 |
| 11 |       4 | 언젠가는 훌륭한 백엔드 개발자가 될 거야 | 2021-02-21 13:09:40 |
| 12 |       1 | My first Tweet                          | 2021-02-21 13:19:32 |
+----+---------+-----------------------------------------+---------------------+
5 rows in set (0.01 sec)

mysql> select * from tweets;
+----+---------+-----------------------------------------+---------------------+
| id | user_id | tweet                                   | created_at          |
+----+---------+-----------------------------------------+---------------------+
|  4 |       4 | My first tweet!                         | 2021-02-21 12:34:58 |
|  7 |       5 | Hello World                             | 2021-02-21 13:02:51 |
| 10 |       1 | Hello World                             | 2021-02-21 13:09:37 |
| 11 |       4 | 언젠가는 훌륭한 백엔드 개발자가 될 거야 | 2021-02-21 13:09:40 |
| 12 |       1 | My first Tweet                          | 2021-02-21 13:19:32 |
| 13 |       5 | heello                                  | 2021-03-01 14:07:15 |
+----+---------+-----------------------------------------+---------------------+
6 rows in set (0.00 sec)
반응형

'SW ENGINEERING > Flask' 카테고리의 다른 글

서버사이드 렌더링 vs 클라이언트 사이드 렌더링  (0) 2021.02.25
XSS  (0) 2021.02.25
보안 점검 SQL Injection  (0) 2021.02.24
API 개발하기(16) - DB Schema  (0) 2021.02.21
API 개발하기(15) - REFACTORING  (0) 2021.02.21
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기