Tangerine-Authは、ユーザー認証とキーと暗号化されたデータの安全な取り扱いのためのユーティリティを提供するPythonライブラリです。パスワードハッシュにBCRYPTを使用し、トークンベースの認証にはJWTを使用します。
注:Tangerine-Authは現在ベータ版です。生産の使用にはまだ推奨されていません。その間に自由にダウンロードして遊んでください!さらにテストとドキュメントの追加に取り組んでいます。バグが見つかったり、提案がある場合は、GitHubで問題を開いてください。
PIPを使用してパッケージをインストールします。
pip install tangerine-authYuzuをアプリケーションに統合するための一般的な手順は次のとおりです。
def get_user_by_email ( email ):
conn = psycopg2 . connect ( "postgresql://postgres:<your postgres password>@localhost:5432/local_development" )
cur = conn . cursor ()
cur . execute ( "SELECT * FROM tangerine.users WHERE email = %s" , ( email ,))
user = cur . fetchone ()
cur . close ()
conn . close ()
if user :
return { '_id' : user [ 0 ], 'email' : user [ 1 ], 'password' : user [ 2 ]}
else :
return None
def create_user ( user_data ):
conn = psycopg2 . connect ( "postgresql://<your postgres password>@localhost:5432/local_development" )
cur = conn . cursor ()
cur . execute ( "INSERT INTO tangerine.users (email, password) VALUES (%s, %s) RETURNING id" , ( user_data [ 'email' ], user_data [ 'password' ]))
user_id = cur . fetchone ()[ 0 ]
conn . commit ()
cur . close ()
conn . close ()
return { '_id' : user_id , 'email' : user_data [ 'email' ], 'password' : user_data [ 'password' ]}キーライムオブジェクトを作成し、ゆうコンストラクターに渡します。キーライムオブジェクトは、キーと暗号化されたデータを安全に処理するために使用されます。キーライムオブジェクトを使用して、データを暗号化および復号化し、キーを保存および取得することができます。
Yuzuオブジェクトを作成し、キーライムオブジェクト、データベース内のユーザーを見つける機能、およびデータベースでユーザーを作成する機能を渡します。
(オプション)YuzuはBcryptからハッシュパスワードを使用します。オプションで、Yuzuコンストラクターにカスタムハッシュ関数を渡すことができます。カスタムハッシュ関数は、パスワード文字列を引数として使用し、ハッシュされたパスワード文字列を返します。
ステップ3が完了した後、Yuzuオブジェクトを使用して新しいユーザーにサインアップし、ユーザーにログインし、ユーザーをログアウトし、認証トークンを確認できます。
Yuzuは、タンジェリンだけでなくFlaskを使用するように構築されました。現在、2つのJWTミドルウェアがYuzuにバンドルされ、1つはフラスコ用、もう1つはタンジェリン用です。 Yuzuクラスを適切に初期化したら、Tangerine Middlewareを使用して使用できます。
app . use ( auth . jwt_middleware ).FlaskバージョンのJWTミドルウェアはまだ実験的であり、問題が発生しやすい可能性があります。より徹底的にテストされるまで、生産の使用には推奨されません。 JWTミドルウェアはフラスコで少し異なります。フラスコで使用するために、デコレーターとして使用します。
from flask import Flask
from yuzu import Yuzu
app = Flask ( __name__ )
def get_user_by_email ( email ):
# Logic to create user in DB
pass
def create_user ( user_data ):
# Logic to create user in DB
pass
auth = Yuzu ( keychain , get_user_by_email , create_user ) # Fill with your functions
@ app . route ( '/secure_route' )
@ auth . flask_jwt_middleware ( auth )
def secure_route ():
# Your secure code here. This will only run if the JWT is valid.
return "This is a secure route"
if __name__ == "__main__" :
app . run ( debug = True )注:AUTHミドルウェアは、ユーザーデータをCTXオブジェクトに追加します。通話して、ルートハンドラーのユーザーデータにアクセスできます
ctx . auth . user or ctx . get ( "user" )Yuzuは、ユーザー認証機能を提供するクラスです。パスワードハッシュとJWTにBCRYPTを使用して、認証トークンを作成および検証します。
以下は、Yuzuクラスの重要な方法です。
- `__init__(self, keychain, get_user_by_email, create_user, hash_func: Optional[Callable] = None)` : Initializes the Yuzu object .
- `get_config(self, key_name: str) -> str` : Fetches the configuration value for a given key .
- `authenticate(self, email: str, password: str) -> bool` : Checks if the given email and password are valid .
- `generate_auth_token(self, user_id: str, email: str) -> str` : Generates an authentication token for the given user .
- `verify_auth_token(self, token: str) -> dict` : Verifies if the given authentication token is valid .
- `sign_up(self, user_data: dict) -> dict` : Signs up a new user with the given user data .
- `login(self, email: str, password: str) -> Tuple[str, str]` : Logs in a user with the given email and password .
- `logout(self)` : Logs out the current user .
- `jwt_middleware()` : Tangerine middleware for JWT authentication .
- `flask_jwt_middleware(yuzu_instance)` : Flask middleware for JWT authentication .KeyLimeは、キーと暗号化されたデータを安全に処理する機能を提供するクラスです。
以下は、キーライムクラスの重要な方法です。
- `__init__(self, keychain: Dict[str, bytes] = {})` : Initializes the KeyLime object .
- `add_key(self, key_name: str, key: bytes)` : Adds a key to the keychain .
- `remove_key(self, key_name: str)` : Removes a key from the keychain .
- `get_key(self, key_name: str) -> bytes` : Fetches a key from the keychain .
- `encrypt(self, key_name: str, message: str) -> str` : Encrypts a given message using a key from the keychain .
- `decrypt(self, key_name: str, cipher_text: str) -> str` : Decrypts a given cipher text using a key from the keychain .これの一般的なconeptは、選択したデータベースシステムでユーザーを見つけるための2つの機能を記述したいということです。1つは選択したデータベースシステムでユーザーを作成するためです。これらの関数は、ユーザーデータの辞書を引数として取得し、ユーザーデータの辞書を返す必要があります。ユーザーデータ辞書には、少なくとも電子メールとパスワードのフィールドが含まれている必要があります。ユーザーデータ辞書には、データベースに保存する他のフィールドを含めることができます。
YuzuとKeylimeクラスの使用方法の例は次のとおりです。
from tangerine import Tangerine , Ctx , Router
from pymongo import MongoClient
from tangerine . key_lime import KeyLime
from tangerine . yuzu import Yuzu
import json
import jwt
import hashlib
app = Tangerine ( debug_level = 1 )
client = MongoClient ( 'mongodb://localhost:27017/' )
keychain = KeyLime ({
"SECRET_KEY" : "ILOVECATS" ,
})
def get_user_by_email ( email ):
db = client [ 'mydatabase' ]
users = db [ 'users' ]
query = { 'email' : email }
user = users . find_one ( query )
if user :
user [ '_id' ] = str ( user [ '_id' ]) # Convert ObjectId to string
return user
def create_user ( user_data ):
db = client [ 'mydatabase' ]
users = db [ 'users' ]
result = users . insert_one ( user_data )
if result . inserted_id :
user_data [ '_id' ] = str ( result . inserted_id ) # Convert ObjectId to string
return user_data
auth = Yuzu ( keychain , get_user_by_email , create_user )
# serve static files to any request not starting with /api
app . static ( '^/(?!api).*$' , './public' )
# This is how you define a custom middleware.
def hello_middle ( ctx : Ctx , next ) -> None :
ctx . hello_message = json . dumps ({ "message" : "Hello from middleware!" })
next ()
# ==================== AUTH HANDLERS ====================
def api_hello_world ( ctx : Ctx ) -> None :
ctx . body = ctx . hello_message
ctx . send ( 200 , content_type = 'application/json' )
def signup ( ctx : Ctx ) -> None :
user_data = ctx . request . body
created_user = auth . sign_up ( user_data )
if created_user :
ctx . body = json . dumps ( created_user )
ctx . send ( 201 , content_type = 'application/json' )
else :
ctx . send ( 500 , content_type = 'application/json' )
def login ( ctx : Ctx ) -> None :
user_data = ctx . request . body
email = user_data [ 'email' ]
password = user_data [ 'password' ]
user_id , token = auth . login ( email , password )
print ( ctx . user , "HELLO FROM LOGIN" )
if token :
ctx . body = json . dumps ({ "message" : "Logged in successfully" , "token" : token })
ctx . set_res_header ( "Set-Cookie" , f"auth_token= { token } ; HttpOnly; Path=/" )
ctx . send ( 200 , content_type = 'application/json' )
# Set the token as a cookie or in the response headers
else :
ctx . body = json . dumps ({ "message" : "Invalid credentials" })
ctx . send ( 401 , content_type = 'application/json' )
def logout ( ctx : Ctx ) -> None :
auth . logout ( ctx )
ctx . body = json . dumps ({ "message" : "Logged out successfully" })
ctx . send ( 200 , content_type = 'application/json' )
@ Router . auth_required
def get_protected_content ( ctx : Ctx ) -> None :
ctx . body = json . dumps ({ "message" : "This is protected content. Only authenticated users can see this. I hope you feel special ???." })
ctx . send ( 200 , content_type = 'application/json' )
# ==================== API ROUTES ====================
# if you need to bind more variables to your handler, you can pass in a closure
api_router = Router ( prefix = '/api' )
api_router . post ( '/logout' , logout )
api_router . post ( '/login' , login )
api_router . post ( '/signup' , signup )
api_router . get ( '/hello' , api_hello_world )
# api_router.get('/users', get_and_delete_users)
api_router . get ( '/protected' , get_protected_content )
app . use ( hello_middle )
app . use ( auth . jwt_middleware )
app . use_router ( api_router )
app . start ()Yuzuは柔軟性があるように設計されており、プロジェクトの特定のニーズに適応させることができます。動作をカスタマイズできる1つの方法は、デフォルトのパスワードのハッシュおよび検証関数を変更することです。
デフォルトでは、Yuzuはbcryptライブラリを使用してパスワードのハッシュと検証を使用しています。別のアプローチを使用したい場合は、独自のハッシュと検証機能をYuzuクラスコンストラクターに渡すことができます。これがそれを行う方法の例です:
import hashlib
def my_hash_func ( password : str , salt : str = None ) -> str :
return hashlib . sha256 ( password . encode ()). hexdigest ()
def my_check_password_func ( password : str , hashed_password : str , salt : str = None ) -> bool :
return hashlib . sha256 ( password . encode ()). hexdigest () == hashed_password
auth = Yuzu ( keychain , get_user_by_email , create_user , hash_func = my_hash_func , checkpw_func = my_check_password_func )Argon2を使用すると、Argon2は、パスワードハッシュコンペティションで推奨される最新の安全なパスワードハッシュアルゴリズムです。これがYuzuでそれを使用する方法の例です:
from argon2 import PasswordHasher , exceptions
ph = PasswordHasher ( time_cost = 16 , memory_cost = 65536 )
def my_hash_func ( password : str , salt : str = None ) -> str :
return ph . hash ( password )
def my_check_password_func ( password : str , hashed_password : str , salt : str = None ) -> bool :
try :
return ph . verify ( hashed_password , password )
except exceptions . VerifyMismatchError :
return False
auth = Yuzu ( keychain , get_user_by_email , create_user , hash_func = my_hash_func , checkpw_func = my_check_password_func )これらの例では、デフォルトのBCRYPTアルゴリズムからSHA256またはArgon2に切り替えることができます。また、これらの関数を変更して、特定の要件に従ってハッシュ関数の難易度(例えば、反復数またはメモリ使用量を増やすことにより)を変更することもできます。
これらの機能を変更すると、アプリケーションのセキュリティに影響を与える可能性があることを忘れないでください。決定を下す前に、選択したハッシュ関数の動作とその長所と短所を理解する必要があります。