Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 340 lines (289 sloc) 13.527 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 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
/*
Copyright 2011 TweetDeck Inc. All rights reserved.
Design and implementation, Max Howell, @mxcl.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY TweetDeck Inc. ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL TweetDeck Inc. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of TweetDeck Inc.
*/

#import "GCOAuth.h"

#import <CommonCrypto/CommonHMAC.h>

#import "NSData+Base64.h"

// static variables
static NSString *GCOAuthUserAgent = nil;
static time_t GCOAuthTimeStampOffset = 0;
static BOOL GCOAuthUseHTTPSCookieStorage = YES;

@interface GCOAuth ()

// properties
@property (nonatomic, copy) NSDictionary *requestParameters;
@property (nonatomic, copy) NSString *HTTPMethod;
@property (nonatomic, copy) NSURL *URL;

// get a nonce string
+ (NSString *)nonce;

// get a timestamp string
+ (NSString *)timeStamp;

// generate properly escaped string for the given parameters
+ (NSString *)queryStringFromParameters:(NSDictionary *)parameters;

// create a request with given oauth values
- (id)initWithConsumerKey:(NSString *)consumerKey
           consumerSecret:(NSString *)consumerSecret
              accessToken:(NSString *)accessToken
              tokenSecret:(NSString *)tokenSecret
          oauthParameters:(NSDictionary*)oauthParameters;

// generate a request
- (NSMutableURLRequest *)request;

// generate authorization header
- (NSString *)authorizationHeader;

// generate signature
- (NSString *)signature;

// generate signature base
- (NSString *)signatureBase;

@end
@interface NSString (GCOAuthAdditions)

// better percent escape
- (NSString *)pcen;

@end

@implementation GCOAuth

@synthesize requestParameters = __parameters;
@synthesize HTTPMethod = __method;
@synthesize URL = __url;

#pragma mark - object methods
- (id)initWithConsumerKey:(NSString *)consumerKey
           consumerSecret:(NSString *)consumerSecret
              accessToken:(NSString *)accessToken
              tokenSecret:(NSString *)tokenSecret
          oauthParameters:(NSDictionary*)oauthParameters {
    self = [super init];
    if (self) {
        
        NSDictionary* libraryParameters = [NSDictionary dictionaryWithObjectsAndKeys:
                           [[consumerKey copy] autorelease], @"oauth_consumer_key",
                           [GCOAuth nonce], @"oauth_nonce",
                           [GCOAuth timeStamp], @"oauth_timestamp",
                           @"1.0", @"oauth_version",
                           @"HMAC-SHA1", @"oauth_signature_method",
                           [[accessToken copy] autorelease], @"oauth_token", // leave accessToken last or you'll break XAuth attempts
                           nil];
        NSMutableDictionary* parameters = oauthParameters ? [oauthParameters mutableCopy] : [[NSMutableDictionary alloc] init];
        [parameters addEntriesFromDictionary:libraryParameters];
        OAuthParameters = parameters;
        signatureSecret = [[NSString stringWithFormat:@"%@&%@", [consumerSecret pcen], [tokenSecret ?: @"" pcen]] retain];
    }
    return self;
}
- (NSMutableURLRequest *)request {
    NSMutableURLRequest *request = [NSMutableURLRequest
                                    requestWithURL:self.URL
                                    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                    timeoutInterval:10.0];
    if (GCOAuthUserAgent) {
        [request setValue:GCOAuthUserAgent forHTTPHeaderField:@"User-Agent"];
    }
    [request setValue:[self authorizationHeader] forHTTPHeaderField:@"Authorization"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [request setHTTPMethod:self.HTTPMethod];
    [request setHTTPShouldHandleCookies:GCOAuthUseHTTPSCookieStorage];
    return request;
}
- (NSString *)authorizationHeader {
    NSMutableArray *entries = [NSMutableArray array];
    NSMutableDictionary *dictionary = [OAuthParameters mutableCopy];
    [dictionary setObject:[self signature] forKey:@"oauth_signature"];
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *entry = [NSString stringWithFormat:@"%@=\"%@\"", [key pcen], [obj pcen]];
        [entries addObject:entry];
    }];
    [dictionary release];
    return [@"OAuth " stringByAppendingString:[entries componentsJoinedByString:@","]];
}
- (NSString *)signature {
    
    // get signature components
    NSData *base = [[self signatureBase] dataUsingEncoding:NSUTF8StringEncoding];
    NSData *secret = [signatureSecret dataUsingEncoding:NSUTF8StringEncoding];
    
    // hmac
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CCHmacContext cx;
    CCHmacInit(&cx, kCCHmacAlgSHA1, [secret bytes], [secret length]);
    CCHmacUpdate(&cx, [base bytes], [base length]);
    CCHmacFinal(&cx, digest);
    
    // base 64
    NSData *data = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
    return [data base64EncodedString];
    
}
- (NSString *)signatureBase {
    
    // normalize parameters
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters addEntriesFromDictionary:OAuthParameters];
    [parameters addEntriesFromDictionary:self.requestParameters];
    NSMutableArray *entries = [NSMutableArray arrayWithCapacity:[parameters count]];
    NSArray *keys = [[parameters allKeys] sortedArrayUsingSelector:@selector(compare:)];
    for (NSString *key in keys) {
        NSString *obj = [parameters objectForKey:key];
        NSString *entry = [NSString stringWithFormat:@"%@=%@", [key pcen], [obj pcen]];
        [entries addObject:entry];
    }
    NSString *normalizedParameters = [entries componentsJoinedByString:@"&"];
    
    // construct request url
    NSURL *URL = self.URL;
    NSString *URLString = [NSString stringWithFormat:@"%@://%@%@",
                           [[URL scheme] lowercaseString],
                           [[URL host] lowercaseString],
                           [URL path]];
    
    // create components
    NSArray *components = [NSArray arrayWithObjects:
                           [self.HTTPMethod pcen],
                           [URLString pcen],
                           [normalizedParameters pcen],
                           nil];
    
    // return
    return [components componentsJoinedByString:@"&"];
    
}
- (void)dealloc {
    self.URL = nil;
    self.HTTPMethod = nil;
    self.requestParameters = nil;
    [OAuthParameters release];
    OAuthParameters = nil;
    [signatureSecret release];
    signatureSecret = nil;
    [super dealloc];
}

#pragma mark - class methods
+ (void)setUserAgent:(NSString *)agent {
    [GCOAuthUserAgent release];
    GCOAuthUserAgent = [agent copy];
}
+ (void)setTimeStampOffset:(time_t)offset {
    GCOAuthTimeStampOffset = offset;
}
+ (void)setHTTPShouldHandleCookies:(BOOL)handle {
    GCOAuthUseHTTPSCookieStorage = handle;
}
+ (NSString *)nonce {
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, uuid);
    CFRelease(uuid);
    return [(NSString *)string autorelease];
}
+ (NSString *)timeStamp {
    time_t t;
    time(&t);
    mktime(gmtime(&t));
    return [NSString stringWithFormat:@"%u", (t + GCOAuthTimeStampOffset)];
}
+ (NSString *)queryStringFromParameters:(NSDictionary *)parameters {
    NSMutableArray *entries = [NSMutableArray array];
    [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *entry = [NSString stringWithFormat:@"%@=%@", [key pcen], [obj pcen]];
        [entries addObject:entry];
    }];
    return [entries componentsJoinedByString:@"&"];
}
+ (NSMutableURLRequest *)URLRequestForPath:(NSString *)path
                      GETParameters:(NSDictionary *)parameters
                               host:(NSString *)host
                        consumerKey:(NSString *)consumerKey
                     consumerSecret:(NSString *)consumerSecret
                        accessToken:(NSString *)accessToken
                        tokenSecret:(NSString *)tokenSecret {
    return [self URLRequestForPath:path
                     GETParameters:parameters
                            scheme:@"http"
                              host:host
                       consumerKey:consumerKey
                    consumerSecret:consumerSecret
                       accessToken:accessToken
                       tokenSecret:tokenSecret];
}
+ (NSMutableURLRequest *)URLRequestForPath:(NSString *)path
                      GETParameters:(NSDictionary *)parameters
                             scheme:(NSString *)scheme
                               host:(NSString *)host
                        consumerKey:(NSString *)consumerKey
                     consumerSecret:(NSString *)consumerSecret
                        accessToken:(NSString *)accessToken
                        tokenSecret:(NSString *)tokenSecret {
    
    // check parameters
    if (host == nil || path == nil) { return nil; }
    
    // create object
    GCOAuth *oauth = [[GCOAuth alloc] initWithConsumerKey:consumerKey
                                           consumerSecret:consumerSecret
                                              accessToken:accessToken
                                              tokenSecret:tokenSecret
                                          oauthParameters:nil];
    oauth.HTTPMethod = @"GET";
    oauth.requestParameters = parameters;
    
    // create url
    NSString *encodedPath = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *URLString = [NSString stringWithFormat:@"%@://%@%@", scheme, host, encodedPath];
    if ([oauth.requestParameters count]) {
        NSString *query = [GCOAuth queryStringFromParameters:oauth.requestParameters];
        URLString = [NSString stringWithFormat:@"%@?%@", URLString, query];
    }
    oauth.URL = [NSURL URLWithString:URLString];
    
    // return
    NSMutableURLRequest *request = [oauth request];
    [oauth release];
    return request;
    
}
+ (NSMutableURLRequest *)URLRequestForPath:(NSString *)path
                     POSTParameters:(NSDictionary *)parameters
                               host:(NSString *)host
                        consumerKey:(NSString *)consumerKey
                     consumerSecret:(NSString *)consumerSecret
                        accessToken:(NSString *)accessToken
                        tokenSecret:(NSString *)tokenSecret
                    oauthParameters:(NSDictionary*)oauthParameters {
    
    // check parameters
    if (host == nil || path == nil) { return nil; }
    
    // create object
    GCOAuth *oauth = [[GCOAuth alloc] initWithConsumerKey:consumerKey
                                           consumerSecret:consumerSecret
                                              accessToken:accessToken
                                              tokenSecret:tokenSecret
                                          oauthParameters:oauthParameters];
    oauth.HTTPMethod = @"POST";
    oauth.requestParameters = parameters;
    NSURL *URL = [[NSURL alloc] initWithScheme:@"https" host:host path:path];
    oauth.URL = URL;
    [URL release];
    
    // create request
    NSMutableURLRequest *request = [oauth request];
    if ([oauth.requestParameters count]) {
        NSString *query = [GCOAuth queryStringFromParameters:oauth.requestParameters];
        NSData *data = [query dataUsingEncoding:NSUTF8StringEncoding];
        NSString *length = [NSString stringWithFormat:@"%lu", (unsigned long)[data length]];
        [request setHTTPBody:data];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setValue:length forHTTPHeaderField:@"Content-Length"];
    }
    
    // return
    [oauth release];
    return request;
    
}

@end
@implementation NSString (GCOAuthAdditions)
- (NSString *)pcen {
    CFStringRef string = CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                 (CFStringRef)self,
                                                                 NULL,
                                                                 CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                 kCFStringEncodingUTF8);
    return [(NSString *)string autorelease];
}
@end
Something went wrong with that request. Please try again.