e3cd4db16e6a05cdaaf51474e128f0c9c680bc74
[atutor.git] / mods / atsocial_iphone_app / Classes / OSConsumer.m
1 //
2 //  OSConsumer.m
3 //  ATutor
4 //
5 //  Created by Quang Anh Do on 29/05/2010.
6 //  Copyright 2010 Quang Anh Do. All rights reserved.
7 //
8
9 #import "OSConsumer.h"
10 #import "OSProvider.h"
11 #import "SFHFKeychainUtils.h"
12 #import "OAMutableURLRequest.h"
13 #import "OAServiceTicket.h"
14 #import "OAConsumer.h"
15 #import "OADataFetcher.h"
16 #import "OAToken.h"
17 #import "OAToken_KeychainExtensions.h"
18 #import <Three20/Three20.h>
19
20 @interface OSConsumer (Private)
21 - (void)setupConsumer;
22 - (void)getRequestToken;
23 - (void)requestTokenCallback:(OAServiceTicket *)ticket didFinishWithResponse:(id)response;
24 - (void)getAccessToken;
25 - (void)accessTokenCallback:(OAServiceTicket *)ticket didFinishWithResponse:(id)response;
26 @end
27
28 @implementation OSConsumer
29
30 @synthesize consumer, accessToken, currentProvider;
31
32 - (void)dealloc {
33         [consumer release];
34         [accessToken release];
35         [currentProvider release];
36         
37         [super dealloc];
38 }
39
40 - (id)init {
41         return [self initWithProvider:[OSProvider getATutorProviderWithKey:kConsumerKey withSecret:kConsumerSecret]];
42 }
43
44 - (id)initWithProvider:(OSProvider *)provider {
45         if (self = [super init]) {
46                 self.accessToken = [[[OAToken alloc] initWithKeychainUsingAppName:kATutor tokenType:@"accessToken"] autorelease];
47                 self.currentProvider = provider;
48                 
49                 [self setupConsumer];
50         }
51         
52         return self;
53 }
54
55 - (void)startAuthProcess {
56         [self getRequestToken];
57 }
58
59 - (void)finishAuthProcess {
60         [self getAccessToken];
61 }
62
63 // Should be called within a handleOpenUrl method. 
64 // This method assumes the request token was authorized and will retrieve the access token
65 - (void)clearAuthentication {
66         [SFHFKeychainUtils storeUsername:@"accessToken" andPassword:@"" forServiceName:kATutor updateExisting:TRUE error:nil];
67         [SFHFKeychainUtils storeUsername:@"requestToken" andPassword:@"" forServiceName:kATutor updateExisting:TRUE error:nil];
68         
69         self.accessToken = nil;
70 }
71
72 - (void)getDataForUrl:(NSString *)relativeUrl andParameters:(NSArray*)params 
73              delegate:(id)delegate didFinishSelector:(SEL)didFinishSelector {
74         if (!accessToken) {
75                 [self startAuthProcess];  
76                 return;
77         }
78         
79         NSLog(@"Getting data with access token: %@ : %@", [accessToken key], [accessToken secret]);
80         
81         NSString *url = [[currentProvider endpointUrl] stringByAppendingString:relativeUrl];  
82         OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] 
83                                                                          initWithURL:[NSURL URLWithString:url] 
84                                                                          parameters:params
85                                                                          consumer:consumer token:accessToken] autorelease]; 
86         [request setHTTPMethod:@"GET"];
87         
88         [OADataFetcher fetchDataWithRequest:request delegate:delegate
89                                           didFinishSelector:didFinishSelector];
90 }
91
92 #pragma mark -
93 #pragma mark Private
94
95 - (void)setupConsumer {
96         self.consumer = [[[OAConsumer alloc] initWithKey:[currentProvider consumerKey] 
97                                                                                           secret:[currentProvider consumerSecret]] autorelease];
98 }
99
100 - (void)getRequestToken {
101         OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] 
102                                                                          initWithURL:[NSURL URLWithString:[currentProvider requestUrl]] 
103                                                                          parameters:[currentProvider extraRequestUrlParams]
104                                                                          consumer:consumer 
105                                                                          token:nil] autorelease];
106         [request setHTTPMethod:@"GET"];
107         
108         [OADataFetcher fetchDataWithRequest:request
109                                                            delegate:self
110                                           didFinishSelector:@selector(requestTokenCallback:didFinishWithResponse:)];
111 }
112
113 - (void)requestTokenCallback:(OAServiceTicket *)ticket didFinishWithResponse:(id)response {
114         if (ticket.didSucceed) {
115                 NSLog(@"%@", response);
116                 OAToken *requestToken = [[OAToken alloc] initWithHTTPResponseBody:response];
117                 [requestToken storeInDefaultKeychainWithAppName:kATutor tokenType:@"requestToken"];    
118                 NSLog(@"Stored this secret and key: %@ : %@", [requestToken key], [requestToken secret]);
119                 
120                 NSString *urlString = [NSString stringWithFormat:@"%@?oauth_callback=internal://finish-auth&oauth_token=%@", 
121                                                            [currentProvider authorizeUrl], [requestToken key]];
122                 
123                 NSLog(@"Request string: %@", urlString);
124                 
125                 [[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath:urlString] applyAnimated:YES]];
126         } else {
127                 NSString *error = [NSString stringWithFormat:@"Got error while requesting request token. %@", response];
128                 NSLog(@"Error retriving request token: %@", error);
129                 
130                 @throw [NSException exceptionWithName:@"RequestTokenException" reason:error  userInfo:nil];
131         }
132 }
133
134 - (void)getAccessToken {  
135         OAToken *requestToken = [[OAToken alloc] initWithKeychainUsingAppName:kATutor 
136                                                                                                                                 tokenType:@"requestToken"];
137         NSLog(@"Getting access token for request token: %@ : %@", [requestToken key], [requestToken secret]);
138         
139         OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] 
140                                                                          initWithURL:[NSURL URLWithString:[currentProvider accessUrl]]
141                                                                          consumer:consumer token:requestToken] autorelease];
142         [request setHTTPMethod:@"GET"];
143         
144         [OADataFetcher fetchDataWithRequest:request delegate:self
145                                           didFinishSelector:@selector(accessTokenCallback:didFinishWithResponse:)];
146 }
147
148 - (void)accessTokenCallback:(OAServiceTicket *)ticket didFinishWithResponse:(id)response {
149         if (ticket.didSucceed) {
150                 self.accessToken = [[[OAToken alloc] initWithHTTPResponseBody:response] autorelease];
151                 [accessToken storeInDefaultKeychainWithAppName:kATutor tokenType:@"accessToken"];
152                 
153                 NSLog(@"Got an access token: %@ : %@", [accessToken key], [accessToken secret]);
154                 
155         } else {
156                 NSString *error = [NSString stringWithFormat:@"Got error while requesting access token. %@", response];
157                 NSLog(@"Error retriving access token: %@", error);
158                 
159                 @throw [NSException exceptionWithName:@"AccessTokenException" reason:error  userInfo:nil];
160         }
161 }
162
163 @end