Tangerine-Auth เป็นไลบรารี Python ที่ให้บริการยูทิลิตี้สำหรับการตรวจสอบสิทธิ์ของผู้ใช้และการจัดการคีย์ที่ปลอดภัยและข้อมูลที่เข้ารหัส มันใช้ BCRYPT สำหรับการแฮชรหัสผ่านและ JWT สำหรับการตรวจสอบความถูกต้องตามโทเค็น
หมายเหตุ: Tangerine-Auth อยู่ในช่วงเบต้า ยังไม่แนะนำสำหรับการใช้งานการผลิต โปรดอย่าลังเลที่จะดาวน์โหลดและเล่นกับมันในระหว่างนี้! เรากำลังดำเนินการเพื่อเพิ่มการทดสอบและเอกสารเพิ่มเติม หากคุณพบข้อบกพร่องใด ๆ หรือมีคำแนะนำใด ๆ โปรดเปิดปัญหาเกี่ยวกับ GitHub
ใช้ PIP เพื่อติดตั้งแพ็คเกจ:
pip install tangerine-authขั้นตอนทั่วไปในการรวมยูซุเข้ากับแอปพลิเคชันของคุณมีดังนี้:
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' ]}สร้างวัตถุ KeyLime และส่งผ่านไปยังตัวสร้าง Yuzu วัตถุ KeyLime ใช้สำหรับการจัดการคีย์และข้อมูลที่เข้ารหัสอย่างปลอดภัย คุณสามารถใช้วัตถุ KeyLime เพื่อเข้ารหัสและถอดรหัสข้อมูลและจัดเก็บและดึงกุญแจ
สร้างวัตถุ Yuzu และส่งผ่านวัตถุ KeyLime ฟังก์ชั่นสำหรับการค้นหาผู้ใช้ในฐานข้อมูลของคุณและฟังก์ชั่นสำหรับการสร้างผู้ใช้ในฐานข้อมูลของคุณ
(ไม่บังคับ) Yuzu ใช้รหัสผ่าน bcrypt เพื่อแฮช คุณสามารถเลือกใช้ฟังก์ชันแฮชแบบกำหนดเองไปยังคอนสตรัคเตอร์ยูซุ ฟังก์ชั่นแฮชแบบกำหนดเองควรใช้สตริงรหัสผ่านเป็นอาร์กิวเมนต์และส่งคืนสตริงรหัสผ่านแฮช
หลังจากขั้นตอนที่ 3 เสร็จสมบูรณ์ตอนนี้คุณสามารถใช้วัตถุ Yuzu เพื่อลงทะเบียนผู้ใช้ใหม่เข้าสู่ระบบผู้ใช้ออกจากระบบผู้ใช้และตรวจสอบโทเค็นการตรวจสอบสิทธิ์
Yuzu ถูกสร้างขึ้นเพื่อทำงานกับ Flask เช่นเดียวกับ Tangerine ปัจจุบันมี JWT Middlewares สองตัวที่รวมกับ Yuzu หนึ่งอันสำหรับ Flask และอีกอันสำหรับ Tangerine เมื่อคุณเริ่มต้นคลาส Yuzu อย่างถูกต้องแล้วคุณสามารถใช้มิดเดิลแวร์ส้มเขียวหวานได้โดยโทร:
app . use ( auth . jwt_middleware ).รุ่น Flask JWT Middleware ยังคงทดลองและอาจเป็นปัญหาได้ง่าย จะไม่แนะนำสำหรับการใช้งานการผลิตจนกว่าจะได้รับการทดสอบอย่างละเอียดมากขึ้น มิดเดิลแวร์ 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 Middleware ต่อท้ายข้อมูลผู้ใช้กับวัตถุ CTX คุณสามารถเข้าถึงข้อมูลผู้ใช้ในตัวจัดการเส้นทางของคุณโดยโทร
ctx . auth . user or ctx . get ( "user" )Yuzu เป็นคลาสที่ให้ฟังก์ชั่นการตรวจสอบผู้ใช้ มันใช้ bcrypt สำหรับการแฮชรหัสผ่านและ JWT สำหรับการสร้างและตรวจสอบโทเค็นการตรวจสอบความถูกต้อง
ด้านล่างนี้เป็นวิธีสำคัญของคลาส 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 เป็นคลาสที่ให้ฟังก์ชันสำหรับการจัดการคีย์และข้อมูลที่เข้ารหัสอย่างปลอดภัย
ด้านล่างนี้เป็นวิธีสำคัญของคลาส 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 ทั่วไปสำหรับเรื่องนี้คือคุณต้องการเขียนสองฟังก์ชั่นหนึ่งสำหรับการค้นหาผู้ใช้ในระบบฐานข้อมูลที่คุณเลือกและอีกหนึ่งสำหรับการสร้างผู้ใช้ในระบบฐานข้อมูลที่คุณเลือก ฟังก์ชั่นเหล่านี้ควรใช้พจนานุกรมข้อมูลผู้ใช้เป็นอาร์กิวเมนต์และส่งคืนพจนานุกรมข้อมูลผู้ใช้ พจนานุกรมข้อมูลผู้ใช้ควรมีฟิลด์อีเมลและรหัสผ่านอย่างน้อย พจนานุกรมข้อมูลผู้ใช้สามารถมีฟิลด์อื่น ๆ ที่คุณต้องการจัดเก็บในฐานข้อมูลของคุณ
นี่คือตัวอย่างของวิธีการใช้คลาส 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 ได้รับการออกแบบให้มีความยืดหยุ่นช่วยให้คุณสามารถปรับให้เข้ากับความต้องการเฉพาะของโครงการของคุณ วิธีหนึ่งที่คุณสามารถปรับแต่งพฤติกรรมของมันคือการเปลี่ยนฟังก์ชั่นการแฮชรหัสผ่านเริ่มต้นและฟังก์ชั่นการตรวจสอบ
โดยค่าเริ่มต้น 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 สำหรับ Hashing 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 นอกจากนี้คุณยังสามารถปรับเปลี่ยนฟังก์ชั่นเหล่านี้เพื่อเปลี่ยนความยากลำบากของฟังก์ชั่นแฮช (เช่นโดยการเพิ่มจำนวนการวนซ้ำหรือการใช้หน่วยความจำ) ตามข้อกำหนดเฉพาะของคุณ
โปรดจำไว้ว่าการเปลี่ยนฟังก์ชั่นเหล่านี้อาจมีผลกระทบต่อความปลอดภัยของแอปพลิเคชันของคุณ คุณควรเข้าใจการทำงานของฟังก์ชั่นแฮชที่เลือกและจุดแข็งและจุดอ่อนก่อนตัดสินใจ