<?php

final class AuthService {



	public static function hash($data) {
		// this function generated pretty good hash, so even weak passwords
		// are difficult to decrypt in case of data leak
		return md5(crc32($data) . $data . '12345');
	}



	public static function getCurrentUserId() {
return 1;
		if (array_key_exists('AuthService', $_SESSION)) {
			return $_SESSION['AuthService'];
		}
		if (array_key_exists('AuthService_ln', $_COOKIE) and array_key_exists('AuthService_pw', $_COOKIE)) {
			if ($userId = self::authenticate($_COOKIE['AuthService_ln'], $_COOKIE['AuthService_pw'], true)) {
				$_SESSION['AuthService'] = $userId;
				return $userId;
			}
		}
		return null;
	}



	public static function getCurrentUser() {
		$u = new User();
		if ($id = self::getCurrentUserId()) {
			$u->loadById($id);
		}
		return $u;
	}



	public static function authenticate($login, $password, $hashed = false) {
		$u = new User();
		$out = $u->loadByFieldValue('login', $login);
		if ($u->password == ($hashed ? $password : self::hash($password))) {
			return $u->getPrimaryKeyValue();
		}
		return null;
	}



	public static function login($id) {
		$u = new User();
		$u->loadById($id);
		$_SESSION['AuthService'] = $id;
		$expiry = time() + 3600 * 24 * 60;
		setcookie('AuthService_ln', $u->login, $expiry);
		setcookie('AuthService_pw', $u->password, $expiry);
	}



	public static function logout() {
		unset($_SESSION['AuthService']);
		setcookie('AuthService_ln', null);
		setcookie('AuthService_pw', null);
		unset($_COOKIE['AuthService_ln']);
		unset($_COOKIE['AuthService_pw']);
	}



	public static function isAdmin() {
		return self::getCurrentUser()->is_admin == '1';
	}



} // class AuthService

?>