forked from CakeDC/users
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocialBehavior.php
More file actions
300 lines (273 loc) · 10.7 KB
/
Copy pathSocialBehavior.php
File metadata and controls
300 lines (273 loc) · 10.7 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
/**
* Copyright 2010 - 2017, Cake Development Corporation (https://www.cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2017, Cake Development Corporation (https://www.cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace CakeDC\Users\Model\Behavior;
use CakeDC\Users\Controller\Component\UsersAuthComponent;
use CakeDC\Users\Exception\AccountNotActiveException;
use CakeDC\Users\Exception\MissingEmailException;
use CakeDC\Users\Exception\UserNotActiveException;
use CakeDC\Users\Traits\RandomStringTrait;
use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventDispatcherTrait;
use Cake\Utility\Hash;
use DateTime;
use InvalidArgumentException;
/**
* Covers social features
*
*/
class SocialBehavior extends BaseTokenBehavior
{
use EventDispatcherTrait;
use RandomStringTrait;
/**
* Username field it can be modified via config
*
* @var string
*/
protected $_username = 'username';
/**
* Initialize an action instance
*
* @param array $config Configuration options passed to the constructor
* @return void
*/
public function initialize(array $config)
{
if (isset($config['username'])) {
$this->_username = $config['username'];
}
parent::initialize($config);
}
/**
* Performs social login
*
* @param array $data Array social login.
* @param array $options Array option data.
* @throws InvalidArgumentException
* @throws UserNotActiveException
* @throws AccountNotActiveException
* @return bool|EntityInterface|mixed
*/
public function socialLogin(array $data, array $options)
{
$reference = Hash::get($data, 'id');
$existingAccount = $this->_table->SocialAccounts->find()
->where([
'SocialAccounts.reference' => $reference,
'SocialAccounts.provider' => Hash::get($data, 'provider')
])
->contain(['Users'])
->first();
if (empty($existingAccount->user)) {
$user = $this->_createSocialUser($data, $options);
if (!empty($user->social_accounts[0])) {
$existingAccount = $user->social_accounts[0];
} else {
//@todo: what if we don't have a social account after createSocialUser?
throw new InvalidArgumentException(__d('CakeDC/Users', 'Unable to login user with reference {0}', $reference));
}
} else {
$user = $existingAccount->user;
$accountData = $this->extractAccountData($data);
$this->_table->SocialAccounts->patchEntity($existingAccount, $accountData);
$this->_table->SocialAccounts->save($existingAccount);
$event = $this->dispatchEvent(UsersAuthComponent::EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT, [
'userEntity' => $user,
'data' => $data
]);
if ($event->result instanceof EntityInterface) {
$user = $this->_table->save($event->result);
}
}
if (!empty($existingAccount)) {
if (!$existingAccount->active) {
throw new AccountNotActiveException([
$existingAccount->provider,
$existingAccount->reference
]);
}
if (!$user->active) {
throw new UserNotActiveException([
$existingAccount->provider,
$existingAccount->$user
]);
}
}
return $user;
}
/**
* Creates social user, populate the user data based on the social login data first and save it
*
* @param array $data Array social user.
* @param array $options Array option data.
* @throws MissingEmailException
* @return bool|EntityInterface|mixed result of the save operation
*/
protected function _createSocialUser($data, $options = [])
{
$useEmail = Hash::get($options, 'use_email');
$validateEmail = Hash::get($options, 'validate_email');
$tokenExpiration = Hash::get($options, 'token_expiration');
$existingUser = null;
$email = Hash::get($data, 'email');
if ($useEmail && empty($email)) {
throw new MissingEmailException(__d('CakeDC/Users', 'Email not present'));
} else {
$existingUser = $this->_table->find('existingForSocialLogin', compact('email'))->first();
}
$user = $this->_populateUser($data, $existingUser, $useEmail, $validateEmail, $tokenExpiration);
$event = $this->dispatchEvent(UsersAuthComponent::EVENT_BEFORE_SOCIAL_LOGIN_USER_CREATE, [
'userEntity' => $user,
]);
if ($event->result instanceof EntityInterface) {
$user = $event->result;
}
$this->_table->isValidateEmail = $validateEmail;
$result = $this->_table->save($user);
return $result;
}
/**
* Build new user entity either by using an existing user or extracting the data from the social login
* data to create a new one
*
* @param array $data Array social login.
* @param EntityInterface $existingUser user data.
* @param string $useEmail email to use.
* @param string $validateEmail email to validate.
* @param string $tokenExpiration token_expires data.
* @return EntityInterface
* @todo refactor
*/
protected function _populateUser($data, $existingUser, $useEmail, $validateEmail, $tokenExpiration)
{
$accountData = $this->extractAccountData($data);
$accountData['active'] = true;
$dataValidated = Hash::get($data, 'validated');
if (empty($existingUser)) {
$firstName = Hash::get($data, 'first_name');
$lastName = Hash::get($data, 'last_name');
if (!empty($firstName) && !empty($lastName)) {
$userData['first_name'] = $firstName;
$userData['last_name'] = $lastName;
} else {
$name = explode(' ', Hash::get($data, 'full_name'));
$userData['first_name'] = Hash::get($name, 0);
array_shift($name);
$userData['last_name'] = implode(' ', $name);
}
$userData['username'] = Hash::get($data, 'username');
$username = Hash::get($userData, 'username');
if (empty($username)) {
$dataEmail = Hash::get($data, 'email');
if (!empty($dataEmail)) {
$email = explode('@', $dataEmail);
$userData['username'] = Hash::get($email, 0);
} else {
$firstName = Hash::get($userData, 'first_name');
$lastName = Hash::get($userData, 'last_name');
$userData['username'] = strtolower($firstName . $lastName);
$userData['username'] = preg_replace('/[^A-Za-z0-9]/i', '', Hash::get($userData, 'username'));
}
}
$userData['username'] = $this->generateUniqueUsername(Hash::get($userData, 'username'));
if ($useEmail) {
$userData['email'] = Hash::get($data, 'email');
if (empty($dataValidated)) {
$accountData['active'] = false;
}
}
$userData['password'] = $this->randomString();
$userData['avatar'] = Hash::get($data, 'avatar');
$userData['validated'] = !empty($dataValidated);
$userData['tos_date'] = date("Y-m-d H:i:s");
$userData['gender'] = Hash::get($data, 'gender');
$userData['social_accounts'][] = $accountData;
$user = $this->_table->newEntity($userData);
$user = $this->_updateActive($user, false, $tokenExpiration);
} else {
if ($useEmail && empty($dataValidated)) {
$accountData['active'] = false;
}
$user = $existingUser;
}
$socialAccount = $this->_table->SocialAccounts->newEntity($accountData);
//ensure provider is present in Entity
$socialAccount['provider'] = Hash::get($data, 'provider');
$user['social_accounts'] = [$socialAccount];
$user['role'] = Configure::read('Users.Registration.defaultRole') ?: 'user';
return $user;
}
/**
* Checks if username exists and generate a new one
*
* @param string $username username data.
* @return string
*/
public function generateUniqueUsername($username)
{
$i = 0;
while (true) {
$existingUsername = $this->_table->find()
->where([$this->_table->aliasField($this->_username) => $username])
->count();
if ($existingUsername > 0) {
$username = $username . $i;
$i++;
continue;
}
break;
}
return $username;
}
/**
* Prepare a query to retrieve existing entity for social login
*
* @param \Cake\ORM\Query $query The base query.
* @param array $options Find options with email key.
*
* @return \Cake\ORM\Query
*/
public function findExistingForSocialLogin(\Cake\ORM\Query $query, array $options)
{
return $query->where([
$this->_table->aliasField('email') => $options['email']
]);
}
/**
* Extract the account data to insert/update
*
* @param array $data Social data.
*
* @throws \Exception
*/
protected function extractAccountData(array $data)
{
$accountData = [];
$accountData['username'] = Hash::get($data, 'username');
$accountData['reference'] = Hash::get($data, 'id');
$accountData['avatar'] = Hash::get($data, 'avatar');
$accountData['link'] = Hash::get($data, 'link');
$accountData['avatar'] = str_replace('normal', 'square', $accountData['avatar']);
$accountData['description'] = Hash::get($data, 'bio');
$accountData['token'] = Hash::get($data, 'credentials.token');
$accountData['token_secret'] = Hash::get($data, 'credentials.secret');
$expires = Hash::get($data, 'credentials.expires');
if (!empty($expires)) {
$expiresTime = new DateTime();
$accountData['token_expires'] = $expiresTime->setTimestamp($expires)->format('Y-m-d H:i:s');
} else {
$accountData['token_expires'] = null;
}
$accountData['data'] = serialize(Hash::get($data, 'raw'));
return $accountData;
}
}