forked from Moidea/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthorizeAction.php
195 lines (154 loc) · 6.98 KB
/
AuthorizeAction.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<?php
/**
* Sinauth Plugin
*
* @copyright Copyright (c) 2015 jimmy.chaw (http://x3d.cnblogs.com)
* @license GNU General Public License 2.0
*
*/
class Sinauth_AuthorizeAction extends Typecho_Widget implements Widget_Interface_Do
{
private $db;
private $config;
private static $pluginName = 'Sinauth';
private static $tableName = 'users_oauth';
public function __construct($request, $response, $params = NULL)
{
parent::__construct($request, $response, $params);
$this->config = Helper::options()->plugin(self::$pluginName);
$this->db = Typecho_Db::get();
}
public function action(){
//跳转
if (!class_exists('SaeTOAuthV2')) {
require_once './saetv2.ex.class.php';
}
$saeto_client = new SaeTOAuthV2($this->config->client_id, $this->config->client_secret);
$authorize_url = $saeto_client->getAuthorizeURL($this->config->callback_url, 'code');
$this->response->redirect($authorize_url);
exit;
}
/**
* 授权回调地址
*/
public function callback(){
if(empty($_GET['code'])) {
throw new Typecho_Exception(_t('无效请求!'));
}
//跳转
if (!class_exists('SaeTOAuthV2')) {
require_once './saetv2.ex.class.php';
}
$saeto_client = new SaeTOAuthV2($this->config->client_id, $this->config->client_secret);
//取access_token
$access_token = $saeto_client->getAccessToken('code', array('code' => trim($_GET['code']), 'redirect_uri' => $this->config->callback_url));
if (empty($access_token) || !is_array($access_token) || empty($access_token['uid'])) {
throw new Typecho_Exception(_t('获取access_token失败,请返回重新授权!'));
}
$table = $this->db->getPrefix() . self::$tableName;
$query = $this->db->query("SELECT * FROM {$table} WHERE openid='{$access_token['uid']}' AND plateform='sina'");
$users_oauth = $this->db->fetchRow($query);
if (!empty($users_oauth['uid'])) { //该新浪帐号已经绑定了用户
if (Typecho_Widget::widget('Widget_User')->hasLogin()) { /** 直接返回 */
$this->response->redirect(Typecho_Widget::widget('Widget_Options')->index);
} else { //让其直接登陆
$this->setUserLogin($users_oauth['uid']);
if (!Typecho_Widget::widget('Widget_User')->pass('contributor', true)) {
/** 不允许普通用户直接跳转后台 */
$this->response->redirect(Typecho_Widget::widget('Widget_Options')->profileUrl);
} else {
$this->response->redirect(Typecho_Widget::widget('Widget_Options')->adminUrl);
}
}
exit;
}
//该新浪帐号未绑定过
/** 如果已经登录 */
if (Typecho_Widget::widget('Widget_User')->hasLogin()) {
/** 直接绑定 */
$cookieUid = Typecho_Cookie::get('__typecho_uid');
$this->bindOauthUser($cookieUid, $access_token['uid'], 'sina', $access_token['expires_in']);
$this->response->redirect(Typecho_Widget::widget('Widget_Options')->index);
} else {
//取用户信息
$saetc_client = new SaeTClientV2($this->config->client_id, $this->config->client_secret, $access_token['access_token']);
$weibo_user = $saetc_client->show_user_by_id($access_token['uid']);
//创建用户
$uid = $this->registerFromWeiboUser($weibo_user);
if (!$uid) {
throw new Typecho_Exception(_t('创建帐号失败,请联系管理员!'));
}
$this->setUserLogin($uid);
$this->bindOauthUser($uid, $access_token['uid'], 'sina', $access_token['expires_in']);
$this->response->redirect(Typecho_Widget::widget('Widget_Options')->profileUrl);
}
//构造用户帐号
exit;
}
/**
* 根据微博用户信息创建帐号
*/
protected function registerFromWeiboUser(&$weibo_user) {
$hasher = new PasswordHash(8, true);
$generatedPassword = Typecho_Common::randString(7);
//TODO 用户名重复的问题
$uname = $weibo_user['name'];
$i = 0;
if (!Typecho_Widget::widget('Widget_Abstract_Users')->nameExists($uname)) { //用户名存在
echo 'here';
for ($i = 1; $i < 999; $i++) {
echo $i;
if (Typecho_Widget::widget('Widget_Abstract_Users')->nameExists($uname . '_' . $i)) {
$uname = $uname . '_' . $i;
break;
}
}
}
$dataStruct = array(
'name' => $uname,
'mail' => $weibo_user['idstr'] . ($i ? '_' . $i : '') . '@localhost.local',
'screenName'=> $weibo_user['screen_name'] . ($i ? '_' . $i : ''),
'password' => $hasher->HashPassword($generatedPassword),
'created' => time(),
'url' => $weibo_user['url'],
'group' => 'subscriber'
);
$insertId = Typecho_Widget::widget('Widget_Abstract_Users')->insert($dataStruct);
return $insertId;
}
public function nameExists($name)
{
$select = $this->db->select()
->from('table.users')
->where('name = ?', $name)
->limit(1);
$user = $this->db->fetchRow($select);
return $user ? false : true;
}
/**
* 设置用户登陆状态
*/
protected function setUserLogin($uid, $expire = 30243600) {
Typecho_Widget::widget('Widget_User')->simpleLogin($uid);
$authCode = function_exists('openssl_random_pseudo_bytes') ?
bin2hex(openssl_random_pseudo_bytes(16)) : sha1(Typecho_Common::randString(20));
Typecho_Cookie::set('__typecho_uid', $uid, time() + $expire);
Typecho_Cookie::set('__typecho_authCode', Typecho_Common::hash($authCode), time() + $expire);
//更新最后登录时间以及验证码
$this->db->query($this->db
->update('table.users')
->expression('logged', 'activated')
->rows(array('authCode' => $authCode))
->where('uid = ?', $uid));
}
public function bindOauthUser($uid, $openid, $plateform = 'sina', $expires_in = 0) {
$rows = array(
'openid' => $openid,
'uid' => $uid,
'plateform' => $plateform,
'bind_time' => time(),
'expires_in' => $expires_in
);
return $this->db->query($this->db->insert('table.users_oauth')->rows($rows));
}
}