Tangerine-Auth是一个Python库,可为用户身份验证和安全处理密钥和加密数据提供实用程序。它使用bcrypt进行密码哈希和JWT进行基于令牌的身份验证。
注意:橘色实施目前正在Beta中。不建议完全用于生产使用。同时,请随时下载并随身携带!我们正在努力添加更多测试和文档。如果您发现任何错误或有任何建议,请在Github上打开问题。
使用PIP安装软件包:
pip install tangerine-auth将Yuzu集成到您的应用程序中的一般步骤如下:
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对象并将其传递给键 - lime对象,数据库中的用户的功能以及在数据库中创建用户的功能。
(可选)Yuzu使用bcrypt进行哈希密码。您可以选择将自定义哈希功能传递给Yuzu构造函数。自定义哈希功能应将密码字符串作为参数,然后返回哈希的密码字符串。
步骤3完成后,您现在可以使用Yuzu对象注册新用户,登录用户,注销用户并验证身份验证令牌。
Yuzu曾与烧瓶和橘子一起工作,目前有两个与Yuzu捆绑在一起的JWT Middlewares,一个用于烧瓶,一个用于橘子。一旦正确初始化了Yuzu类,就可以通过致电:
app . use ( auth . jwt_middleware ).烧瓶版本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 )注意:验证中间件将用户数据附加到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是一个提供安全处理密钥和加密数据的功能的类。
以下是钥匙扣类的关键方法:
- `__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 .为此,您要编写两个功能,一个用于在所选数据库系统中找到用户,一个用于在所选数据库系统中创建用户。这些功能应将用户数据的字典作为参数,并返回用户数据的字典。用户数据字典至少应包含电子邮件和密码字段。用户数据字典可以包含您要存储在数据库中的任何其他字段。
这是如何使用yuzu和钥匙液类的示例:
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。您还可以根据您的特定要求来修改这些功能,以更改哈希功能的难度(例如,通过增加迭代次数或内存使用量)。
请记住,更改这些功能可能会对您的应用程序的安全性产生影响。在做出决定之前,您应该了解所选哈希功能及其优势和劣势的工作。