import pathlib
from snek.system import security
from snek.system.service import BaseService
class UserService(BaseService):
mapper_name = "user"
async def search(self, query, **kwargs):
query = query.strip().lower()
if not query:
raise []
results = []
async for result in self.find(username={"ilike": "%" + query + "%"}, **kwargs):
results.append(result)
return results
async def validate_login(self, username, password):
model = await self.get(username=username)
if not model:
return False
if not await security.verify(password, model["password"]):
return False
return True
async def save(self, user):
if not user["color"]:
user["color"] = await self.services.util.random_light_hex_color()
return await super().save(user)
async def authenticate(self, username, password):
print(username, password, flush=True)
success = await self.validate_login(username, password)
print(success, flush=True)
if not success:
return None
model = await self.get(username=username, deleted_at=None)
return model
async def get_home_folder(self, user_uid):
folder = pathlib.Path(f"./drive/{user_uid}")
if not folder.exists():
folder.mkdir(parents=True, exist_ok=True)
return folder
async def register(self, email, username, password):
if await self.exists(username=username):
raise Exception("User already exists.")
model = await self.new()
model["nick"] = username
model["color"] = await self.services.util.random_light_hex_color()
model.email.value = email
model.username.value = username
model.password.value = await security.hash(password)
if await self.save(model):
if model:
channel = await self.services.channel.ensure_public_channel(
model["uid"]
)
if not channel:
raise Exception("Failed to create public channel.")
return model
raise Exception(f"Failed to create user: {model.errors}.")