forked from foursquare/foursquare-ios-oauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTJFoursquareAuthentication.m
306 lines (271 loc) · 14.5 KB
/
TJFoursquareAuthentication.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
//
// TJFoursquareAuthentication.m
// Quotidian
//
// Created by Tim Johnsen on 2/16/18.
//
#import "TJFoursquareAuthentication.h"
#import <AuthenticationServices/AuthenticationServices.h>
#if !defined(__IPHONE_12_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_12_0
#import <SafariServices/SafariServices.h>
#endif
// DO NOT mark as Obj-C direct, will lead to exceptions.
@interface TJFoursquareAuthenticatorWebAuthenticationPresentationContextProvider : NSObject
@end
@implementation TJFoursquareAuthenticatorWebAuthenticationPresentationContextProvider
#pragma mark - ASWebAuthenticationPresentationContextProviding
+ (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session API_AVAILABLE(ios(13.0))
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return [[UIApplication sharedApplication] keyWindow];
#pragma clang diagnostic pop
}
@end
#if defined(__has_attribute) && __has_attribute(objc_direct_members)
__attribute__((objc_direct_members))
#endif
@interface TJFoursquareAuthentication ()
@property (nonatomic, copy, class, setter=tj_setClientIdentifier:) NSString *tj_clientIdentifier;
@property (nonatomic, class, setter=tj_setRedirectURI:) NSURL *tj_redirectURI;
@property (nonatomic, copy, class, setter=tj_setClientSecret:) NSString *tj_clientSecret;
@property (nonatomic, copy, class, setter=tj_setCompletion:) void (^tj_completion)(NSString *accessToken);
@end
#if defined(__has_attribute) && __has_attribute(objc_direct_members)
__attribute__((objc_direct_members))
#endif
@implementation TJFoursquareAuthentication
#pragma mark - Properties
static NSString *_tj_clientIdentifier;
static NSURL *_tj_redirectURI;
static NSString *_tj_clientSecret;
static void (^_tj_completion)(NSString *accessToken);
+ (void)tj_setClientIdentifier:(NSString *)tj_clientIdentifier
{
_tj_clientIdentifier = tj_clientIdentifier;
}
+ (void)tj_setRedirectURI:(NSURL *)tj_redirectURI
{
_tj_redirectURI = tj_redirectURI;
}
+ (void)tj_setClientSecret:(NSString *)tj_clientSecret
{
_tj_clientSecret = tj_clientSecret;
}
+ (void)tj_setCompletion:(void (^)(NSString *))tj_completion
{
_tj_completion = tj_completion;
}
+ (NSString *)tj_clientIdentifier
{
return _tj_clientIdentifier;
}
+ (NSURL *)tj_redirectURI
{
return _tj_redirectURI;
}
+ (NSString *)tj_clientSecret
{
return _tj_clientSecret;
}
+ (void (^)(NSString *))tj_completion
{
return _tj_completion;
}
#pragma mark - Authentication
+ (void)authenticateWithClientIdentifier:(NSString *const)clientIdentifier
redirectURI:(NSURL *const)redirectURI
clientSecret:(NSString *const)clientSecret
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
presentationContextProvider:(id<ASWebAuthenticationPresentationContextProviding>)presentationContextProvider
#pragma clang diagnostic pop
completion:(void (^)(NSString *))completion
{
NSURLComponents *const urlComponents = [NSURLComponents componentsWithString:@"foursquareauth://authorize"];
urlComponents.queryItems = @[[NSURLQueryItem queryItemWithName:@"client_id" value:clientIdentifier],
[NSURLQueryItem queryItemWithName:@"v" value:@"20130509"],
[NSURLQueryItem queryItemWithName:@"redirect_uri" value:redirectURI.absoluteString],
];
NSURL *const url = urlComponents.URL;
if ([self isFoursquareAppAvailable]) {
#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
if (@available(iOS 10.0, *)) {
#endif
[[UIApplication sharedApplication] openURL:url
options:@{}
completionHandler:^(BOOL success) {
if (success) {
[self tj_setClientIdentifier:clientIdentifier];
[self tj_setRedirectURI:redirectURI];
[self tj_setClientSecret:clientSecret];
[self tj_setCompletion:completion];
} else {
[self authenticateUsingSafariWithClientIdentifier:clientIdentifier
redirectURI:redirectURI
clientSecret:clientSecret
presentationContextProvider:presentationContextProvider
completion:completion];
}
}];
return;
#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
} else {
if (![[[[NSBundle mainBundle] infoDictionary] valueForKeyPath:@"CFBundleURLTypes.CFBundleURLSchemes.@unionOfArrays.self"] containsObject:redirectURI.scheme]) { // https://forums.developer.apple.com/thread/31307
NSAssert(NO, @"You must add the \"%@\" scheme to your info.plist's \"CFBundleURLTypes\"", redirectURI.scheme);
}
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[self setTj_clientIdentifier:clientIdentifier];
[self setTj_redirectURI:redirectURI];
[self setTj_clientSecret:clientSecret];
[self setTj_completion:completion];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] openURL:url];
#pragma clang diagnostic pop
return;
}
}
#endif
}
[self authenticateUsingSafariWithClientIdentifier:clientIdentifier
redirectURI:redirectURI
clientSecret:clientSecret
presentationContextProvider:presentationContextProvider
completion:completion];
}
+ (void)authenticateUsingSafariWithClientIdentifier:(NSString *const)clientIdentifier
redirectURI:(NSURL *const)redirectURI
clientSecret:(NSString *const)clientSecret
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
presentationContextProvider:(id<ASWebAuthenticationPresentationContextProviding>)presentationContextProvider
#pragma clang diagnostic pop
completion:(void (^)(NSString *))completion
{
NSURLComponents *const urlComponents = [NSURLComponents componentsWithString:@"https://foursquare.com/oauth2/authenticate"];
urlComponents.queryItems = @[[NSURLQueryItem queryItemWithName:@"client_id" value:clientIdentifier],
[NSURLQueryItem queryItemWithName:@"response_type" value:@"code"],
[NSURLQueryItem queryItemWithName:@"redirect_uri" value:redirectURI.absoluteString],
];
NSURL *const url = urlComponents.URL;
// Reference needs to be held as long as this is in progress, otherwise the UI disappears.
static id session;
void (^completionHandler)(NSURL *, NSError *) = ^(NSURL * _Nullable callbackURL, NSError * _Nullable error) {
// Process results.
[self tryHandleAuthenticationCallbackWithURL:callbackURL
clientIdentifier:clientIdentifier
redirectURI:redirectURI
clientSecret:clientSecret
completion:completion];
// Break reference so session is deallocated.
session = nil;
};
if (@available(iOS 12.0, *)) {
session = [[ASWebAuthenticationSession alloc] initWithURL:url
callbackURLScheme:redirectURI.scheme
completionHandler:completionHandler];
if (@available(iOS 13.0, *)) {
[(ASWebAuthenticationSession *)session setPresentationContextProvider:presentationContextProvider ?: (id<ASWebAuthenticationPresentationContextProviding>)[TJFoursquareAuthenticatorWebAuthenticationPresentationContextProvider class]];
}
[(ASWebAuthenticationSession *)session start];
#if !defined(__IPHONE_12_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_12_0
} else if (@available(iOS 11.0, *)) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
session = [[SFAuthenticationSession alloc] initWithURL:url
callbackURLScheme:redirectURI.scheme
completionHandler:completionHandler];
[(SFAuthenticationSession *)session start];
#pragma clang diagnostic pop
#endif
} else {
if (@available(iOS 10.0, *)) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
if (success) {
[self tj_setClientIdentifier:clientIdentifier];
[self tj_setRedirectURI:redirectURI];
[self tj_setClientSecret:clientSecret];
[self tj_setCompletion:completion];
} else {
completion(nil);
}
}];
#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
} else {
[self setTj_clientIdentifier:clientIdentifier];
[self setTj_redirectURI:redirectURI];
[self setTj_clientSecret:clientSecret];
[self setTj_completion:completion];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] openURL:url];
#pragma clang diagnostic pop
#endif
}
}
}
+ (BOOL)tryHandleAuthenticationCallbackWithURL:(NSURL *const)url
{
return [self tryHandleAuthenticationCallbackWithURL:url
clientIdentifier:[self tj_clientIdentifier]
redirectURI:[self tj_redirectURI]
clientSecret:[self tj_clientSecret]
completion:[self tj_completion]];
}
+ (BOOL)tryHandleAuthenticationCallbackWithURL:(NSURL *const)url
clientIdentifier:(NSString *const)clientIdentifier
redirectURI:(NSURL *const)redirectURI
clientSecret:(NSString *const)clientSecret
completion:(void (^)(NSString *))completion
{
BOOL handledURL = NO;
if (redirectURI && [url.absoluteString hasPrefix:redirectURI.absoluteString]) {
NSURLComponents *const components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES];
NSString *code = nil;
for (NSURLQueryItem *queryItem in components.queryItems) {
if ([queryItem.name isEqualToString:@"code"]) {
code = queryItem.value;
break;
}
}
if (code) {
NSURLComponents *urlComponents = [NSURLComponents componentsWithString:@"https://foursquare.com/oauth2/access_token"];
urlComponents.queryItems = @[[NSURLQueryItem queryItemWithName:@"client_id" value:clientIdentifier],
[NSURLQueryItem queryItemWithName:@"client_secret" value:clientSecret],
[NSURLQueryItem queryItemWithName:@"grant_type" value:@"authorization_code"],
[NSURLQueryItem queryItemWithName:@"redirect_uri" value:redirectURI.absoluteString],
[NSURLQueryItem queryItemWithName:@"code" value:code],
];
[[[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]] dataTaskWithURL:urlComponents.URL
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *accessToken = nil;
if (data.length > 0) {
const id jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
if ([jsonObject isKindOfClass:[NSDictionary class]]) {
accessToken = jsonObject[@"access_token"];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(accessToken);
});
}] resume];
} else {
completion(nil);
}
[self tj_setClientIdentifier:nil];
[self tj_setRedirectURI:nil];
[self tj_setClientSecret:nil];
[self tj_setCompletion:nil];
handledURL = YES;
}
return handledURL;
}
+ (BOOL)isFoursquareAppAvailable
{
// Dec 15, 2024
return [[NSDate date] timeIntervalSince1970] < 1734220800.0;
}
@end