rewrite the constructor of User class

This commit is contained in:
printempw 2016-08-16 13:27:06 +08:00
parent 321262d737
commit 0b17fa4799
19 changed files with 161 additions and 120 deletions

View File

@ -125,9 +125,9 @@ class AdminController extends BaseController
View::json('修改配色成功', 0);
}
$user = new User('', Utils::getValue('uid', $_POST));
$user = new User(Utils::getValue('uid', $_POST));
$current_user = new User($_SESSION['email']);
$current_user = new User(0, ['email' => $_SESSION['email']]);
if (!$user->is_registered)
throw new E('用户不存在', 1);
@ -246,7 +246,7 @@ class AdminController extends BaseController
if (!is_numeric($_POST['uid']))
View::json('无效的参数', 0);
$user = new User('', $_POST['uid']);
$user = new User($_POST['uid']);
if (!$user->is_registered)
View::json('不存在的用户', 1);

View File

@ -10,6 +10,7 @@ use Mail;
use View;
use Utils;
use Option;
use Http;
class AuthController extends BaseController
{
@ -20,7 +21,10 @@ class AuthController extends BaseController
public function handleLogin()
{
$user = new User($_POST['email']);
// instantiate user
$user = ($_SESSION['auth_type'] = 'email') ?
new User(0, ['email' => $_POST['email']]) :
new User(0, ['username' => $_POST['username']]);
if (Utils::getValue('login_fails', $_SESSION) > 3) {
if (strtolower(Utils::getValue('captcha', $_POST)) != strtolower($_SESSION['phrase']))
@ -31,15 +35,15 @@ class AuthController extends BaseController
View::json('用户不存在哦', 2);
} else {
if ($user->checkPasswd($_POST['password'])) {
$_SESSION['token'] = $user->getToken();
unset($_SESSION['login_fails']);
header('Content-type: application/json');
$_SESSION['uid'] = $user->uid;
$_SESSION['token'] = $user->getToken();
// setcookie('email', $user->email, time()+3600, '/');
// setcookie('token', $user->getToken(), time()+3600, '/');
setcookie('uid', $user->uid, time()+3600, '/');
setcookie('token', $user->getToken(), time()+3600, '/');
echo json_encode([
View::json([
'errno' => 0,
'msg' => '登录成功,欢迎回来~',
'token' => $user->getToken()
@ -47,6 +51,7 @@ class AuthController extends BaseController
} else {
$_SESSION['login_fails'] = isset($_SESSION['login_fails']) ?
$_SESSION['login_fails'] + 1 : 1;
View::json([
'errno' => 1,
'msg' => '邮箱或密码不对哦~',
@ -60,6 +65,10 @@ class AuthController extends BaseController
{
if (isset($_SESSION['token'])) {
session_destroy();
setcookie('uid', $user->uid, time()-3600, '/');
setcookie('token', $user->getToken(), time()-3600, '/');
View::json('登出成功~', 0);
} else {
throw new E('并没有有效的 session', 1);
@ -80,19 +89,23 @@ class AuthController extends BaseController
if (strtolower(Utils::getValue('captcha', $_POST)) != strtolower($_SESSION['phrase']))
View::json('验证码填写错误', 1);
$user = new User($_POST['email']);
$user = new User(0, ['email' => $_POST['email']]);
if (!$user->is_registered) {
if (Option::get('user_can_register') == 1) {
if (\Validate::password($_POST['password'])) {
// If amount of registered accounts of IP is more than allowed mounts,
// then reject the registration.
if (count(UserModel::where('ip', \Http::getRealIP())->get()) < Option::get('regs_per_ip')) {
// use once md5 to encrypt password
$user = $user->register($_POST['password'], \Http::getRealIP());
if (Validate::password($_POST['password'])) {
// If amount of registered accounts of IP is more than allowed amounts,
// then reject the register.
if (UserModel::where('ip', Http::getRealIP())->count() < Option::get('regs_per_ip'))
{
if (Validate::nickname(Utils::getValue('nickname', $_POST)))
View::json('无效的昵称,昵称不能包含奇怪的字符', 1);
// register new user
$user = $user->register($_POST['password'], Http::getRealIP());
$user->setNickName($_POST['nickname']);
echo json_encode([
View::json([
'errno' => 0,
'msg' => '注册成功,正在跳转~',
'token' => $user->getToken()
@ -130,7 +143,7 @@ class AuthController extends BaseController
if (isset($_SESSION['last_mail_time']) && (time() - $_SESSION['last_mail_time']) < 60)
View::json('你邮件发送得太频繁啦,过 60 秒后再点发送吧', 1);
$user = new User($_POST['email']);
$user = new User(0, ['email' => $_POST['email']]);
if (!$user->is_registered)
View::json('该邮箱尚未注册', 1);
@ -141,13 +154,14 @@ class AuthController extends BaseController
->to($_POST['email'])
->subject('重置您在 '.Option::get('site_name').' 上的账户密码');
$uid = $user->uid;
$uid = $user->uid;
$token = base64_encode($user->getToken().substr(time(), 4, 6).Utils::generateRndString(16));
$url = Option::get('site_url')."/auth/reset?uid={$uid}&token=$token";
$content = View::make('auth.mail')->with('reset_url', $url)->render();
$url = Option::get('site_url')."/auth/reset?uid=$uid&token=$token";
if(!$mail->content($content)->send()) {
$mail->content(View::make('auth.mail')->with('reset_url', $url)->render());
if (!$mail->send()) {
View::json('邮件发送失败,详细信息:'.$mail->getLastError(), 2);
} else {
$_SESSION['last_mail_time'] = time();
@ -159,35 +173,35 @@ class AuthController extends BaseController
public function reset()
{
if (isset($_GET['uid']) && isset($_GET['token'])) {
$user = new User('', $_GET['uid']);
$user = new User($_GET['uid']);
if (!$user->is_registered)
\Http::redirect('./forgot', '无效的链接');
Http::redirect('./forgot', '无效的链接');
$token = substr(base64_decode($_GET['token']), 0, -22);
if ($user->getToken() != $token) {
\Http::redirect('./forgot', '无效的链接');
Http::redirect('./forgot', '无效的链接');
}
$timestamp = substr(base64_decode($_GET['token']), strlen($token), 6);
// more than 1 hour
if ((substr(time(), 4, 6) - $timestamp) > 3600) {
\Http::redirect('./forgot', '链接已过期');
Http::redirect('./forgot', '链接已过期');
}
echo View::make('auth.reset')->with('user', $user);
} else {
\Http::redirect('./login', '非法访问');
Http::redirect('./login', '非法访问');
}
}
public function handleReset()
{
\Validate::checkPost(['uid', 'password']);
Validate::checkPost(['uid', 'password']);
if (\Validate::password($_POST['password'])) {
$user = new User('', $_POST['uid']);
if (Validate::password($_POST['password'])) {
$user = new User($_POST['uid']);
$user->changePasswd($_POST['password']);

View File

@ -16,7 +16,7 @@ class ClosetController extends BaseController
function __construct()
{
$this->closet = new Closet((new User($_SESSION['email']))->uid);
$this->closet = new Closet((new User(0, ['email' => $_SESSION['email']]))->uid);
}
public function index()
@ -33,7 +33,7 @@ class ClosetController extends BaseController
->with('page', $page)
->with('category', $category)
->with('total_pages', $total_pages)
->with('user', (new User($_SESSION['email'])))
->with('user', (new User(0, ['email' => $_SESSION['email']])))
->render();
}

View File

@ -22,7 +22,7 @@ class HomeController extends BaseController
}
}
$user = isset($_SESSION['email']) ? new User($_SESSION['email']) : null;
$user = isset($_SESSION['email']) ? new User(0, ['email' => $_SESSION['email']]) : null;
echo \View::make('index')->with('user', $user);
}

View File

@ -27,7 +27,7 @@ class PlayerController extends BaseController
public function index()
{
echo View::make('user.player')->with('players', (new User($_SESSION['email']))->getPlayers()->toArray())->with('user', new User($_SESSION['email']));
echo View::make('user.player')->with('players', (new User(0, ['email' => $_SESSION['email']]))->getPlayers()->toArray())->with('user', new User(0, ['email' => $_SESSION['email']]));
}
public function add()
@ -46,7 +46,7 @@ class PlayerController extends BaseController
if (!PlayerModel::where('player_name', $player_name)->get()->isEmpty())
View::json('该角色名已经被其他人注册掉啦', 6);
$user = new User($_SESSION['email']);
$user = new User(0, ['email' => $_SESSION['email']]);
if ($user->getScore() < Option::get('score_per_player'))
View::json('积分不够添加角色啦', 7);
@ -69,7 +69,7 @@ class PlayerController extends BaseController
$player_name = $this->player->eloquent_model->player_name;
$this->player->eloquent_model->delete();
(new User($_SESSION['email']))->setScore(Option::get('score_per_player'), 'plus');
(new User(0, ['email' => $_SESSION['email']]))->setScore(Option::get('score_per_player'), 'plus');
View::json('角色 '.$player_name.' 已被删除', 0);
}

View File

@ -17,7 +17,7 @@ class SkinlibController extends BaseController
function __construct()
{
$this->user = isset($_SESSION['email']) ? new User($_SESSION['email']) : null;
$this->user = isset($_SESSION['email']) ? new User(0, ['email' => $_SESSION['email']]) : null;
}
public function index()

File diff suppressed because one or more lines are too long

View File

@ -16,7 +16,7 @@ class UserController extends BaseController
function __construct()
{
$this->action = isset($_GET['action']) ? $_GET['action'] : "";
$this->user = new User($_SESSION['email']);
$this->user = new User(0, ['email' => $_SESSION['email']]);
}
public function index()
@ -109,7 +109,7 @@ class UserController extends BaseController
if ($result) {
if ($result->type == "cape") throw new E('披风可不能设置为头像哦~', 1);
if ((new User($_SESSION['email']))->setAvatar($_POST['tid'])) {
if ((new User(0, ['email' => $_SESSION['email']]))->setAvatar($_POST['tid'])) {
View::json('设置成功!', 0);
}
} else {

View File

@ -17,7 +17,7 @@ class CheckLoggedInMiddleware implements IMiddleware
}
if (isset($_SESSION['email'])) {
$user = new User($_SESSION['email']);
$user = new User(0, ['email' => $_SESSION['email']]);
if ($_SESSION['token'] != $user->getToken())
\Http::redirect('../auth/login', '无效的 token请重新登录~');

View File

@ -12,23 +12,26 @@ class CheckPostMiddleware implements IMiddleware
{
public function handle(Request $request)
{
if (isset($_POST['email']) && $_POST['email'] != "") {
if (Utils::getValue('email', $_POST) != "") {
if (!Validate::email($_POST['email'])) {
View::json('邮箱格式错误', 3);
}
if ($request->getUri() == "/auth/forgot") return true;
if (isset($_POST['nickname']) && ($_POST['nickname'] != \Utils::convertString($_POST['nickname'])))
View::json('无效的昵称,昵称不能包含奇怪的字符', 1);
if (isset($_POST['password']) && $_POST['password'] != "") {
return true;
} else {
View::json('密码不能为空哦', 2);
$_SESSION['auth_type'] = 'email';
} elseif (Utils::getValue('username', $_POST) != "") {
if (!Validate::playerName($_POST['username'])) {
View::json('角色名格式错误', 3);
}
$_SESSION['auth_type'] = 'username';
} else {
View::json('邮箱地址不能为空哦', 3);
View::json('无效的参数', 3);
}
if ($request->getUri() == "/auth/forgot") return true;
if (isset($_POST['password']) && $_POST['password'] != "") {
return true;
} else {
View::json('密码不能为空哦', 2);
}
}
}

View File

@ -16,7 +16,7 @@ class RedirectIfLoggedInMiddleware implements IMiddleware
}
if (isset($_SESSION['email'])) {
if ($_SESSION['token'] != (new User($_SESSION['email']))->getToken())
if ($_SESSION['token'] != (new User(0, ['email' => $_SESSION['email']]))->getToken())
{
$_SESSION['msg'] = "无效的 token请重新登录~";
} else {

View File

@ -12,7 +12,7 @@ class Player
public $is_banned = false;
public $eloquent_model = null;
public $model = null;
/**
* Construct player with pid or playername
@ -23,18 +23,18 @@ class Player
{
if ($player_name == "") {
$this->pid = $pid;
$this->eloquent_model = PlayerModel::find($pid);
$this->model = PlayerModel::find($pid);
} else {
$this->eloquent_model = PlayerModel::where('player_name', $player_name)->first();
@$this->pid = $this->eloquent_model->pid;
$this->model = PlayerModel::where('player_name', $player_name)->first();
@$this->pid = $this->model->pid;
}
if (!$this->eloquent_model)
if (!$this->model)
\Http::abort(404, '角色不存在');
$this->player_name = $this->eloquent_model->player_name;
$this->player_name = $this->model->player_name;
if ((new User('', $this->eloquent_model->uid))->getPermission() == "-1")
if ((new User($this->model->uid))->getPermission() == "-1")
$this->is_banned = true;
}
@ -48,7 +48,7 @@ class Player
if ($type == "skin")
$type = ($this->getPreference() == "default") ? "steve" : "alex";
if ($type == "steve" | $type == "alex" | $type == "cape") {
$tid = $this->eloquent_model['tid_'.$type];
$tid = $this->model['tid_'.$type];
return Texture::find($tid)['hash'];
}
return false;
@ -61,12 +61,12 @@ class Player
throw new E('Invalid parameters.', 1);
}
$this->eloquent_model->tid_steve = isset($tids['tid_steve']) ? $tids['tid_steve'] : $this->eloquent_model['tid_steve'];
$this->eloquent_model->tid_alex = isset($tids['tid_alex']) ? $tids['tid_alex'] : $this->eloquent_model['tid_alex'];
$this->eloquent_model->tid_cape = isset($tids['tid_cape']) ? $tids['tid_cape'] : $this->eloquent_model['tid_cape'];
$this->model->tid_steve = isset($tids['tid_steve']) ? $tids['tid_steve'] : $this->model['tid_steve'];
$this->model->tid_alex = isset($tids['tid_alex']) ? $tids['tid_alex'] : $this->model['tid_alex'];
$this->model->tid_cape = isset($tids['tid_cape']) ? $tids['tid_cape'] : $this->model['tid_cape'];
$this->eloquent_model->last_modified = Utils::getTimeFormatted();
return $this->eloquent_model->save();
$this->model->last_modified = Utils::getTimeFormatted();
return $this->model->save();
}
public function getBinaryTexture($type)
@ -95,18 +95,18 @@ class Player
*/
public function setPreference($type) {
return $this->eloquent_model->update([
return $this->model->update([
'preference' => $type,
'last_modified' => Utils::getTimeFormatted()
]);
}
public function getPreference() {
return $this->eloquent_model['preference'];
return $this->model['preference'];
}
public function setOwner($uid) {
return $this->eloquent_model->update(['uid' => $uid]);
return $this->model->update(['uid' => $uid]);
}
/**
@ -141,7 +141,7 @@ class Player
public function updateLastModified() {
// @see http://stackoverflow.com/questions/2215354/php-date-format-when-inserting-into-datetime-in-mysql
return $this->eloquent_model->update(['last_modified' => Utils::getTimeFormatted()]);
return $this->model->update(['last_modified' => Utils::getTimeFormatted()]);
}
/**
@ -149,7 +149,7 @@ class Player
* @return timestamp
*/
public function getLastModified() {
return strtotime($this->eloquent_model['last_modified']);
return strtotime($this->model['last_modified']);
}
}

View File

@ -25,7 +25,7 @@ class User
* Instance of App\Models\UserModel
* @var null
*/
private $eloquent_model = null;
private $model = null;
/**
* Instance of App\Models\Closet
@ -37,28 +37,45 @@ class User
public $is_admin = false;
/**
* You can construct a User object with both email & uid
* Pass uid or an array to instantiate a user
*
* @param string $email
* @param int $uid
* $info = [
* 'username' => 'foo',
* 'email' => 'foo@bar.com'
* ];
*
* @param int $uid
* @param array $info
*/
function __construct($email, $uid = 0)
public function __construct($uid, Array $info)
{
$this->email = Utils::convertString($email);
$this->eloquent_model = ($uid == 0) ? UserModel::where('email', $this->email)->first() : UserModel::find($uid);
// Construct user with uid|email|player_name
if ($uid != 0) {
$this->uid = $uid;
$this->model = UserModel::find($uid);
} else {
if (isset($info['email'])) {
$this->email = Utils::convertString($email);
$this->model = UserModel::where('email', $this->email)->first();
} elseif (isset($info['username'])) {
$this->uid = PlayerModel::where('player_name', $info['username'])->first()['uid'];
$this->model = UserModel::find($this->uid);
} else {
throw new \InvalidArgumentException('Invalid arguments');
}
}
$class_name = "App\Services\Cipher\\".$_ENV['PWD_METHOD'];
$this->cipher = new $class_name;
if (!is_null($this->eloquent_model)) {
if (!is_null($this->model)) {
$this->is_registered = true;
$this->uid = $this->eloquent_model->uid;
$this->email = $this->eloquent_model->email;
$this->password = $this->eloquent_model->password;
$this->uid = $this->model->uid;
$this->email = $this->model->email;
$this->password = $this->model->password;
$this->token = md5($this->email . $this->password . $_ENV['SALT']);
$this->closet = new Closet($this->uid);
$this->is_admin = $this->eloquent_model->permission == 1 ||
$this->eloquent_model->permission == 2;
$this->is_admin = $this->model->permission == 1 || $this->model->permission == 2;
}
}
@ -69,13 +86,13 @@ class User
public function changePasswd($new_passwd)
{
$this->eloquent_model->password = $this->cipher->encrypt($new_passwd, $_ENV['SALT']);
return $this->eloquent_model->save();
$this->model->password = $this->cipher->encrypt($new_passwd, $_ENV['SALT']);
return $this->model->save();
}
public function getPermission()
{
return $this->eloquent_model->permission;
return $this->model->permission;
}
/**
@ -88,13 +105,13 @@ class User
*/
public function setPermission($permission)
{
return $this->eloquent_model->update(['permission' => $permission]);
return $this->model->update(['permission' => $permission]);
}
public function setEmail($new_email)
{
$this->eloquent_model->email = $new_email;
return $this->eloquent_model->save();
$this->model->email = $new_email;
return $this->model->save();
}
public function getNickName()
@ -102,44 +119,44 @@ class User
if (!$this->is_registered) {
return "不存在的用户";
} else {
return ($this->eloquent_model->nickname == "") ? $this->email : $this->eloquent_model->nickname;
return ($this->model->nickname == "") ? $this->email : $this->model->nickname;
}
}
public function setNickName($new_nickname)
{
$this->eloquent_model->nickname = $new_nickname;
return $this->eloquent_model->save();
$this->model->nickname = $new_nickname;
return $this->model->save();
}
public function getToken()
{
if ($this->token === "")
$this->token = md5($this->eloquent_model->email . $this->eloquent_model->password . $_ENV['SALT']);
$this->token = md5($this->model->email . $this->model->password . $_ENV['SALT']);
return $this->token;
}
public function getScore()
{
return $this->eloquent_model->score;
return $this->model->score;
}
public function setScore($score, $mode = "set")
{
switch ($mode) {
case 'set':
$this->eloquent_model->score = $score;
$this->model->score = $score;
break;
case 'plus':
$this->eloquent_model->score += $score;
$this->model->score += $score;
break;
case 'minus':
$this->eloquent_model->score -= $score;
$this->model->score -= $score;
break;
}
return $this->eloquent_model->save();
return $this->model->save();
}
public function getStorageUsed()
@ -162,8 +179,8 @@ class User
$sign_score = explode(',', Option::get('sign_score'));
$aquired_score = rand($sign_score[0], $sign_score[1]);
$this->setScore($aquired_score, 'plus');
$this->eloquent_model->last_sign_at = Utils::getTimeFormatted();
$this->eloquent_model->save();
$this->model->last_sign_at = Utils::getTimeFormatted();
$this->model->save();
return $aquired_score;
} else {
return false;
@ -188,7 +205,7 @@ class User
public function getLastSignTime()
{
return $this->eloquent_model->last_sign_at;
return $this->model->last_sign_at;
}
/**
@ -215,7 +232,7 @@ class User
$closet->textures = "";
$closet->save();
$this->eloquent_model = $user;
$this->model = $user;
return $this;
}
@ -234,7 +251,7 @@ class User
public function getAvatar($size)
{
// output image directly
if (!is_null($this->eloquent_model) && $this->getAvatarId()) {
if (!is_null($this->model) && $this->getAvatarId()) {
$png = \Minecraft::generateAvatarFromSkin(BASE_DIR."/textures/".Texture::find($this->getAvatarId())->hash, $size);
header('Content-Type: image/png');
imagepng($png);
@ -251,20 +268,20 @@ class User
public function getAvatarId()
{
return $this->eloquent_model->avatar;
return $this->model->avatar;
}
public function setAvatar($tid)
{
$this->eloquent_model->avatar = $tid;
return $this->eloquent_model->save();
$this->model->avatar = $tid;
return $this->model->save();
}
public function delete()
{
PlayerModel::where('uid', $this->uid)->delete();
ClosetModel::where('uid', $this->uid)->delete();
return $this->eloquent_model->delete();
return $this->model->delete();
}
}

View File

@ -28,6 +28,11 @@ class Validate
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
public static function nickname($nickname)
{
return $nickname != Utils::convertString($nickname);
}
public static function playerName($player_name)
{
$regx = (Option::get('allow_chinese_playername') == "1") ?

View File

@ -19,7 +19,7 @@
<style>{!! Option::get('custom_css') !!}</style>
</head>
<?php $user = new App\Models\User($_SESSION['email']); ?>
<?php $user = new App\Models\User(0, ['email' => $_SESSION['email']]); ?>
<body class="hold-transition {{ Option::get('color_scheme') }} sidebar-mini">
<div class="wrapper">

View File

@ -26,7 +26,7 @@
</h1>
</section>
<?php $current_user = new App\Models\User($_SESSION['email']); ?>
<?php $current_user = new App\Models\User(0, ['email' => $_SESSION['email']]); ?>
<!-- Main content -->
<section class="content">

View File

@ -85,7 +85,7 @@
</tr>
<tr>
<td>上传者</td>
<?php $uploader = new App\Models\User('', $texture->uploader); ?>
<?php $uploader = new App\Models\User($texture->uploader); ?>
<td><a href="../skinlib?filter=user&uid={{ $uploader->uid }}&sort=time">{{ $uploader->getNickName() }}</a></td>
</tr>
<tr>

View File

@ -85,7 +85,7 @@ switch ($step) {
}
// register super admin
$user = new App\Models\User($_POST['email']);
$user = new App\Models\User(0, ['email' => $_POST['email']]);
$user->register($_POST['password'], Http::getRealIP());
$user->setPermission('2');

View File

@ -32,7 +32,7 @@ if (isset($_COOKIE['email']) && isset($_COOKIE['token'])) {
// check permission
if (isset($_SESSION['email'])) {
$user = new App\Models\User($_SESSION['email']);
$user = new App\Models\User(0, ['email' => $_SESSION['email']]);
if ($_SESSION['token'] != $user->getToken())
Http::redirect('../../auth/login', '无效的 token请重新登录~');