This repository was archived by the owner on Aug 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathSimpleAuthFaceBookWebProvider.m
More file actions
259 lines (224 loc) · 10.6 KB
/
SimpleAuthFaceBookWebProvider.m
File metadata and controls
259 lines (224 loc) · 10.6 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
//
// SimpleAuthFaceBookWebProvider.m
// SimpleAuth
//
// Created by Caleb Davenport on 1/22/14.
// Copyright (c) 2014 Byliner, Inc. All rights reserved.
//
#import "SimpleAuthFaceBookWebProvider.h"
#import "SimpleAuthFacebookWebLoginViewController.h"
#import "UIViewController+SimpleAuthAdditions.h"
#import <ReactiveCocoa/ReactiveCocoa.h>
@implementation SimpleAuthFaceBookWebProvider
#pragma mark - SimpleAuthProvider
+ (NSString *)type {
return @"facebook-web";
}
+ (NSDictionary *)defaultOptions {
// Default present block
SimpleAuthInterfaceHandler presentBlock = ^(UIViewController *controller) {
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:controller];
navigation.modalPresentationStyle = UIModalPresentationFormSheet;
UIViewController *presented = [UIViewController SimpleAuth_presentedViewController];
[presented presentViewController:navigation animated:YES completion:nil];
};
// Default dismiss block
SimpleAuthInterfaceHandler dismissBlock = ^(id controller) {
[controller dismissViewControllerAnimated:YES completion:nil];
};
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithDictionary:[super defaultOptions]];
dictionary[SimpleAuthPresentInterfaceBlockKey] = presentBlock;
dictionary[SimpleAuthDismissInterfaceBlockKey] = dismissBlock;
dictionary[SimpleAuthRedirectURIKey] = @"https://www.facebook.com/connect/login_success.html";
dictionary[@"permissions"] = @[ @"email" ];
return dictionary;
}
- (void)authorizeWithCompletion:(SimpleAuthRequestHandler)completion {
[[[self accessToken]
flattenMap:^(NSDictionary *response) {
NSArray *signals = @[
[self accountWithAccessToken:response],
[RACSignal return:response]
];
return [self rac_liftSelector:@selector(dictionaryWithAccount:accessToken:) withSignalsFromArray:signals];
}]
subscribeNext:^(id x) {
completion(x, nil);
}
error:^(NSError *error) {
completion(nil, error);
}];
}
- (void)reAuthorizeWithToken:(NSString *)token completionHandler:(SimpleAuthRequestHandler)completion{
if (token.length <= 0) {
// There is no token so we are going to use the standard login method
[self authorizeWithCompletion:completion];
return;
}
[[[self reAuthAccessTokenWithToken:token]
flattenMap:^(NSDictionary *response) {
NSArray *signals = @[
[self accountWithAccessToken:response],
[RACSignal return:response]
];
return [self rac_liftSelector:@selector(dictionaryWithAccount:accessToken:) withSignalsFromArray:signals];
}]
subscribeNext:^(id x) {
completion(x, nil);
}
error:^(NSError *error) {
completion(nil, error);
}];
}
#pragma mark - Private
- (RACSignal *)accessToken {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
dispatch_async(dispatch_get_main_queue(), ^{
SimpleAuthFacebookWebLoginViewController *login = [[SimpleAuthFacebookWebLoginViewController alloc] initWithOptions:self.options];
login.completion = ^(UIViewController *controller, NSURL *URL, NSError *error) {
SimpleAuthInterfaceHandler block = self.options[SimpleAuthDismissInterfaceBlockKey];
block(controller);
// Parse URL
NSString *fragment = [URL fragment];
NSDictionary *dictionary = [CMDQueryStringSerialization dictionaryWithQueryString:fragment];
id token = dictionary[@"access_token"];
id expiration = dictionary[@"expires_in"];
// Check for error
if (!token || !expiration) {
[subscriber sendError:error];
return;
}
// Send completion
[subscriber sendNext:dictionary];
[subscriber sendCompleted];
};
SimpleAuthInterfaceHandler block = self.options[SimpleAuthPresentInterfaceBlockKey];
block(login);
});
return nil;
}];
}
- (RACSignal *)reAuthAccessTokenWithToken:(NSString *)preToken {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *parameters = @{
@"client_id" : self.options[@"app_id"],
@"grant_type" :@"fb_exchange_token",
@"response_type" : @"token",
@"grant_type" :@"fb_exchange_token",
@"client_secret" : self.options[@"app_secret"],
@"fb_exchange_token" : preToken
};
NSString *URLString = [NSString stringWithFormat:
@"https://graph.facebook.com/oauth/access_token?%@",
[CMDQueryStringSerialization queryStringWithDictionary:parameters]];
NSError *responseError = nil;
NSURLResponse *response = nil;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
NSData *dataResponse = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&responseError];
if (!responseError){
NSString *responseString = [[NSString alloc] initWithData:dataResponse encoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [CMDQueryStringSerialization dictionaryWithQueryString:responseString];
id token = dictionary[@"access_token"];
id expiration = dictionary[@"expires"];
// Check for error
if (!token || !expiration) {
[subscriber sendError:[NSError errorWithDomain:@"Missing token or experation from facebook" code:101 userInfo:nil]];
return;
}
// Send completion
[subscriber sendNext:@{@"access_token" : token, @"expires_in" : expiration}];
[subscriber sendCompleted];
}
else {
[subscriber sendError:responseError];
return ;
}
});
return nil;
}];
}
- (RACSignal *)accountWithAccessToken:(NSDictionary *)accessToken {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
NSDictionary *parameters = @{
@"access_token" : accessToken[@"access_token"],
@"fields" : @"name,first_name,last_name,verified,email,location,link"
};
NSString *URLString = [NSString stringWithFormat:
@"https://graph.facebook.com/me?%@",
[CMDQueryStringSerialization queryStringWithDictionary:parameters]];
NSURL *URL = [NSURL URLWithString:URLString];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[NSURLConnection sendAsynchronousRequest:request queue:self.operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 99)];
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if ([indexSet containsIndex:statusCode] && data) {
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parseError];
if (dictionary) {
[subscriber sendNext:dictionary];
[subscriber sendCompleted];
}
else {
NSMutableDictionary *dictionary = [NSMutableDictionary new];
if (parseError) {
dictionary[NSUnderlyingErrorKey] = parseError;
}
NSError *error = [NSError errorWithDomain:SimpleAuthErrorDomain code:SimpleAuthErrorInvalidData userInfo:dictionary];
[subscriber sendNext:error];
}
}
else {
NSMutableDictionary *dictionary = [NSMutableDictionary new];
if (connectionError) {
dictionary[NSUnderlyingErrorKey] = connectionError;
}
dictionary[SimpleAuthErrorStatusCodeKey] = @(statusCode);
NSError *error = [NSError errorWithDomain:SimpleAuthErrorDomain code:SimpleAuthErrorNetwork userInfo:dictionary];
[subscriber sendError:error];
}
}];
return nil;
}];
}
- (NSDictionary *)dictionaryWithAccount:(NSDictionary *)account accessToken:(NSDictionary *)accessToken {
NSMutableDictionary *dictionary = [NSMutableDictionary new];
// Provider
dictionary[@"provider"] = [[self class] type];
// Credentials
NSTimeInterval expiresAtInterval = [accessToken[@"expires_in"] doubleValue];
NSDate *expiresAtDate = [NSDate dateWithTimeIntervalSinceNow:expiresAtInterval];
dictionary[@"credentials"] = @{
@"token" : accessToken[@"access_token"],
@"expires_at" : expiresAtDate
};
// User ID
dictionary[@"uid"] = account[@"id"];
// Raw response
dictionary[@"extra"] = @{
@"raw_info" : account
};
// Profile image
NSString *avatar = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", account[@"id"]];
// Location
NSString *location = account[@"location"][@"name"];
// User info
NSMutableDictionary *user = [NSMutableDictionary new];
if (account[@"email"]) {
user[@"email"] = account[@"email"];
}
user[@"name"] = account[@"name"];
user[@"first_name"] = account[@"first_name"];
user[@"last_name"] = account[@"last_name"];
user[@"image"] = avatar;
if (location) {
user[@"location"] = location;
}
user[@"verified"] = account[@"verified"] ?: @NO;
user[@"urls"] = @{
@"Facebook" : account[@"link"],
};
dictionary[@"info"] = user;
return dictionary;
}
@end