init
This commit is contained in:
82
auth/app/auth.py
Normal file
82
auth/app/auth.py
Normal file
@ -0,0 +1,82 @@
|
||||
from fastapi import HTTPException
|
||||
from .models import UserLogin, UserInDB, Session, UserCreate
|
||||
from .utils import (
|
||||
verify_password,
|
||||
get_password_hash,
|
||||
create_access_token,
|
||||
decode_token,
|
||||
)
|
||||
from .database import users_collection, sessions_collection
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
class AuthService:
|
||||
async def register(self, user: UserCreate):
|
||||
# Проверяем, существует ли пользователь
|
||||
if await users_collection.find_one({"username": user.username}):
|
||||
raise HTTPException(status_code=400, detail="Username already taken")
|
||||
|
||||
# Хешируем пароль
|
||||
hashed_password = get_password_hash(user.password)
|
||||
|
||||
# Создаём UUID для Minecraft
|
||||
user_uuid = str(uuid.uuid4())
|
||||
|
||||
# Сохраняем в MongoDB
|
||||
new_user = UserInDB(
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
hashed_password=hashed_password,
|
||||
uuid=user_uuid,
|
||||
)
|
||||
await users_collection.insert_one(new_user.dict())
|
||||
return {"status": "success", "uuid": user_uuid}
|
||||
|
||||
async def login(self, credentials: UserLogin):
|
||||
# Ищем пользователя
|
||||
user = await users_collection.find_one({"username": credentials.username})
|
||||
if not user or not verify_password(credentials.password, user["hashed_password"]):
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
|
||||
# Генерируем токены
|
||||
access_token = create_access_token({"sub": user["username"], "uuid": user["uuid"]})
|
||||
client_token = str(uuid.uuid4())
|
||||
|
||||
# Сохраняем сессию
|
||||
session = Session(
|
||||
access_token=access_token,
|
||||
client_token=client_token,
|
||||
user_uuid=user["uuid"],
|
||||
expires_at=datetime.utcnow() + timedelta(minutes=1440),
|
||||
)
|
||||
await sessions_collection.insert_one(session.dict())
|
||||
|
||||
return {
|
||||
"accessToken": access_token,
|
||||
"clientToken": client_token,
|
||||
"selectedProfile": {
|
||||
"id": user["uuid"],
|
||||
"name": user["username"],
|
||||
},
|
||||
}
|
||||
|
||||
async def validate(self, access_token: str, client_token: str):
|
||||
session = await sessions_collection.find_one({
|
||||
"access_token": access_token,
|
||||
"client_token": client_token,
|
||||
})
|
||||
if not session or datetime.utcnow() > session["expires_at"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def refresh(self, access_token: str, client_token: str):
|
||||
if not await self.validate(access_token, client_token):
|
||||
return None
|
||||
|
||||
# Обновляем токен
|
||||
new_access_token = create_access_token({"sub": "user", "uuid": "user_uuid"})
|
||||
await sessions_collection.update_one(
|
||||
{"access_token": access_token},
|
||||
{"$set": {"access_token": new_access_token}},
|
||||
)
|
||||
return {"accessToken": new_access_token, "clientToken": client_token}
|
Reference in New Issue
Block a user