-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
トークン発行API #12
Merged
Merged
トークン発行API #12
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
51a443d
トークン認証機能/ユーザーテーブル/作成
furutahidehiko 704c674
Merge remote-tracking branch 'origin' into feature/auth
furutahidehiko 5fe6c14
lintの指摘修正
furutahidehiko e24cdf1
fixtureのデータ追加/load_jsonの修正
furutahidehiko b47bc6b
application/migrations/versions/ae357bab00d5_.py
furutahidehiko f5d451f
不要なコメントアウトアウト削除
furutahidehiko 45b7212
処理分割とリフレッシュトークンによる認証
furutahidehiko 7e9e0bb
シークレットキー追加/readme修正
furutahidehiko 9115af5
fix: userモデルにemailカラム追加/認証処理リファクタリング/fixturesデータ修正/router修正
furutahidehiko a3fa691
リファクタリング
furutahidehiko 3480947
変数名をuser_idからemailに修正
furutahidehiko 519f929
不要なコメントアウト削除
furutahidehiko 83a447b
👍 :bcryptを利用してパスワードをハッシュ化
furutahidehiko ed0c439
🚿 :passlibライブラリ削除
furutahidehiko 90803fd
👍 :テストユーザーのパスワードのfixture修正
furutahidehiko cc55a84
♻️ : formatter適用
furutahidehiko File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
"""このモジュールは、トークン認証の機能を提供します.""" | ||
from typing import Optional | ||
|
||
from fastapi import HTTPException, status | ||
from jose import JWTError, jwt | ||
from sqlalchemy.ext.asyncio import AsyncSession | ||
|
||
from config.environment import jwt_settings | ||
from crud import get_user | ||
from domain.user.token import create_token | ||
from models.user import User | ||
from schemas.user import AuthUserResponse | ||
|
||
|
||
async def auth_password( | ||
email: str, | ||
password: str, | ||
async_session: AsyncSession, | ||
) -> AuthUserResponse: | ||
"""id/passwordによる認証を行う関数. | ||
|
||
Parameters: | ||
- auth_data (AuthUserModel): 認証するためユーザー情報。 | ||
- async_session (AsyncSession): DBとのセッション。 | ||
|
||
Returns: | ||
- create_tokenのレスポンス | ||
""" | ||
|
||
def authenticate_user(user: Optional[User]): | ||
if user is None: | ||
return False | ||
return user.check_password(password) | ||
|
||
user = await get_user(async_session, email) | ||
|
||
if not authenticate_user(user): | ||
raise HTTPException( | ||
status_code=status.HTTP_400_BAD_REQUEST, | ||
detail={ | ||
"error": "bad_request", | ||
"error_description": "メールアドレスかpasswordが異なります", | ||
}, | ||
) | ||
|
||
return await create_token(user.id) | ||
|
||
|
||
async def auth_token(refresh_token: str) -> AuthUserResponse: | ||
"""リフレッシュトークンによる認証を行う関数. | ||
|
||
Parameters: | ||
- auth_data (AuthUserModel): 認証するためのユーザー情報。 | ||
|
||
Returns: | ||
- AuthUserResponse: アクセストークン及びリフレッシュトークン。 | ||
""" | ||
try: | ||
payload = jwt.decode( | ||
refresh_token, | ||
jwt_settings.JWT_SECRET_REFRESH_KEY, | ||
algorithms=jwt_settings.JWT_ALGORITHM, | ||
) | ||
user_id = payload.get("sub") | ||
if user_id is None: | ||
raise HTTPException( | ||
status_code=status.HTTP_401_UNAUTHORIZED, | ||
detail={ | ||
"error": "unknown_user", | ||
"error_description": "不明なユーザーです", | ||
}, | ||
) | ||
except JWTError: | ||
raise HTTPException( | ||
status_code=status.HTTP_401_UNAUTHORIZED, | ||
detail={ | ||
"error": "invalid_token", | ||
"error_description": "アクセストークンの有効期限切れです。", | ||
}, | ||
) | ||
|
||
return await create_token(str(user_id)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
"""このモジュールは、トークン認証の機能を提供します.""" | ||
from datetime import datetime, timedelta | ||
from zoneinfo import ZoneInfo | ||
|
||
from jose import jwt | ||
|
||
from config.environment import jwt_settings | ||
from schemas.user import AuthUserResponse | ||
|
||
|
||
async def create_token(user_id: str) -> AuthUserResponse: | ||
"""アクセストークン及びリフレッシュトークンを生成する関数. | ||
|
||
Parameters: | ||
- auth_data (AuthUserModel): 認証するためのユーザー情報。 | ||
|
||
Returns: | ||
- AuthUserResponse: アクセストークン及びリフレッシュトークン。 | ||
""" | ||
hours = timedelta(hours=jwt_settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES) | ||
month = timedelta(days=jwt_settings.JWT_REFRESH_TOKEN_EXPIRE_MINUTES) | ||
expire = datetime.now(ZoneInfo("Asia/Tokyo")) + hours | ||
refresh_expire = datetime.now(ZoneInfo("Asia/Tokyo")) + month | ||
access_token = jwt.encode( | ||
{"sub": str(user_id), "exp": expire}, | ||
jwt_settings.JWT_SECRET_ACCESS_KEY, | ||
algorithm=jwt_settings.JWT_ALGORITHM, | ||
) | ||
refresh_token = jwt.encode( | ||
{"sub": str(user_id), "exp": refresh_expire}, | ||
jwt_settings.JWT_SECRET_REFRESH_KEY, | ||
algorithm=jwt_settings.JWT_ALGORITHM, | ||
) | ||
return AuthUserResponse( | ||
access_token=access_token, refresh_token=refresh_token | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
"""CustomerテーブルのORM.""" | ||
from sqlalchemy import String | ||
from sqlalchemy.orm import Mapped, mapped_column | ||
|
||
from models.base import Base, PasswordMixin | ||
|
||
|
||
class User(Base, PasswordMixin): | ||
"""ユーザーテーブルのORM.""" | ||
|
||
__tablename__ = "user" | ||
|
||
email: Mapped[str] = mapped_column( | ||
String(254), nullable=False, unique=True, comment="メールアドレス" | ||
) |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,7 +13,6 @@ asyncpg = "^0.28.0" | |
alembic = "^1.12.0" | ||
ulid-py = "^1.1.0" | ||
bcrypt = "^4.0.1" | ||
passlib = { version = "^1.7.4", extras = ["bcrypt"] } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [memo] |
||
python-multipart = "^0.0.6" | ||
python-jose = { version = "^3.3.0", extras = ["cryptography"] } | ||
beautifulsoup4 = "^4.12.3" | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[memo]
設定したパスワード(userテーブルに保存されたデータ)と入力されたパスワードが一致しているか確認するためにエンコードする。
bcrypt.checkpwでinput_password_hash(入力されたパスワード)とhashed_password (設定したパスワード)の突き合わせを実施