You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.6 KiB
PHP

<?php
namespace Eater\Glim\Service;
use Eater\Glim\Model\Base\UserQuery;
use Eater\Glim\Model\InviteQuery;
use Eater\Glim\Model\Invite;
use Eater\Glim\Model\User as UserModel;
class User extends Main
{
/**
* @param string $invite
* @param string $username
* @param string $password
* @return Eater\Glim\Model\User
* @throws \Exception
*/
public function register($invite, $username, $password)
{
$invite = InviteQuery::create()->findOneByInvite($invite);
if ($invite === null) {
throw new \Exception("Invalid invite code");
}
$this->validateUserParams($username, $password);
$user = new UserModel();
$user->setUsername($username);
$user->setPassword(\password_hash($password, PASSWORD_DEFAULT));
$user->save();
$invite->delete();
return $user;
}
public function validateUserParams($username, $password) {
if ($username === "") {
throw new \Exception("No username given");
}
if (!preg_match('~^[a-z0-9\-]+$~', $username)) {
throw new \Exception("Username can only consist of a-z, 0-9 and -");
}
if ($password === "") {
throw new \Exception("Password is nothing, though strong. we rather not have you use that");
}
if (strlen($password) < 9) {
throw new \Exception("Please pick a password with more then 8 characters");
}
if ($this->exists($username)) {
throw new \Exception("User already exists");
}
}
public function createSuperuser($username, $password) {
$this->validateUserParams($username, $password);
$user = new UserModel();
$user->setUsername($username);
$user->setPassword(\password_hash($password, PASSWORD_DEFAULT));
$user->setSuperuser(true);
$user->save();
return $user;
}
/**
* @param string $username
* @return bool
*/
public function exists($username)
{
$amount = UserQuery::create()->findByUsername($username)->count();
return $amount > 0;
}
public function login($username, $password)
{
$user = UserQuery::create()->findOneByUsername($username);
if ($user === null || !password_verify($password, $user->getPassword())) {
return null;
}
return $user;
}
/**
* @return string
*/
public function createInvite()
{
$invite = new Invite();
$invite->setInvite(bin2hex(openssl_random_pseudo_bytes(20)));
$invite->save();
return $invite->getInvite();
}
}