Добавить аутентификацию: Argon2id, Basic-вход, Bearer-сессии с TTL и отзывом
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""Password KDF and HTTP credential parsing, without framework dependencies."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import VerificationError, InvalidHashError
|
||||
from .domain import ApiError, invalid, string
|
||||
|
||||
|
||||
class Authentication:
|
||||
def __init__(self, repository, ttl):
|
||||
self.repository = repository
|
||||
self.ttl = ttl
|
||||
self.hasher = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=2,
|
||||
hash_len=32, salt_len=16, type=Type.ID)
|
||||
self._dummy = self.hasher.hash(secrets.token_urlsafe(32))
|
||||
|
||||
@staticmethod
|
||||
def password(value):
|
||||
string(value, 128)
|
||||
if len(value) < 12:
|
||||
invalid('Password must contain 12 to 128 Unicode characters')
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def digest(token):
|
||||
return hashlib.sha256(token.encode('ascii')).hexdigest()
|
||||
|
||||
def bearer(self, header):
|
||||
parts = (header or '').split()
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer' or not re.fullmatch(r'[A-Za-z0-9_-]{43}', parts[1]):
|
||||
raise ApiError(401, 'unauthorized', 'Valid Bearer session required')
|
||||
token_hash = self.digest(parts[1])
|
||||
return self.repository.session_user(token_hash), token_hash
|
||||
|
||||
def login(self, header):
|
||||
def denied():
|
||||
raise ApiError(401, 'unauthorized', 'Invalid credentials')
|
||||
try:
|
||||
parts = (header or '').split()
|
||||
if len(parts) != 2 or parts[0].lower() != 'basic':
|
||||
denied()
|
||||
username, password = base64.b64decode(parts[1], validate=True).decode('utf-8').split(':', 1)
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}', username) or not 12 <= len(password) <= 128:
|
||||
denied()
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
denied()
|
||||
row = self.repository.credentials(username)
|
||||
try:
|
||||
self.hasher.verify(row['password_hash'] if row else self._dummy, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
denied()
|
||||
if row is None:
|
||||
denied()
|
||||
user = {key: value for key, value in row.items() if key != 'password_hash'}
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = self.repository.create_session(user['id'], self.digest(token), self.ttl)
|
||||
return {'token': token, 'token_type': 'Bearer', 'expires_at': expires_at, 'user': user}
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Use cases; independent of Flask and the concrete storage adapter."""
|
||||
import re
|
||||
from .domain import fields, string, uuid_value, invalid, ApiError
|
||||
from .repository import Repository
|
||||
from .pagination import Pagination
|
||||
from .security import Authentication
|
||||
|
||||
|
||||
class Messenger:
|
||||
def __init__(self, repository: Repository, session_ttl=3600):
|
||||
self.repository = repository
|
||||
self.pagination = Pagination(repository.cursor_key())
|
||||
self.auth = Authentication(repository, session_ttl)
|
||||
|
||||
def register(self, body):
|
||||
fields(body, ('username', 'display_name', 'password'))
|
||||
username = string(body['username'], 32)
|
||||
if not re.fullmatch(r'[a-z0-9_]{3,32}', username):
|
||||
invalid('Invalid username')
|
||||
display_name = string(body['display_name'], 100)
|
||||
password = self.auth.password(body['password'])
|
||||
return self.repository.create_user(username, display_name, self.auth.hasher.hash(password))
|
||||
|
||||
def create_chat(self, actor, body):
|
||||
fields(body, ('title', 'member_ids'))
|
||||
title = string(body['title'], 100)
|
||||
members = body['member_ids']
|
||||
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
||||
invalid('Invalid member list')
|
||||
members = [uuid_value(m) for m in members]
|
||||
if len(set(members)) != len(members):
|
||||
invalid('Duplicate members')
|
||||
return self.repository.create_chat(actor, title, members)
|
||||
|
||||
def chat(self, actor, chat_id):
|
||||
return self.repository.chat(actor, uuid_value(chat_id))
|
||||
|
||||
def send(self, actor, chat_id, body):
|
||||
self.chat(actor, chat_id)
|
||||
fields(body, ('text',))
|
||||
return self.repository.create_message(actor, uuid_value(chat_id), string(body['text'], 4000))
|
||||
|
||||
def chats(self, actor, limit, cursor):
|
||||
scope = 'chats:' + actor
|
||||
limit, after = self.pagination.decode(scope, limit, cursor)
|
||||
return self.pagination.page(self.repository.chats(actor, limit + 1, after), scope, limit)
|
||||
|
||||
def history(self, actor, chat_id, limit, cursor):
|
||||
chat_id = uuid_value(chat_id)
|
||||
self.repository.chat(actor, chat_id)
|
||||
scope = 'messages:' + chat_id
|
||||
limit, after = self.pagination.decode(scope, limit, cursor)
|
||||
return self.pagination.page(self.repository.messages(actor, chat_id, limit + 1, after), scope, limit)
|
||||
Reference in New Issue
Block a user