-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathOAuthModule.php
More file actions
935 lines (807 loc) · 25.8 KB
/
Copy pathOAuthModule.php
File metadata and controls
935 lines (807 loc) · 25.8 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
<?php
include_once(dirname(__DIR__).'/oauth-php/library/OAuthStore.php');
include_once(dirname(__DIR__).'/oauth-php/library/OAuthRequester.php');
/**
* Abstract class, implements OAuth flow and data storage for specific modules to subclass
*
* @package StartupAPI
* @subpackage Authentication
*/
abstract class OAuthAuthenticationModule extends AuthenticationModule
{
/**
* @var string Service display name
*/
protected $serviceName;
/**
* @var string Name of user credentials class for this module, created and overriden by subclass
*/
protected $userCredentialsClass;
/**
* @var OAuthStoreMySQLi OAuth store instance - using MySQLi store as the rest of the app uses MySQLi
*/
protected $oAuthStore;
/**************************************************************************
*
* OAuth parameters
*
**************************************************************************/
/**
* @var string Root URL for all API calls using this provider
*/
protected $oAuthAPIRootURL;
/**
* @var string OAuth consumer key
*/
protected $oAuthConsumerKey;
/**
* @var string OAuth consumer secret
*/
protected $oAuthConsumerSecret;
/**
* @var string URL of OAuth endpoint for getting request tokens
*/
protected $oAuthRequestTokenURL;
/**
* @var string URL of OAuth endpoint for getting access tokens
*/
protected $oAuthAccessTokenURL;
/**
* @var string Authorization/authentication dialog URL to redirect user to
*/
protected $oAuthAuthorizeURL;
/**
* @var array Array of signature methods supported by the service, e.g. 'HMAC-SHA1'
*/
protected $oAuthSignatureMethods = array();
/**
* @var string Requested permission scopes (zero or more scope strings, usually URLs, separated by spaces)
*/
protected $oAuthScope;
/**************************************************************************
*
* Look and feel
*
**************************************************************************/
/**
* @var type Sign-up button image URL
*/
protected $signUpButtonURL;
/**
* @var type Login button image URL
*/
protected $logInButtonURL;
/**
* @var type Connect button image URL
*/
protected $connectButtonURL;
/**************************************************************************
*
* Activities. Subclasses must assign unique integer IDs
*
**************************************************************************/
/**
* @var array Login activity configuration array
*/
protected $USERBASE_ACTIVITY_OAUTH_MODULE_LOGIN;
/**
* @var array Connection added activity configuration array
*/
protected $USERBASE_ACTIVITY_OAUTH_MODULE_ADDED;
/**
* @var array Connection removed activity configuration array
*/
protected $USERBASE_ACTIVITY_OAUTH_MODULE_REMOVED;
/**
* @var array Registration activity configuration array
*/
protected $USERBASE_ACTIVITY_OAUTH_MODULE_REGISTER;
/**
* Instantiates a new OAuth-based module and registers it in the system
*
* @param string $serviceName Service display name
* @param string $oAuthAPIRootURL Root URL for all API calls using this provider
* @param string $oAuthConsumerKey OAuth consumer key
* @param string $oAuthConsumerSecret OAuth consumer secret
* @param string $oAuthRequestTokenURL URL of OAuth endpoint for getting request tokens
* @param string $oAuthAccessTokenURL URL of OAuth endpoint for getting access tokens
* @param string $oAuthAuthorizeURL Authorization/authentication dialog URL to redirect user to
* @param array $oAuthSignatureMethods Array of signature methods supported by the service, e.g. 'HMAC-SHA1'
* @param string $oAuthScope Requested permission scopes (zero or more scope strings, usually URLs, separated by spaces)
* @param string $signUpButtonURL Sign-up button image URL
* @param string $logInButtonURL Login button image URL
* @param string $connectButtonURL Connect button image URL
* @param array $activities Array of user activity configuration entries (see UserConfig::$activities)
*/
public function __construct($serviceName,
$oAuthAPIRootURL,
$oAuthConsumerKey, $oAuthConsumerSecret,
$oAuthRequestTokenURL, $oAuthAccessTokenURL, $oAuthAuthorizeURL,
$oAuthSignatureMethods,
$oAuthScope,
$signUpButtonURL = null,
$logInButtonURL = null,
$connectButtonURL = null,
$activities = null)
{
parent::__construct();
$this->serviceName = $serviceName;
$this->oAuthAPIRootURL = $oAuthAPIRootURL;
$this->oAuthConsumerKey = $oAuthConsumerKey;
$this->oAuthConsumerSecret= $oAuthConsumerSecret;
$this->oAuthRequestTokenURL = $oAuthRequestTokenURL;
$this->oAuthAccessTokenURL = $oAuthAccessTokenURL;
$this->oAuthAuthorizeURL = $oAuthAuthorizeURL;
$this->oAuthSignatureMethods = $oAuthSignatureMethods;
$this->oAuthScope = $oAuthScope;
$this->signUpButtonURL = $signUpButtonURL;
$this->logInButtonURL = $logInButtonURL;
$this->connectButtonURL = $connectButtonURL;
if (!is_null($activities)) {
$this->USERBASE_ACTIVITY_OAUTH_MODULE_LOGIN = $activities[0][0];
$this->USERBASE_ACTIVITY_OAUTH_MODULE_ADDED = $activities[1][0];
$this->USERBASE_ACTIVITY_OAUTH_MODULE_REMOVED = $activities[2][0];
$this->USERBASE_ACTIVITY_OAUTH_MODULE_REGISTER = $activities[3][0];
UserConfig::$activities[$activities[0][0]] = array($activities[0][1], $activities[0][2]);
UserConfig::$activities[$activities[1][0]] = array($activities[1][1], $activities[1][2]);
UserConfig::$activities[$activities[2][0]] = array($activities[2][1], $activities[2][2]);
UserConfig::$activities[$activities[3][0]] = array($activities[3][1], $activities[3][2]);
}
$this->oAuthStore = OAuthStore::instance('MySQLi', array(
'conn' => UserConfig::getDB(),
'table_prefix' => 'u_'
));
}
/**************************************************************************
*
* Methods related to OAuth handling
*
**************************************************************************/
/**
* Each module is supposed to implement this service to retrieve identity info from the server.
*
* Relying on the key only is not enough as some servers might not return same access_token
* for the same user. Also, access_tokens can expire or be revoked eventually, but this doesn't
* mean that the system user identity has changed.
*
* @param int $oauth_user_id OAuth user id to get identity for
*
* @return array $identity Identity array that includes user info including 'id' column which
* uniquely identifies the user on server and 'name' value that can be
* used as user's name upon registration
*/
abstract public function getIdentity($oauth_user_id);
/**
* Initializes the server entry in the database if it wasn't initialized beforehand
*/
protected function initOAuthServer() {
// check if server is already registered in our database, otherwise, create the entry
try {
$this->oAuthStore->getServerForUri($this->oAuthAPIRootURL, null);
} catch (OAuthException2 $e) {
$this->oAuthStore->updateServer(array(
'server_uri' => $this->oAuthAPIRootURL,
'consumer_key' => $this->oAuthConsumerKey,
'consumer_secret' => $this->oAuthConsumerSecret,
'authorize_uri' => $this->oAuthAuthorizeURL,
'request_token_uri' => $this->oAuthRequestTokenURL,
'access_token_uri' => $this->oAuthAccessTokenURL,
'signature_methods' => $this->oAuthSignatureMethods,
'user_id' => null
), null, true);
}
}
/**
* Starts OAuth flow
*
* @throws StartupAPIException
*/
protected function startOAuthFlow() {
// generate new user id since we're logging in and have no idea who the user is
$oauth_user_id = $this->getNewOAuthUserID();
$storage = new MrClay_CookieStorage(array(
'secret' => UserConfig::$SESSION_SECRET,
'mode' => MrClay_CookieStorage::MODE_ENCRYPT,
'path' => UserConfig::$SITEROOTURL,
'httponly' => true
));
if (!$storage->store(UserConfig::$oauth_user_id_key, $oauth_user_id)) {
throw new StartupAPIException(implode('; ', $storage->errors));
}
try
{
$callback = UserConfig::$USERSROOTFULLURL.'/oauth_callback.php?module='.$this->getID();
$this->initOAuthServer();
$params = array(
'oauth_callback' => $callback
);
if (!is_null($this->oAuthScope)) {
$params['scope'] = $this->oAuthScope;
}
if (!is_null(UserConfig::$OAuthAppName)) {
$params['xoauth_displayname'] = UserConfig::$OAuthAppName;
}
// STEP 1: get a request token
$tokenResultParams = OAuthRequester::requestRequestToken(
$this->oAuthConsumerKey,
$oauth_user_id,
$params
);
$authorize_url = $this->getAuthorizeURL($tokenResultParams);
// redirect to the authorization page, they will redirect back
header("Location: " . $authorize_url . "?oauth_token=" . rawurlencode($tokenResultParams['token']));
exit;
} catch(OAuthException2 $e) {
error_log(var_export($e, true));
}
}
/**
* By default returns pre-defined authorization URL, but subclasses can override
* this function to get authorization URL from token parameters passed back.
*
* @param array $tokenResultParams array of OAuth token information passed in by provider
*
* @return string Returns OAuth Authorization URL
*/
protected function getAuthorizeURL($tokenResultParams) {
return $this->oAuthAuthorizeURL;
}
/**
* When we don't know current user, we need to create a new OAuth User ID to use for new connection.
* If we know the user when OAuth comes through, we'll replace current OAuth User ID with the new one.
*
* @return string New/temporary OAuth user ID
*
* @throws DBException
*/
protected function getNewOAuthUserID() {
$this->initOAuthServer();
$db = UserConfig::getDB();
$module = $this->getID();
if ($stmt = $db->prepare('INSERT INTO u_user_oauth_identity (module) VALUES (?)'))
{
if (!$stmt->bind_param('s', $module))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
$oauth_user_id = $stmt->insert_id;
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
return $oauth_user_id;
}
/**
* Adds user identity to OAuth user
*
* @param User $user User who this OAuth credentials belong
* @param array $identity Identity array provided for this OAuth user
* @param int $oauth_user_id OAuth user id
*
* @throws DBException
*/
public function addUserOAuthIdentity($user, $identity, $oauth_user_id) {
$db = UserConfig::getDB();
$user_id = $user->getID();
$server_unique_id = $identity['id'];
$serialized_userinfo = serialize($identity);
$module = $this->getID();
// updating new recently created entry
if ($stmt = $db->prepare('UPDATE u_user_oauth_identity SET user_id = ?, identity = ?, userinfo = ? WHERE oauth_user_id = ? AND module = ?'))
{
if (!$stmt->bind_param('issis', $user_id, $server_unique_id, $serialized_userinfo, $oauth_user_id, $module))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
}
/**
* Deletes OAuth user credentials
*
* @param int $oauth_user_id OAuth user ID
*
* @throws DBException
*/
public function deleteOAuthUser($oauth_user_id) {
$db = UserConfig::getDB();
if ($stmt = $db->prepare('DELETE FROM u_user_oauth_identity WHERE oauth_user_id = ?'))
{
if (!$stmt->bind_param('i', $oauth_user_id))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
}
/**
* Returns a user for OAuth credentials
*
* Gets StartupAPI user by server identity and resets user_id -> oauth_user_id if necessary
*
* @param array $identity Identity array provided for this OAuth user
* @param int $oauth_user_id OAuth user id
*
* @return User|null User object or null if these credentials are not connected to any user
*
* @throws DBException
*/
public function getUserByOAuthIdentity($identity, $oauth_user_id) {
$db = UserConfig::getDB();
$user_id = null;
$old_oauth_user_id = null;
$server_unique_id = $identity['id'];
$module = $this->getID();
if ($stmt = $db->prepare('SELECT oauth_user_id, user_id FROM u_user_oauth_identity WHERE module = ? AND identity = ?'))
{
if (!$stmt->bind_param('ss', $module, $server_unique_id))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($old_oauth_user_id, $user_id))
{
throw new DBBindResultException($db, $stmt);
}
$stmt->fetch();
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
// nobody registered with this identity yet
if (!$user_id) {
return null;
}
if ($old_oauth_user_id != $oauth_user_id) {
// let's re-map from old oauth_user_id to new one
// deleting old one first
$this->deleteOAuthUser($old_oauth_user_id);
$serialized_userinfo = serialize($identity);
// updating new recently created entry
if ($stmt = $db->prepare('UPDATE u_user_oauth_identity SET user_id = ?, identity = ?, userinfo = ? WHERE oauth_user_id = ?'))
{
if (!$stmt->bind_param('issi', $user_id, $server_unique_id, $serialized_userinfo, $oauth_user_id))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
}
return User::getUser($user_id);
}
/**
* Retrieves OAuth access token from the service
*
* @param int $oauth_user_id OAuth user ID
*/
public function getAccessToken($oauth_user_id) {
// STEP 2: Get an access token
$oauthToken = $_GET["oauth_token"];
// echo "oauth_verifier = '" . $oauthVerifier . "'<br/>";
$tokenResultParams = $_GET;
OAuthRequester::requestAccessToken(
$this->oAuthConsumerKey,
$oauthToken,
$oauth_user_id,
'POST',
$_GET
);
}
/**************************************************************************
*
* Methods related to Startup API mechanics
*
**************************************************************************/
/**
* Renders login form HTML with a single button
*
* Uses self::$loginButtonURL for a button image if supplied
*
* @param string $action Action URL the form should submit data to
*/
public function renderLoginForm($template_info, $action)
{
$slug = $this->getID();
$template_info['slug'] = $slug;
$template_info['action'] = $action;
$template_info['serviceName'] = $this->serviceName;
$template_info['logInButtonURL'] = $this->logInButtonURL;
// using same template for OAuth and OAuth2
return StartupAPI::$template->render("@startupapi/oauth_login_form.html.twig", $template_info);
}
/**
* Renders registration form HTML with a single button
*
* Uses self::$signUpButtonURL for a button image if supplied
*
* @param array[] $template_info Array of base information for Twig template
* @param boolean $full Whatever or not to display a short version of the form or full
* @param string $action Action URL the form should submit data to
* @param array $errors An array of error messages to be displayed to the user on error
* @param array $data An array of data passed by a form on previous submission to display back to user
*/
public function renderRegistrationForm($template_info, $full = false, $action = null, $errors = null , $data = null)
{
if (is_null($action))
{
$action = UserConfig::$USERSROOTURL.'/register.php?module='.$this->getID();
}
$template_info['slug'] = $this->getID();
$template_info['action'] = $action;
$template_info['full'] = $full ? TRUE : FALSE;
$template_info['errors'] = $errors;
$template_info['data'] = $data;
$template_info['serviceName'] = $this->serviceName;
$template_info['signUpButtonURL'] = $this->signUpButtonURL;
// using same template for OAuth and OAuth2
return StartupAPI::$template->render("@startupapi/oauth_registration_form.html.twig", $template_info);
}
/**
* Renders user editing form
*
* Uses self::$connectButtonURL for a button image if supplied
*
* @param array[] $template_info Array of base information for Twig template
* @param string $action Form action URL to post back to
* @param array $errors Array of error messages to display
* @param User $user User object for current user that is being edited
* @param array $data Data submitted to the form
*
* @return string Rendered user ediging form for this module
*
* @throws DBException
*/
public function renderEditUserForm($template_info, $action, $errors, $user, $data)
{
$db = UserConfig::getDB();
$user_id = $user->getID();
$module = $this->getID();
$oauth_user_id = null;
$serialized_userinfo = null;
if ($stmt = $db->prepare('SELECT oauth_user_id, userinfo FROM u_user_oauth_identity WHERE user_id = ? AND module = ?'))
{
if (!$stmt->bind_param('is', $user_id, $module))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($oauth_user_id, $serialized_userinfo))
{
throw new DBBindResultException($db, $stmt);
}
$stmt->fetch();
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
$template_info['slug'] = $this->getID();
$template_info['action'] = $action;
$template_info['errors'] = $errors;
$template_info['data'] = $data;
$template_info['connectButtonURL'] = $this->connectButtonURL;
$template_info['title'] = $this->getTitle();
$template_info['oauth_user_id'] = $oauth_user_id;
$template_info['rendered_userinfo'] = $this->renderUserInfo($serialized_userinfo);
return StartupAPI::$template->render("@startupapi/oauth_edit_user_form.html.twig", $template_info);
}
/**
* Returns user credentials
*
* Creates a new object of self::$userCredentialsClass class and returns it
*
* @param User $user User to get credentials for
*
* @return OAuthUserCredentials User credentials object specific to the module
*
* @throws DBException
*/
public function getUserCredentials($user)
{
$db = UserConfig::getDB();
$user_id = $user->getID();
$module = $this->getID();
$oauth_user_id = null;
$serialized_userinfo = null;
if ($stmt = $db->prepare('SELECT oauth_user_id, userinfo FROM u_user_oauth_identity WHERE user_id = ? AND module = ?'))
{
if (!$stmt->bind_param('is', $user_id, $module))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($oauth_user_id, $serialized_userinfo))
{
throw new DBBindResultException($db, $stmt);
}
$stmt->fetch();
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
if (is_null($serialized_userinfo)) {
return null;
}
return new $this->userCredentialsClass($oauth_user_id, unserialize($serialized_userinfo));
}
/**
* Renders user information as HTML
*
* Subclasses can override to add links to user profiles on destination sites, userpics and etc.
*
* @param array $serialized_userinfo Array of user info parameters from provider with "id" and "name" required
*
* @return string Rendered user information HTML
*/
protected function renderUserInfo($serialized_userinfo) {
$user_info = unserialize($serialized_userinfo);
if (is_array($user_info) && array_key_exists('name', $user_info)) {
return $user_info['name'];
} else {
return NULL;
}
}
/**
* Called when login form is submitted
*
* This method never returns user information, it redirects to OAuth flow
* ending on oauth_callback.php which implements the logic instead of login.php
*
* @param array $data Form data
* @param boolean $remember whatever or not to remember the user
*
* @return null This method never returns user information
*/
public function processLogin($data, &$remember)
{
$this->startOAuthFlow();
return null; // it never reaches this point
}
/**
* Called when registration form is submitted
*
* This method never returns user information, it redirects to OAuth flow
* ending on oauth_callback.php which implements the logic instead of register.php
*
* @param array $data Form data
* @param boolean $remember whatever or not to remember the user
*
* @return null This method never returns user information
*/
public function processRegistration($data, &$remember)
{
$this->startOAuthFlow();
return null; // it never reaches this point
}
/**
* Updates user connection information
*
* @param User $user User object
* @param array $data Form data
*
* @return boolean True if successful and false if unsuccessful
* @throws DBException
*/
public function processEditUser($user, $data)
{
if (array_key_exists('remove', $data) && array_key_exists('oauth_user_id', $data)) {
$db = UserConfig::getDB();
$oauth_user_id = $data['oauth_user_id'];
$user_id = $user->getID();
if ($stmt = $db->prepare('DELETE FROM u_user_oauth_identity WHERE oauth_user_id = ? AND user_id = ?'))
{
if (!$stmt->bind_param('ii', $oauth_user_id, $user_id))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
if (!is_null($this->USERBASE_ACTIVITY_OAUTH_MODULE_REMOVED)) {
$user->recordActivity($this->USERBASE_ACTIVITY_OAUTH_MODULE_REMOVED);
}
return true;
}
if (array_key_exists('add', $data)) {
$this->startOAuthFlow();
}
}
/**
* Records login activity for a user
*
* @param User $user User object
*/
public function recordLoginActivity($user) {
if (!is_null($this->USERBASE_ACTIVITY_OAUTH_MODULE_LOGIN)) {
$user->recordActivity($this->USERBASE_ACTIVITY_OAUTH_MODULE_LOGIN);
}
}
/**
* Records registration activity for a user
*
* @param User $user User object
*/
public function recordRegistrationActivity($user) {
if (!is_null($this->USERBASE_ACTIVITY_OAUTH_MODULE_REGISTER)) {
$user->recordActivity($this->USERBASE_ACTIVITY_OAUTH_MODULE_REGISTER);
}
}
/**
* Records connection added activity for a user
*
* @param User $user User object
*/
public function recordAddActivity($user) {
if (!is_null($this->USERBASE_ACTIVITY_OAUTH_MODULE_ADDED)) {
$user->recordActivity($this->USERBASE_ACTIVITY_OAUTH_MODULE_ADDED);
}
}
/**
* Returns totsal number of users connected using the module
*
* @return int Number of users connected using the module
*
* @throws DBException
*/
public function getTotalConnectedUsers()
{
$db = UserConfig::getDB();
$module_id = $this->getID();
$conns = 0;
if ($stmt = $db->prepare('SELECT count(*) AS conns FROM u_users u LEFT JOIN u_user_oauth_identity oa ON u.id = oa.user_id WHERE oa.oauth_user_id IS NOT NULL AND oa.module = ?'))
{
if (!$stmt->bind_param('s', $module_id))
{
throw new DBBindParamException($db, $stmt);
}
if (!$stmt->execute())
{
throw new DBExecuteStmtException($db, $stmt);
}
if (!$stmt->bind_result($conns))
{
throw new DBBindResultException($db, $stmt);
}
$stmt->fetch();
$stmt->close();
}
else
{
throw new DBPrepareStmtException($db);
}
return $conns;
}
/**
* All OAuth-based systems have very small footprint
*
* @return boolean Always returns true
*/
public function isCompact() {
return true;
}
}
/**
* Abstract class representing user credentials for making OAuth API calls
*
* Should be extended by subclasses to implement additional features and customize
* formatting for user information, e.g. add links to user profiles, userpics and so on.
*
* @package StartupAPI
* @subpackage Authentication
*/
abstract class OAuthUserCredentials extends UserCredentials {
/**
* @var int OAuth user id
*/
protected $oauth_user_id;
/**
* @var array User info object specific to a subclass
*/
protected $userinfo;
/**
* Creates new OAuth credentials
*
* @param int $oauth_user_id OAuth user ID
* @param array $userinfo User info array as retrieved from provider
*/
public function __construct($oauth_user_id, $userinfo) {
$this->oauth_user_id = $oauth_user_id;
$this->userinfo = $userinfo;
}
/**
* Returns OAuth user ID
*
* @return string OAuth user ID
*/
public function getOAuthUserID() {
return $this->oauth_user_id;
}
/**
* Returns an array of user information key-value pairs
*
* @return array Array of user-specific information
*/
public function getUserInfo() {
return $this->userinfo;
}
/**
* Returns a chunk of HTML to display user's credentials
*
* This method will most likely be implemented by a subclass using $this->userinfo object.
* For some providers it can be returning a code to include a JavaScript widget.
*
* @return string HTML to display user information
*/
public function getHTML() {
return $this->userinfo['name'];
}
/**
* Makes HTTP request with OAuth authentication
*
* This method allows requesting information on behalf of the user from a 3rd party provider.
* Possibly the most important feature of the whole system.
*
* @param string $request Request URL
* @param string $method HTTP method (e.g. GET, POST, PUT, etc)
* @param array $params Request parameters key->value array
* @param string $body Request body
* @param array $files Array of file names (currently supports 1 max untilmultipart/form-data is supported)
*
* @return array Response data (code=>int, headers=>array(), body=>string)
*/
public function makeOAuthRequest($request, $method = null, $params = null, $body = null, $files = null) {
$request = new OAuthRequester($request, $method, $params, $body, $files);
return $request->doRequest($this->oauth_user_id);
}
}