-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
FBSession.m
2416 lines (2087 loc) · 112 KB
/
FBSession.m
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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBSession.h"
#import "FBSession+Internal.h"
#import <Accounts/Accounts.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIDevice.h>
#import "FBAccessTokenData+Internal.h"
#import "FBAppBridge.h"
#import "FBAppCall+Internal.h"
#import "FBAppEvents+Internal.h"
#import "FBAppEvents.h"
#import "FBDataDiskCache.h"
#import "FBDialogConfig.h"
#import "FBDialogs+Internal.h"
#import "FBError.h"
#import "FBErrorUtility+Internal.h"
#import "FBInternalSettings.h"
#import "FBLogger.h"
#import "FBLoginDialog.h"
#import "FBRequest+Internal.h"
#import "FBSession+Protected.h"
#import "FBSessionAppSwitchingLoginStategy.h"
#import "FBSessionAuthLogger.h"
#import "FBSessionInlineWebViewLoginStategy.h"
#import "FBSessionSystemLoginStategy.h"
#import "FBSessionTokenCachingStrategy.h"
#import "FBSessionUtility.h"
#import "FBSettings+Internal.h"
#import "FBSystemAccountStoreAdapter.h"
#import "FBUtility.h"
#import "Facebook.h"
#import "FacebookSDK.h"
static NSString *const FBAuthURLScheme = @"fbauth";
static NSString *const FBAuthURLPath = @"authorize";
static NSString *const FBRedirectURL = @"fbconnect://success";
static NSString *const FBLoginDialogMethod = @"oauth";
static NSString *const FBLoginUXClientID = @"client_id";
static NSString *const FBLoginUXRedirectURI = @"redirect_uri";
static NSString *const FBLoginUXTouch = @"touch";
static NSString *const FBLoginUXDisplay = @"display";
static NSString *const FBLoginUXIOS = @"ios";
static NSString *const FBLoginUXSDK = @"sdk";
static NSString *const FBLoginUXReturnScopesYES = @"true";
static NSString *const FBLoginUXReturnScopes = @"return_scopes";
static NSString *const FBLoginUXDefaultAudience = @"default_audience";
static NSString *const FBLoginParamsExpiresIn = @"expires_in";
static NSString *const FBLoginParamsPermissions = @"permissions";
static NSString *const FBLoginParamsGrantedScopes = @"granted_scopes";
static NSString *const FBLoginParamsDeniedScopes = @"denied_scopes";
static NSString *const FBLoginParamsSDKVersion = @"sdk_version";
static NSString *const FBLoginParamsLegacyOverride = @"legacy_override";
NSString *const FBLoginUXResponseTypeTokenAndSignedRequest = @"token,signed_request";
NSString *const FBLoginUXResponseType = @"response_type";
// client state related strings
NSString *const FBLoginUXClientState = @"state";
NSString *const FBLoginUXClientStateIsClientState = @"com.facebook.sdk_client_state";
NSString *const FBLoginUXClientStateIsOpenSession = @"is_open_session";
NSString *const FBLoginUXClientStateIsActiveSession = @"is_active_session";
// the following constant strings are used by NSNotificationCenter
NSString *const FBSessionDidSetActiveSessionNotification = @"com.facebook.sdk:FBSessionDidSetActiveSessionNotification";
NSString *const FBSessionDidUnsetActiveSessionNotification = @"com.facebook.sdk:FBSessionDidUnsetActiveSessionNotification";
NSString *const FBSessionDidBecomeOpenActiveSessionNotification = @"com.facebook.sdk:FBSessionDidBecomeOpenActiveSessionNotification";
NSString *const FBSessionDidBecomeClosedActiveSessionNotification = @"com.facebook.sdk:FBSessionDidBecomeClosedActiveSessionNotification";
NSString *const FBSessionDidSetActiveSessionNotificationUserInfoIsOpening = @"com.facebook.sdk:FBSessionDidSetActiveSessionNotificationUserInfoIsOpening";
// the following const strings name properties for which KVO is manually handled
// if name changes occur, these strings must be modified to match, else KVO will fail
static NSString *const FBisOpenPropertyName = @"isOpen";
static NSString *const FBstatusPropertyName = @"state";
static NSString *const FBaccessTokenPropertyName = @"accessToken";
static NSString *const FBexpirationDatePropertyName = @"expirationDate";
static NSString *const FBaccessTokenDataPropertyName = @"accessTokenData";
static int const FBTokenExtendThresholdSeconds = 24 * 60 * 60; // day
static int const FBTokenRetryExtendSeconds = 60 * 60; // hour
// the following constant strings are used as keys into response url parameters during authorization flow
// Key used to access an inner error object in the response parameters. Currently used by Native Login only.
NSString *const FBInnerErrorObjectKey = @"inner_error_object";
NSString *const FacebookNativeApplicationLoginDomain = @"com.facebook.Facebook.platform.login";
// module scoped globals
static FBSession *g_activeSession = nil;
@interface FBSession () <FBLoginDialogDelegate> {
@protected
// public-property ivars
NSString *_urlSchemeSuffix;
// private property and non-property ivars
BOOL _isInStateTransition;
FBSessionLoginType _loginTypeOfPendingOpenUrlCallback;
FBSessionDefaultAudience _defaultDefaultAudience;
FBSessionLoginBehavior _loginBehavior;
NSMutableArray *_declinedPermissions;
NSArray *_requestedReauthPermissions;
}
// private setters
@property (readwrite) FBSessionState state;
@property (readwrite, copy) NSString *appID;
@property (readwrite, copy) NSString *urlSchemeSuffix;
@property (readwrite, copy) FBAccessTokenData *accessTokenData;
@property (readwrite, copy) NSArray *initializedPermissions;
@property (readwrite, assign) FBSessionDefaultAudience lastRequestedSystemAudience;
// A hack to the session state machine to enable repairing of sessions
// (i.e., for sessions whose token have been invalidated such as by
// expiration or password change was NOT un-tossed). We use this flag
// to avoid changing the FBSessionState surface area and to re-use
// the re-auth flow.
@property (atomic, assign) BOOL isRepairing;
// private properties
@property (readwrite, retain) FBSessionTokenCachingStrategy *tokenCachingStrategy;
@property (readwrite, copy) NSDate *attemptedRefreshDate;
@property (readwrite, copy) NSDate *attemptedPermissionsRefreshDate;
@property (readwrite, copy) FBSessionStateHandler loginHandler;
@property (readwrite, copy) FBSessionRequestPermissionResultHandler reauthorizeHandler;
@property (readonly) NSString *appBaseUrl;
@property (readwrite, retain) FBLoginDialog *loginDialog;
@property (readwrite, retain) NSThread *affinitizedThread;
@property (readwrite, retain) FBSessionAppEventsState *appEventsState;
@property (readwrite, retain) FBSessionAuthLogger *authLogger;
@end
@implementation FBSession : NSObject
#pragma mark Lifecycle
- (instancetype)init {
return [self initWithAppID:nil
permissions:nil
urlSchemeSuffix:nil
tokenCacheStrategy:nil];
}
- (instancetype)initWithPermissions:(NSArray *)permissions {
return [self initWithAppID:nil
permissions:permissions
urlSchemeSuffix:nil
tokenCacheStrategy:nil];
}
- (instancetype)initWithAppID:(NSString *)appID
permissions:(NSArray *)permissions
urlSchemeSuffix:(NSString *)urlSchemeSuffix
tokenCacheStrategy:(FBSessionTokenCachingStrategy *)tokenCachingStrategy {
return [self initWithAppID:appID
permissions:permissions
defaultAudience:FBSessionDefaultAudienceNone
urlSchemeSuffix:urlSchemeSuffix
tokenCacheStrategy:tokenCachingStrategy];
}
- (instancetype)initWithAppID:(NSString *)appID
permissions:(NSArray *)permissions
defaultAudience:(FBSessionDefaultAudience)defaultAudience
urlSchemeSuffix:(NSString *)urlSchemeSuffix
tokenCacheStrategy:(FBSessionTokenCachingStrategy *)tokenCachingStrategy {
self = [super init];
if (self) {
// setup values where nil implies a default
if (!appID) {
appID = [FBSettings defaultAppID];
}
if (!permissions) {
permissions = [NSArray array];
}
if (!urlSchemeSuffix) {
urlSchemeSuffix = [FBSettings defaultUrlSchemeSuffix];
}
if (!tokenCachingStrategy) {
tokenCachingStrategy = [FBSessionTokenCachingStrategy defaultInstance];
}
// if we don't have an appID by here, fail -- this is almost certainly an app-bug
if (!appID) {
[[NSException exceptionWithName:FBInvalidOperationException
reason:@"FBSession: No AppID provided; either pass an "
@"AppID to init, or add a string valued key with the "
@"appropriate id named FacebookAppID to the bundle *.plist"
userInfo:nil]
raise];
}
// assign arguments;
_appID = [appID copy];
_initializedPermissions = [permissions copy];
_urlSchemeSuffix = [urlSchemeSuffix copy];
_tokenCachingStrategy = [tokenCachingStrategy retain];
// additional setup
_isInStateTransition = NO;
_loginTypeOfPendingOpenUrlCallback = FBSessionLoginTypeNone;
_defaultDefaultAudience = defaultAudience;
_appEventsState = [[FBSessionAppEventsState alloc] init];
_attemptedRefreshDate = [[NSDate distantPast] copy];
_attemptedPermissionsRefreshDate = [[NSDate distantPast] copy];
_state = FBSessionStateCreated;
_affinitizedThread = [[NSThread currentThread] retain];
[FBLogger registerCurrentTime:FBLoggingBehaviorPerformanceCharacteristics
withTag:self];
// Default the login behavior, but it can be overwritten by the cached token below.
_loginBehavior = FBSessionLoginBehaviorWithFallbackToWebView;
FBAccessTokenData *cachedTokenData = [self.tokenCachingStrategy fetchFBAccessTokenData];
if (cachedTokenData && ![self initializeFromCachedToken:cachedTokenData withPermissions:permissions]) {
[self.tokenCachingStrategy clearToken];
};
}
return self;
}
// Helper method to initialize current state from a cached token. This will transition to
// FBSessionStateCreatedTokenLoaded if the `cachedToken` is viable and return YES. Otherwise, it returns NO.
// This method will return NO immediately if the current state is not FBSessionStateCreated.
- (BOOL)initializeFromCachedToken:(FBAccessTokenData *)cachedToken withPermissions:(NSArray *)permissions
{
if (cachedToken && self.state == FBSessionStateCreated) {
BOOL isAppID = (!cachedToken.appID || [cachedToken.appID isEqualToString:self.appID]);
if (isAppID && (NSOrderedDescending == [cachedToken.expirationDate compare:[NSDate date]])) {
_loginBehavior = [FBSessionUtility loginBehaviorForLoginType:self.accessTokenData.loginType];
[self transitionToState:FBSessionStateCreatedTokenLoaded
withAccessTokenData:cachedToken
shouldCache:NO];
return YES;
}
}
return NO;
}
- (void)dealloc {
[_loginDialog release];
[_attemptedRefreshDate release];
[_attemptedPermissionsRefreshDate release];
[_accessTokenData release];
[_reauthorizeHandler release];
[_loginHandler release];
[_appID release];
[_urlSchemeSuffix release];
[_initializedPermissions release];
[_tokenCachingStrategy release];
[_affinitizedThread release];
[_appEventsState release];
[_authLogger release];
[_declinedPermissions release];
[_requestedReauthPermissions release];
[super dealloc];
}
#pragma mark - Public Properties
- (NSArray *)permissions {
if (self.accessTokenData) {
return self.accessTokenData.permissions;
} else {
return self.initializedPermissions;
}
}
- (NSArray *)declinedPermissions {
if (self.accessTokenData) {
return self.accessTokenData.declinedPermissions;
}
return [NSArray array];
}
- (NSDate *)refreshDate {
return self.accessTokenData.refreshDate;
}
- (NSString *)accessToken {
return self.accessTokenData.accessToken;
}
- (NSDate *)expirationDate {
return self.accessTokenData.expirationDate;
}
- (FBSessionLoginType) loginType {
if (self.accessTokenData) {
return self.accessTokenData.loginType;
} else {
return FBSessionLoginTypeNone;
}
}
#pragma mark - Public Members
//deprecated
- (void)openWithCompletionHandler:(FBSessionStateHandler)handler {
[self openWithCompletionHandler:handler fromViewController:nil];
}
- (void)openWithCompletionHandler:(FBSessionStateHandler)handler fromViewController:(UIViewController *)fromViewController
{
[self openWithBehavior:FBSessionLoginBehaviorWithFallbackToWebView
fromViewController:fromViewController
completionHandler:handler];
}
//deprecated
- (void)openWithBehavior:(FBSessionLoginBehavior)behavior
completionHandler:(FBSessionStateHandler)handler {
[self openWithBehavior:behavior
fromViewController:nil
completionHandler:handler];
}
- (void)openWithBehavior:(FBSessionLoginBehavior)behavior
fromViewController:(UIViewController *)fromViewController
completionHandler:(FBSessionStateHandler)handler
{
self.fromViewController = fromViewController;
// is everything in good order?
[FBSessionUtility validateRequestForPermissions:_initializedPermissions
defaultAudience:_defaultDefaultAudience
allowSystemAccount:behavior == FBSessionLoginBehaviorUseSystemAccountIfPresent
isRead:[FBUtility areAllPermissionsReadPermissions:_initializedPermissions]];
[self checkThreadAffinity];
switch (behavior) {
case FBSessionLoginBehaviorForcingWebView:
case FBSessionLoginBehaviorUseSystemAccountIfPresent:
case FBSessionLoginBehaviorWithFallbackToWebView:
case FBSessionLoginBehaviorWithNoFallbackToWebView:
case FBSessionLoginBehaviorForcingSafari:
// valid behavior; no-op.
break;
default:
[FBLogger singleShotLogEntry:FBLoggingBehaviorDeveloperErrors formatString:@"%lu is not a valid FBSessionLoginBehavior. Ignoring open call.", (unsigned long)behavior];
return;
}
if (!(self.state == FBSessionStateCreated ||
self.state == FBSessionStateCreatedTokenLoaded)) {
// login may only be called once, and only from one of the two initial states
[[NSException exceptionWithName:FBInvalidOperationException
reason:@"FBSession: an attempt was made to open an already opened or closed session"
userInfo:nil]
raise];
}
_loginBehavior = behavior;
if (handler != nil) {
// Note blocks are not value comparable, so this can intentionally result in false positives; nonetheless, let's
// log it for easier identification/reporting in case developers do run into this edge case unexpectedly.
if (self.loginHandler != NULL && self.loginHandler != handler) {
[FBLogger singleShotLogEntry:FBLoggingBehaviorDeveloperErrors logEntry:@"An existing state change handler was assigned to the session and will be overwritten."];
}
self.loginHandler = handler;
}
if ([FBSettings restrictedTreatment] == FBRestrictedTreatmentYES) {
NSError *error = [self errorLoginFailedWithReason:FBErrorLoginFailedReasonOtherError
errorCode:[@(FBErrorOperationDisallowedForRestrictedTreatment) stringValue]
innerError:nil];
[self transitionAndCallHandlerWithState:FBSessionStateClosedLoginFailed
error:error
tokenData:nil
shouldCache:NO];
return;
}
// normal login depends on the availability of a valid cached token
if (self.state == FBSessionStateCreated) {
// set the state and token info
[self transitionToState:FBSessionStateCreatedOpening
withAccessTokenData:nil
shouldCache:NO];
[self authorizeWithPermissions:self.initializedPermissions
behavior:behavior
defaultAudience:_defaultDefaultAudience
isReauthorize:NO];
} else { // self.status == FBSessionStateLoadedValidToken
// this case implies that a valid cached token was found, and preserves the
// "1-session-1-identity" rule, by transitioning to logged in, without a transition to login UX
[self transitionAndCallHandlerWithState:FBSessionStateOpen
error:nil
tokenData:nil
shouldCache:NO];
}
}
- (void)reauthorizeWithPermissions:(NSArray *)permissions
behavior:(FBSessionLoginBehavior)behavior
completionHandler:(FBSessionReauthorizeResultHandler)handler {
[self reauthorizeWithPermissions:permissions
isRead:NO
behavior:behavior
defaultAudience:FBSessionDefaultAudienceNone
completionHandler:handler];
}
- (void)reauthorizeWithReadPermissions:(NSArray *)readPermissions
completionHandler:(FBSessionReauthorizeResultHandler)handler {
[self requestNewReadPermissions:readPermissions
completionHandler:handler];
}
- (void)reauthorizeWithPublishPermissions:(NSArray *)writePermissions
defaultAudience:(FBSessionDefaultAudience)audience
completionHandler:(FBSessionReauthorizeResultHandler)handler {
[self requestNewPublishPermissions:writePermissions
defaultAudience:audience
completionHandler:handler];
}
- (void)requestNewReadPermissions:(NSArray *)readPermissions
completionHandler:(FBSessionRequestPermissionResultHandler)handler {
[self reauthorizeWithPermissions:readPermissions
isRead:YES
behavior:_loginBehavior
defaultAudience:FBSessionDefaultAudienceNone
completionHandler:handler];
}
- (void)requestNewPublishPermissions:(NSArray *)writePermissions
defaultAudience:(FBSessionDefaultAudience)audience
completionHandler:(FBSessionRequestPermissionResultHandler)handler {
[self reauthorizeWithPermissions:writePermissions
isRead:NO
behavior:_loginBehavior
defaultAudience:audience
completionHandler:handler];
}
- (void)refreshPermissionsWithCompletionHandler:(FBSessionRequestPermissionResultHandler)handler {
FBRequestConnection *connection = [[[FBRequestConnection alloc] init] autorelease];
FBRequest *request = [[[FBRequest alloc] initWithSession:self graphPath:@"me/permissions"] autorelease];
request.canCloseSessionOnError = NO;
[connection addRequest:request
completionHandler:^(FBRequestConnection *innerConnection, id result, NSError *error) {
if (!error) {
[self handleRefreshPermissions:result];
}
if (handler) {
handler(self, error);
}
}];
[connection start];
}
- (void)close {
[self checkThreadAffinity];
FBSessionState state;
if (self.state == FBSessionStateCreatedOpening) {
state = FBSessionStateClosedLoginFailed;
} else {
state = FBSessionStateClosed;
}
[self transitionAndCallHandlerWithState:state
error:nil
tokenData:nil
shouldCache:NO];
}
- (void)closeAndClearTokenInformation {
[self closeAndClearTokenInformation:nil];
}
// Helper method to transistion token state correctly when
// the app is called back in cases of either app switch
// or FBLoginDialog
- (BOOL)handleAuthorizationCallbacks:(NSString *)accessToken params:(NSDictionary *)params loginType:(FBSessionLoginType)loginType {
// Make sure our logger is setup to finish up the authorization roundtrip
if (!self.authLogger) {
NSDictionary *clientState = [FBSessionUtility clientStateFromQueryParams:params];
NSString *ID = clientState[FBSessionAuthLoggerParamIDKey];
NSString *authMethod = clientState[FBSessionAuthLoggerParamAuthMethodKey];
if (ID || authMethod) {
self.authLogger = [[[FBSessionAuthLogger alloc] initWithSession:self ID:ID authMethod:authMethod] autorelease];
}
}
switch (self.state) {
case FBSessionStateCreatedOpening:
return [self handleAuthorizationOpen:params
accessToken:accessToken
loginType:loginType];
case FBSessionStateOpen:
case FBSessionStateOpenTokenExtended:
if (loginType == FBSessionLoginTypeNone) {
// If loginType == None, then we were not expecting a re-auth
// and entered here from an app link into an existing session
// so we should immediately return NO to prevent a false transition
// to TokenExtended.
return NO;
} else {
return [self handleReauthorize:params
accessToken:accessToken];
}
default:
return NO;
}
}
- (BOOL)handleOpenURL:(NSURL *)url {
[self checkThreadAffinity];
NSDictionary *params = [FBSessionUtility queryParamsFromLoginURL:url
appID:self.appID
urlSchemeSuffix:self.urlSchemeSuffix];
// if the URL's structure doesn't match the structure used for Facebook authorization, abort.
if (!params) {
// We need to not discard native login responses, since the app might not have updated its
// AppDelegate to call into FBAppCall. We are impersonating the native Facebook application's
// bundle Id here. This is no less secure than old FBSession url handling
__block BOOL completionHandlerFound = YES;
BOOL handled = [[FBAppBridge sharedInstance] handleOpenURL:url
sourceApplication:@"com.facebook.Facebook"
session:self
fallbackHandler:^(FBAppCall *call) {
completionHandlerFound = NO;
}];
return handled && completionHandlerFound;
}
FBSessionLoginType loginType = _loginTypeOfPendingOpenUrlCallback;
_loginTypeOfPendingOpenUrlCallback = FBSessionLoginTypeNone;
NSString *accessToken = [params objectForKey:@"access_token"];
return [self handleAuthorizationCallbacks:accessToken params:params loginType:loginType];
}
- (BOOL)openFromAccessTokenData:(FBAccessTokenData *)accessTokenData completionHandler:(FBSessionStateHandler)handler {
return [self openFromAccessTokenData:accessTokenData
completionHandler:handler
raiseExceptionIfInvalidState:YES];
}
- (void)handleDidBecomeActive {
// Unexpected calls to app delegate's applicationDidBecomeActive are
// handled by this method. If a pending fast-app-switch [re]authorization
// is in flight, it is cancelled. Otherwise, this method is a no-op.
[self authorizeRequestWasImplicitlyCancelled];
// This is forward-compatibility. If an AppDelegate isn't updated to use AppCall,
// we still want to provide a good AppBridge experience if possible.
[[FBAppBridge sharedInstance] handleDidBecomeActive];
}
- (BOOL)isOpen {
return FB_ISSESSIONOPENWITHSTATE(self.state);
}
- (NSString *)urlSchemeSuffix {
[self checkThreadAffinity];
return _urlSchemeSuffix ? _urlSchemeSuffix : @"";
}
// actually a private member, but wanted to be close to its public colleague
- (void)setUrlSchemeSuffix:(NSString *)newValue {
if (_urlSchemeSuffix != newValue) {
[_urlSchemeSuffix release];
_urlSchemeSuffix = [(newValue ? newValue : @"") copy];
}
}
- (void)setStateChangeHandler:(FBSessionStateHandler)stateChangeHandler {
if (stateChangeHandler != NULL) {
if (self.loginHandler) {
[FBLogger singleShotLogEntry:FBLoggingBehaviorDeveloperErrors logEntry:@"An existing state change handler was assigned to the session and will be overwritten."];
}
self.loginHandler = [stateChangeHandler copy];
}
}
- (BOOL)hasGranted:(NSString *)permission {
return [self.accessTokenData.permissions containsObject:permission];
}
#pragma mark -
#pragma mark Class Methods
//deprecated
+ (BOOL)openActiveSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
return [self openActiveSessionWithAllowLoginUI:allowLoginUI fromViewController:nil];
}
+ (BOOL)openActiveSessionWithAllowLoginUI:(BOOL)allowLoginUI fromViewController:(UIViewController *)fromViewController
{
return [FBSession openActiveSessionWithPermissions:nil
allowLoginUI:allowLoginUI
allowSystemAccount:NO
isRead:YES
defaultAudience:FBSessionDefaultAudienceNone
fromViewController:fromViewController
completionHandler:nil];
}
// deprecated (and used by tests)
+ (BOOL)openActiveSessionWithPermissions:(NSArray *)permissions
allowLoginUI:(BOOL)allowLoginUI
completionHandler:(FBSessionStateHandler)handler {
return [FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
defaultAudience:FBSessionDefaultAudienceNone
fromViewController:nil
completionHandler:handler];
}
// This should only be used by internal code that needs to support mixed
// permissions backwards compability and specify an audience.
+ (BOOL)openActiveSessionWithPermissions:(NSArray *)permissions
allowLoginUI:(BOOL)allowLoginUI
defaultAudience:(FBSessionDefaultAudience)defaultAudience
fromViewController:(UIViewController *)fromViewController
completionHandler:(FBSessionStateHandler)handler {
return [FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
allowSystemAccount:NO
isRead:NO
defaultAudience:defaultAudience
fromViewController:fromViewController
completionHandler:handler];
}
//deprecated
+ (BOOL)openActiveSessionWithReadPermissions:(NSArray *)readPermissions
allowLoginUI:(BOOL)allowLoginUI
completionHandler:(FBSessionStateHandler)handler
{
return [self openActiveSessionWithReadPermissions:readPermissions
allowLoginUI:allowLoginUI
fromViewController:nil
completionHandler:handler];
}
+ (BOOL)openActiveSessionWithReadPermissions:(NSArray *)readPermissions
allowLoginUI:(BOOL)allowLoginUI
fromViewController:(UIViewController *)fromViewController
completionHandler:(FBSessionStateHandler)handler
{
return [FBSession openActiveSessionWithPermissions:readPermissions
allowLoginUI:allowLoginUI
allowSystemAccount:NO
isRead:YES
defaultAudience:FBSessionDefaultAudienceNone
fromViewController:fromViewController
completionHandler:handler];
}
//deprecated
+ (BOOL)openActiveSessionWithPublishPermissions:(NSArray *)publishPermissions
defaultAudience:(FBSessionDefaultAudience)defaultAudience
allowLoginUI:(BOOL)allowLoginUI
completionHandler:(FBSessionStateHandler)handler
{
return [self openActiveSessionWithPublishPermissions:publishPermissions
defaultAudience:defaultAudience
allowLoginUI:allowLoginUI
fromViewController:nil
completionHandler:handler];
}
+ (BOOL)openActiveSessionWithPublishPermissions:(NSArray *)publishPermissions
defaultAudience:(FBSessionDefaultAudience)defaultAudience
allowLoginUI:(BOOL)allowLoginUI
fromViewController:(UIViewController *)fromViewController
completionHandler:(FBSessionStateHandler)handler
{
return [FBSession openActiveSessionWithPermissions:publishPermissions
allowLoginUI:allowLoginUI
allowSystemAccount:NO
isRead:NO
defaultAudience:defaultAudience
fromViewController:fromViewController
completionHandler:handler];
}
+ (FBSession *)activeSession {
if (!g_activeSession) {
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];
[session release];
}
return [[g_activeSession retain] autorelease];
}
+ (FBSession *)setActiveSession:(FBSession *)session {
return [self setActiveSession:session userInfo:nil];
}
+ (FBSession *)setActiveSession:(FBSession *)session userInfo:(NSDictionary *)userInfo {
if (session != g_activeSession) {
// we will close this, but we want any resulting
// handlers to see the new active session
FBSession *toRelease = g_activeSession;
// if we are being replaced, then we close you
[toRelease close];
// set the new session
g_activeSession = [session retain];
// some housekeeping needs to happen if we had a previous session
if (toRelease) {
// now the notification/release of the prior active
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionDidUnsetActiveSessionNotification
object:toRelease];
[toRelease release];
}
// we don't notify nil sets
if (session) {
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionDidSetActiveSessionNotification
object:session
userInfo:userInfo];
if (session.isOpen) {
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionDidBecomeOpenActiveSessionNotification
object:session
userInfo:userInfo];
}
}
}
return session;
}
+ (void)setDefaultAppID:(NSString *)appID {
[FBSettings setDefaultAppID:appID];
}
+ (NSString *)defaultAppID {
return [FBSettings defaultAppID];
}
+ (void)setDefaultUrlSchemeSuffix:(NSString *)urlSchemeSuffix {
[FBSettings setDefaultUrlSchemeSuffix:urlSchemeSuffix];
}
+ (NSString *)defaultUrlSchemeSuffix {
return [FBSettings defaultUrlSchemeSuffix];
}
+ (void)renewSystemCredentials:(FBSessionRenewSystemCredentialsHandler)handler {
[[FBSystemAccountStoreAdapter sharedInstance] renewSystemAuthorization:handler];
}
#pragma mark -
#pragma mark Private Members (core session members)
// private methods are broken into two categories: core session and helpers
// core member that owns all state transitions as well as property setting for status and isOpen
// `tokenData` will NOT be retained, it will be used to construct a
// new instance - the difference is for things that should not change
// if the session already had a token (e.g., loginType).
- (BOOL)transitionToState:(FBSessionState)state
withAccessTokenData:(FBAccessTokenData *)tokenData
shouldCache:(BOOL)shouldCache {
// is this a valid transition?
BOOL isValidTransition;
FBSessionState statePrior;
statePrior = self.state;
switch (state) {
default:
case FBSessionStateCreated:
isValidTransition = NO;
break;
case FBSessionStateOpen:
isValidTransition = (
statePrior == FBSessionStateCreatedTokenLoaded ||
statePrior == FBSessionStateCreatedOpening
);
break;
case FBSessionStateCreatedOpening:
case FBSessionStateCreatedTokenLoaded:
isValidTransition = statePrior == FBSessionStateCreated;
break;
case FBSessionStateClosedLoginFailed:
isValidTransition = (
statePrior == FBSessionStateCreated ||
statePrior == FBSessionStateCreatedTokenLoaded ||
statePrior == FBSessionStateCreatedOpening
);
break;
case FBSessionStateOpenTokenExtended:
isValidTransition = (
statePrior == FBSessionStateOpen ||
statePrior == FBSessionStateOpenTokenExtended
);
break;
case FBSessionStateClosed:
isValidTransition = (
statePrior == FBSessionStateOpen ||
statePrior == FBSessionStateOpenTokenExtended
);
break;
}
// invalid transition short circuits
if (!isValidTransition) {
[FBLogger singleShotLogEntry:FBLoggingBehaviorSessionStateTransitions
logEntry:[NSString stringWithFormat:@"FBSession **INVALID** transition from %@ to %@",
[FBSessionUtility sessionStateDescription:statePrior],
[FBSessionUtility sessionStateDescription:state]]];
return NO;
}
// if this is yes, someone called a method on FBSession from within a KVO will change handler
if (_isInStateTransition) {
[[NSException exceptionWithName:FBInvalidOperationException
reason:@"FBSession: An attempt to change an FBSession object was "
@"made while a change was in flight; this is most likely due to "
@"a KVO observer calling a method on FBSession while handling a "
@"NSKeyValueObservingOptionPrior notification"
userInfo:nil]
raise];
}
// valid transitions notify
NSString *logString = [NSString stringWithFormat:@"FBSession transition from %@ to %@ ",
[FBSessionUtility sessionStateDescription:statePrior],
[FBSessionUtility sessionStateDescription:state]];
[FBLogger singleShotLogEntry:FBLoggingBehaviorSessionStateTransitions logEntry:logString];
[FBLogger singleShotLogEntry:FBLoggingBehaviorPerformanceCharacteristics
timestampTag:self
formatString:@"%@", logString];
// Re-start session transition timer for the next time around.
[FBLogger registerCurrentTime:FBLoggingBehaviorPerformanceCharacteristics
withTag:self];
// identify whether we will update token and date, and what the values will be
BOOL changingTokenAndDate = NO;
if (tokenData.accessToken && tokenData.expirationDate) {
changingTokenAndDate = YES;
} else if (!FB_ISSESSIONOPENWITHSTATE(state) &&
FB_ISSESSIONOPENWITHSTATE(statePrior)) {
changingTokenAndDate = YES;
tokenData = nil;
}
BOOL changingIsOpen = FB_ISSESSIONOPENWITHSTATE(state) != FB_ISSESSIONOPENWITHSTATE(statePrior);
// should only ever be YES from here...
_isInStateTransition = YES;
// KVO property will change notifications, for state change
[self willChangeValueForKey:FBstatusPropertyName];
if (changingIsOpen) {
[self willChangeValueForKey:FBisOpenPropertyName];
}
if (changingTokenAndDate) {
FBSessionLoginType newLoginType = tokenData.loginType;
// if we are just about to transition to open or token loaded, and the caller
// wants to specify a login type other than none, then we set the login type
FBSessionLoginType loginTypeUpdated = self.accessTokenData.loginType;
if (isValidTransition &&
(state == FBSessionStateOpen || state == FBSessionStateCreatedTokenLoaded) &&
newLoginType != FBSessionLoginTypeNone) {
loginTypeUpdated = newLoginType;
}
// KVO property will-change notifications for token and date
[self willChangeValueForKey:FBaccessTokenPropertyName];
[self willChangeValueForKey:FBaccessTokenDataPropertyName];
[self willChangeValueForKey:FBexpirationDatePropertyName];
// set the new access token as a copy of any existing token with the updated
// token string and expiration date.
// Note if we're opening for the first time, we always set permissions refresh date to distantPast
// to force a permissions refresh piggyback with the next request.
if (tokenData.accessToken) {
FBAccessTokenData *fbAccessToken = [FBAccessTokenData createTokenFromString:tokenData.accessToken
permissions:tokenData.permissions
declinedPermissions:tokenData.declinedPermissions
expirationDate:tokenData.expirationDate
loginType:loginTypeUpdated
refreshDate:tokenData.refreshDate
permissionsRefreshDate:changingIsOpen ? [NSDate distantPast] : tokenData.permissionsRefreshDate
appID:tokenData.appID
userID:tokenData.userID];
self.accessTokenData = fbAccessToken;
} else {
self.accessTokenData = nil;
}
}
// change the actual state
// note: we should not inject any callbacks between this and the token/date changes above
self.state = state;
// ... to here -- if YES
_isInStateTransition = NO;
if (changingTokenAndDate) {
// update the cache
if (shouldCache) {
[self.tokenCachingStrategy cacheFBAccessTokenData:self.accessTokenData];
}
// KVO property change notifications token and date
[self didChangeValueForKey:FBexpirationDatePropertyName];
[self didChangeValueForKey:FBaccessTokenPropertyName];
[self didChangeValueForKey:FBaccessTokenDataPropertyName];
}
// KVO property did change notifications, for state change
if (changingIsOpen) {
[self didChangeValueForKey:FBisOpenPropertyName];
}
[self didChangeValueForKey:FBstatusPropertyName];
// if we are the active session, and we changed is-valid, notify
if (changingIsOpen && g_activeSession == self) {
if (FB_ISSESSIONOPENWITHSTATE(state)) {
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionDidBecomeOpenActiveSessionNotification
object:self];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionDidBecomeClosedActiveSessionNotification
object:self];
}
}
// Note! It is important that no processing occur after the KVO notifications have been raised, in order to
// assure the state is cohesive in common reintrant scenarios
// the NO case short-circuits after the state switch/case
return YES;
}
// core authorization UX flow
- (void)authorizeWithPermissions:(NSArray *)permissions
behavior:(FBSessionLoginBehavior)behavior
defaultAudience:(FBSessionDefaultAudience)audience
isReauthorize:(BOOL)isReauthorize {
BOOL tryIntegratedAuth = NO, tryFacebookLogin = NO, tryFallback = NO, trySafari = NO;
NSString *behaviorString;
switch (behavior) {
case FBSessionLoginBehaviorForcingWebView:
tryFallback = YES;
behaviorString = @"FBSessionLoginBehaviorForcingWebView";
break;
case FBSessionLoginBehaviorUseSystemAccountIfPresent:
tryIntegratedAuth = tryFacebookLogin = trySafari = YES;
behaviorString = @"FBSessionLoginBehaviorUseSystemAccountIfPresent";
break;
case FBSessionLoginBehaviorWithFallbackToWebView:
tryFallback = tryFacebookLogin = trySafari = YES;
behaviorString = @"FBSessionLoginBehaviorWithFallbackToWebView";
break;
case FBSessionLoginBehaviorWithNoFallbackToWebView:
tryFacebookLogin = trySafari = YES;
behaviorString = @"FBSessionLoginBehaviorWithNoFallbackToWebView";
break;
case FBSessionLoginBehaviorForcingSafari:
trySafari = YES;
behaviorString = @"FBSessionLoginBehaviorForcingSafari";
break;
}
self.authLogger = [[[FBSessionAuthLogger alloc] initWithSession:self] autorelease];
[self.authLogger addExtrasForNextEvent:@{
@"tryIntegratedAuth": [NSNumber numberWithBool:tryIntegratedAuth],
@"tryFBAppAuth": [NSNumber numberWithBool:tryFacebookLogin],