/
FBSession.m
1309 lines (1113 loc) · 55.6 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 2012 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 <Foundation/Foundation.h>
#import <UIKit/UIDevice.h>
#import "FBSession.h"
#import "FBSession+Internal.h"
#import "FBSession+Protected.h"
#import "FBSessionTokenCachingStrategy.h"
#import "FBSettings.h"
#import "FBError.h"
#import "FBLogger.h"
#import "FBUtility.h"
// the sooner we can remove these the better
#import "Facebook.h"
#import "FBLoginDialog.h"
// these are helpful macros for testing various login methods, should always checkin as NO/NO
#define TEST_DISABLE_MULTITASKING_LOGIN NO
#define TEST_DISABLE_FACEBOOKLOGIN NO
// this macro turns on IOS6 preview support
#ifdef __IPHONE_6_0
#define IOS6_PREVIEW_SUPPORT
#endif
// we turn this on for 5 so that we can build our production libs using a production compiler,
// rather than a preview compiler -- however integrated Facebook support will only be on when running on 6
#ifdef __IPHONE_5_0
#define IOS6_PREVIEW_SUPPORT
#endif
#ifdef IOS6_PREVIEW_SUPPORT
// we dynamically bind to a few methods, and this protocol helps
// us manage warnings from the call-sites
@protocol FBWarningHelperProtocol
- (id)accountTypeWithAccountTypeIdentifier:(id)type;
- (void)requestAccessToAccountsWithType:(id)accountTypeFB
options:(id)options
completion:(id)handler;
- (NSArray*)accountsWithAccountType:(id)type;
- (id)credential;
- (id)oauthToken;
@end
#endif
// extern const strings
NSString *const FBErrorLoginFailedReasonInlineCancelledValue = @"com.facebook.sdk:InlineLoginCancelled";
NSString *const FBErrorLoginFailedReasonInlineNotCancelledValue = @"com.facebook.sdk:ErrorLoginNotCancelled";
// const strings
static NSString *const FBPLISTAppIDKey = @"FacebookAppID";
// for unit testing mode only (DO NOT store application secrets in a published application plist)
static NSString *const FBPLISTAppSecretKey = @"FacebookAppSecret";
static NSString *const FBAuthURLScheme = @"fbauth";
static NSString *const FBAuthURLPath = @"authorize";
static NSString *const FBRedirectURL = @"fbconnect://success";
static NSString *const FBDialogBaseURL = @"https://m." FB_BASE_URL @"/dialog/";
static NSString *const FBLoginDialogMethod = @"oauth";
static NSString *const FBLoginUXClientID = @"client_id";
static NSString *const FBLoginUXUserAgent = @"user_agent";
static NSString *const FBLoginUXType = @"type";
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";
// 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";
// 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 = @"status";
static NSString *const FBaccessTokenPropertyName = @"accessToken";
static NSString *const FBexpirationDatePropertyName = @"expirationDate";
static int const FBTokenExtendThresholdSeconds = 24 * 60 * 60; // day
static int const FBTokenRetryExtendSeconds = 60 * 60; // hour
// module scoped globals
static NSString *g_defaultAppID = nil;
static FBSession *g_activeSession = nil;
@interface FBSession () <FBLoginDialogDelegate> {
@private
// public-property ivars
NSString *_urlSchemeSuffix;
// private property and non-property ivars
BOOL _isInStateTransition;
BOOL _isFacebookLoginToken;
}
// private setters
@property(readwrite) FBSessionState state;
@property(readwrite, copy) NSString *appID;
@property(readwrite, copy) NSString *urlSchemeSuffix;
@property(readwrite, copy) NSString *accessToken;
@property(readwrite, copy) NSDate *expirationDate;
@property(readwrite, copy) NSArray *permissions;
// private properties
@property(readwrite, retain) FBSessionTokenCachingStrategy *tokenCachingStrategy;
@property(readwrite, copy) NSDate *refreshDate;
@property(readwrite, copy) NSDate *attemptedRefreshDate;
@property(readwrite, copy) FBSessionStateHandler loginHandler;
@property(readwrite, copy) FBSessionReauthorizeResultHandler reauthorizeHandler;
@property(readwrite, copy) NSArray *reauthorizePermissions;
@property(readonly) NSString *appBaseUrl;
@property(readwrite, retain) FBLoginDialog *loginDialog;
@property(readwrite, retain) NSThread *affinitizedThread;
// private members
- (void)authorizeWithPermissions:(NSArray*)permissions
integratedAuth:(BOOL)tryIntegratedAuth
FBAppAuth:(BOOL)tryFBAppAuth
safariAuth:(BOOL)trySafariAuth
fallback:(BOOL)tryFallback;
- (BOOL)handleOpenURLPreOpen:(NSDictionary*)parameters
accessToken:(NSString*)accessToken;
- (BOOL)handleOpenURLReauthorize:(NSDictionary*)parameters
accessToken:(NSString*)accessToken;
- (void)callReauthorizeHandlerAndClearState:(NSError*)error;
// class members
+ (BOOL)areRequiredPermissions:(NSArray*)requiredPermissions
aSubsetOfPermissions:(NSArray*)cachedPermissions;
+ (NSString *)sessionStateDescription:(FBSessionState)sessionState;
@end
@implementation FBSession : NSObject
@synthesize
// public properties
appID = _appID,
permissions = _permissions,
// following properties use manual KVO -- changes to names require
// changes to static property name variables (e.g. FBisOpenPropertyName)
state = _state,
accessToken = _accessToken,
expirationDate = _expirationDate,
// private properties
tokenCachingStrategy = _tokenCachingStrategy,
refreshDate = _refreshDate,
attemptedRefreshDate = _attemptedRefreshDate,
loginDialog = _loginDialog,
affinitizedThread = _affinitizedThread,
loginHandler = _loginHandler,
reauthorizeHandler = _reauthorizeHandler,
reauthorizePermissions = _reauthorizePermissions;
#pragma mark Lifecycle
- (id)init {
return [self initWithAppID:nil
permissions:nil
urlSchemeSuffix:nil
tokenCacheStrategy:nil];
}
- (id)initWithPermissions:(NSArray*)permissions {
return [self initWithAppID:nil
permissions:permissions
urlSchemeSuffix:nil
tokenCacheStrategy:nil];
}
- (id)initWithAppID:(NSString*)appID
permissions:(NSArray*)permissions
urlSchemeSuffix:(NSString*)urlSchemeSuffix
tokenCacheStrategy:(FBSessionTokenCachingStrategy*)tokenCachingStrategy {
self = [super init];
if (self) {
// setup values where nil implies a default
if (!appID) {
appID = [FBSession defaultAppID];
}
if (!permissions) {
permissions = [NSArray array];
}
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;
self.appID = appID;
self.permissions = permissions;
self.urlSchemeSuffix = urlSchemeSuffix;
self.tokenCachingStrategy = tokenCachingStrategy;
// additional setup
_isInStateTransition = NO;
_isFacebookLoginToken = NO;
self.attemptedRefreshDate = [NSDate distantPast];
self.refreshDate = nil;
self.state = FBSessionStateCreated;
self.affinitizedThread = [NSThread currentThread];
[FBLogger registerCurrentTime:FBLoggingBehaviorPerformanceCharacteristics
withTag:self];
// use cached token if present
NSDictionary *tokenInfo = [tokenCachingStrategy fetchTokenInformation];
if ([FBSessionTokenCachingStrategy isValidTokenInformation:tokenInfo]) {
NSDate *cachedTokenExpirationDate = [tokenInfo objectForKey:FBTokenInformationExpirationDateKey];
NSString *cachedToken = [tokenInfo objectForKey:FBTokenInformationTokenKey];
// get the cached permissions, and do a subset check
NSArray *cachedPermissions = [tokenInfo objectForKey:FBTokenInformationPermissionsKey];
BOOL isSubset = [FBSession areRequiredPermissions:permissions
aSubsetOfPermissions:cachedPermissions];
if (isSubset &&
// check to see if expiration date is later than now
(NSOrderedDescending == [cachedTokenExpirationDate compare:[NSDate date]])) {
// if we had cached anything at all, use those
if (cachedPermissions) {
self.permissions = cachedPermissions;
}
// if we have cached an optional refresh date or Facebook Login indicator, pick them up here
self.refreshDate = [tokenInfo objectForKey:FBTokenInformationRefreshDateKey];
_isFacebookLoginToken = [[tokenInfo objectForKey:FBTokenInformationIsFacebookLoginKey] boolValue];
// set the state and token info
[self transitionToState:FBSessionStateCreatedTokenLoaded
andUpdateToken:cachedToken
andExpirationDate:cachedTokenExpirationDate
shouldCache:NO];
} else {
// else this token is expired and should be cleared from cache
[tokenCachingStrategy clearToken];
}
}
}
return self;
}
- (void)dealloc {
[_loginDialog release];
[_attemptedRefreshDate release];
[_refreshDate release];
[_reauthorizeHandler release];
[_loginHandler release];
[_reauthorizePermissions release];
[_appID release];
[_urlSchemeSuffix release];
[_accessToken release];
[_expirationDate release];
[_permissions release];
[_tokenCachingStrategy release];
[_affinitizedThread release];
[super dealloc];
}
#pragma mark -
#pragma mark Public Members
- (void)openWithCompletionHandler:(FBSessionStateHandler)handler {
[self openWithBehavior:FBSessionLoginBehaviorWithFallbackToWebView completionHandler:handler];
}
- (void)openWithBehavior:(FBSessionLoginBehavior)behavior
completionHandler:(FBSessionStateHandler)handler {
NSAssert(self.affinitizedThread == [NSThread currentThread], @"FBSession: should only be used from a single thread");
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];
}
self.loginHandler = handler;
// normal login depends on the availability of a valid cached token
if (self.state == FBSessionStateCreated) {
// set the state and token info
[self transitionToState:FBSessionStateCreatedOpening
andUpdateToken:nil
andExpirationDate:nil
shouldCache:NO];
[self authorizeWithPermissions:self.permissions
behavior:behavior];
} 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
token:nil
expirationDate:nil
shouldCache:NO];
}
}
- (void)reauthorizeWithPermissions:(NSArray*)permissions
behavior:(FBSessionLoginBehavior)behavior
completionHandler:(FBSessionReauthorizeResultHandler)handler {
if (!self.isOpen) {
// session must be open in order to reauthorize
[[NSException exceptionWithName:FBInvalidOperationException
reason:@"FBSession: an attempt was made reauthorize permissions on an unopened session"
userInfo:nil]
raise];
}
if (self.reauthorizeHandler) {
// block must be cleared (meaning it has been called back) before a reauthorize can happen again
[[NSException exceptionWithName:FBInvalidOperationException
reason:@"FBSession: It is not valid to reauthorize while a previous "
@"reauthorize call has not yet completed."
userInfo:nil]
raise];
}
// setup handler and permissions and perform the actual reauthorize
self.reauthorizePermissions = permissions;
self.reauthorizeHandler = handler;
[self authorizeWithPermissions:permissions
behavior:behavior];
}
- (void)close {
NSAssert(self.affinitizedThread == [NSThread currentThread], @"FBSession: should only be used from a single thread");
FBSessionState state;
if (self.state == FBSessionStateCreatedOpening) {
state = FBSessionStateClosedLoginFailed;
} else {
state = FBSessionStateClosed;
}
[self transitionAndCallHandlerWithState:state
error:nil
token:nil
expirationDate:nil
shouldCache:NO];
}
- (void)closeAndClearTokenInformation {
NSAssert(self.affinitizedThread == [NSThread currentThread], @"FBSession: should only be used from a single thread");
[self.tokenCachingStrategy clearToken];
[self transitionAndCallHandlerWithState:FBSessionStateClosed
error:nil
token:nil
expirationDate:nil
shouldCache:NO];
}
- (BOOL)handleOpenURL:(NSURL *)url {
NSAssert(self.affinitizedThread == [NSThread currentThread], @"FBSession: should only be used from a single thread");
// if the URL's structure doesn't match the structure used for Facebook authorization, abort.
if (![[url absoluteString] hasPrefix:self.appBaseUrl]) {
return NO;
}
// version 3.2.3 of the Facebook app encodes the parameters in the query but
// version 3.3 and above encode the parameters in the fragment; check first for
// fragment, and if missing fall back to query
NSString *query = [url fragment];
if (!query) {
query = [url query];
}
NSDictionary *params = [FBUtility dictionaryByParsingURLQueryPart:query];
NSString *accessToken = [params objectForKey:@"access_token"];
switch (self.state) {
case FBSessionStateCreatedOpening:
return [self handleOpenURLPreOpen:params
accessToken:accessToken];
case FBSessionStateOpen:
case FBSessionStateOpenTokenExtended:
return [self handleOpenURLReauthorize:params
accessToken:accessToken];
default:
NSAssert(NO, @"handleOpenURL should not be called once a session has closed");
return NO;
}
}
- (BOOL)isOpen {
return FB_ISSESSIONOPENWITHSTATE(self.state);
}
- (NSString*)urlSchemeSuffix {
NSAssert(self.affinitizedThread == [NSThread currentThread], @"FBSession: should only be used from a single thread");
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];
}
}
#pragma mark -
#pragma mark Class Methods
/*!
@abstract
This is the simplest method for opening a session with Facebook. Using sessionOpen logs on a user,
and sets the static activeSession which becomes the default session object for any Facebook UI controls
used by the application.
*/
+ (FBSession*)sessionOpen {
return [FBSession sessionOpenWithPermissions:nil
completionHandler:nil];
}
+ (FBSession*)sessionOpenWithPermissions:(NSArray*)permissions
completionHandler:(FBSessionStateHandler)handler {
FBSession *session = [[[FBSession alloc] initWithPermissions:permissions] autorelease];
[FBSession setActiveSession:session];
// we open after the fact, in order to avoid overlapping close
// and open handler calls for blocks
[session openWithCompletionHandler:handler];
return session;
}
+ (FBSession*)activeSession {
if (!g_activeSession) {
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];
[session release];
}
return [[g_activeSession retain] autorelease];
}
+ (FBSession*)setActiveSession:(FBSession*)session {
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];
if (session.isOpen) {
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionDidBecomeOpenActiveSessionNotification
object:session];
}
}
}
return session;
}
+ (void)setDefaultAppID:(NSString*)appID {
NSString *oldValue = g_defaultAppID;
g_defaultAppID = [appID copy];
[oldValue release];
}
+ (NSString*)defaultAppID {
if (!g_defaultAppID) {
NSBundle* bundle = [NSBundle mainBundle];
g_defaultAppID = [bundle objectForInfoDictionaryKey:FBPLISTAppIDKey];
}
return g_defaultAppID;
}
#pragma mark -
#pragma mark Private Members
// private methods are broken into two categories: core session and helpers
// core session members
// core member that owns all state transitions as well as property setting for status and isOpen
- (BOOL)transitionToState:(FBSessionState)state
andUpdateToken:(NSString*)token
andExpirationDate:(NSDate*)date
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 == FBSessionStateCreatedOpening;
break;
case FBSessionStateOpenTokenExtended:
isValidTransition = (
statePrior == FBSessionStateOpen ||
statePrior == FBSessionStateOpenTokenExtended
);
break;
case FBSessionStateClosed:
isValidTransition = (
statePrior == FBSessionStateOpen ||
statePrior == FBSessionStateOpenTokenExtended ||
statePrior == FBSessionStateCreatedTokenLoaded
);
break;
}
// invalid transition short circuits
if (!isValidTransition) {
[FBLogger singleShotLogEntry:FBLoggingBehaviorSessionStateTransitions
logEntry:[NSString stringWithFormat:@"FBSession **INVALID** transition from %@ to %@",
[FBSession sessionStateDescription:statePrior],
[FBSession 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 %@ ",
[FBSession sessionStateDescription:statePrior],
[FBSession 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 (token && date) {
changingTokenAndDate = YES;
} else if (!FB_ISSESSIONOPENWITHSTATE(state) &&
FB_ISSESSIONOPENWITHSTATE(statePrior)) {
changingTokenAndDate = YES;
token = nil;
date = 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) {
// KVO property will-change notifications for token and date
[self willChangeValueForKey:FBaccessTokenPropertyName];
[self willChangeValueForKey:FBexpirationDatePropertyName];
// change the token and date values, should be kept near to state change following the conditional
self.accessToken = token;
self.expirationDate = date;
}
// 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) {
NSMutableDictionary *tokenInfo = [NSMutableDictionary dictionaryWithCapacity:4];
// we don't consider it a valid cache without these two values
[tokenInfo setObject:token forKey:FBTokenInformationTokenKey];
[tokenInfo setObject:date forKey:FBTokenInformationExpirationDateKey];
// but these following values are optional
if (self.refreshDate) {
[tokenInfo setObject:self.refreshDate forKey:FBTokenInformationRefreshDateKey];
}
if (_isFacebookLoginToken) {
[tokenInfo setObject:[NSNumber numberWithBool:YES] forKey:FBTokenInformationIsFacebookLoginKey];
}
if (self.permissions) {
[tokenInfo setObject:self.permissions forKey:FBTokenInformationPermissionsKey];
}
[self.tokenCachingStrategy cacheTokenInformation:tokenInfo];
}
// KVO property change notifications token and date
[self didChangeValueForKey:FBexpirationDatePropertyName];
[self didChangeValueForKey:FBaccessTokenPropertyName];
}
// 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 {
BOOL tryFacebookLogin = (behavior == FBSessionLoginBehaviorWithFallbackToWebView) ||
(behavior == FBSessionLoginBehaviorWithNoFallbackToWebView);
BOOL tryFallback = (behavior == FBSessionLoginBehaviorWithFallbackToWebView) ||
(behavior == FBSessionLoginBehaviorForcingWebView);
[self authorizeWithPermissions:(NSArray*)permissions
integratedAuth:tryFacebookLogin
FBAppAuth:tryFacebookLogin
safariAuth:tryFacebookLogin
fallback:tryFallback];
}
- (void)authorizeWithPermissions:(NSArray*)permissions
integratedAuth:(BOOL)tryIntegratedAuth
FBAppAuth:(BOOL)tryFBAppAuth
safariAuth:(BOOL)trySafariAuth
fallback:(BOOL)tryFallback {
// setup parameters for either the safari or inline login
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
self.appID, FBLoginUXClientID,
FBLoginUXUserAgent, FBLoginUXType,
FBRedirectURL, FBLoginUXRedirectURI,
FBLoginUXTouch, FBLoginUXDisplay,
FBLoginUXIOS, FBLoginUXSDK,
nil];
NSString *loginDialogURL = [FBDialogBaseURL stringByAppendingString:FBLoginDialogMethod];
if (permissions != nil) {
NSString* scope = [permissions componentsJoinedByString:@","];
[params setValue:scope forKey:@"scope"];
}
if (_urlSchemeSuffix) {
[params setValue:_urlSchemeSuffix forKey:@"local_client_id"];
}
// To avoid surprises, delete any cookies we currently have.
[FBSession deleteFacebookCookies];
// when iOS 6 ships we will have enough cases here to justify refactoring to a nicer
// approach to managing our fallback auth methods -- however while we are still previewing
// iOS 6 functionality, we will keep the logic essentially as is, with a series of ifs
BOOL didAuthNWithSystemAccount = NO;
#ifdef IOS6_PREVIEW_SUPPORT
id accountStore = nil;
id accountTypeFB = nil;
// do we want and have the ability to attempt integrated authn
if (tryIntegratedAuth &&
(accountStore = [[[NSClassFromString(@"ACAccountStore") alloc] init] autorelease]) &&
(accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:@"com.apple.facebook"])) {
// looks like we will get to attempt a login with integrated authn
didAuthNWithSystemAccount = YES;
// BUG: this works around a bug in the current iOS preview that requires
// at least one permission in order to get an access token -- user_likes
// was selected as a generally innocuous permission to request in the case
// where the application only needs basic access; will remove in production
NSArray *permissionsToUse = permissions;
if (!permissionsToUse.count) {
permissionsToUse = [NSArray arrayWithObject:@"user_likes"];
}
// construct access options
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
self.appID, @"ACFacebookAppIdKey",
permissionsToUse, @"ACFacebookPermissionsKey",
@"read_write", @"ACFacebookPermissionGroupKey",
nil];
// we will attempt an iOS integrated facebook login
[accountStore requestAccessToAccountsWithType:accountTypeFB
options:options
completion:^(BOOL granted, NSError *error) {
// requestAccessToAccountsWithType:options:completion: completes on an
// arbitrary thread; let's process this back on our main thread
dispatch_async( dispatch_get_main_queue(), ^{
NSString *oauthToken = nil;
if (granted) {
NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
id account = [fbAccounts objectAtIndex:0];
id credential = [account credential];
oauthToken = [credential oauthToken];
}
if (oauthToken) {
// this is one of two ways that we get an Facebook Login token (the other is from cache)
_isFacebookLoginToken = YES;
// we received a token just now
self.refreshDate = [NSDate date];
// set token and date, state transition, and call the handler if there is one
[self transitionAndCallHandlerWithState:FBSessionStateOpen
error:nil
token:oauthToken
// BUG: we need a means for fetching the expiration date of the token
expirationDate:[NSDate distantFuture]
shouldCache:YES];
} else {
// BUG: in all failed cases we fall back to other authn schemes,
// in order to allow for some instability in the new API; post
// preview, a failed integrated authentication will result in a
// failed login for the session
[self authorizeWithPermissions:permissions
integratedAuth:NO
FBAppAuth:YES
safariAuth:YES
fallback:YES];
}
});
}];
}
#endif
// If the device is running a version of iOS that supports multitasking,
// try to obtain the access token from the Facebook app installed
// on the device.
// If the Facebook app isn't installed or it doesn't support
// the fbauth:// URL scheme, fall back on Safari for obtaining the access token.
// This minimizes the chance that the user will have to enter his or
// her credentials in order to authorize the application.
UIDevice *device = [UIDevice currentDevice];
if (!didAuthNWithSystemAccount &&
[device respondsToSelector:@selector(isMultitaskingSupported)] &&
[device isMultitaskingSupported] &&
!TEST_DISABLE_MULTITASKING_LOGIN) {
if (tryFBAppAuth &&
!TEST_DISABLE_FACEBOOKLOGIN) {
NSString *scheme = FBAuthURLScheme;
if (_urlSchemeSuffix) {
scheme = [scheme stringByAppendingString:@"2"];
}
NSString *urlPrefix = [NSString stringWithFormat:@"%@://%@", scheme, FBAuthURLPath];
NSString *fbAppUrl = [FBRequest serializeURL:urlPrefix params:params];
didAuthNWithSystemAccount = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]];
}
if (trySafariAuth && !didAuthNWithSystemAccount) {
NSString *nextUrl = self.appBaseUrl;
[params setValue:nextUrl forKey:@"redirect_uri"];
NSString *fbAppUrl = [FBRequest serializeURL:loginDialogURL params:params];
didAuthNWithSystemAccount = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]];
}
}
// If single sign-on failed, see if we should attempt to fallback
if (!didAuthNWithSystemAccount) {
if (tryFallback) {
// open an inline login dialog. This will require the user to enter his or her credentials.
self.loginDialog = [[[FBLoginDialog alloc] initWithURL:loginDialogURL
loginParams:params
delegate:self]
autorelease];
[self.loginDialog show];
} else {
// Can't fallback and Facebook Login failed, so transition to an error state
NSError *error = [FBSession errorLoginFailedWithReason:FBErrorLoginFailedReasonInlineNotCancelledValue
errorCode:nil];
// state transition, and call the handler if there is one
[self transitionAndCallHandlerWithState:FBSessionStateClosedLoginFailed
error:error
token:nil
expirationDate:nil
shouldCache:NO];
}
}
}
- (BOOL)handleOpenURLPreOpen:(NSDictionary*)parameters
accessToken:(NSString*)accessToken {
// if the URL doesn't contain the access token, an error has occurred.
if (!accessToken) {
NSString *errorReason = [parameters objectForKey:@"error"];
// if the error response indicates that we should try again using Safari, open
// the authorization dialog in Safari.
if (errorReason && [errorReason isEqualToString:@"service_disabled_use_browser"]) {
[self authorizeWithPermissions:self.permissions
integratedAuth:NO
FBAppAuth:NO
safariAuth:YES
fallback:NO];
return YES;
}
// if the error response indicates that we should try the authorization flow
// in an inline dialog, do that.
if (errorReason && [errorReason isEqualToString:@"service_disabled"]) {
[self authorizeWithPermissions:self.permissions
integratedAuth:NO
FBAppAuth:NO
safariAuth:NO
fallback:NO];
return YES;
}
// the facebook app may return an error_code parameter in case it
// encounters a UIWebViewDelegate error
NSString *errorCode = [parameters objectForKey:@"error_code"];
// create an error object with additional info regarding failed login
NSError *error = [FBSession errorLoginFailedWithReason:errorReason
errorCode:errorCode];
// state transition, and call the handler if there is one
[self transitionAndCallHandlerWithState:FBSessionStateClosedLoginFailed
error:error
token:nil
expirationDate:nil
shouldCache:NO];
} else {
// we have an access token, so parse the expiration date.
NSString *expTime = [parameters objectForKey:@"expires_in"];
NSDate *expirationDate = [FBSession expirationDateFromExpirationTimeString:expTime];
if (!expirationDate) {
expirationDate = [NSDate distantFuture];
}
// this is one of two ways that we get an Facebook Login token (the other is from cache)
_isFacebookLoginToken = YES;
// we received a token just now
self.refreshDate = [NSDate date];
// set token and date, state transition, and call the handler if there is one
[self transitionAndCallHandlerWithState:FBSessionStateOpen
error:nil
token:accessToken
expirationDate:expirationDate
shouldCache:YES];
}
return YES;
}
- (BOOL)handleOpenURLReauthorize:(NSDictionary*)parameters
accessToken:(NSString*)accessToken {
// if the URL doesn't contain the access token, an error has occurred.
if (!accessToken) {
// no token in this case implies that the user cancelled the permissions upgrade
NSError *error = [FBSession errorLoginFailedWithReason:FBErrorReauthorizeFailedReasonUserCancelled
errorCode:nil];
[self callReauthorizeHandlerAndClearState:error];
} else {
// we have an access token, so parse the expiration date.
NSString *expTime = [parameters objectForKey:@"expires_in"];
NSDate *expirationDate = [FBSession expirationDateFromExpirationTimeString:expTime];
if (!expirationDate) {
expirationDate = [NSDate distantFuture];
}
// now we are going to kick-off a batch request, where we confirm that the new token
// refers to the same fbid as the old, and if so we will succeed the reauthorize call
FBRequest *requestSessionMe = [FBRequest requestForGraphPath:@"me"];
[requestSessionMe setSession:self];
FBRequest *requestNewTokenMe = [[[FBRequest alloc] initWithSession:nil
graphPath:@"me"
parameters:[NSDictionary dictionaryWithObjectsAndKeys:
accessToken, @"access_token",
nil]
HTTPMethod:nil]
autorelease];
FBRequest *requestPermissions = [FBRequest requestForGraphPath:@"me/permissions"];
[requestPermissions setSession:self];
// we create a block here with related state -- which will be the main handler block for all
// three requests -- wrapped by smaller blocks to provide context
// we will use these to compare fbid's
__block id fbid = nil;
__block id fbid2 = nil;
__block id permissionsRefreshed = nil;
// and this to assure we notice when we have been called three times
__block int callsPending = 3;
void (^handleBatch)(id<FBGraphUser>,id) = [^(id<FBGraphUser> user,
id permissions) {
// here we accumulate state from the various callbacks
if (user && !fbid) {
fbid = [[user objectForKey:@"id"] retain];
} else if (user && !fbid2) {
fbid2 = [[user objectForKey:@"id"] retain];
} else if (permissions) {
permissionsRefreshed = [permissions retain];
}