Skip to content

Commit f9d3944

Browse files
committed
token api request
1 parent f6cd9a9 commit f9d3944

12 files changed

Lines changed: 63 additions & 154 deletions

File tree

Pipfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ marshmallow-jsonapi = "*"
2020
flask-script = "*"
2121
flask-basicauth = "*"
2222
pyjwt = "*"
23-
bcrypt = "*"
23+
flask-bcrypt = "*"
2424

2525
[requires]
2626
python_version = "3.7"

Pipfile.lock

Lines changed: 8 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

app/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@
1212

1313
SQLALCHEMY_DATABASE_URI = \
1414
("mysql+pymysql://{USER}:{PASSWORD}@{ADDR}:{PORT}/{NAME}?charset=utf8")
15-
15+
1616
# 설명할 API에 대한 것
1717
MA = Marshmallow()
18+
1819
def create_app() -> (Flask):
1920
""" create_app() 함수를 호출해 앱을 초기화 """
2021

app/api/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
from app.posts.views import API as posts_api
44
from app.api.auth_type import ACCESS_TOKEN, BASIC_AUTH
55

6-
76
REST_API = Api(authorizations={**ACCESS_TOKEN, **BASIC_AUTH})
87

98
REST_API.add_namespace(users_api, '/user')
10-
REST_API.add_namespace(posts_api, '/posts')
9+
REST_API.add_namespace(posts_api, '/posts')

app/api/auth_type.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
from flask import request
2+
from functools import wraps
3+
import jwt
4+
15
SECERET_KEY = "Hello"
26
ACCESS_TOKEN = {
37
'Access Token': {
@@ -12,4 +16,25 @@
1216
'in': 'header',
1317
'name': 'Authorization'
1418
},
15-
}
19+
}
20+
21+
def login_required(f):
22+
@wraps(f)
23+
def decorated_function(*args, **kwargs):
24+
access_token = request.headers['Authorization']
25+
if access_token is not None:
26+
try:
27+
payload = jwt.decode(access_token, SECERET_KEY, "HS256")
28+
except jwt.InvalidTokenError:
29+
payload = None
30+
31+
# if payload is None:
32+
# return Response(status=401)
33+
34+
user_id = payload["user_id"]
35+
# g.user = get_user_info(user_id) if user_id else None
36+
else:
37+
return Response(status=401)
38+
39+
return f(*args, **kwargs)
40+
return decorated_function

app/posts/views.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
from app.constants import GET, POST, PATCH, DELETE
99
from app.posts.models import Post, PostSchema
1010
from app.api.database import DB
11+
from app.api.auth_type import login_required
12+
from app.api.auth_type import BASIC_AUTH, ACCESS_TOKEN, SECERET_KEY
1113

1214
API = Namespace('Posts', description="Post's REST API")
1315

@@ -32,6 +34,8 @@ class Posts(Resource):
3234
parser.add_argument('author_id', required=True, type=int,
3335
help="post's author", location='json')
3436

37+
@API.doc(responses=GET, security=ACCESS_TOKEN)
38+
@login_required
3539
def get(self):
3640
try:
3741
posts_query = Post.query.all()

app/users/views.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
import jwt
3-
import bcrypt
43
import datetime
4+
import bcrypt
55
from http import HTTPStatus
66
from flask import jsonify
77
from flask import make_response
@@ -13,6 +13,7 @@
1313
from app.constants import GET, POST, PATCH, DELETE
1414
from app.api.database import DB
1515
from app.api.auth_type import BASIC_AUTH, ACCESS_TOKEN, SECERET_KEY
16+
from app.api.auth_type import login_required
1617

1718
API = Namespace('Users', description="User's REST API")
1819

@@ -75,6 +76,7 @@ class UsersList(Resource):
7576
'password': fields.String
7677
})
7778
@API.doc(responses=GET, security=ACCESS_TOKEN)
79+
@login_required
7880
def get(self):
7981
users_query = Users.query.all()
8082
results = USERS_SCHEMA.dump(users_query, many=True).data
@@ -83,7 +85,10 @@ def get(self):
8385
@API.expect(user_field)
8486
def post(self):
8587
args = self.parser.parse_args()
86-
user = Users(args['name'], args['email'], args['password'])
88+
temp = args['password']
89+
hash_pw = bcrypt.hashpw(temp.encode(), bcrypt.gensalt())
90+
t1 = bcrypt.checkpw(temp.encode(), hash_pw)
91+
user = Users(args['name'], args['email'], hash_pw)
8792
try:
8893
DB.session.add(user)
8994
DB.session.commit()
@@ -110,20 +115,19 @@ class GetUser(Resource):
110115
'password': fields.String
111116
})
112117

113-
@API.doc(responses=POST, security=ACCESS_TOKEN)
118+
@API.doc(responses=POST)
114119
@API.expect(user_field)
115120
def post(self):
116121
args = self.parser.parse_args()
117122
try:
118-
#, Users.password == args['password']
119123
user = Users.query.filter(Users.name == args['name']).first()
120-
if bcrypt.checkpw(args['password'].encode("UTF-8"), user.password.encode("UTF-8")):
124+
if bcrypt.checkpw(args['password'].encode('utf-8'), user.password.encode('utf-8')):
121125
#여기서 이제 토큰 발급해서 보내주기
122126
payload = {
123-
"exp" : str(datetime.date.today())
127+
'user_id' : user.name
124128
}
125129
token = jwt.encode(payload, SECERET_KEY, "HS256")
126-
body = jsonify({"access_token": token.decode("UTF-8"), "user": USERS_SCHEMA.dump(user).data})
130+
body = jsonify({"access_token": token.decode('utf-8'), "user": {"id" : user.id}})
127131
if user:
128132
code = HTTPStatus.OK
129133
else:

migrations/versions/42d37d473148_.py

Lines changed: 0 additions & 28 deletions
This file was deleted.

migrations/versions/76e0c583e527_.py

Lines changed: 0 additions & 30 deletions
This file was deleted.
Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
"""empty message
22
3-
Revision ID: b25fcdb3cfcc
3+
Revision ID: 9e7208e2f6e8
44
Revises:
5-
Create Date: 2019-07-19 21:28:12.190440
5+
Create Date: 2019-07-22 11:02:10.139072
66
77
"""
88
from alembic import op
99
import sqlalchemy as sa
1010

1111

1212
# revision identifiers, used by Alembic.
13-
revision = 'b25fcdb3cfcc'
13+
revision = '9e7208e2f6e8'
1414
down_revision = None
1515
branch_labels = None
1616
depends_on = None
@@ -25,13 +25,16 @@ def upgrade():
2525
sa.Column('password', sa.String(length=255), nullable=False),
2626
sa.Column('created', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
2727
sa.PrimaryKeyConstraint('id'),
28-
sa.UniqueConstraint('email'),
28+
sa.UniqueConstraint('name'),
2929
mysql_collate='utf8_general_ci'
3030
)
31-
op.create_table('teams',
31+
op.create_table('posts',
3232
sa.Column('id', sa.Integer(), nullable=False),
33-
sa.Column('name', sa.String(length=255), nullable=False),
3433
sa.Column('author_id', sa.Integer(), nullable=True),
34+
sa.Column('name', sa.String(length=255), nullable=False),
35+
sa.Column('title', sa.String(length=255), nullable=False),
36+
sa.Column('body', sa.String(length=1024), nullable=False),
37+
sa.Column('created', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
3538
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),
3639
sa.PrimaryKeyConstraint('id'),
3740
mysql_collate='utf8_general_ci'
@@ -41,6 +44,6 @@ def upgrade():
4144

4245
def downgrade():
4346
# ### commands auto generated by Alembic - please adjust! ###
44-
op.drop_table('teams')
47+
op.drop_table('posts')
4548
op.drop_table('users')
4649
# ### end Alembic commands ###

0 commit comments

Comments
 (0)