Skip to content

Commit

Permalink
Merge pull request #685 from wordpress-mobile/issue/673-fix-checkWPco…
Browse files Browse the repository at this point in the history
…mAuthentication

#673 - Fix WP.com auth to use OAuth2 token and wipe when fails
  • Loading branch information
sendhil committed Nov 27, 2013
2 parents 9ccacc6 + 025fafe commit ccb2376
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 30 deletions.
4 changes: 3 additions & 1 deletion WordPress/Classes/Blog.m
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#import "NSURL+IDN.h"
#import "NSString+XMLExtensions.h"
#import "WPError.h"
#import "WordPressComApi.h"

@interface Blog (PrivateMethods)
- (WPXMLRPCRequestOperation *)operationForOptionsWithSuccess:(void (^)())success failure:(void (^)(NSError *error))failure;
Expand Down Expand Up @@ -596,6 +597,7 @@ - (WPXMLRPCClient *)api {
// Enable compression for wp.com only, as some self hosted have connection issues
if (self.isWPcom) {
[_api setDefaultHeader:@"gzip, deflate" value:@"Accept-Encoding"];
[_api setAuthorizationHeaderWithToken:[WordPressComApi sharedApi].authToken];
}
}
return _api;
Expand All @@ -611,7 +613,7 @@ - (WPXMLRPCRequestOperation *)operationForOptionsWithSuccess:(void (^)())success
return;

self.options = [NSDictionary dictionaryWithDictionary:(NSDictionary *)responseObject];
NSString *minimumVersion = @"3.1";
NSString *minimumVersion = @"3.5";
float version = [[self version] floatValue];
if (version < [minimumVersion floatValue]) {
if (self.lastUpdateWarning == nil || [self.lastUpdateWarning floatValue] < [minimumVersion floatValue]) {
Expand Down
25 changes: 12 additions & 13 deletions WordPress/Classes/WordPressAppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,10 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
[WPMobileStats initializeStats];
[[GPPSignIn sharedInstance] setClientID:[WordPressComApiCredentials googlePlusClientId]];

if([[NSUserDefaults standardUserDefaults] objectForKey:@"wpcom_authenticated_flag"] != nil) {
NSString *tempIsAuthenticated = (NSString *)[[NSUserDefaults standardUserDefaults] objectForKey:@"wpcom_authenticated_flag"];
if([tempIsAuthenticated isEqualToString:@"1"])
self.isWPcomAuthenticated = YES;
}
// Temporarily set the is authenticated flag based upon if we have a WP.com OAuth2 token
// TODO :: Move this BOOL to a method on the WordPressComApi along with checkWPcomAuthentication
BOOL tempIsAuthenticated = [[WordPressComApi sharedApi] authToken].length > 0;
self.isWPcomAuthenticated = tempIsAuthenticated;

// Set current directory for WordPress app
NSFileManager *fileManager = [NSFileManager defaultManager];
Expand Down Expand Up @@ -920,35 +919,35 @@ - (void)setAppBadge {
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

// TODO :: Eliminate this check or at least move it to WordPressComApi (or WPAccount)
- (void)checkWPcomAuthentication {
NSString *authURL = @"https://wordpress.com/xmlrpc.php";

WPAccount *account = [WPAccount defaultWordPressComAccount];
if (account) {
WPXMLRPCClient *client = [WPXMLRPCClient clientWithXMLRPCEndpoint:[NSURL URLWithString:authURL]];
[client setAuthorizationHeaderWithToken:[[WordPressComApi sharedApi] authToken]];
[client callMethod:@"wp.getUsersBlogs"
parameters:[NSArray arrayWithObjects:account.username, account.password, nil]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
isWPcomAuthenticated = YES;
DDLogInfo(@"Logged in to WordPress.com as %@", account.username);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if ([error.domain isEqualToString:@"XMLRPC"] && error.code == 403) {
if ([error.domain isEqualToString:@"WPXMLRPCFaultError"] ||
([error.domain isEqualToString:@"XMLRPC"] && error.code == 403)) {
isWPcomAuthenticated = NO;
[[WordPressComApi sharedApi] invalidateOAuth2Token];
}

DDLogError(@"Error authenticating %@ with WordPress.com: %@", account.username, [error description]);
}];
} else {
isWPcomAuthenticated = NO;
}

if (isWPcomAuthenticated)
[[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"wpcom_authenticated_flag"];
else
[[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"wpcom_authenticated_flag"];
}


- (void) checkIfStatsShouldRun {
- (void)checkIfStatsShouldRun {
if (NO) { // Switch this to YES to debug stats/update check
[self runStats];
return;
Expand Down Expand Up @@ -1117,7 +1116,7 @@ - (void)toggleExtraDebuggingIfNeeded {
}

int num_blogs = [Blog countWithContext:[self managedObjectContext]];
BOOL authed = [[[NSUserDefaults standardUserDefaults] objectForKey:@"wpcom_authenticated_flag"] boolValue];
BOOL authed = isWPcomAuthenticated;
if (num_blogs == 0 && !authed) {
// When there are no blogs in the app the settings screen is unavailable.
// In this case, enable extra_debugging by default to help troubleshoot any issues.
Expand Down
4 changes: 3 additions & 1 deletion WordPress/WordPressApi/WordPressComApi.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ extern NSString *const WordPressComApiErrorMessageKey;
@interface WordPressComApi : AFHTTPClient
@property (nonatomic,readonly,strong) NSString *username;
@property (nonatomic,readonly,strong) NSString *password;
@property (nonatomic, readonly, strong) NSString *authToken;

+ (WordPressComApi *)sharedApi;

Expand All @@ -49,6 +50,8 @@ extern NSString *const WordPressComApiErrorMessageKey;
- (void)signInWithToken:(NSString *)token DEPRECATED_ATTRIBUTE;
- (void)signOut;
- (BOOL)hasCredentials;
// Wipe the OAuth2 token
- (void)invalidateOAuth2Token;
- (void)validateWPComAccountWithEmail:(NSString *)email andUsername:(NSString *)username andPassword:(NSString *)password success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure;
- (void)createWPComAccountWithEmail:(NSString *)email andUsername:(NSString *)username andPassword:(NSString *)password success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure;
- (void)validateWPComBlogWithUrl:(NSString *)blogUrl andBlogTitle:(NSString *)blogTitle andLanguageId:(NSNumber *)languageId success:(void (^)(id))success failure:(void (^)(NSError *))failure;
Expand Down Expand Up @@ -129,7 +132,6 @@ extern NSString *const WordPressComApiErrorMessageKey;
/// @name OAuth info
///-----------------

- (NSString *)authToken;
+ (NSString *)WordPressAppId;
+ (NSString *)WordPressAppSecret;

Expand Down
26 changes: 11 additions & 15 deletions WordPress/WordPressApi/WordPressComApi.m
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,13 @@ - (NSError *)error {
@interface WordPressComApi ()
@property (readwrite, nonatomic, strong) NSString *username;
@property (readwrite, nonatomic, strong) NSString *password;
@property (nonatomic, strong) NSString *authToken;
@property (readwrite, nonatomic, strong) NSString *authToken;

- (void)clearWpcomCookies;

@end

@implementation WordPressComApi {
NSString *_authToken;
}
@implementation WordPressComApi

+ (WordPressComApi *)sharedApi {
static WordPressComApi *_sharedApi = nil;
Expand All @@ -105,9 +103,9 @@ + (WordPressComApi *)sharedApi {
andServiceName:WordPressComApiOauthServiceName
error:&error];
if (error) {
DDLogError(@"Error getting WordPress.com OAuth token: %@", error);
DDLogError(@"Error getting WordPress.com OAuth2 token: %@", error);
} else {
DDLogVerbose(@"Found token for API: %@", authToken ? @"YES" : @"NO");
DDLogVerbose(@"Found OAuth2 token for API: %@", authToken.length > 0 ? @"YES" : @"NO");
}
}
_sharedApi = [[self alloc] initWithBaseURL:[NSURL URLWithString:WordPressComApiClientEndpointURL] ];
Expand Down Expand Up @@ -172,7 +170,6 @@ - (void)signInWithUsername:(NSString *)username password:(NSString *)password su
} else {
WPFLog(@"Signed in as %@", self.username);
[[NSUserDefaults standardUserDefaults] setObject:self.username forKey:@"wpcom_username_preference"];
[[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"wpcom_authenticated_flag"];
[[NSUserDefaults standardUserDefaults] synchronize];
[WordPressAppDelegate sharedWordPressApplicationDelegate].isWPcomAuthenticated = YES;
[[WordPressAppDelegate sharedWordPressApplicationDelegate] registerForPushNotifications];
Expand Down Expand Up @@ -229,7 +226,6 @@ - (void)signOut {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:kApnsDeviceTokenPrefKey]; //Remove the token from Preferences, otherwise the token is never sent to the server on the next login
[SFHFKeychainUtils deleteItemForUsername:self.username andServiceName:WordPressComApiOauthServiceName error:&error];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"wpcom_username_preference"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"wpcom_authenticated_flag"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.authToken = nil;
self.username = nil;
Expand All @@ -246,7 +242,11 @@ - (void)signOut {
}

- (BOOL)hasCredentials {
return _authToken != nil;
return self.authToken.length > 0;
}

- (void)invalidateOAuth2Token {
[self setAuthToken:nil];
}

- (void)validateWPComAccountWithEmail:(NSString *)email andUsername:(NSString *)username andPassword:(NSString *)password success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure
Expand Down Expand Up @@ -530,9 +530,9 @@ - (void)syncPushNotificationInfo {
};
WPXMLRPCRequest *tokenRequest = [api XMLRPCRequestWithMethod:@"wpcom.mobile_push_register_token" parameters:[NSArray arrayWithObjects:[self usernameForXmlrpc], [self passwordForXmlrpc], token, tokenOptions, nil]];
WPXMLRPCRequestOperation *tokenOperation = [api XMLRPCRequestOperationWithRequest:tokenRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
WPFLog(@"Registered token %@" , token);
WPFLog(@"Registered APN token %@" , token);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
WPFLog(@"Couldn't register token: %@", [error localizedDescription]);
WPFLog(@"Couldn't register APN token: %@", [error localizedDescription]);
}];

[operations addObject:tokenOperation];
Expand Down Expand Up @@ -732,10 +732,6 @@ - (NSString *)passwordForXmlrpc {

#pragma mark - Oauth methods

- (NSString *)authToken {
return _authToken;
}

- (void)setAuthToken:(NSString *)authToken {
_authToken = authToken;
NSError *error;
Expand Down

0 comments on commit ccb2376

Please sign in to comment.