From 3bc8843a21c66eb2d0788b85ad2b739db6c01848 Mon Sep 17 00:00:00 2001 From: nasli Date: Mon, 10 Jul 2017 14:12:12 +0200 Subject: [PATCH 01/50] Add user agent implemtation --- OCCommunicationLib/OCCommunicationLib/OCCommunication.h | 2 +- OCCommunicationLib/OCCommunicationLib/OCCommunication.m | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index d2c02a40..a4d7d376 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -151,7 +151,7 @@ typedef enum { * * @param userAgent -> String with the user agent. Ex. "iOS-ownCloud" */ -- (void) setUserAgent:(NSString *)userAgent; +- (void) setUserAgent:(NSString *) userAgent; /* diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 6aaca946..6c62cda3 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -176,6 +176,11 @@ - (void) setCredentialsOauthWithToken:(NSString*) token { self.password = token; } +#pragma mark - Setting User Agent +- (void) setUserAgent:(NSString *) userAgent { + self.userAgent = userAgent; +} + ///----------------------------------- /// @name getRequestWithCredentials ///----------------------------------- From 735f5d2e737e1660ebc87618b8ebb13b147d4fa4 Mon Sep 17 00:00:00 2001 From: nasli Date: Tue, 11 Jul 2017 15:44:18 +0200 Subject: [PATCH 02/50] Use custom setter for user agent instead default to support also with swift --- OCCommunicationLib/OCCommunicationLib/OCCommunication.h | 6 +++++- OCCommunicationLib/OCCommunicationLib/OCCommunication.m | 3 +-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index a4d7d376..7aa2ec13 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -144,6 +144,10 @@ typedef enum { */ - (void) setCredentialsOauthWithToken:(NSString*) token; +///----------------------------------- +/// @name Set User Agent +///----------------------------------- + /** * @optional * @@ -151,7 +155,7 @@ typedef enum { * * @param userAgent -> String with the user agent. Ex. "iOS-ownCloud" */ -- (void) setUserAgent:(NSString *) userAgent; +- (void) setValueOfUserAgent:(NSString *) userAgent; /* diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 6c62cda3..d91447d2 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -176,8 +176,7 @@ - (void) setCredentialsOauthWithToken:(NSString*) token { self.password = token; } -#pragma mark - Setting User Agent -- (void) setUserAgent:(NSString *) userAgent { +- (void) setValueOfUserAgent:(NSString *) userAgent { self.userAgent = userAgent; } From b4cc7688249e1da736c682507da544224f0eb5d0 Mon Sep 17 00:00:00 2001 From: nasli Date: Tue, 11 Jul 2017 15:58:29 +0200 Subject: [PATCH 03/50] Fix precated messages --- .../OCWebDavClient/OCWebDAVClient.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h index 299eb65b..7369d4c1 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h @@ -322,7 +322,7 @@ extern NSString * _Nullable OCWebDAVModificationDateKey; ///----------------------------------- /** - * DEPRECATED use - shareFileOrFolderByServerPath:andPath:password:expirationTime:publicUpload:linkName:onCommunication instead + * DEPRECATED use - shareByLinkFileOrFolderByServer:andPath:password:expirationTime:publicUpload:linkName:permissions:onCommunication instead * * Method to share a file or folder with password * @@ -338,14 +338,14 @@ extern NSString * _Nullable OCWebDAVModificationDateKey; onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure -__deprecated_msg("Use - shareFileOrFolderByServerPath:andPath:password:expirationTime:publicUpload:linkName:onCommunication instead"); +__deprecated_msg("Use - shareByLinkFileOrFolderByServer:andPath:password:expirationTime:publicUpload:linkName:permissions:onCommunication instead"); ///----------------------------------- /// @name shareFileOrFolderByServer ///----------------------------------- /** - * DEPRECATED use - shareFileOrFolderByServerPath:andPath:password:expirationTime:publicUpload:linkName:onCommunication instead + * DEPRECATED use - shareByLinkFileOrFolderByServer:andPath:password:expirationTime:publicUpload:linkName:permissions:onCommunication instead * * Method to share a file or folder * @@ -360,7 +360,7 @@ __deprecated_msg("Use - shareFileOrFolderByServerPath:andPath:password:expiratio onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure -__deprecated_msg("Use - shareFileOrFolderByServerPath:andPath:password:expirationTime:publicUpload:linkName:onCommunication instead"); +__deprecated_msg("Use - shareByLinkFileOrFolderByServer:andPath:password:expirationTime:publicUpload:linkName:permissions:onCommunication instead"); ///----------------------------------- @@ -456,7 +456,7 @@ __deprecated_msg("Use - shareFileOrFolderByServerPath:andPath:password:expiratio ///----------------------------------- /** - * DEPRECATED use - updateShareItem:ofServerPath:withPasswordProtect:andExpirationTime:andPermissions:andLinkName:andLinkName:onCommunication: instead + * DEPRECATED use - updateShareItem:ofServerPath:withPasswordProtect:andExpirationTime:andPublicUpload:andLinkName:andPermissions:onCommunication: instead * * Method to update a share link * @@ -477,7 +477,7 @@ __deprecated_msg("Use - shareFileOrFolderByServerPath:andPath:password:expiratio onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull operation, id _Nonnull response))success failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull operation, id _Nullable responseObject, NSError * _Nonnull error))failure -__deprecated_msg("Use - updateShare:ofServerPath:withPasswordProtect:andExpirationTime:andPermissions:andLinkName:onCommunication: instead"); +__deprecated_msg("Use - updateShareItem:ofServerPath:withPasswordProtect:andExpirationTime:andPublicUpload:andLinkName:andPermissions:onCommunication: instead"); ///----------------------------------- /// @name searchUsersAndGroupsWith From 95535260c953b68c7c099d3eb1fc4bf4afd44a2e Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Fri, 11 Aug 2017 12:24:23 +0200 Subject: [PATCH 04/50] Add error codes --- .../OCCommunicationLib/OCCommunication.h | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 7aa2ec13..9fc50e76 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -51,9 +51,30 @@ typedef enum { OCErrorMovingFolderInsideItself = 112, //On move file or folder OCErrorFileToUploadDoesNotExist = 120, //The file that we want upload does not exist OCErrorForbiddenUnknown = 130, //For example, no write permissions to the target folder of an upload - OCErrorForbiddenWithSpecificMessage = 131 // For example, forbidden due to a firewall rule + OCErrorForbiddenWithSpecificMessage = 131, // For example, forbidden due to a firewall rule + + OCErrorWrongConnection = 1000, + OCErrorNoNetworkConntion = 1010, + OCErrorTimeout = 1020, + OCErrorConnectTimeout = 1030, + OCErrorHostNotAvailable = 1040, + OCErrorServiceUnavailable = 1050, + OCErrorSslRecoverablePeerUnverified = 1060, + OCErrorBadVersion = 1070, + OCErrorIncorrectAddress = 1080, + OCErrorSslError = 1090, + OCErrorUnauthorized = 1100, + OCErrorServerNotConfigured = 1110, + OCErrorFileNotFound = 1120, + OCErrorOAuth2Error = 1130, + OCErrorOAuth2ErrorAccessDenied = 1140, + OCErrorAccountNotNew = 1150, + OCErrorAccountNotTheSame = 1160, + OCErrorRedirectToNonSecureConnection = 1170 + } OCErrorEnum; + //Private properties @property NSInteger kindOfCredential; @property (nonatomic, strong) NSString *user; From 13ad10be12d25267c58c10052aa0280639e030e8 Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Fri, 18 Aug 2017 10:32:10 +0200 Subject: [PATCH 05/50] Add OCCredentialsDto to library and unify methods to set credentials for OCCommunication instances in a single one --- .../OCCommunicationLib/OCCommunication.h | 32 ++------- .../OCCommunicationLib/OCCommunication.m | 20 ++++++ .../OCCommunicationLib/OCCredentialsDto.h | 41 +++++++++++ .../OCCommunicationLib/OCCredentialsDto.m | 71 +++++++++++++++++++ .../OCCommunicationLibTests.m | 6 +- .../project.pbxproj | 6 ++ 6 files changed, 148 insertions(+), 28 deletions(-) create mode 100644 OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h create mode 100644 OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 9fc50e76..78adfd72 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -25,6 +25,7 @@ #import #import "OCServerFeatures.h" +#import "OCCredentialsDto.h" @class OCHTTPRequestOperation; @class AFURLSessionManager; @@ -128,42 +129,19 @@ typedef enum { #pragma mark - Credentials -///----------------------------------- -/// @name Set Credential With User -///----------------------------------- - -/** - * Method to set credentials with user and password - * - * @param user -> NSString username - * @param password -> NSString password - */ -- (void) setCredentialsWithUser:(NSString*) user andPassword:(NSString*) password; - ///----------------------------------- -/// @name Set Credential with cookie +/// @name Set Credentials ///----------------------------------- /** - * Method that set credentials with cookie. - * Used for SAML servers. + * Method to set credentials with user and password * - * @param cookie -> NSString cookie string + * @param credentials -> OCCredentialsDto credentials */ -- (void) setCredentialsWithCookie:(NSString*) cookie; - -///----------------------------------- -/// @name Set Credential with OAuth -///----------------------------------- +- (void) setCredentials:(OCCredentialsDto *) credentials; -/** - * Method to set credentials for OAuth with token - * - * @param token -> NSString token - */ -- (void) setCredentialsOauthWithToken:(NSString*) token; ///----------------------------------- /// @name Set User Agent diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index d91447d2..ead53757 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -160,6 +160,26 @@ - (void)setSecurityPolicyManagers:(AFSecurityPolicy *)securityPolicy { #pragma mark - Setting Credentials + +- (void) setCredentials:(OCCredentialsDto *) credentials { + + switch (credentials.authenticationMethod) { + case AuthenticationMethodSAML_WEB_SSO: + + [self setCredentialsWithCookie:credentials.accessToken]; + break; + + case AuthenticationMethodBEARER_TOKEN: + + [self setCredentialsOauthWithToken:credentials.accessToken]; + break; + + default: + [self setCredentialsWithUser:credentials.userName andPassword:credentials.accessToken]; + break; + } +} + - (void) setCredentialsWithUser:(NSString*) user andPassword:(NSString*) password { self.kindOfCredential = credentialNormal; self.user = user; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h new file mode 100644 index 00000000..33d569bb --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h @@ -0,0 +1,41 @@ +// +// OCCredentialsDto.h +// Owncloud iOs library +// +// Created by Noelia Alvarez on 27/10/14. +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +#import + +typedef NS_ENUM (NSUInteger, AuthenticationMethod){ + AuthenticationMethodUNKNOWN = 0, + AuthenticationMethodNONE = 1, + AuthenticationMethodBASIC_HTTP_AUTH = 2, + AuthenticationMethodBEARER_TOKEN = 3, + AuthenticationMethodSAML_WEB_SSO = 4, +}; + +@interface OCCredentialsDto : NSObject + +@property (nonatomic, copy) NSString *userName; +@property (nonatomic, copy) NSString *accessToken; // password for basic auth, cookies for SAML, access token for OAuth2... +@property (nonatomic) AuthenticationMethod authenticationMethod; + +//optionals credentials used with oauth2 +@property (nonatomic, copy) NSString *refreshToken; +@property (nonatomic, copy) NSString *expiresIn; +@property (nonatomic, copy) NSString *tokenType; + + +- (void)encodeWithCoder:(NSCoder *)aCoder; +- (id)initWithCoder:(NSCoder *)aDecoder; + +@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m new file mode 100644 index 00000000..378de57c --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m @@ -0,0 +1,71 @@ +// +// OCCredentialsDto.m +// ownCloud iOS library +// +// Created by Noelia Alvarez on 27/10/14. +// + +/* + Copyright (C) 2016, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +#import "OCCredentialsDto.h" + +@implementation OCCredentialsDto + +- (id)initWithCredentialsDto:(OCCredentialsDto *)oCredDto{ + + self = [super init]; + if (self) { + // Custom initialization + _userName = oCredDto.userName; + _accessToken = oCredDto.accessToken; + _refreshToken = oCredDto.refreshToken; + _expiresIn = oCredDto.expiresIn; + _tokenType = oCredDto.tokenType; + _authenticationMethod = oCredDto.authenticationMethod; + } + + return self; +} + +-(id) copyWithZone:(NSZone *)zone { + OCCredentialsDto *credDtoCopy = [[OCCredentialsDto alloc]init]; + credDtoCopy.userName = self.userName; + credDtoCopy.accessToken = self.accessToken; + credDtoCopy.refreshToken = self.refreshToken; + credDtoCopy.expiresIn = self.expiresIn; + credDtoCopy.tokenType = self.tokenType; + credDtoCopy.authenticationMethod = self.authenticationMethod; + + return credDtoCopy; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeObject:self.userName forKey:@"userName"]; + [aCoder encodeObject:self.accessToken forKey:@"accessToken"]; + [aCoder encodeObject:self.refreshToken forKey:@"refreshToken"]; + [aCoder encodeObject:self.expiresIn forKey:@"expiresIn"]; + [aCoder encodeObject:self.tokenType forKey:@"tokenType"]; + [aCoder encodeInteger:self.authenticationMethod forKey:@"authenticationMethod"]; +} + +- (id)initWithCoder:(NSCoder *)aDecoder +{ + if (self = [super init]) { + self.userName = [aDecoder decodeObjectForKey:@"userName"]; + self.accessToken = [aDecoder decodeObjectForKey:@"accessToken"]; + self.refreshToken = [aDecoder decodeObjectForKey:@"refreshToken"]; + self.expiresIn = [aDecoder decodeObjectForKey:@"tokenType"]; + self.tokenType = [aDecoder decodeObjectForKey:@"tokenType"]; + self.authenticationMethod = [aDecoder decodeIntegerForKey:@"authenticationMethod"]; + } + return self; +} + +@end diff --git a/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m b/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m index 9d6791d6..0a497f1e 100644 --- a/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m +++ b/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m @@ -68,7 +68,11 @@ - (void)setUp [super setUp]; _sharedOCCommunication = [[OCCommunication alloc] init]; - [_sharedOCCommunication setCredentialsWithUser:k_user andPassword:k_password]; + OCCredentialsDto* credentials = [[OCCredentialsDto alloc] init]; + credentials.authenticationMethod = AuthenticationMethodBASIC_HTTP_AUTH; + credentials.userName = k_user; + credentials.accessToken = k_password; + [_sharedOCCommunication setCredentials credentials]; [_sharedOCCommunication setSecurityPolicyManagers:[_sharedOCCommunication createSecurityPolicy]]; //Create Tests folder diff --git a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj index 0b1e5443..52213f3b 100644 --- a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj +++ b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj @@ -18,6 +18,7 @@ 59A5B722191907F100724BE3 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 59A5B717191907F100724BE3 /* AFURLRequestSerialization.m */; }; 59A5B723191907F100724BE3 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 59A5B719191907F100724BE3 /* AFURLResponseSerialization.m */; }; 59A5B724191907F100724BE3 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 59A5B71B191907F100724BE3 /* AFURLSessionManager.m */; }; + 7F6F496D1F46C70C009F8813 /* OCCredentialsDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F6F496C1F46C70C009F8813 /* OCCredentialsDto.m */; }; EA05999A1BB96D14002C2864 /* OCShareUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EA0599991BB96D14002C2864 /* OCShareUser.m */; }; EA73DC831B1C48EA00C3AC21 /* OCXMLServerErrorsParser.m in Sources */ = {isa = PBXBuildFile; fileRef = EA73DC821B1C48EA00C3AC21 /* OCXMLServerErrorsParser.m */; }; EA7CC89B183E11E600B6A4B4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA7CC89A183E11E600B6A4B4 /* Foundation.framework */; }; @@ -99,6 +100,8 @@ 59A5B719191907F100724BE3 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLResponseSerialization.m; path = ExternalLibs/AFNetworking/AFURLResponseSerialization.m; sourceTree = ""; }; 59A5B71A191907F100724BE3 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLSessionManager.h; path = ExternalLibs/AFNetworking/AFURLSessionManager.h; sourceTree = ""; }; 59A5B71B191907F100724BE3 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLSessionManager.m; path = ExternalLibs/AFNetworking/AFURLSessionManager.m; sourceTree = ""; }; + 7F6F496B1F46C6EB009F8813 /* OCCredentialsDto.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OCCredentialsDto.h; sourceTree = ""; }; + 7F6F496C1F46C70C009F8813 /* OCCredentialsDto.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCCredentialsDto.m; sourceTree = ""; }; EA0599981BB96D14002C2864 /* OCShareUser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OCShareUser.h; sourceTree = ""; }; EA0599991BB96D14002C2864 /* OCShareUser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCShareUser.m; sourceTree = ""; }; EA73DC811B1C48EA00C3AC21 /* OCXMLServerErrorsParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OCXMLServerErrorsParser.h; path = OCWebDavClient/Parsers/OCXMLServerErrorsParser.h; sourceTree = ""; }; @@ -214,6 +217,8 @@ children = ( EAABAA30183E688900909831 /* OCFileDto.h */, EAABAA31183E688900909831 /* OCFileDto.m */, + 7F6F496B1F46C6EB009F8813 /* OCCredentialsDto.h */, + 7F6F496C1F46C70C009F8813 /* OCCredentialsDto.m */, EA0599981BB96D14002C2864 /* OCShareUser.h */, EA0599991BB96D14002C2864 /* OCShareUser.m */, 13AA8634187C211900A10927 /* OCSharedDto.h */, @@ -444,6 +449,7 @@ EA05999A1BB96D14002C2864 /* OCShareUser.m in Sources */, 59A5B723191907F100724BE3 /* AFURLResponseSerialization.m in Sources */, EA7CC92C183E14A100B6A4B4 /* OCHTTPRequestOperation.m in Sources */, + 7F6F496D1F46C70C009F8813 /* OCCredentialsDto.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From 51565384fe34273bf255d04903803a03b467d4b8 Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Fri, 25 Aug 2017 10:42:08 +0200 Subject: [PATCH 06/50] Clean-up erro codes --- .../OCCommunicationLib/OCCommunication.h | 22 ++++--------------- 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 78adfd72..17f1ed8f 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -54,25 +54,11 @@ typedef enum { OCErrorForbiddenUnknown = 130, //For example, no write permissions to the target folder of an upload OCErrorForbiddenWithSpecificMessage = 131, // For example, forbidden due to a firewall rule - OCErrorWrongConnection = 1000, - OCErrorNoNetworkConntion = 1010, - OCErrorTimeout = 1020, - OCErrorConnectTimeout = 1030, - OCErrorHostNotAvailable = 1040, - OCErrorServiceUnavailable = 1050, - OCErrorSslRecoverablePeerUnverified = 1060, - OCErrorBadVersion = 1070, - OCErrorIncorrectAddress = 1080, - OCErrorSslError = 1090, - OCErrorUnauthorized = 1100, - OCErrorServerNotConfigured = 1110, - OCErrorFileNotFound = 1120, - OCErrorOAuth2Error = 1130, - OCErrorOAuth2ErrorAccessDenied = 1140, - OCErrorAccountNotNew = 1150, - OCErrorAccountNotTheSame = 1160, - OCErrorRedirectToNonSecureConnection = 1170 + OCErrorOAuth2Error = 1000, + OCErrorOAuth2ErrorAccessDenied = 1010, + OCErrorSslRecoverablePeerUnverified = 1100 + } OCErrorEnum; From 757342e899323fa89c24ecfe39d3e3613c9e84d0 Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Fri, 25 Aug 2017 12:33:35 +0200 Subject: [PATCH 07/50] Fix typo breaking tests build --- .../OCCommunicationLibTests/OCCommunicationLibTests.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m b/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m index 0a497f1e..18142c24 100644 --- a/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m +++ b/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m @@ -72,7 +72,7 @@ - (void)setUp credentials.authenticationMethod = AuthenticationMethodBASIC_HTTP_AUTH; credentials.userName = k_user; credentials.accessToken = k_password; - [_sharedOCCommunication setCredentials credentials]; + [_sharedOCCommunication setCredentials:credentials]; [_sharedOCCommunication setSecurityPolicyManagers:[_sharedOCCommunication createSecurityPolicy]]; //Create Tests folder From 8f3eac765e77eb35d355eb64771d30ae9533ef20 Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Thu, 7 Sep 2017 14:17:56 +0200 Subject: [PATCH 08/50] Add specific NSError for server in maintenance mode --- .../OCCommunicationLib/OCCommunication.h | 1 + .../OCCommunicationLib/Utils/UtilsFramework.m | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 17f1ed8f..fad2d71c 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -53,6 +53,7 @@ typedef enum { OCErrorFileToUploadDoesNotExist = 120, //The file that we want upload does not exist OCErrorForbiddenUnknown = 130, //For example, no write permissions to the target folder of an upload OCErrorForbiddenWithSpecificMessage = 131, // For example, forbidden due to a firewall rule + OCErrorServerMaintenanceMode = 140, OCErrorOAuth2Error = 1000, OCErrorOAuth2ErrorAccessDenied = 1010, diff --git a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m index 6c20022a..9ace3506 100644 --- a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m +++ b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m @@ -238,6 +238,17 @@ + (NSError *) getErrorByCodeId:(int) errorCode { error = [NSError errorWithDomain:k_domain_error_code code:kOCErrorServerForbidden userInfo:details]; break; } + + case OCErrorServerMaintenanceMode: + case kOCErrorServerMaintenanceError: + { + NSMutableDictionary* details = [NSMutableDictionary dictionary]; + [details setValue:NSLocalizedString(@"maintenance_mode_on_server_message", nil) forKey:NSLocalizedDescriptionKey]; + + error = [NSError errorWithDomain:k_domain_error_code code:kOCErrorServerForbidden userInfo:details]; + break; + } + case OCErrorForbiddenUnknown: { NSMutableDictionary* details = [NSMutableDictionary dictionary]; From f3e8ad4bf8a7fc53e7a2f72432e33c436f3ad981 Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Wed, 13 Sep 2017 10:29:27 +0200 Subject: [PATCH 09/50] Add some more HTTP error codes as known constants --- OCCommunicationLib/OCCommunicationLib/OCErrorMsg.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCErrorMsg.h b/OCCommunicationLib/OCCommunicationLib/OCErrorMsg.h index 435a8322..afea6383 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCErrorMsg.h +++ b/OCCommunicationLib/OCCommunicationLib/OCErrorMsg.h @@ -24,14 +24,17 @@ // +#define kOCErrorServerBadRequest 400 #define kOCErrorServerUnauthorized 401 -//In the server we received a 403 also when the server is enforce to set a password. #define kOCErrorServerForbidden 403 #define kOCErrorServerPathNotFound 404 #define kOCErrorServerMethodNotPermitted 405 #define kOCErrorProxyAuth 407 #define kOCErrorServerTimeout 408 +#define kOCErrorServerConflict 409 #define kOCErrorServerInternalError 500 +#define kOCErrorServerNotImplemented 501 +#define kOCErrorServerBadGateway 502 #define kOCErrorServerMaintenanceError 503 #define kOCErrorServerInsufficientStorage 507 From 1de571b4cc62e094d8e6a4fc41d4a464e658155f Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Wed, 13 Sep 2017 12:42:13 +0200 Subject: [PATCH 10/50] Add OAuth2 errors to UtilsFramework.getErrorById() --- .../OCCommunicationLib/Utils/UtilsFramework.m | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m index 9ace3506..06500c78 100644 --- a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m +++ b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m @@ -257,6 +257,25 @@ + (NSError *) getErrorByCodeId:(int) errorCode { error = [NSError errorWithDomain:k_domain_error_code code:OCErrorForbiddenUnknown userInfo:details]; break; } + + case OCErrorOAuth2ErrorAccessDenied: + { + NSMutableDictionary* details = [NSMutableDictionary dictionary]; + [details setValue:NSLocalizedString(@"oauth2_error_access_denied", nil) forKey:NSLocalizedDescriptionKey]; + + error = [NSError errorWithDomain:k_domain_error_code code:OCErrorForbiddenUnknown userInfo:details]; + break; + } + + case OCErrorOAuth2Error: + { + NSMutableDictionary* details = [NSMutableDictionary dictionary]; + [details setValue:NSLocalizedString(@"oauth2_error", nil) forKey:NSLocalizedDescriptionKey]; + + error = [NSError errorWithDomain:k_domain_error_code code:OCErrorForbiddenUnknown userInfo:details]; + break; + } + default: { NSMutableDictionary* details = [NSMutableDictionary dictionary]; From 4b5de106c0d314f386d010fd2b93608c169bd0d6 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 11 Aug 2017 15:32:08 +0200 Subject: [PATCH 11/50] Add refresh token to request --- .../OCCommunicationLib/OCCommunication.h | 3 +++ .../OCCommunicationLib/OCCommunication.m | 4 ++-- .../OCCommunicationLib/Utils/UtilsFramework.m | 13 ++++++++++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index fad2d71c..7908b677 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -67,6 +67,9 @@ typedef enum { @property NSInteger kindOfCredential; @property (nonatomic, strong) NSString *user; @property (nonatomic, strong) NSString *password; +@property (nonatomic, strong) NSString *refreshToken; +@property (nonatomic, strong) NSDate *expiresIn; + @property (nonatomic, strong) NSString *userAgent; //Public properties diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index ead53757..0d518a96 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -171,7 +171,7 @@ - (void) setCredentials:(OCCredentialsDto *) credentials { case AuthenticationMethodBEARER_TOKEN: - [self setCredentialsOauthWithToken:credentials.accessToken]; + [self setCredentialsOauthWithToken:credentials.accessToken refreshToken:credentials.refreshToken expiresIn:credentials.expiresIn]; break; default: @@ -191,7 +191,7 @@ - (void) setCredentialsWithCookie:(NSString*) cookie { self.password = cookie; } -- (void) setCredentialsOauthWithToken:(NSString*) token { +- (void) setCredentialsOauthWithToken:(NSString*)token refreshToken:(NSString *)refreshToken expiresIn:(NSString *)expiresIn { self.kindOfCredential = credentialOauth; self.password = token; } diff --git a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m index 06500c78..3c4962df 100644 --- a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m +++ b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m @@ -664,10 +664,21 @@ + (BOOL) isPermissionToReadCreateUpdate:(NSInteger) permissionValue { BOOL canCreate = [self isPermissionToCanCreate:permissionValue]; BOOL canChange = [self isPermissionToCanChange:permissionValue]; - BOOL canEdit = (canCreate && canChange && canRead); return canEdit; +} + ++(BOOL) isTokenExpired:(NSString *)expiresIn { + + BOOL expired = NO; + NSDate* now = [NSDate date]; + //TODO: + + + return expired; } + + @end From dd0b2498c6cb223ec180645433f3f58d8dec4aa2 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 25 Aug 2017 11:02:45 +0200 Subject: [PATCH 12/50] Update occommunication to store refresh token and expires in --- OCCommunicationLib/OCCommunicationLib/OCCommunication.h | 2 +- OCCommunicationLib/OCCommunicationLib/OCCommunication.m | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 7908b677..43b67344 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -68,7 +68,7 @@ typedef enum { @property (nonatomic, strong) NSString *user; @property (nonatomic, strong) NSString *password; @property (nonatomic, strong) NSString *refreshToken; -@property (nonatomic, strong) NSDate *expiresIn; +@property (nonatomic, strong) NSString *expiresIn; @property (nonatomic, strong) NSString *userAgent; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 0d518a96..fba3e873 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -194,6 +194,8 @@ - (void) setCredentialsWithCookie:(NSString*) cookie { - (void) setCredentialsOauthWithToken:(NSString*)token refreshToken:(NSString *)refreshToken expiresIn:(NSString *)expiresIn { self.kindOfCredential = credentialOauth; self.password = token; + self.refreshToken = refreshToken; + self.expiresIn = expiresIn; } - (void) setValueOfUserAgent:(NSString *) userAgent { From 9d7bc7cff7864f3d36b2e23c6628754ed3375359 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 25 Aug 2017 11:06:36 +0200 Subject: [PATCH 13/50] Add retry n tiemes in all network requests --- .../OCWebDavClient/OCWebDAVClient.m | 87 +++++++++++++++---- 1 file changed, 68 insertions(+), 19 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index dc20bdb2..1f51b732 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -116,6 +116,55 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque return operation; } +- (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { + + //If is not nil is a redirection so we keep the original url server + if (!self.originalUrlServer) { + self.originalUrlServer = [request.URL absoluteString]; + } + + if (sharedOCCommunication.isCookiesAvailable) { + //We add the cookies of that URL + request = [UtilsFramework getRequestWithCookiesByRequest:request andOriginalUrlServer:self.originalUrlServer]; + } else { + [UtilsFramework deleteAllCookies]; + } + + + OCHTTPRequestOperation *operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (!error) { + success((NSHTTPURLResponse*)response,responseObject); + } else { + + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (ntimes <= 0) { + if (failure) { + failure((NSHTTPURLResponse*)response, responseObject, error); + } + } else { + + //TODO: get refresh token + //TODO: set new token. + //NSString *refreshToken = @"newToken"; + //sharedOCCommunication.password = refreshToken; + + [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + onCommunication:sharedOCCommunication + success:success + failure:failure + ]; + } + } else { + failure((NSHTTPURLResponse*)response, responseObject, error); + + } + } + }]; + + return operation; + +} + - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { //If is not nil is a redirection so we keep the original url server @@ -181,7 +230,7 @@ - (void)movePath:(NSString *)source toPath:(NSString *)destination NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:source parameters:nil]; [request setValue:destination forHTTPHeaderField:@"Destination"]; [request setValue:@"T" forHTTPHeaderField:@"Overwrite"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -193,7 +242,7 @@ - (void)deletePath:(NSString *)path _requestMethod = @"DELETE"; NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:path parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -220,7 +269,7 @@ - (void)mr_listPath:(NSString *)path depth:(NSUInteger)depth onCommunication: [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -316,7 +365,7 @@ - (void)makeCollection:(NSString *)path onCommunication: failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { _requestMethod = @"MKCOL"; NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:path parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -387,7 +436,7 @@ - (void) requestUserNameOfServer:(NSString * _Nonnull) path byCookie:(NSString * NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path: apiUserUrl parameters: nil]; [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -404,7 +453,7 @@ - (void) getStatusOfTheServer:(NSString *)serverPath onCommunication: request.HTTPShouldHandleCookies = false; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -420,7 +469,7 @@ - (void)listSharedByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -438,7 +487,7 @@ - (void)listSharedByServer:(NSString *)serverPath andPath:(NSString *) path NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -487,7 +536,7 @@ - (void)shareByLinkFileOrFolderByServer:(NSString * _Nonnull)serverPath [request setHTTPBody:[self.postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -504,7 +553,7 @@ - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString _postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=3&password=%@",filePath,password]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -521,7 +570,7 @@ - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString _postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=3",filePath]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -538,7 +587,7 @@ - (void)shareWith:(NSString *)userOrGroup shareeType:(NSInteger)shareeType inSer self.postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=%ld&shareWith=%@&permissions=%ld",filePath, (long)shareeType, userOrGroup, (long)permissions]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -554,7 +603,7 @@ - (void)unShareFileOrFolderByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -570,7 +619,7 @@ - (void)isShareFileOrFolderByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -612,7 +661,7 @@ - (void) updateShareItem:(NSInteger)shareId [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -642,7 +691,7 @@ - (void) updateShareItem:(NSInteger)shareId [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -665,7 +714,7 @@ - (void) searchUsersAndGroupsWith:(NSString *)searchString forPage:(NSInteger)pa NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -679,7 +728,7 @@ - (void) getCapabilitiesOfServer:(NSString*)serverPath onCommunication:(OCCommun NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; @@ -699,7 +748,7 @@ - (OCHTTPRequestOperation *) getRemoteThumbnailByServer:(NSString*)serverPath of NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; return operation; From 23ba7f235250a0af6094d8a92d0d639f60486429 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 25 Aug 2017 12:58:48 +0200 Subject: [PATCH 14/50] Use constant to ntimes retry variable --- .../OCWebDavClient/OCWebDAVClient.m | 39 ++++++++++--------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 1f51b732..0db5a5b6 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -39,6 +39,7 @@ #define k_server_information_json @"status.php" #define k_api_header_request @"OCS-APIREQUEST" #define k_group_sharee_type 1 +#define k_retry_ntimes 2 NSString const *OCWebDAVContentTypeKey = @"getcontenttype"; @@ -230,7 +231,7 @@ - (void)movePath:(NSString *)source toPath:(NSString *)destination NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:source parameters:nil]; [request setValue:destination forHTTPHeaderField:@"Destination"]; [request setValue:@"T" forHTTPHeaderField:@"Overwrite"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -242,7 +243,7 @@ - (void)deletePath:(NSString *)path _requestMethod = @"DELETE"; NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:path parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -269,7 +270,7 @@ - (void)mr_listPath:(NSString *)path depth:(NSUInteger)depth onCommunication: [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -365,7 +366,7 @@ - (void)makeCollection:(NSString *)path onCommunication: failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { _requestMethod = @"MKCOL"; NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:path parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -436,7 +437,7 @@ - (void) requestUserNameOfServer:(NSString * _Nonnull) path byCookie:(NSString * NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path: apiUserUrl parameters: nil]; [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -453,7 +454,7 @@ - (void) getStatusOfTheServer:(NSString *)serverPath onCommunication: request.HTTPShouldHandleCookies = false; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -469,7 +470,7 @@ - (void)listSharedByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -487,7 +488,7 @@ - (void)listSharedByServer:(NSString *)serverPath andPath:(NSString *) path NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -536,7 +537,7 @@ - (void)shareByLinkFileOrFolderByServer:(NSString * _Nonnull)serverPath [request setHTTPBody:[self.postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -553,7 +554,7 @@ - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString _postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=3&password=%@",filePath,password]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -570,7 +571,7 @@ - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString _postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=3",filePath]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -587,7 +588,7 @@ - (void)shareWith:(NSString *)userOrGroup shareeType:(NSInteger)shareeType inSer self.postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=%ld&shareWith=%@&permissions=%ld",filePath, (long)shareeType, userOrGroup, (long)permissions]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -603,7 +604,7 @@ - (void)unShareFileOrFolderByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -619,7 +620,7 @@ - (void)isShareFileOrFolderByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -661,7 +662,7 @@ - (void) updateShareItem:(NSInteger)shareId [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -691,7 +692,7 @@ - (void) updateShareItem:(NSInteger)shareId [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -714,7 +715,7 @@ - (void) searchUsersAndGroupsWith:(NSString *)searchString forPage:(NSInteger)pa NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } @@ -728,7 +729,7 @@ - (void) getCapabilitiesOfServer:(NSString*)serverPath onCommunication:(OCCommun NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; @@ -748,7 +749,7 @@ - (OCHTTPRequestOperation *) getRemoteThumbnailByServer:(NSString*)serverPath of NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:2 onCommunication:sharedOCCommunication success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; return operation; From 7785619d3394811090b07d4f049ded49de3c562e Mon Sep 17 00:00:00 2001 From: nasli Date: Tue, 29 Aug 2017 10:47:38 +0200 Subject: [PATCH 15/50] Add new OAuth2 configuration class that manages all OAuth parameters. Add oauth refresh token request --- .../OCCommunicationLib/OCCredentialsDto.h | 31 +++-- .../OCCommunicationLib/OCCredentialsDto.m | 26 +++-- .../OCOAuth2Configuration.h | 40 +++++++ .../OCOAuth2Configuration.m | 50 ++++++++ .../OCOAuth2Authentication/OCOAuth2Manager.h | 40 +++++++ .../OCOAuth2Authentication/OCOAuth2Manager.m | 109 ++++++++++++++++++ .../OCWebDavClient/OCWebDAVClient.m | 3 + .../project.pbxproj | 24 +++- 8 files changed, 305 insertions(+), 18 deletions(-) create mode 100644 OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h create mode 100644 OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m create mode 100644 OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h create mode 100644 OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h index 33d569bb..45d0012b 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h @@ -1,17 +1,30 @@ // // OCCredentialsDto.h -// Owncloud iOs library +// ownCloud iOS library // // Created by Noelia Alvarez on 27/10/14. // - -/* - Copyright (C) 2017, ownCloud GmbH. - This code is covered by the GNU Public License Version 3. - For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ - You should have received a copy of this license - along with this program. If not, see . - */ +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// #import diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m index 378de57c..00c5ef34 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m @@ -4,14 +4,26 @@ // // Created by Noelia Alvarez on 27/10/14. // +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. -/* - Copyright (C) 2016, ownCloud GmbH. - This code is covered by the GNU Public License Version 3. - For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ - You should have received a copy of this license - along with this program. If not, see . - */ +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// #import "OCCredentialsDto.h" diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h new file mode 100644 index 00000000..030c99cf --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h @@ -0,0 +1,40 @@ +// +// OCOAuth2Configuration.h +// ownCloud iOS library +// +// Created by Noelia Alvarez on 28/08/2017. +// +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#import + +@interface OCOAuth2Configuration : NSObject + +@property (nonatomic, copy) NSURL *mURL; +@property (nonatomic, copy) NSString *mClientId; +@property (nonatomic, copy) NSString *mClientSecret; +@property (nonatomic, copy) NSString *mRedirectUri; +@property (nonatomic, copy) NSString *mAuthorizationEndpoint; +@property (nonatomic, copy) NSString *mTokenEndpoint; +@property (nonatomic, copy) NSString *mUserAgent; + +@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m new file mode 100644 index 00000000..40abfd3c --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m @@ -0,0 +1,50 @@ +// +// OCOAuth2Configuration.m +// ownCloud iOS library +// +// Created by Noelia Alvarez on 28/08/2017. +// +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#import "OCOAuth2Configuration.h" + +@implementation OCOAuth2Configuration + + +- (id)initWithURL:(NSURL *)url ClientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint userAgent:(NSString *)userAgent{ + + self = [super init]; + if (self) { + // Custom initialization + _mURL = url; + _mClientId = clientId; + _mClientSecret = clientSecret; + _mRedirectUri = redirectUri; + _mAuthorizationEndpoint = authorizationEndpoint; + _mTokenEndpoint = tokenEndpoint; + _mUserAgent = userAgent; + } + + return self; +} + +@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h new file mode 100644 index 00000000..1b276edb --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -0,0 +1,40 @@ +// +// OCOAuth2Manager.h +// ownCloud iOS library +// +// Created by Noelia Alvarez on 28/08/2017. +// +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#import +#import "OCCredentialsDto.h" +#import "OCCommunication.h" +#import "OCOAuth2Configuration.h" +#import "UtilsFramework.h" + +@interface OCOAuth2Manager : NSObject + +- (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + refreshToken:(NSString *)refreshToken + success:(void(^)(OCCredentialsDto *userCredDto))success + failure:(void(^)(NSString *error))failure; +@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m new file mode 100644 index 00000000..cb782fdf --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -0,0 +1,109 @@ +// +// OCOAuth2Manager.m +// ownCloud iOS library +// +// Created by Noelia Alvarez on 28/08/2017. +// +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#import "OCOAuth2Manager.h" + +@implementation OCOAuth2Manager + +- (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + refreshToken:(NSString *)refreshToken + success:(void(^)(OCCredentialsDto *userCredDto))success + failure:(void(^)(NSString *error))failure { + + [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration refreshToken:refreshToken success:^(NSData *data, NSError *error) { + + NSDictionary *dictJSON; + OCCredentialsDto *userCredDto; + + if (data != nil) { + + NSError *errorJSON = nil; + dictJSON = [NSJSONSerialization JSONObjectWithData:data + options:kNilOptions + error:&errorJSON]; + if (errorJSON != nil) { + if (dictJSON[@"error"] != nil && ![dictJSON[@"error"] isEqual:[NSNull null]] ) { + failure(dictJSON[@"error"]); + } else { + userCredDto.userName = dictJSON[@"user_id"]; + userCredDto.accessToken = dictJSON[@"access_token"]; + userCredDto.refreshToken = dictJSON[@"refresh_token"]; + userCredDto.expiresIn = dictJSON[@"expires_in"]; + userCredDto.tokenType = dictJSON[@"token_type"]; + userCredDto.authenticationMethod = AuthenticationMethodBEARER_TOKEN; + + success(userCredDto); + } + } + + } else { + failure(error.localizedDescription); + } + + } failure:^(NSHTTPURLResponse *response, NSError *error) { + + }]; + +} + +- (void) refreshTokenAuthRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + refreshToken:(NSString *)refreshToken + success:(void(^)(NSData *data, NSError *error))success + failure:(void(^)(NSHTTPURLResponse *response, NSError *error))failure { + + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:oauth2Configuration.mURL]; + + [request setHTTPMethod:@"POST"]; + [request setValue:oauth2Configuration.mUserAgent forHTTPHeaderField:@"User-Agent"]; + [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + + NSString *authId = [NSString stringWithFormat:@"%@:%@",oauth2Configuration.mClientId,oauth2Configuration.mClientSecret]; + NSString *base64EncodedAuthId = [UtilsFramework AFBase64EncodedStringFromString:authId]; + NSString *authorizationValue = [NSString stringWithFormat:@"Basic %@",base64EncodedAuthId]; + [request setValue:authorizationValue forHTTPHeaderField:@"Authorization"]; + + NSString *body = [NSString stringWithFormat:@"grant_type=refresh_token&refresh_token=%@&redirect_uri=%@&client_id=%@",refreshToken,oauth2Configuration.mRedirectUri,oauth2Configuration.mClientId]; + [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; + + NSURLSession *session = nil; + + session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; + + NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { + + if (data != nil) { + success(data, error); + } else { + NSLog(@"Error %@",error.localizedDescription); + failure((NSHTTPURLResponse*)response, error); + } + }]; + + [task resume]; +} + +@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 0db5a5b6..2595bad6 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -34,6 +34,7 @@ #import "AFURLSessionManager.h" #import "NSString+Encode.h" #import "OCConstants.h" +#import "OCOAuth2Manager.h" #define k_api_user_url_json @"ocs/v1.php/cloud/user?format=json" #define k_server_information_json @"status.php" @@ -117,6 +118,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque return operation; } +#pragma mark - Main network operation - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { //If is not nil is a redirection so we keep the original url server @@ -145,6 +147,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //TODO: get refresh token + //TODO: set new token. //NSString *refreshToken = @"newToken"; //sharedOCCommunication.password = refreshToken; diff --git a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj index 52213f3b..709e3027 100644 --- a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj +++ b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj @@ -11,6 +11,8 @@ 1345E4601884213400153F14 /* OCXMLShareByLinkParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 1345E45F1884213400153F14 /* OCXMLShareByLinkParser.m */; }; 13AA8636187C211900A10927 /* OCSharedDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 13AA8635187C211900A10927 /* OCSharedDto.m */; }; 13AA8640187C3B9700A10927 /* OCXMLParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 13AA863F187C3B9700A10927 /* OCXMLParser.m */; }; + 4033BE531F5429F900D76200 /* OCOAuth2Manager.m in Sources */ = {isa = PBXBuildFile; fileRef = 4033BE521F5429F900D76200 /* OCOAuth2Manager.m */; }; + 4033BE561F54385900D76200 /* OCOAuth2Configuration.m in Sources */ = {isa = PBXBuildFile; fileRef = 4033BE551F54385900D76200 /* OCOAuth2Configuration.m */; }; 40D4039D1E955C020003A855 /* OCServerFeatures.m in Sources */ = {isa = PBXBuildFile; fileRef = 40D4039C1E955C020003A855 /* OCServerFeatures.m */; }; 59A5B71E191907F100724BE3 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 59A5B70E191907F100724BE3 /* AFHTTPSessionManager.m */; }; 59A5B71F191907F100724BE3 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 59A5B711191907F100724BE3 /* AFNetworkReachabilityManager.m */; }; @@ -83,6 +85,10 @@ 13AA8635187C211900A10927 /* OCSharedDto.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; path = OCSharedDto.m; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objc; }; 13AA863E187C3B9700A10927 /* OCXMLParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; name = OCXMLParser.h; path = OCWebDavClient/Parsers/OCXMLParser.h; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; }; 13AA863F187C3B9700A10927 /* OCXMLParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; name = OCXMLParser.m; path = OCWebDavClient/Parsers/OCXMLParser.m; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objc; }; + 4033BE511F5429F900D76200 /* OCOAuth2Manager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OCOAuth2Manager.h; sourceTree = ""; }; + 4033BE521F5429F900D76200 /* OCOAuth2Manager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCOAuth2Manager.m; sourceTree = ""; }; + 4033BE541F54385900D76200 /* OCOAuth2Configuration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OCOAuth2Configuration.h; path = OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h; sourceTree = SOURCE_ROOT; }; + 4033BE551F54385900D76200 /* OCOAuth2Configuration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = OCOAuth2Configuration.m; path = OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m; sourceTree = SOURCE_ROOT; }; 40D4039B1E955C020003A855 /* OCServerFeatures.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OCServerFeatures.h; sourceTree = ""; }; 40D4039C1E955C020003A855 /* OCServerFeatures.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCServerFeatures.m; sourceTree = ""; }; 591BFBF31B1C809000AB8D3A /* OCConstants.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = OCConstants.h; path = Utils/OCConstants.h; sourceTree = ""; }; @@ -182,6 +188,17 @@ name = Parsers; sourceTree = ""; }; + 4033BE571F54386400D76200 /* OCOAuth2Authentication */ = { + isa = PBXGroup; + children = ( + 4033BE511F5429F900D76200 /* OCOAuth2Manager.h */, + 4033BE521F5429F900D76200 /* OCOAuth2Manager.m */, + 4033BE541F54385900D76200 /* OCOAuth2Configuration.h */, + 4033BE551F54385900D76200 /* OCOAuth2Configuration.m */, + ); + path = OCOAuth2Authentication; + sourceTree = ""; + }; EA7CC88E183E11E600B6A4B4 = { isa = PBXGroup; children = ( @@ -215,10 +232,11 @@ EA7CC89C183E11E600B6A4B4 /* OCCommunicationLib */ = { isa = PBXGroup; children = ( - EAABAA30183E688900909831 /* OCFileDto.h */, - EAABAA31183E688900909831 /* OCFileDto.m */, + 4033BE571F54386400D76200 /* OCOAuth2Authentication */, 7F6F496B1F46C6EB009F8813 /* OCCredentialsDto.h */, 7F6F496C1F46C70C009F8813 /* OCCredentialsDto.m */, + EAABAA30183E688900909831 /* OCFileDto.h */, + EAABAA31183E688900909831 /* OCFileDto.m */, EA0599981BB96D14002C2864 /* OCShareUser.h */, EA0599991BB96D14002C2864 /* OCShareUser.m */, 13AA8634187C211900A10927 /* OCSharedDto.h */, @@ -432,6 +450,7 @@ 59A5B71F191907F100724BE3 /* AFNetworkReachabilityManager.m in Sources */, EA7CC92E183E14A100B6A4B4 /* OCWebDAVClient.m in Sources */, EAABAB1E1858594A00909831 /* OCChunkDto.m in Sources */, + 4033BE531F5429F900D76200 /* OCOAuth2Manager.m in Sources */, EA73DC831B1C48EA00C3AC21 /* OCXMLServerErrorsParser.m in Sources */, 1345E4601884213400153F14 /* OCXMLShareByLinkParser.m in Sources */, 59A5B720191907F100724BE3 /* AFSecurityPolicy.m in Sources */, @@ -439,6 +458,7 @@ EA7CC934183E150000B6A4B4 /* OCCommunication.m in Sources */, 131C67B9187C3E360009030E /* OCXMLSharedParser.m in Sources */, 13AA8640187C3B9700A10927 /* OCXMLParser.m in Sources */, + 4033BE561F54385900D76200 /* OCOAuth2Configuration.m in Sources */, EA7CC912183E146000B6A4B4 /* UtilsFramework.m in Sources */, EA7CC92A183E14A100B6A4B4 /* NSDate+RFC1123.m in Sources */, 13AA8636187C211900A10927 /* OCSharedDto.m in Sources */, From 1c173da51aa3e9dc9a9ffb6806ccc7f3e7f04e2e Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 30 Aug 2017 17:54:43 +0200 Subject: [PATCH 16/50] Update oauth manager class to retry a sucessfull new credentials. Add retry after new credentials also on network main operation with token --- .../OCCommunicationLib/OCCommunication.h | 4 + .../OCCommunicationLib/OCCommunication.m | 1 - .../OCOAuth2Configuration.h | 15 +-- .../OCOAuth2Configuration.m | 16 ++- .../OCOAuth2Authentication/OCOAuth2Manager.h | 26 ++++- .../OCOAuth2Authentication/OCOAuth2Manager.m | 52 ++++++--- .../OCWebDavClient/OCWebDAVClient.m | 102 ++++++++++-------- .../OCCommunicationLibTests.m | 2 + 8 files changed, 137 insertions(+), 81 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 43b67344..996f817d 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -26,6 +26,7 @@ #import #import "OCServerFeatures.h" #import "OCCredentialsDto.h" +#import "OCOAuth2Configuration.h" @class OCHTTPRequestOperation; @class AFURLSessionManager; @@ -72,6 +73,8 @@ typedef enum { @property (nonatomic, strong) NSString *userAgent; +@property (nonatomic, strong) OCOAuth2Configuration *oauth2Configuration; + //Public properties @property (nonatomic, strong) NSMutableArray *downloadTaskNetworkQueueArray; @@ -128,6 +131,7 @@ typedef enum { * Method to set credentials with user and password * * @param credentials -> OCCredentialsDto credentials + * @param oauth2Configuration -> OCOAuth2Configuration for bearer auth method, send it as nil for any other method of authentication */ - (void) setCredentials:(OCCredentialsDto *) credentials; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index fba3e873..c0a61bab 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -160,7 +160,6 @@ - (void)setSecurityPolicyManagers:(AFSecurityPolicy *)securityPolicy { #pragma mark - Setting Credentials - - (void) setCredentials:(OCCredentialsDto *) credentials { switch (credentials.authenticationMethod) { diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h index 030c99cf..69953d8e 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h @@ -29,12 +29,13 @@ @interface OCOAuth2Configuration : NSObject -@property (nonatomic, copy) NSURL *mURL; -@property (nonatomic, copy) NSString *mClientId; -@property (nonatomic, copy) NSString *mClientSecret; -@property (nonatomic, copy) NSString *mRedirectUri; -@property (nonatomic, copy) NSString *mAuthorizationEndpoint; -@property (nonatomic, copy) NSString *mTokenEndpoint; -@property (nonatomic, copy) NSString *mUserAgent; +@property (nonatomic, copy) NSURL *url; +@property (nonatomic, copy) NSString *clientId; +@property (nonatomic, copy) NSString *clientSecret; +@property (nonatomic, copy) NSString *redirectUri; +@property (nonatomic, copy) NSString *authorizationEndpoint; +@property (nonatomic, copy) NSString *tokenEndpoint; +- (id)initWithURL:(NSURL *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint; + @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m index 40abfd3c..cc3b8703 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m @@ -30,20 +30,18 @@ @implementation OCOAuth2Configuration -- (id)initWithURL:(NSURL *)url ClientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint userAgent:(NSString *)userAgent{ +- (id)initWithURL:(NSURL *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint { self = [super init]; if (self) { // Custom initialization - _mURL = url; - _mClientId = clientId; - _mClientSecret = clientSecret; - _mRedirectUri = redirectUri; - _mAuthorizationEndpoint = authorizationEndpoint; - _mTokenEndpoint = tokenEndpoint; - _mUserAgent = userAgent; + _url = url; + _clientId = clientId; + _clientSecret = clientSecret; + _redirectUri = redirectUri; + _authorizationEndpoint = authorizationEndpoint; + _tokenEndpoint = tokenEndpoint; } - return self; } diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h index 1b276edb..efeb163d 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -31,10 +31,26 @@ #import "OCOAuth2Configuration.h" #import "UtilsFramework.h" -@interface OCOAuth2Manager : NSObject +@interface OCOAuth2Manager : NSObject + + +/** + * Method to get the new auth data by the oauth refresh token + * + * @param url -> NSURL with the url of the path + * Ex: http://www.myowncloudserver.com/owncloud/remote.php/webdav/Music + * + * @param oauth2Configuration -> OCOAuth2Configuration with all the oauth parameters + * @param refreshToken -> NSString with the refreshToken + * @param userAgent -> NSString with the custom user agent or nil + * +**/ + ++ (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + refreshToken:(NSString *)refreshToken + userAgent:(NSString *)userAgent + success:(void(^)(OCCredentialsDto *userCredDto))success + failure:(void(^)(NSError *error))failure; + -- (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration - refreshToken:(NSString *)refreshToken - success:(void(^)(OCCredentialsDto *userCredDto))success - failure:(void(^)(NSString *error))failure; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index cb782fdf..00760a99 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -29,12 +29,17 @@ @implementation OCOAuth2Manager -- (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration ++ (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration refreshToken:(NSString *)refreshToken + userAgent:(NSString *)userAgent success:(void(^)(OCCredentialsDto *userCredDto))success - failure:(void(^)(NSString *error))failure { + failure:(void(^)(NSError *error))failure { - [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration refreshToken:refreshToken success:^(NSData *data, NSError *error) { + [UtilsFramework deleteAllCookies]; + + [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration refreshToken:refreshToken userAgent:userAgent + + success:^(NSHTTPURLResponse *response, NSError *error, NSData *data) { NSDictionary *dictJSON; OCCredentialsDto *userCredDto; @@ -42,12 +47,22 @@ - (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configu if (data != nil) { NSError *errorJSON = nil; + NSLog(@"data = %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); dictJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJSON]; - if (errorJSON != nil) { + if (errorJSON == nil) { if (dictJSON[@"error"] != nil && ![dictJSON[@"error"] isEqual:[NSNull null]] ) { - failure(dictJSON[@"error"]); + + NSString *message = (NSString*)[dictJSON objectForKey:@"error"]; + + if ([message isKindOfClass:[NSNull class]]) { + message = @""; + } + + NSError *error = [UtilsFramework getErrorWithCode:response.statusCode andCustomMessageFromTheServer:message]; + + failure(error); } else { userCredDto.userName = dictJSON[@"user_id"]; userCredDto.accessToken = dictJSON[@"access_token"]; @@ -61,42 +76,49 @@ - (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configu } } else { - failure(error.localizedDescription); + failure(error); } } failure:^(NSHTTPURLResponse *response, NSError *error) { - + failure(error); }]; } -- (void) refreshTokenAuthRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration ++ (void) refreshTokenAuthRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration refreshToken:(NSString *)refreshToken - success:(void(^)(NSData *data, NSError *error))success + userAgent:(NSString *)userAgent + success:(void(^)(NSHTTPURLResponse *response, NSError *error, NSData *data))success failure:(void(^)(NSHTTPURLResponse *response, NSError *error))failure { + + NSString *url = [NSString stringWithFormat:@"%@/%@",oauth2Configuration.url, oauth2Configuration.tokenEndpoint]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:oauth2Configuration.mURL]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; [request setHTTPMethod:@"POST"]; - [request setValue:oauth2Configuration.mUserAgent forHTTPHeaderField:@"User-Agent"]; + if (userAgent != nil) { + [request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - NSString *authId = [NSString stringWithFormat:@"%@:%@",oauth2Configuration.mClientId,oauth2Configuration.mClientSecret]; + NSString *authId = [NSString stringWithFormat:@"%@:%@",oauth2Configuration.clientId,oauth2Configuration.clientSecret]; NSString *base64EncodedAuthId = [UtilsFramework AFBase64EncodedStringFromString:authId]; NSString *authorizationValue = [NSString stringWithFormat:@"Basic %@",base64EncodedAuthId]; [request setValue:authorizationValue forHTTPHeaderField:@"Authorization"]; - NSString *body = [NSString stringWithFormat:@"grant_type=refresh_token&refresh_token=%@&redirect_uri=%@&client_id=%@",refreshToken,oauth2Configuration.mRedirectUri,oauth2Configuration.mClientId]; + NSString *body = [NSString stringWithFormat:@"grant_type=refresh_token&client_id=%@&refresh_token=%@",oauth2Configuration.clientId,refreshToken]; + [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; NSURLSession *session = nil; - session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; + session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (data != nil) { - success(data, error); + success((NSHTTPURLResponse*)response, error, data); } else { NSLog(@"Error %@",error.localizedDescription); failure((NSHTTPURLResponse*)response, error); diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 2595bad6..683d7fd1 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -93,7 +93,9 @@ - (void)setUserAgent:(NSString *)userAgent{ [self.defaultHeaders setObject:userAgent forKey:@"User-Agent"]; } -- (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request onCommunication:(OCCommunication *)sharedOCCommunication withUserSessionToken:(NSString*)token success:(void(^)(NSHTTPURLResponse *operation, id response, NSString *token))success failure:(void(^)(NSHTTPURLResponse *operation, id _Nullable responseObject, NSError *error, NSString *token))failure { +#pragma mark - Main network operation token + +- (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication withUserSessionToken:(NSString*)token success:(void(^)(NSHTTPURLResponse *operation, id response, NSString *token))success failure:(void(^)(NSHTTPURLResponse *operation, id _Nullable responseObject, NSError *error, NSString *token))failure { //If is not nil is a redirection so we keep the original url server if (!self.originalUrlServer) { @@ -111,7 +113,39 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque if (!error) { success((NSHTTPURLResponse*)response,responseObject, token); } else { - failure((NSHTTPURLResponse*)response, responseObject, error, token); + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (ntimes <= 0) { + if (failure) { + failure((NSHTTPURLResponse*)response, responseObject, error, token); + } + } else { + + //get refresh token + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.refreshToken userAgent:sharedOCCommunication.userAgent + + success:^(OCCredentialsDto *userCredDto) { + //TODO: set and store new token. + + + NSString *newAccessToken = userCredDto.accessToken; + sharedOCCommunication.password = newAccessToken; + + [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + onCommunication:sharedOCCommunication + withUserSessionToken:token + success:success + failure:failure + ]; + + + } failure:^(NSError *error) { + failure(nil, nil, error, nil); + + }]; + } + } else { + failure((NSHTTPURLResponse*)response, responseObject, error, token); + } } }]; @@ -133,7 +167,6 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [UtilsFramework deleteAllCookies]; } - OCHTTPRequestOperation *operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { success((NSHTTPURLResponse*)response,responseObject); @@ -146,18 +179,27 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } } else { - //TODO: get refresh token - - //TODO: set new token. - //NSString *refreshToken = @"newToken"; - //sharedOCCommunication.password = refreshToken; - - [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) - onCommunication:sharedOCCommunication - success:success - failure:failure - ]; - } + //get refresh token + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.refreshToken userAgent:sharedOCCommunication.userAgent + + success:^(OCCredentialsDto *userCredDto) { + //TODO: set and store new token. + + + NSString *newAccessToken = userCredDto.accessToken; + sharedOCCommunication.password = newAccessToken; + + [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + onCommunication:sharedOCCommunication + success:success + failure:failure + ]; + + + } failure:^(NSError *error) { + failure(nil,nil,error); + }]; + } } else { failure((NSHTTPURLResponse*)response, responseObject, error); @@ -166,34 +208,6 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque }]; return operation; - -} - -- (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { - - //If is not nil is a redirection so we keep the original url server - if (!self.originalUrlServer) { - self.originalUrlServer = [request.URL absoluteString]; - } - - if (sharedOCCommunication.isCookiesAvailable) { - //We add the cookies of that URL - request = [UtilsFramework getRequestWithCookiesByRequest:request andOriginalUrlServer:self.originalUrlServer]; - } else { - [UtilsFramework deleteAllCookies]; - } - - - OCHTTPRequestOperation *operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - if (!error) { - success((NSHTTPURLResponse*)response,responseObject); - } else { - failure((NSHTTPURLResponse*)response, responseObject, error); - } - }]; - - return operation; - } - (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters { @@ -299,7 +313,7 @@ - (void)mr_listPath:(NSString *)path depth:(NSUInteger)depth withUserSessionToke [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication withUserSessionToken:token success:success failure:failure]; + OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication withUserSessionToken:token success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } diff --git a/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m b/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m index 18142c24..c36b946a 100644 --- a/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m +++ b/OCCommunicationLib/OCCommunicationLibTests/OCCommunicationLibTests.m @@ -75,6 +75,8 @@ - (void)setUp [_sharedOCCommunication setCredentials:credentials]; [_sharedOCCommunication setSecurityPolicyManagers:[_sharedOCCommunication createSecurityPolicy]]; + //TODO: set oauthconfiguration an credentialsStorage + //Create Tests folder [self createFolderWithName:k_path_test_folder]; From fd7685d53efef220fdd9d4d6b25894fd80c2d8ad Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 30 Aug 2017 19:20:46 +0200 Subject: [PATCH 17/50] Add protocol to store new credentials --- .../OCCommunicationLib/OCCommunication.h | 3 ++ .../OCCommunicationLib/OCCommunication.m | 1 - .../OCCredentialsStorage.h | 36 +++++++++++++++++++ .../OCWebDavClient/OCWebDAVClient.m | 2 ++ .../project.pbxproj | 2 ++ 5 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 996f817d..a491a0f7 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -27,6 +27,7 @@ #import "OCServerFeatures.h" #import "OCCredentialsDto.h" #import "OCOAuth2Configuration.h" +#import "OCCredentialsStorage.h" @class OCHTTPRequestOperation; @class AFURLSessionManager; @@ -74,6 +75,8 @@ typedef enum { @property (nonatomic, strong) NSString *userAgent; @property (nonatomic, strong) OCOAuth2Configuration *oauth2Configuration; +@property (weak) id credentialsStorage; + //Public properties @property (nonatomic, strong) NSMutableArray *downloadTaskNetworkQueueArray; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index c0a61bab..3b8dea7b 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -169,7 +169,6 @@ - (void) setCredentials:(OCCredentialsDto *) credentials { break; case AuthenticationMethodBEARER_TOKEN: - [self setCredentialsOauthWithToken:credentials.accessToken refreshToken:credentials.refreshToken expiresIn:credentials.expiresIn]; break; diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h new file mode 100644 index 00000000..cb23d5a3 --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h @@ -0,0 +1,36 @@ +// +// OCCredentialsStorage.h +// ownCloud iOS library +// +// Created by Noelia Alvarez on 30/08/2017. +// +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#import +#import "OCCredentialsDto.h" + +@protocol OCCredentialsStorageDelegate + + +- (void)storeCredentials:(OCCredentialsDto *)credentials; + +@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 683d7fd1..5409e1ac 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -126,6 +126,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque success:^(OCCredentialsDto *userCredDto) { //TODO: set and store new token. + [sharedOCCommunication.credentialsStorage storeCredentials:userCredDto]; NSString *newAccessToken = userCredDto.accessToken; sharedOCCommunication.password = newAccessToken; @@ -185,6 +186,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque success:^(OCCredentialsDto *userCredDto) { //TODO: set and store new token. + [sharedOCCommunication.credentialsStorage storeCredentials:userCredDto]; NSString *newAccessToken = userCredDto.accessToken; sharedOCCommunication.password = newAccessToken; diff --git a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj index 709e3027..90e6a6a0 100644 --- a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj +++ b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj @@ -89,6 +89,7 @@ 4033BE521F5429F900D76200 /* OCOAuth2Manager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCOAuth2Manager.m; sourceTree = ""; }; 4033BE541F54385900D76200 /* OCOAuth2Configuration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OCOAuth2Configuration.h; path = OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h; sourceTree = SOURCE_ROOT; }; 4033BE551F54385900D76200 /* OCOAuth2Configuration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = OCOAuth2Configuration.m; path = OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m; sourceTree = SOURCE_ROOT; }; + 40B2981A1F57196F008EC53F /* OCCredentialsStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OCCredentialsStorage.h; sourceTree = ""; }; 40D4039B1E955C020003A855 /* OCServerFeatures.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OCServerFeatures.h; sourceTree = ""; }; 40D4039C1E955C020003A855 /* OCServerFeatures.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCServerFeatures.m; sourceTree = ""; }; 591BFBF31B1C809000AB8D3A /* OCConstants.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = OCConstants.h; path = Utils/OCConstants.h; sourceTree = ""; }; @@ -195,6 +196,7 @@ 4033BE521F5429F900D76200 /* OCOAuth2Manager.m */, 4033BE541F54385900D76200 /* OCOAuth2Configuration.h */, 4033BE551F54385900D76200 /* OCOAuth2Configuration.m */, + 40B2981A1F57196F008EC53F /* OCCredentialsStorage.h */, ); path = OCOAuth2Authentication; sourceTree = ""; From a1c239e40715c44c6530dd1d16db151016ce5520 Mon Sep 17 00:00:00 2001 From: nasli Date: Thu, 31 Aug 2017 16:00:15 +0200 Subject: [PATCH 18/50] Update credentials to store new tokens --- .../OCCommunicationLib/OCCommunication.h | 7 +--- .../OCCommunicationLib/OCCommunication.m | 41 ++++++------------- .../OCCredentialsStorage.h | 6 ++- .../OCOAuth2Configuration.h | 4 +- .../OCOAuth2Configuration.m | 2 +- .../OCWebDavClient/OCWebDAVClient.m | 24 ++++++----- 6 files changed, 34 insertions(+), 50 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index a491a0f7..3b3b69c3 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -34,6 +34,7 @@ @class AFSecurityPolicy; @class OCCapabilities; +@protocol OCCredentialsStorageDelegate; @interface OCCommunication : NSObject @@ -67,10 +68,7 @@ typedef enum { //Private properties @property NSInteger kindOfCredential; -@property (nonatomic, strong) NSString *user; -@property (nonatomic, strong) NSString *password; -@property (nonatomic, strong) NSString *refreshToken; -@property (nonatomic, strong) NSString *expiresIn; +@property (nonatomic, strong) OCCredentialsDto *credDto; @property (nonatomic, strong) NSString *userAgent; @@ -134,7 +132,6 @@ typedef enum { * Method to set credentials with user and password * * @param credentials -> OCCredentialsDto credentials - * @param oauth2Configuration -> OCOAuth2Configuration for bearer auth method, send it as nil for any other method of authentication */ - (void) setCredentials:(OCCredentialsDto *) credentials; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 3b8dea7b..136690a6 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -161,40 +161,24 @@ - (void)setSecurityPolicyManagers:(AFSecurityPolicy *)securityPolicy { #pragma mark - Setting Credentials - (void) setCredentials:(OCCredentialsDto *) credentials { - + + self.credDto = credentials; + switch (credentials.authenticationMethod) { case AuthenticationMethodSAML_WEB_SSO: - - [self setCredentialsWithCookie:credentials.accessToken]; + self.kindOfCredential = credentialCookie; break; case AuthenticationMethodBEARER_TOKEN: - [self setCredentialsOauthWithToken:credentials.accessToken refreshToken:credentials.refreshToken expiresIn:credentials.expiresIn]; + self.kindOfCredential = credentialOauth; break; default: - [self setCredentialsWithUser:credentials.userName andPassword:credentials.accessToken]; + self.kindOfCredential = credentialNormal; break; } } -- (void) setCredentialsWithUser:(NSString*) user andPassword:(NSString*) password { - self.kindOfCredential = credentialNormal; - self.user = user; - self.password = password; -} - -- (void) setCredentialsWithCookie:(NSString*) cookie { - self.kindOfCredential = credentialCookie; - self.password = cookie; -} - -- (void) setCredentialsOauthWithToken:(NSString*)token refreshToken:(NSString *)refreshToken expiresIn:(NSString *)expiresIn { - self.kindOfCredential = credentialOauth; - self.password = token; - self.refreshToken = refreshToken; - self.expiresIn = expiresIn; -} - (void) setValueOfUserAgent:(NSString *) userAgent { self.userAgent = userAgent; @@ -223,16 +207,15 @@ - (id) getRequestWithCredentials:(id) request { break; case credentialNormal: { - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.user, self.password]; + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.credDto.userName, self.credDto.accessToken]; [myRequest addValue:[NSString stringWithFormat:@"Basic %@", [UtilsFramework AFBase64EncodedStringFromString:basicAuthCredentials]] forHTTPHeaderField:@"Authorization"]; break; } case credentialCookie: - //NSLog(@"Cookie: %@", self.password); - [myRequest addValue:self.password forHTTPHeaderField:@"Cookie"]; + [myRequest addValue:self.credDto.accessToken forHTTPHeaderField:@"Cookie"]; break; case credentialOauth: - [myRequest addValue:[NSString stringWithFormat:@"Bearer %@", self.password] forHTTPHeaderField:@"Authorization"]; + [myRequest addValue:[NSString stringWithFormat:@"Bearer %@", self.credDto.accessToken] forHTTPHeaderField:@"Authorization"]; break; default: break; @@ -252,13 +235,13 @@ - (id) getRequestWithCredentials:(id) request { //Without credentials break; case credentialNormal: - [myRequest setAuthorizationHeaderWithUsername:self.user password:self.password]; + [myRequest setAuthorizationHeaderWithUsername:self.credDto.userName password:self.credDto.accessToken]; break; case credentialCookie: - [myRequest setAuthorizationHeaderWithCookie:self.password]; + [myRequest setAuthorizationHeaderWithCookie:self.credDto.accessToken]; break; case credentialOauth: - [myRequest setAuthorizationHeaderWithToken:[NSString stringWithFormat:@"Bearer %@", self.password]]; + [myRequest setAuthorizationHeaderWithToken:[NSString stringWithFormat:@"Bearer %@", self.credDto.accessToken]]; break; default: break; diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h index cb23d5a3..36237a36 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h @@ -26,11 +26,13 @@ // #import -#import "OCCredentialsDto.h" +#import "OCCommunication.h" + +@class OCCommunication; @protocol OCCredentialsStorageDelegate -- (void)storeCredentials:(OCCredentialsDto *)credentials; ++ (void)storeCurrentCredentialsOfSharedOCCommunication:(OCCommunication *)sharedOCCommunication; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h index 69953d8e..e25b2769 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h @@ -29,13 +29,13 @@ @interface OCOAuth2Configuration : NSObject -@property (nonatomic, copy) NSURL *url; +@property (nonatomic, copy) NSString *url; @property (nonatomic, copy) NSString *clientId; @property (nonatomic, copy) NSString *clientSecret; @property (nonatomic, copy) NSString *redirectUri; @property (nonatomic, copy) NSString *authorizationEndpoint; @property (nonatomic, copy) NSString *tokenEndpoint; -- (id)initWithURL:(NSURL *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint; +- (id)initWithURLString:(NSString *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m index cc3b8703..fe8bd92a 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m @@ -30,7 +30,7 @@ @implementation OCOAuth2Configuration -- (id)initWithURL:(NSURL *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint { +- (id)initWithURLString:(NSString *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint { self = [super init]; if (self) { diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 5409e1ac..28f53308 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -121,15 +121,16 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.refreshToken userAgent:sharedOCCommunication.userAgent + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { - //TODO: set and store new token. - [sharedOCCommunication.credentialsStorage storeCredentials:userCredDto]; + //set and store new credentials + [sharedOCCommunication setCredentials:userCredDto]; - NSString *newAccessToken = userCredDto.accessToken; - sharedOCCommunication.password = newAccessToken; + if (sharedOCCommunication.credentialsStorage != nil) { + [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + } [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) onCommunication:sharedOCCommunication @@ -181,15 +182,16 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.refreshToken userAgent:sharedOCCommunication.userAgent + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { - //TODO: set and store new token. + + //set and store new credentials + [sharedOCCommunication setCredentials:userCredDto]; - [sharedOCCommunication.credentialsStorage storeCredentials:userCredDto]; - - NSString *newAccessToken = userCredDto.accessToken; - sharedOCCommunication.password = newAccessToken; + if (sharedOCCommunication.credentialsStorage != nil) { + [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + } [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) onCommunication:sharedOCCommunication From 2e7786095f0e7269f68f38cca7e03a6431573e03 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 1 Sep 2017 13:30:48 +0200 Subject: [PATCH 19/50] Add parameter identifier into credentials object --- OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h | 1 + OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h index 45d0012b..934d3f21 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h @@ -38,6 +38,7 @@ typedef NS_ENUM (NSUInteger, AuthenticationMethod){ @interface OCCredentialsDto : NSObject +@property (nonatomic, copy) NSString *userId; @property (nonatomic, copy) NSString *userName; @property (nonatomic, copy) NSString *accessToken; // password for basic auth, cookies for SAML, access token for OAuth2... @property (nonatomic) AuthenticationMethod authenticationMethod; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m index 00c5ef34..3147e702 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m @@ -34,6 +34,7 @@ - (id)initWithCredentialsDto:(OCCredentialsDto *)oCredDto{ self = [super init]; if (self) { // Custom initialization + _userId = oCredDto.userId; _userName = oCredDto.userName; _accessToken = oCredDto.accessToken; _refreshToken = oCredDto.refreshToken; @@ -47,6 +48,7 @@ - (id)initWithCredentialsDto:(OCCredentialsDto *)oCredDto{ -(id) copyWithZone:(NSZone *)zone { OCCredentialsDto *credDtoCopy = [[OCCredentialsDto alloc]init]; + credDtoCopy.userId = self.userId; credDtoCopy.userName = self.userName; credDtoCopy.accessToken = self.accessToken; credDtoCopy.refreshToken = self.refreshToken; @@ -59,6 +61,7 @@ -(id) copyWithZone:(NSZone *)zone { - (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:self.userId forKey:@"userId"]; [aCoder encodeObject:self.userName forKey:@"userName"]; [aCoder encodeObject:self.accessToken forKey:@"accessToken"]; [aCoder encodeObject:self.refreshToken forKey:@"refreshToken"]; @@ -70,6 +73,7 @@ - (void)encodeWithCoder:(NSCoder *)aCoder - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { + self.userId = [aDecoder decodeObjectForKey:@"userId"]; self.userName = [aDecoder decodeObjectForKey:@"userName"]; self.accessToken = [aDecoder decodeObjectForKey:@"accessToken"]; self.refreshToken = [aDecoder decodeObjectForKey:@"refreshToken"]; From ebc76ee6055b583d80b75de89aa32cfb62c5483b Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 1 Sep 2017 13:45:02 +0200 Subject: [PATCH 20/50] Set same userId for new credentials --- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 28f53308..da64bd84 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -126,6 +126,8 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque success:^(OCCredentialsDto *userCredDto) { //set and store new credentials + + userCredDto.userId = sharedOCCommunication.credDto.userId; [sharedOCCommunication setCredentials:userCredDto]; if (sharedOCCommunication.credentialsStorage != nil) { @@ -187,6 +189,8 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque success:^(OCCredentialsDto *userCredDto) { //set and store new credentials + + userCredDto.userId = sharedOCCommunication.credDto.userId; [sharedOCCommunication setCredentials:userCredDto]; if (sharedOCCommunication.credentialsStorage != nil) { From 93c3ba8fbe0a79a711d0589df5a42a82b04d8358 Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 6 Sep 2017 11:45:38 +0200 Subject: [PATCH 21/50] Refresh token and store new credentials propertly --- .../OCCommunicationLib/OCCommunication.h | 6 +++- .../OCCommunicationLib/OCCommunication.m | 9 +++++ .../OCCommunicationLib/OCFrameworkConstants.h | 8 +++++ .../OCCredentialsStorage.h | 2 +- .../OCOAuth2Configuration.h | 3 +- .../OCOAuth2Configuration.m | 3 +- .../OCOAuth2Authentication/OCOAuth2Manager.h | 10 +++--- .../OCOAuth2Authentication/OCOAuth2Manager.m | 34 ++++++++++++------- .../OCWebDavClient/OCWebDAVClient.m | 7 ++-- .../OCCommunicationLib/Utils/UtilsFramework.m | 11 ------ 10 files changed, 57 insertions(+), 36 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 3b3b69c3..5a0b24be 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -73,7 +73,7 @@ typedef enum { @property (nonatomic, strong) NSString *userAgent; @property (nonatomic, strong) OCOAuth2Configuration *oauth2Configuration; -@property (weak) id credentialsStorage; +@property (nonatomic, strong) id credentialsStorage; //Public properties @@ -151,6 +151,10 @@ typedef enum { - (void) setValueOfUserAgent:(NSString *) userAgent; +- (void) setValueOauth2Configuration:(OCOAuth2Configuration *)oauth2Configuration; + +- (void) setValueCredentialsStorage:(id)credentialsStorage; + /* * Method to update the a request with the current credentials */ diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 136690a6..125123b3 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -184,6 +184,15 @@ - (void) setValueOfUserAgent:(NSString *) userAgent { self.userAgent = userAgent; } + +- (void) setValueOauth2Configuration:(OCOAuth2Configuration *)oauth2Configuration { + self.oauth2Configuration = oauth2Configuration; +} + +- (void) setValueCredentialsStorage:(id)credentialsStorage { + self.credentialsStorage = credentialsStorage; +} + ///----------------------------------- /// @name getRequestWithCredentials ///----------------------------------- diff --git a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h index 7abafaf7..de890dd3 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h +++ b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h @@ -37,6 +37,14 @@ #define k_domain_error_code @"com.owncloud" +//URL for webdav +//#define k_url_webdav_server @"remote.php/odav/" +#define k_url_webdav_server @"remote.php/webdav/" +#define k_url_webdav_server_without_last_slash @"remote.php/webdav" + +//URL path for list of files in web interface +#define k_url_path_list_of_files_in_web @"index.php/apps/files" + //Url to access to Shared API to create #define k_url_acces_shared_api @"ocs/v1.php/apps/files_sharing/api/v1/shares" diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h index 36237a36..ffeac649 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h @@ -33,6 +33,6 @@ @protocol OCCredentialsStorageDelegate -+ (void)storeCurrentCredentialsOfSharedOCCommunication:(OCCommunication *)sharedOCCommunication; +- (void)storeCurrentCredentialsOfSharedOCCommunication:(OCCommunication *)sharedOCCommunication; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h index e25b2769..1a5a6440 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.h @@ -29,13 +29,12 @@ @interface OCOAuth2Configuration : NSObject -@property (nonatomic, copy) NSString *url; @property (nonatomic, copy) NSString *clientId; @property (nonatomic, copy) NSString *clientSecret; @property (nonatomic, copy) NSString *redirectUri; @property (nonatomic, copy) NSString *authorizationEndpoint; @property (nonatomic, copy) NSString *tokenEndpoint; -- (id)initWithURLString:(NSString *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint; +- (id)initWithClientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m index fe8bd92a..0d1ad210 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Configuration.m @@ -30,12 +30,11 @@ @implementation OCOAuth2Configuration -- (id)initWithURLString:(NSString *)url clientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint { +- (id)initWithClientId:(NSString *)clientId clientSecret:(NSString *)clientSecret redirectUri:(NSString *)redirectUri authorizationEndpoint:(NSString *)authorizationEndpoint tokenEndpoint:(NSString *)tokenEndpoint { self = [super init]; if (self) { // Custom initialization - _url = url; _clientId = clientId; _clientSecret = clientSecret; _redirectUri = redirectUri; diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h index efeb163d..1008a0cb 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -30,6 +30,7 @@ #import "OCCommunication.h" #import "OCOAuth2Configuration.h" #import "UtilsFramework.h" +#import "OCFrameworkConstants.h" @interface OCOAuth2Manager : NSObject @@ -47,10 +48,11 @@ **/ + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration - refreshToken:(NSString *)refreshToken - userAgent:(NSString *)userAgent - success:(void(^)(OCCredentialsDto *userCredDto))success - failure:(void(^)(NSError *error))failure; + withOriginalURLString:(NSString *)originalURL + refreshToken:(NSString *)refreshToken + userAgent:(NSString *)userAgent + success:(void(^)(OCCredentialsDto *userCredDto))success + failure:(void(^)(NSError *error))failure; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 00760a99..180351c7 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -30,19 +30,20 @@ @implementation OCOAuth2Manager + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration - refreshToken:(NSString *)refreshToken - userAgent:(NSString *)userAgent - success:(void(^)(OCCredentialsDto *userCredDto))success - failure:(void(^)(NSError *error))failure { + withOriginalURLString:(NSString *)originalURL + refreshToken:(NSString *)refreshToken + userAgent:(NSString *)userAgent + success:(void(^)(OCCredentialsDto *userCredDto))success + failure:(void(^)(NSError *error))failure { [UtilsFramework deleteAllCookies]; - [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration refreshToken:refreshToken userAgent:userAgent + [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration withOriginalURLString:originalURL refreshToken:refreshToken userAgent:userAgent success:^(NSHTTPURLResponse *response, NSError *error, NSData *data) { NSDictionary *dictJSON; - OCCredentialsDto *userCredDto; + OCCredentialsDto *userCredDto = [OCCredentialsDto new]; if (data != nil) { @@ -86,14 +87,21 @@ + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configu } + (void) refreshTokenAuthRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration - refreshToken:(NSString *)refreshToken - userAgent:(NSString *)userAgent - success:(void(^)(NSHTTPURLResponse *response, NSError *error, NSData *data))success - failure:(void(^)(NSHTTPURLResponse *response, NSError *error))failure { - - NSString *url = [NSString stringWithFormat:@"%@/%@",oauth2Configuration.url, oauth2Configuration.tokenEndpoint]; + withOriginalURLString:(NSString *)originalURL + refreshToken:(NSString *)refreshToken + userAgent:(NSString *)userAgent + success:(void(^)(NSHTTPURLResponse *response, NSError *error, NSData *data))success + failure:(void(^)(NSHTTPURLResponse *response, NSError *error))failure { + + NSString *originalURLStringWithoutWebdavPath = originalURL; + NSString *partToRemove = k_url_webdav_server; + if([originalURL length] >= [partToRemove length]){ + originalURLStringWithoutWebdavPath = [originalURL substringToIndex:[originalURL length] - [partToRemove length]]; + } + + NSURL *urlToGetToken = [[NSURL URLWithString:originalURLStringWithoutWebdavPath] URLByAppendingPathComponent:oauth2Configuration.tokenEndpoint]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlToGetToken]; [request setHTTPMethod:@"POST"]; if (userAgent != nil) { diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index da64bd84..68e8e602 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -121,7 +121,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withOriginalURLString:self.originalUrlServer refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { @@ -129,6 +129,8 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque userCredDto.userId = sharedOCCommunication.credDto.userId; [sharedOCCommunication setCredentials:userCredDto]; + [request addValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; + if (sharedOCCommunication.credentialsStorage != nil) { [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; @@ -184,7 +186,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withOriginalURLString:self.originalUrlServer refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { @@ -192,6 +194,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque userCredDto.userId = sharedOCCommunication.credDto.userId; [sharedOCCommunication setCredentials:userCredDto]; + [request addValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; diff --git a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m index 3c4962df..13dfd03f 100644 --- a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m +++ b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m @@ -669,16 +669,5 @@ + (BOOL) isPermissionToReadCreateUpdate:(NSInteger) permissionValue { return canEdit; } -+(BOOL) isTokenExpired:(NSString *)expiresIn { - - BOOL expired = NO; - - NSDate* now = [NSDate date]; - //TODO: - - - return expired; -} - @end From 680bdc4b6585240ff5f4f897cf9456ac44815e7b Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 6 Sep 2017 12:13:38 +0200 Subject: [PATCH 22/50] Update git ignore file to avoid xcshareddata --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 6e137049..7e7e245b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Xcode .DS_Store */build/* +_build/ *.pbxuser !default.pbxuser *.mode1v3 @@ -16,6 +17,8 @@ DerivedData .idea/ *.hmap *.xccheckout +*.pyc +xcshareddata/ #CocoaPods Pods From 04f3f4faf74be9f96a412cf9b4fc3f72248af113 Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 6 Sep 2017 13:34:31 +0200 Subject: [PATCH 23/50] Resume new retry operation and set auth header value instead add to fix and successfully retry newtwork request with the new access token. :) --- .../OCWebDavClient/OCWebDAVClient.m | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 68e8e602..2b53f8dc 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -109,7 +109,9 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [UtilsFramework deleteAllCookies]; } - OCHTTPRequestOperation *operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + __block OCHTTPRequestOperation *operation; + + operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { success((NSHTTPURLResponse*)response,responseObject, token); } else { @@ -129,20 +131,21 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque userCredDto.userId = sharedOCCommunication.credDto.userId; [sharedOCCommunication setCredentials:userCredDto]; - [request addValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; + + [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; } - [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + operation = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) onCommunication:sharedOCCommunication withUserSessionToken:token success:success failure:failure ]; - + [operation resume]; } failure:^(NSError *error) { failure(nil, nil, error, nil); @@ -173,7 +176,9 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [UtilsFramework deleteAllCookies]; } - OCHTTPRequestOperation *operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + __block OCHTTPRequestOperation *operation; + + operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { success((NSHTTPURLResponse*)response,responseObject); } else { @@ -194,18 +199,18 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque userCredDto.userId = sharedOCCommunication.credDto.userId; [sharedOCCommunication setCredentials:userCredDto]; - [request addValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; + [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; } - [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + operation = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) onCommunication:sharedOCCommunication success:success failure:failure - ]; - + ]; + [operation resume]; } failure:^(NSError *error) { failure(nil,nil,error); From 3134037d822ae3f196c77edca9066525d7ab6e5b Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 6 Sep 2017 17:10:09 +0200 Subject: [PATCH 24/50] Set redirection block also for retries. --- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 2b53f8dc..f6de34d4 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -145,6 +145,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque success:success failure:failure ]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } failure:^(NSError *error) { @@ -210,6 +211,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque success:success failure:failure ]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; [operation resume]; } failure:^(NSError *error) { @@ -375,6 +377,9 @@ - (NSURLSessionDownloadTask *)downloadWithSessionPath:(NSString *)remoteSource t return localDestinationUrl; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { if (error) { + + //TODO:retry op + failure(response, error); } else { success(response,filePath); @@ -444,6 +449,9 @@ - (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRe uploadProgress(progress); } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (error) { + + //TODO:retry op + failure(response, responseObject, error); } else { success(response,responseObject); From 5004bfd16b354afc409e87ebbda23f6aedbe2dab Mon Sep 17 00:00:00 2001 From: nasli Date: Thu, 7 Sep 2017 12:21:03 +0200 Subject: [PATCH 25/50] Refactor uploads to retry ntimes --- .../OCCommunicationLib/OCCommunication.m | 3 +- .../OCCommunicationLib/OCFrameworkConstants.h | 3 + .../OCWebDavClient/OCHTTPRequestOperation.h | 1 + .../OCWebDavClient/OCWebDAVClient.h | 3 +- .../OCWebDavClient/OCWebDAVClient.m | 74 +++++++++++++++---- 5 files changed, 68 insertions(+), 16 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 125123b3..6a97294e 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -39,6 +39,7 @@ #import "OCCapabilities.h" #import "OCServerFeatures.h" + @interface OCCommunication () @property (nonatomic, strong) NSString *currentServerVersion; @@ -508,7 +509,7 @@ - (NSURLSessionUploadTask *) uploadFileSession:(NSString *) localPath toDestiny: remotePath = [remotePath encodeString:NSUTF8StringEncoding]; - NSURLSessionUploadTask *uploadTask = [request putWithSessionLocalPath:localPath atRemotePath:remotePath onCommunication:sharedOCCommunication progress:^(NSProgress *progress) { + NSURLSessionUploadTask *uploadTask = [request putWithSessionLocalPath:localPath atRemotePath:remotePath retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication progress:^(NSProgress *progress) { uploadProgress(progress); } success:^(NSURLResponse *response, id responseObjec){ [UtilsFramework addCookiesToStorageFromResponse:(NSURLResponse *) response andPath:[NSURL URLWithString:remotePath]]; diff --git a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h index de890dd3..305a835a 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h +++ b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h @@ -23,6 +23,9 @@ // THE SOFTWARE. // +//Retry ntimes request +#define k_retry_ntimes 2 + //Timeout to weddav requests #define k_timeout_webdav 30 //seconds diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h index 986f1408..eefdd1c2 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h @@ -23,6 +23,7 @@ // THE SOFTWARE. // +//TODO: remove class @interface OCHTTPRequestOperation : NSURLSessionDataTask diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h index 7369d4c1..375a2d03 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h @@ -207,13 +207,14 @@ extern NSString * _Nullable OCWebDAVModificationDateKey; @param localSource is a string with the path of the file to upload @param remoteDestination A remote path, relative to the HTTP client's base URL, to write the data to. + @param retryingNumberOfTimes The number of times that the request will be silently retry @param progress A progress object monitoring the current upload progress. @param success A block callback, to be fired upon successful completion, with NSURLResponse and string of redirected server. @param failure A block callback, to be fired upon the failure of either the request or the parsing of the request's data, with two arguments: the request operation and the network or parsing error that occurred. * @warning NSURLSession and NSRULSessionUploadTask only can be supported in iOS 7. */ -- (NSURLSessionUploadTask * _Nonnull)putWithSessionLocalPath:(NSString * _Nonnull)localSource atRemotePath:(NSString * _Nonnull)remoteDestination onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication progress:(void(^ _Nonnull)(NSProgress * _Nonnull progress))uploadProgress success:(void(^ _Nonnull)(NSURLResponse * _Nonnull, NSString * _Nonnull))success failure:(void(^ _Nonnull)(NSURLResponse * _Nonnull, id _Nonnull, NSError * _Nonnull))failure failureBeforeRequest:(void(^ _Nonnull)(NSError * _Nonnull)) failureBeforeRequest; +- (NSURLSessionUploadTask * _Nonnull)putWithSessionLocalPath:(NSString * _Nonnull)localSource atRemotePath:(NSString * _Nonnull)remoteDestination retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication progress:(void(^ _Nonnull)(NSProgress * _Nonnull progress))uploadProgress success:(void(^ _Nonnull)(NSURLResponse * _Nonnull, NSString * _Nonnull))success failure:(void(^ _Nonnull)(NSURLResponse * _Nonnull, id _Nonnull, NSError * _Nonnull))failure failureBeforeRequest:(void(^ _Nonnull)(NSError * _Nonnull)) failureBeforeRequest; ///----------------------------------- /// @name requestForUserNameByCookie diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index f6de34d4..4c49630c 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -40,7 +40,6 @@ #define k_server_information_json @"status.php" #define k_api_header_request @"OCS-APIREQUEST" #define k_group_sharee_type 1 -#define k_retry_ntimes 2 NSString const *OCWebDAVContentTypeKey = @"getcontenttype"; @@ -409,7 +408,64 @@ - (void)makeCollection:(NSString *)path onCommunication: [operation resume]; } -- (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRemotePath:(NSString *)remoteDestination onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress success:(void(^)(NSURLResponse *, NSString *))success failure:(void(^)(NSURLResponse *, id, NSError *))failure failureBeforeRequest:(void(^)(NSError *)) failureBeforeRequest { +#pragma mark - upload requests + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request fromFileURL:(NSURL *)fileURL retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress success:(void(^)(NSURLResponse *, NSString *))success failure:(void(^)(NSURLResponse *, id, NSError *))failure { + + __block NSURLSessionUploadTask *uploadTask = [sharedOCCommunication.uploadSessionManager uploadTaskWithRequest:request fromFile:fileURL progress:^(NSProgress * _Nonnull progress) { + uploadProgress(progress); + } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (!error) { + success(response,responseObject); + } else { + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (ntimes <= 0) { + if (failure) { + failure(response, responseObject, error); + } + } else { + //TODO:retry op + //get refresh token + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withOriginalURLString:self.originalUrlServer refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent + + success:^(OCCredentialsDto *userCredDto) { + + //set and store new credentials + + userCredDto.userId = sharedOCCommunication.credDto.userId; + [sharedOCCommunication setCredentials:userCredDto]; + + [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; + + + if (sharedOCCommunication.credentialsStorage != nil) { + [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + } + + uploadTask = [self uploadTaskWithRequest:request + fromFileURL:fileURL + retryingNumberOfTimes:(ntimes -1) + onCommunication:sharedOCCommunication + progress:uploadProgress + success:success + failure:failure]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.uploadSessionManager]; + [uploadTask resume]; + + } failure:^(NSError *error) { + failure(response, responseObject, error); + }]; + } + } else { + failure(response, responseObject, error); + } + } + }]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRemotePath:(NSString *)remoteDestination retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress success:(void(^)(NSURLResponse *, NSString *))success failure:(void(^)(NSURLResponse *, id, NSError *))failure failureBeforeRequest:(void(^)(NSError *)) failureBeforeRequest { NSFileManager *fileManager = [NSFileManager defaultManager]; @@ -445,21 +501,11 @@ - (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRe sharedOCCommunication.uploadSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; - NSURLSessionUploadTask *uploadTask = [sharedOCCommunication.uploadSessionManager uploadTaskWithRequest:request fromFile:file progress:^(NSProgress * _Nonnull progress) { - uploadProgress(progress); - } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - if (error) { - - //TODO:retry op - - failure(response, responseObject, error); - } else { - success(response,responseObject); - } - }]; + NSURLSessionUploadTask *uploadTask = [self uploadTaskWithRequest:request fromFileURL:file retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication progress:uploadProgress success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.uploadSessionManager]; [uploadTask resume]; + return uploadTask; } } From 8cfdee4839bc5b031c2d5fe307b32e470adbf1f1 Mon Sep 17 00:00:00 2001 From: nasli Date: Thu, 7 Sep 2017 12:33:09 +0200 Subject: [PATCH 26/50] Remove not used retry --- OCCommunicationLib/OCCommunicationLib/OCCommunication.m | 2 +- OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h | 3 --- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h | 2 +- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m | 3 ++- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 6a97294e..2fd5914a 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -509,7 +509,7 @@ - (NSURLSessionUploadTask *) uploadFileSession:(NSString *) localPath toDestiny: remotePath = [remotePath encodeString:NSUTF8StringEncoding]; - NSURLSessionUploadTask *uploadTask = [request putWithSessionLocalPath:localPath atRemotePath:remotePath retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication progress:^(NSProgress *progress) { + NSURLSessionUploadTask *uploadTask = [request putWithSessionLocalPath:localPath atRemotePath:remotePath onCommunication:sharedOCCommunication progress:^(NSProgress *progress) { uploadProgress(progress); } success:^(NSURLResponse *response, id responseObjec){ [UtilsFramework addCookiesToStorageFromResponse:(NSURLResponse *) response andPath:[NSURL URLWithString:remotePath]]; diff --git a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h index 305a835a..de890dd3 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h +++ b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h @@ -23,9 +23,6 @@ // THE SOFTWARE. // -//Retry ntimes request -#define k_retry_ntimes 2 - //Timeout to weddav requests #define k_timeout_webdav 30 //seconds diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h index 375a2d03..a4d882c0 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h @@ -214,7 +214,7 @@ extern NSString * _Nullable OCWebDAVModificationDateKey; * @warning NSURLSession and NSRULSessionUploadTask only can be supported in iOS 7. */ -- (NSURLSessionUploadTask * _Nonnull)putWithSessionLocalPath:(NSString * _Nonnull)localSource atRemotePath:(NSString * _Nonnull)remoteDestination retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication progress:(void(^ _Nonnull)(NSProgress * _Nonnull progress))uploadProgress success:(void(^ _Nonnull)(NSURLResponse * _Nonnull, NSString * _Nonnull))success failure:(void(^ _Nonnull)(NSURLResponse * _Nonnull, id _Nonnull, NSError * _Nonnull))failure failureBeforeRequest:(void(^ _Nonnull)(NSError * _Nonnull)) failureBeforeRequest; +- (NSURLSessionUploadTask * _Nonnull)putWithSessionLocalPath:(NSString * _Nonnull)localSource atRemotePath:(NSString * _Nonnull)remoteDestination onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication progress:(void(^ _Nonnull)(NSProgress * _Nonnull progress))uploadProgress success:(void(^ _Nonnull)(NSURLResponse * _Nonnull, NSString * _Nonnull))success failure:(void(^ _Nonnull)(NSURLResponse * _Nonnull, id _Nonnull, NSError * _Nonnull))failure failureBeforeRequest:(void(^ _Nonnull)(NSError * _Nonnull)) failureBeforeRequest; ///----------------------------------- /// @name requestForUserNameByCookie diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 4c49630c..d7fd7c7e 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -40,6 +40,7 @@ #define k_server_information_json @"status.php" #define k_api_header_request @"OCS-APIREQUEST" #define k_group_sharee_type 1 +#define k_retry_ntimes 2 //Retry ntimes request NSString const *OCWebDAVContentTypeKey = @"getcontenttype"; @@ -465,7 +466,7 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request return uploadTask; } -- (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRemotePath:(NSString *)remoteDestination retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress success:(void(^)(NSURLResponse *, NSString *))success failure:(void(^)(NSURLResponse *, id, NSError *))failure failureBeforeRequest:(void(^)(NSError *)) failureBeforeRequest { +- (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRemotePath:(NSString *)remoteDestination onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress success:(void(^)(NSURLResponse *, NSString *))success failure:(void(^)(NSURLResponse *, id, NSError *))failure failureBeforeRequest:(void(^)(NSError *)) failureBeforeRequest { NSFileManager *fileManager = [NSFileManager defaultManager]; From 1af7472064754cb559143f12a74baa9452538903 Mon Sep 17 00:00:00 2001 From: nasli Date: Thu, 7 Sep 2017 14:25:01 +0200 Subject: [PATCH 27/50] Fix base url. --- .../OCCommunicationLib/OCCredentialsDto.h | 1 + .../OCCommunicationLib/OCCredentialsDto.m | 4 ++++ .../OCOAuth2Authentication/OCOAuth2Manager.h | 2 +- .../OCOAuth2Authentication/OCOAuth2Manager.m | 15 +++++---------- .../OCWebDavClient/OCWebDAVClient.m | 9 ++++++--- 5 files changed, 17 insertions(+), 14 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h index 934d3f21..02035a47 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h @@ -39,6 +39,7 @@ typedef NS_ENUM (NSUInteger, AuthenticationMethod){ @interface OCCredentialsDto : NSObject @property (nonatomic, copy) NSString *userId; +@property (nonatomic, copy) NSString *baseURL; @property (nonatomic, copy) NSString *userName; @property (nonatomic, copy) NSString *accessToken; // password for basic auth, cookies for SAML, access token for OAuth2... @property (nonatomic) AuthenticationMethod authenticationMethod; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m index 3147e702..8fc85baf 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m @@ -35,6 +35,7 @@ - (id)initWithCredentialsDto:(OCCredentialsDto *)oCredDto{ if (self) { // Custom initialization _userId = oCredDto.userId; + _baseURL = oCredDto.baseURL; _userName = oCredDto.userName; _accessToken = oCredDto.accessToken; _refreshToken = oCredDto.refreshToken; @@ -49,6 +50,7 @@ - (id)initWithCredentialsDto:(OCCredentialsDto *)oCredDto{ -(id) copyWithZone:(NSZone *)zone { OCCredentialsDto *credDtoCopy = [[OCCredentialsDto alloc]init]; credDtoCopy.userId = self.userId; + credDtoCopy.baseURL = self.baseURL; credDtoCopy.userName = self.userName; credDtoCopy.accessToken = self.accessToken; credDtoCopy.refreshToken = self.refreshToken; @@ -62,6 +64,7 @@ -(id) copyWithZone:(NSZone *)zone { - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.userId forKey:@"userId"]; + [aCoder encodeObject:self.baseURL forKey:@"baseURL"]; [aCoder encodeObject:self.userName forKey:@"userName"]; [aCoder encodeObject:self.accessToken forKey:@"accessToken"]; [aCoder encodeObject:self.refreshToken forKey:@"refreshToken"]; @@ -74,6 +77,7 @@ - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { self.userId = [aDecoder decodeObjectForKey:@"userId"]; + self.baseURL = [aDecoder decodeObjectForKey:@"baseURL"]; self.userName = [aDecoder decodeObjectForKey:@"userName"]; self.accessToken = [aDecoder decodeObjectForKey:@"accessToken"]; self.refreshToken = [aDecoder decodeObjectForKey:@"refreshToken"]; diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h index 1008a0cb..6710cbc9 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -48,7 +48,7 @@ **/ + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration - withOriginalURLString:(NSString *)originalURL + withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent success:(void(^)(OCCredentialsDto *userCredDto))success diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 180351c7..e9125d98 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -30,7 +30,7 @@ @implementation OCOAuth2Manager + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration - withOriginalURLString:(NSString *)originalURL + withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent success:(void(^)(OCCredentialsDto *userCredDto))success @@ -38,7 +38,7 @@ + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configu [UtilsFramework deleteAllCookies]; - [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration withOriginalURLString:originalURL refreshToken:refreshToken userAgent:userAgent + [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration withBaseURL:baseURL refreshToken:refreshToken userAgent:userAgent success:^(NSHTTPURLResponse *response, NSError *error, NSData *data) { @@ -87,19 +87,14 @@ + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configu } + (void) refreshTokenAuthRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration - withOriginalURLString:(NSString *)originalURL + withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent success:(void(^)(NSHTTPURLResponse *response, NSError *error, NSData *data))success failure:(void(^)(NSHTTPURLResponse *response, NSError *error))failure { + - NSString *originalURLStringWithoutWebdavPath = originalURL; - NSString *partToRemove = k_url_webdav_server; - if([originalURL length] >= [partToRemove length]){ - originalURLStringWithoutWebdavPath = [originalURL substringToIndex:[originalURL length] - [partToRemove length]]; - } - - NSURL *urlToGetToken = [[NSURL URLWithString:originalURLStringWithoutWebdavPath] URLByAppendingPathComponent:oauth2Configuration.tokenEndpoint]; + NSURL *urlToGetToken = [[NSURL URLWithString:baseURL] URLByAppendingPathComponent:oauth2Configuration.tokenEndpoint]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlToGetToken]; diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index d7fd7c7e..fbc0afdc 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -123,13 +123,14 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withOriginalURLString:self.originalUrlServer refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { //set and store new credentials userCredDto.userId = sharedOCCommunication.credDto.userId; + userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; @@ -192,13 +193,14 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withOriginalURLString:self.originalUrlServer refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { //set and store new credentials userCredDto.userId = sharedOCCommunication.credDto.userId; + userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; @@ -427,13 +429,14 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request } else { //TODO:retry op //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withOriginalURLString:self.originalUrlServer refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { //set and store new credentials userCredDto.userId = sharedOCCommunication.credDto.userId; + userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; From a9db816ba68bde607f93452ddba5ef55ff590336 Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 13 Sep 2017 12:40:26 +0200 Subject: [PATCH 28/50] Add silently retries into downloads network tasks --- .../OCWebDavClient/OCWebDAVClient.m | 163 ++++++++++++++---- 1 file changed, 128 insertions(+), 35 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index fbc0afdc..a4b482c8 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -123,8 +123,10 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent - + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + withBaseURL:sharedOCCommunication.credDto.baseURL + refreshToken:sharedOCCommunication.credDto.refreshToken + userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { //set and store new credentials @@ -193,8 +195,10 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent - + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + withBaseURL:sharedOCCommunication.credDto.baseURL + refreshToken:sharedOCCommunication.credDto.refreshToken + userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { //set and store new credentials @@ -359,7 +363,89 @@ - (void)listPath:(NSString *)path [self mr_listPath:path depth:1 withUserSessionToken:token onCommunication:sharedOCCommunication success:success failure:failure]; } -- (NSURLSessionDownloadTask *)downloadWithSessionPath:(NSString *)remoteSource toPath:(NSString *)localDestination defaultPriority:(BOOL)defaultPriority onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))downloadProgress success:(void(^)(NSURLResponse *response, NSURL *filePath))success failure:(void(^)(NSURLResponse *response, NSError *error))failure{ + +#pragma mark - download requests + +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)request + toPath:(NSString *)localDestination + defaultPriority:(BOOL)defaultPriority + retryingNumberOfTimes:(NSInteger)ntimes + onCommunication:(OCCommunication *)sharedOCCommunication + progress:(void(^)(NSProgress *progress))downloadProgress + success:(void(^)(NSURLResponse *response, NSURL *filePath))success failure:(void(^)(NSURLResponse *response, NSError *error))failure { + + NSURL *localDestinationUrl = [NSURL fileURLWithPath:localDestination]; + + __block NSURLSessionDownloadTask *downloadTask = [sharedOCCommunication.downloadSessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull progress) { + //TODO: detect corrupted file + downloadProgress(progress); + } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { + //TODO: detect corrupted file + return localDestinationUrl; + } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { + + if (!error) { + success(response,filePath); + } else { + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (ntimes <= 0) { + if (failure) { + failure(response, error); + } + } else { + //get refresh token + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + withBaseURL:sharedOCCommunication.credDto.baseURL + refreshToken:sharedOCCommunication.credDto.refreshToken + userAgent:sharedOCCommunication.userAgent + success:^(OCCredentialsDto *userCredDto) { + + //set and store new credentials + + userCredDto.userId = sharedOCCommunication.credDto.userId; + userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; + [sharedOCCommunication setCredentials:userCredDto]; + + [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; + + if (sharedOCCommunication.credentialsStorage != nil) { + [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + } + + downloadTask = [self downloadTaskWithRequest:request + toPath:localDestination + defaultPriority:defaultPriority + retryingNumberOfTimes:(ntimes -1) + onCommunication:sharedOCCommunication + progress:downloadProgress + success:success + failure:failure]; + + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.downloadSessionManager]; + [downloadTask resume]; + + } failure:^(NSError *error) { + failure(response, error); + }]; + } + } else { + failure(response, error); + } + } + }]; + + return downloadTask; +} + + + +- (NSURLSessionDownloadTask *)downloadWithSessionPath:(NSString *)remoteSource + toPath:(NSString *)localDestination + defaultPriority:(BOOL)defaultPriority + onCommunication:(OCCommunication *)sharedOCCommunication + progress:(void(^)(NSProgress *progress))downloadProgress + success:(void(^)(NSURLResponse *response, NSURL *filePath))success + failure:(void(^)(NSURLResponse *response, NSError *error))failure { NSMutableURLRequest *request = [self requestWithMethod:@"GET" path:remoteSource parameters:nil]; @@ -371,33 +457,22 @@ - (NSURLSessionDownloadTask *)downloadWithSessionPath:(NSString *)remoteSource t //We add the cookies of that URL request = [UtilsFramework getRequestWithCookiesByRequest:request andOriginalUrlServer:self.originalUrlServer]; - NSURL *localDestinationUrl = [NSURL fileURLWithPath:localDestination]; - - NSURLSessionDownloadTask *downloadTask = [sharedOCCommunication.downloadSessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull progress) { - downloadProgress(progress); - } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { - return localDestinationUrl; - } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { - if (error) { - - //TODO:retry op - - failure(response, error); - } else { - success(response,filePath); - } - }]; - + NSURLSessionDownloadTask *downloadTask = [self downloadTaskWithRequest:request + toPath:localDestination + defaultPriority:defaultPriority + retryingNumberOfTimes:k_retry_ntimes + onCommunication:sharedOCCommunication + progress:downloadProgress + success:success + failure:failure]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.downloadSessionManager]; - - if (defaultPriority) { + //if (defaultPriority) { [downloadTask resume]; - } + // } return downloadTask; - - } - (void)makeCollection:(NSString *)path onCommunication: @@ -413,7 +488,13 @@ - (void)makeCollection:(NSString *)path onCommunication: #pragma mark - upload requests -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request fromFileURL:(NSURL *)fileURL retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress success:(void(^)(NSURLResponse *, NSString *))success failure:(void(^)(NSURLResponse *, id, NSError *))failure { +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request + fromFileURL:(NSURL *)fileURL + retryingNumberOfTimes:(NSInteger)ntimes + onCommunication:(OCCommunication *)sharedOCCommunication + progress:(void(^)(NSProgress *progress))uploadProgress + success:(void(^)(NSURLResponse *, NSString *))success + failure:(void(^)(NSURLResponse *, id, NSError *))failure { __block NSURLSessionUploadTask *uploadTask = [sharedOCCommunication.uploadSessionManager uploadTaskWithRequest:request fromFile:fileURL progress:^(NSProgress * _Nonnull progress) { uploadProgress(progress); @@ -427,21 +508,21 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request failure(response, responseObject, error); } } else { - //TODO:retry op //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent - + [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + withBaseURL:sharedOCCommunication.credDto.baseURL + refreshToken:sharedOCCommunication.credDto.refreshToken + userAgent:sharedOCCommunication.userAgent success:^(OCCredentialsDto *userCredDto) { //set and store new credentials - + userCredDto.userId = sharedOCCommunication.credDto.userId; userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; - if (sharedOCCommunication.credentialsStorage != nil) { [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; } @@ -469,7 +550,13 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request return uploadTask; } -- (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRemotePath:(NSString *)remoteDestination onCommunication:(OCCommunication *)sharedOCCommunication progress:(void(^)(NSProgress *progress))uploadProgress success:(void(^)(NSURLResponse *, NSString *))success failure:(void(^)(NSURLResponse *, id, NSError *))failure failureBeforeRequest:(void(^)(NSError *)) failureBeforeRequest { +- (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource + atRemotePath:(NSString *)remoteDestination + onCommunication:(OCCommunication *)sharedOCCommunication + progress:(void(^)(NSProgress *progress))uploadProgress + success:(void(^)(NSURLResponse *, NSString *))success + failure:(void(^)(NSURLResponse *, id, NSError *))failure + failureBeforeRequest:(void(^)(NSError *)) failureBeforeRequest { NSFileManager *fileManager = [NSFileManager defaultManager]; @@ -505,7 +592,13 @@ - (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource atRe sharedOCCommunication.uploadSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; - NSURLSessionUploadTask *uploadTask = [self uploadTaskWithRequest:request fromFileURL:file retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication progress:uploadProgress success:success failure:failure]; + NSURLSessionUploadTask *uploadTask = [self uploadTaskWithRequest:request + fromFileURL:file + retryingNumberOfTimes:k_retry_ntimes + onCommunication:sharedOCCommunication + progress:uploadProgress + success:success + failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.uploadSessionManager]; [uploadTask resume]; From e8565c44a1c0e1f917f3cba74680060694f78f3e Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 13 Sep 2017 16:03:35 +0200 Subject: [PATCH 29/50] Fix network lib issue that report delegate location previous the failure with 401 errors --- .../OCWebDavClient/OCWebDAVClient.m | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index a4b482c8..19872b94 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -377,11 +377,14 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req NSURL *localDestinationUrl = [NSURL fileURLWithPath:localDestination]; __block NSURLSessionDownloadTask *downloadTask = [sharedOCCommunication.downloadSessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull progress) { - //TODO: detect corrupted file downloadProgress(progress); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { - //TODO: detect corrupted file - return localDestinationUrl; + + if (((NSHTTPURLResponse*)response).statusCode == 401) { + return nil; + } else { + return localDestinationUrl; + } } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { if (!error) { @@ -468,10 +471,10 @@ - (NSURLSessionDownloadTask *)downloadWithSessionPath:(NSString *)remoteSource [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.downloadSessionManager]; - //if (defaultPriority) { + if (defaultPriority) { [downloadTask resume]; - // } - + } + return downloadTask; } From 624428d9fab78d4fae71b052e511a9e1233708af Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 22 Sep 2017 10:59:12 +0200 Subject: [PATCH 30/50] Remove property not longer needed --- .../OCCommunicationLib/OCCommunication.h | 10 ----- .../OCCommunicationLib/OCCommunication.m | 45 +++++-------------- .../OCWebDavClient/OCWebDAVClient.m | 8 ++-- 3 files changed, 16 insertions(+), 47 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 5a0b24be..33ec21a4 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -38,15 +38,6 @@ @interface OCCommunication : NSObject -//Type of credential -typedef enum { - credentialNotSet = -1, - credentialNormal = 0, //user, password - credentialCookie = 1, - credentialOauth = 2 -} kindOfCredentialEnum; - - typedef enum { OCErrorUnknown = 90, //On all errors OCErrorForbiddenCharacters = 100, //On create folder and rename @@ -67,7 +58,6 @@ typedef enum { //Private properties -@property NSInteger kindOfCredential; @property (nonatomic, strong) OCCredentialsDto *credDto; @property (nonatomic, strong) NSString *userAgent; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 2fd5914a..e5cb7c24 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -58,9 +58,6 @@ -(id) init { //Init the Donwload queue array self.downloadTaskNetworkQueueArray = [NSMutableArray new]; - //Credentials not set yet - self.kindOfCredential = credentialNotSet; - [self setSecurityPolicyManagers:[self createSecurityPolicy]]; self.isCookiesAvailable = YES; @@ -116,9 +113,6 @@ -(id) initWithUploadSessionManager:(AFURLSessionManager *) uploadSessionManager self.isCookiesAvailable = YES; self.isForbiddenCharactersAvailable = NO; - //Credentials not set yet - self.kindOfCredential = credentialNotSet; - [self setSecurityPolicyManagers:[self createSecurityPolicy]]; self.uploadSessionManager = uploadSessionManager; @@ -136,9 +130,6 @@ -(id) initWithUploadSessionManager:(AFURLSessionManager *) uploadSessionManager //Init the Donwload queue array self.downloadTaskNetworkQueueArray = [NSMutableArray new]; - //Credentials not set yet - self.kindOfCredential = credentialNotSet; - [self setSecurityPolicyManagers:[self createSecurityPolicy]]; self.uploadSessionManager = uploadSessionManager; @@ -164,20 +155,6 @@ - (void)setSecurityPolicyManagers:(AFSecurityPolicy *)securityPolicy { - (void) setCredentials:(OCCredentialsDto *) credentials { self.credDto = credentials; - - switch (credentials.authenticationMethod) { - case AuthenticationMethodSAML_WEB_SSO: - self.kindOfCredential = credentialCookie; - break; - - case AuthenticationMethodBEARER_TOKEN: - self.kindOfCredential = credentialOauth; - break; - - default: - self.kindOfCredential = credentialNormal; - break; - } } @@ -211,20 +188,21 @@ - (id) getRequestWithCredentials:(id) request { if ([request isKindOfClass:[NSMutableURLRequest class]]) { NSMutableURLRequest *myRequest = (NSMutableURLRequest *)request; - switch (self.kindOfCredential) { - case credentialNotSet: + switch (self.credDto.authenticationMethod) { + case AuthenticationMethodNONE: + case AuthenticationMethodUNKNOWN: //Without credentials break; - case credentialNormal: + case AuthenticationMethodBASIC_HTTP_AUTH: { NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.credDto.userName, self.credDto.accessToken]; [myRequest addValue:[NSString stringWithFormat:@"Basic %@", [UtilsFramework AFBase64EncodedStringFromString:basicAuthCredentials]] forHTTPHeaderField:@"Authorization"]; break; } - case credentialCookie: + case AuthenticationMethodSAML_WEB_SSO: [myRequest addValue:self.credDto.accessToken forHTTPHeaderField:@"Cookie"]; break; - case credentialOauth: + case AuthenticationMethodBEARER_TOKEN: [myRequest addValue:[NSString stringWithFormat:@"Bearer %@", self.credDto.accessToken] forHTTPHeaderField:@"Authorization"]; break; default: @@ -240,17 +218,18 @@ - (id) getRequestWithCredentials:(id) request { } else if([request isKindOfClass:[OCWebDAVClient class]]) { OCWebDAVClient *myRequest = (OCWebDAVClient *)request; - switch (self.kindOfCredential) { - case credentialNotSet: + switch (self.credDto.authenticationMethod) { + case AuthenticationMethodNONE: + case AuthenticationMethodUNKNOWN: //Without credentials break; - case credentialNormal: + case AuthenticationMethodBASIC_HTTP_AUTH: [myRequest setAuthorizationHeaderWithUsername:self.credDto.userName password:self.credDto.accessToken]; break; - case credentialCookie: + case AuthenticationMethodSAML_WEB_SSO: [myRequest setAuthorizationHeaderWithCookie:self.credDto.accessToken]; break; - case credentialOauth: + case AuthenticationMethodBEARER_TOKEN: [myRequest setAuthorizationHeaderWithToken:[NSString stringWithFormat:@"Bearer %@", self.credDto.accessToken]]; break; default: diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 19872b94..d6d430a4 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -115,7 +115,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque if (!error) { success((NSHTTPURLResponse*)response,responseObject, token); } else { - if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) { if (ntimes <= 0) { if (failure) { failure((NSHTTPURLResponse*)response, responseObject, error, token); @@ -187,7 +187,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque success((NSHTTPURLResponse*)response,responseObject); } else { - if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) { if (ntimes <= 0) { if (failure) { failure((NSHTTPURLResponse*)response, responseObject, error); @@ -390,7 +390,7 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req if (!error) { success(response,filePath); } else { - if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) { if (ntimes <= 0) { if (failure) { failure(response, error); @@ -505,7 +505,7 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request if (!error) { success(response,responseObject); } else { - if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.kindOfCredential == credentialOauth) { + if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) { if (ntimes <= 0) { if (failure) { failure(response, responseObject, error); From 9cd5bf6a9cd123089a6e3074f8dbb27aed0c3a22 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 22 Sep 2017 14:33:54 +0200 Subject: [PATCH 31/50] Use credentials object directly since is no longer needed the full communication object --- .../OCOAuth2Authentication/OCCredentialsStorage.h | 4 ++-- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h index ffeac649..bb4a67e4 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h @@ -28,11 +28,11 @@ #import #import "OCCommunication.h" -@class OCCommunication; +@class OCCredentialsDto; @protocol OCCredentialsStorageDelegate -- (void)storeCurrentCredentialsOfSharedOCCommunication:(OCCommunication *)sharedOCCommunication; +- (void)storeCredentials:(OCCredentialsDto *)credDto; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index d6d430a4..7a3e0763 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -139,7 +139,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; } operation = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) @@ -209,7 +209,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; } operation = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) @@ -412,7 +412,7 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; } downloadTask = [self downloadTaskWithRequest:request @@ -527,7 +527,7 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCurrentCredentialsOfSharedOCCommunication:sharedOCCommunication]; + [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; } uploadTask = [self uploadTaskWithRequest:request From 35fc856d86e703f2c795365027f1265d562b139c Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 22 Sep 2017 14:45:56 +0200 Subject: [PATCH 32/50] Rename some OAuth methods with accurate description --- .../OCOAuth2Authentication/OCOAuth2Manager.h | 2 +- .../OCOAuth2Authentication/OCOAuth2Manager.m | 6 +++--- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h index 6710cbc9..089c6cd8 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -47,7 +47,7 @@ * **/ -+ (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration ++ (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index e9125d98..0d63ff2f 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -29,7 +29,7 @@ @implementation OCOAuth2Manager -+ (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration ++ (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent @@ -38,7 +38,7 @@ + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configu [UtilsFramework deleteAllCookies]; - [self refreshTokenAuthRequestByOAuth2Configuration:oauth2Configuration withBaseURL:baseURL refreshToken:refreshToken userAgent:userAgent + [self refreshAuthDataRequestByOAuth2Configuration:oauth2Configuration withBaseURL:baseURL refreshToken:refreshToken userAgent:userAgent success:^(NSHTTPURLResponse *response, NSError *error, NSData *data) { @@ -86,7 +86,7 @@ + (void) getAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configu } -+ (void) refreshTokenAuthRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration ++ (void) refreshAuthDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 7a3e0763..c0076a1c 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -123,7 +123,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent @@ -195,7 +195,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent @@ -397,7 +397,7 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req } } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent @@ -512,7 +512,7 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request } } else { //get refresh token - [OCOAuth2Manager getAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent From 3eb39dc7af291bec80f75cb3bc0fafaf90c01f4a Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 22 Sep 2017 15:47:32 +0200 Subject: [PATCH 33/50] Use default message with more information for user --- .../OCOAuth2Authentication/OCOAuth2Manager.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 0d63ff2f..f6867eb5 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -61,8 +61,8 @@ + (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con message = @""; } - NSError *error = [UtilsFramework getErrorWithCode:response.statusCode andCustomMessageFromTheServer:message]; - + NSError *error = [UtilsFramework getErrorByCodeId:OCErrorOAuth2Error]; + failure(error); } else { userCredDto.userName = dictJSON[@"user_id"]; From 081d6a96c2adac28df4504c619e01aaaf12e4826 Mon Sep 17 00:00:00 2001 From: nasli Date: Mon, 25 Sep 2017 10:13:51 +0200 Subject: [PATCH 34/50] Remove unnecessary class and update references --- .../OCCommunicationLib/OCCommunication.h | 1 - .../OCCommunicationLib/OCCommunication.m | 7 +- .../OCWebDavClient/OCHTTPRequestOperation.h | 34 ------ .../OCWebDavClient/OCHTTPRequestOperation.m | 38 ------- .../OCWebDavClient/OCWebDAVClient.h | 3 +- .../OCWebDavClient/OCWebDAVClient.m | 106 +++++++++--------- .../project.pbxproj | 8 -- 7 files changed, 57 insertions(+), 140 deletions(-) delete mode 100644 OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h delete mode 100644 OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.m diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 33ec21a4..77c1b55d 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -29,7 +29,6 @@ #import "OCOAuth2Configuration.h" #import "OCCredentialsStorage.h" -@class OCHTTPRequestOperation; @class AFURLSessionManager; @class AFSecurityPolicy; @class OCCapabilities; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index e5cb7c24..64d07e72 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -24,7 +24,6 @@ // #import "OCCommunication.h" -#import "OCHTTPRequestOperation.h" #import "UtilsFramework.h" #import "OCXMLParser.h" #import "OCXMLSharedParser.h" @@ -1409,7 +1408,7 @@ - (NSURLSessionTask *) getRemoteThumbnailByServer:(NSString*)serverPath ofFilePa request = [self getRequestWithCredentials:request]; - OCHTTPRequestOperation *operation = [request getRemoteThumbnailByServer:serverPath ofFilePath:filePath withWidth:fileWidth andHeight:fileHeight onCommunication:sharedOCComunication + NSURLSessionDataTask *sessionDataTask = [request getRemoteThumbnailByServer:serverPath ofFilePath:filePath withWidth:fileWidth andHeight:fileHeight onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) { NSData *responseData = (NSData*) responseObject; @@ -1419,9 +1418,9 @@ - (NSURLSessionTask *) getRemoteThumbnailByServer:(NSString*)serverPath ofFilePa failureRequest(response, error, request.redirectedServer); }]; - [operation resume]; + [sessionDataTask resume]; - return operation; + return sessionDataTask; } #pragma mark - Clear Cache diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h deleted file mode 100644 index eefdd1c2..00000000 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.h +++ /dev/null @@ -1,34 +0,0 @@ -// -// OCHTTPRequestOperation.h -// Owncloud iOs Client -// -// Copyright (C) 2016, ownCloud GmbH. ( http://www.owncloud.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: - -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -//TODO: remove class - -@interface OCHTTPRequestOperation : NSURLSessionDataTask - -@property (nonatomic, strong) NSString *localSource; - - - -@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.m deleted file mode 100644 index 5287739f..00000000 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCHTTPRequestOperation.m +++ /dev/null @@ -1,38 +0,0 @@ -// -// OCHTTPRequestOperation.m -// Owncloud iOs Client -// -// Copyright (C) 2016, ownCloud GmbH. ( http://www.owncloud.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: - -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - - -#import "OCHTTPRequestOperation.h" - -@interface OCHTTPRequestOperation () -@property (readwrite, nonatomic, strong) NSMutableURLRequest *request; -@end - - -@implementation OCHTTPRequestOperation - -@synthesize request; - -@end diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h index a4d882c0..bc40c135 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h @@ -27,7 +27,6 @@ #import "AFHTTPSessionManager.h" -#import "OCHTTPRequestOperation.h" @class OCCommunication; @class OCChunkDto; @@ -534,7 +533,7 @@ __deprecated_msg("Use - updateShareItem:ofServerPath:withPasswordProtect:andExpi * @return nsData -> thumbnail of the file with the size requested * */ -- (OCHTTPRequestOperation * _Nonnull) getRemoteThumbnailByServer:(NSString * _Nonnull)serverPath ofFilePath:(NSString * _Nonnull)filePath withWidth:(NSInteger)fileWidth andHeight:(NSInteger)fileHeight onCommunication:(OCCommunication * _Nonnull)sharedOCComunication +- (NSURLSessionDataTask * _Nonnull) getRemoteThumbnailByServer:(NSString * _Nonnull)serverPath ofFilePath:(NSString * _Nonnull)filePath withWidth:(NSInteger)fileWidth andHeight:(NSInteger)fileHeight onCommunication:(OCCommunication * _Nonnull)sharedOCComunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull operation, id _Nonnull response))success failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull operation, id _Nullable responseObject, NSError * _Nonnull error))failure; diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index c0076a1c..320ac684 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -95,7 +95,7 @@ - (void)setUserAgent:(NSString *)userAgent{ #pragma mark - Main network operation token -- (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication withUserSessionToken:(NSString*)token success:(void(^)(NSHTTPURLResponse *operation, id response, NSString *token))success failure:(void(^)(NSHTTPURLResponse *operation, id _Nullable responseObject, NSError *error, NSString *token))failure { +- (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication withUserSessionToken:(NSString*)token success:(void(^)(NSHTTPURLResponse *operation, id response, NSString *token))success failure:(void(^)(NSHTTPURLResponse *operation, id _Nullable responseObject, NSError *error, NSString *token))failure { //If is not nil is a redirection so we keep the original url server if (!self.originalUrlServer) { @@ -109,9 +109,9 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [UtilsFramework deleteAllCookies]; } - __block OCHTTPRequestOperation *operation; + __block NSURLSessionDataTask *sessionDataTask; - operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + sessionDataTask = [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { success((NSHTTPURLResponse*)response,responseObject, token); } else { @@ -142,14 +142,14 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; } - operation = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) onCommunication:sharedOCCommunication withUserSessionToken:token success:success failure:failure ]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } failure:^(NSError *error) { failure(nil, nil, error, nil); @@ -162,11 +162,11 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } }]; - return operation; + return sessionDataTask; } #pragma mark - Main network operation -- (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)request retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { +- (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request retryingNumberOfTimes:(NSInteger)ntimes onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { //If is not nil is a redirection so we keep the original url server if (!self.originalUrlServer) { @@ -180,9 +180,9 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [UtilsFramework deleteAllCookies]; } - __block OCHTTPRequestOperation *operation; + __block NSURLSessionDataTask *sessionDataTask; - operation = (OCHTTPRequestOperation*) [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + sessionDataTask = [sharedOCCommunication.networkSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (!error) { success((NSHTTPURLResponse*)response,responseObject); } else { @@ -212,13 +212,13 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; } - operation = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) onCommunication:sharedOCCommunication success:success failure:failure ]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } failure:^(NSError *error) { failure(nil,nil,error); @@ -231,7 +231,7 @@ - (OCHTTPRequestOperation *)mr_operationWithRequest:(NSMutableURLRequest *)reque } }]; - return operation; + return sessionDataTask; } - (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters { @@ -272,9 +272,9 @@ - (void)movePath:(NSString *)source toPath:(NSString *)destination NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:source parameters:nil]; [request setValue:destination forHTTPHeaderField:@"Destination"]; [request setValue:@"T" forHTTPHeaderField:@"Overwrite"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)deletePath:(NSString *)path @@ -284,9 +284,9 @@ - (void)deletePath:(NSString *)path _requestMethod = @"DELETE"; NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:path parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } @@ -311,9 +311,9 @@ - (void)mr_listPath:(NSString *)path depth:(NSUInteger)depth onCommunication: [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)mr_listPath:(NSString *)path depth:(NSUInteger)depth withUserSessionToken:(NSString*)token onCommunication: @@ -337,9 +337,9 @@ - (void)mr_listPath:(NSString *)path depth:(NSUInteger)depth withUserSessionToke [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication withUserSessionToken:token success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication withUserSessionToken:token success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)propertiesOfPath:(NSString *)path @@ -484,9 +484,9 @@ - (void)makeCollection:(NSString *)path onCommunication: failure:(void(^)(NSHTTPURLResponse *, id _Nullable responseObject, NSError *))failure { _requestMethod = @"MKCOL"; NSMutableURLRequest *request = [self requestWithMethod:_requestMethod path:path parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } #pragma mark - upload requests @@ -624,9 +624,9 @@ - (void) requestUserNameOfServer:(NSString * _Nonnull) path byCookie:(NSString * NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path: apiUserUrl parameters: nil]; [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void) getStatusOfTheServer:(NSString *)serverPath onCommunication: @@ -641,9 +641,9 @@ - (void) getStatusOfTheServer:(NSString *)serverPath onCommunication: request.HTTPShouldHandleCookies = false; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)listSharedByServer:(NSString *)serverPath @@ -657,9 +657,9 @@ - (void)listSharedByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)listSharedByServer:(NSString *)serverPath andPath:(NSString *) path @@ -675,9 +675,9 @@ - (void)listSharedByServer:(NSString *)serverPath andPath:(NSString *) path NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } @@ -724,9 +724,9 @@ - (void)shareByLinkFileOrFolderByServer:(NSString * _Nonnull)serverPath [request setHTTPBody:[self.postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString *) filePath andPassword:(NSString *)password @@ -741,9 +741,9 @@ - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString _postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=3&password=%@",filePath,password]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString *) filePath @@ -758,9 +758,9 @@ - (void)shareByLinkFileOrFolderByServer:(NSString *)serverPath andPath:(NSString _postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=3",filePath]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void)shareWith:(NSString *)userOrGroup shareeType:(NSInteger)shareeType inServer:(NSString *) serverPath andPath:(NSString *) filePath andPermissions:(NSInteger) permissions onCommunication:(OCCommunication *)sharedOCCommunication @@ -775,9 +775,9 @@ - (void)shareWith:(NSString *)userOrGroup shareeType:(NSInteger)shareeType inSer self.postStringForShare = [NSString stringWithFormat: @"path=%@&shareType=%ld&shareWith=%@&permissions=%ld",filePath, (long)shareeType, userOrGroup, (long)permissions]; [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } @@ -791,9 +791,9 @@ - (void)unShareFileOrFolderByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } @@ -807,9 +807,9 @@ - (void)isShareFileOrFolderByServer:(NSString *)serverPath NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void) updateShareItem:(NSInteger)shareId @@ -849,9 +849,9 @@ - (void) updateShareItem:(NSInteger)shareId [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void) updateShareItem:(NSInteger)shareId @@ -879,9 +879,9 @@ - (void) updateShareItem:(NSInteger)shareId [request setHTTPBody:[_postStringForShare dataUsingEncoding:NSUTF8StringEncoding]]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void) searchUsersAndGroupsWith:(NSString *)searchString forPage:(NSInteger)page with:(NSInteger)resultsPerPage ofServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *operation, id response))success @@ -902,9 +902,9 @@ - (void) searchUsersAndGroupsWith:(NSString *)searchString forPage:(NSInteger)pa NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } - (void) getCapabilitiesOfServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *operation, id response))success @@ -916,9 +916,9 @@ - (void) getCapabilitiesOfServer:(NSString*)serverPath onCommunication:(OCCommun NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [operation resume]; + [sessionDataTask resume]; } @@ -926,7 +926,7 @@ - (void) getCapabilitiesOfServer:(NSString*)serverPath onCommunication:(OCCommun #pragma mark - Remote thumbnails -- (OCHTTPRequestOperation *) getRemoteThumbnailByServer:(NSString*)serverPath ofFilePath:(NSString*)filePath withWidth:(NSInteger)fileWidth andHeight:(NSInteger)fileHeight onCommunication:(OCCommunication *)sharedOCCommunication +- (NSURLSessionDataTask *) getRemoteThumbnailByServer:(NSString*)serverPath ofFilePath:(NSString*)filePath withWidth:(NSInteger)fileWidth andHeight:(NSInteger)fileHeight onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *operation, id response))success failure:(void(^)(NSHTTPURLResponse *operation, id _Nullable responseObject, NSError *error))failure{ _requestMethod = @"GET"; @@ -936,10 +936,10 @@ - (OCHTTPRequestOperation *) getRemoteThumbnailByServer:(NSString*)serverPath of NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil]; - OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - return operation; + return sessionDataTask; } diff --git a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj index 90e6a6a0..7c055c54 100644 --- a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj +++ b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj @@ -36,8 +36,6 @@ EA7CC929183E14A100B6A4B4 /* NSDate+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC91E183E14A100B6A4B4 /* NSDate+ISO8601.m */; }; EA7CC92A183E14A100B6A4B4 /* NSDate+RFC1123.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC920183E14A100B6A4B4 /* NSDate+RFC1123.m */; }; EA7CC92B183E14A100B6A4B4 /* NSDate+RFC1123.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC920183E14A100B6A4B4 /* NSDate+RFC1123.m */; }; - EA7CC92C183E14A100B6A4B4 /* OCHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC923183E14A100B6A4B4 /* OCHTTPRequestOperation.m */; }; - EA7CC92D183E14A100B6A4B4 /* OCHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC923183E14A100B6A4B4 /* OCHTTPRequestOperation.m */; }; EA7CC92E183E14A100B6A4B4 /* OCWebDAVClient.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC925183E14A100B6A4B4 /* OCWebDAVClient.m */; }; EA7CC92F183E14A100B6A4B4 /* OCWebDAVClient.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC925183E14A100B6A4B4 /* OCWebDAVClient.m */; }; EA7CC934183E150000B6A4B4 /* OCCommunication.m in Sources */ = {isa = PBXBuildFile; fileRef = EA7CC933183E150000B6A4B4 /* OCCommunication.m */; }; @@ -128,8 +126,6 @@ EA7CC91E183E14A100B6A4B4 /* NSDate+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; name = "NSDate+ISO8601.m"; path = "OCWebDavClient/NSDate+ISO8601.m"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objc; }; EA7CC91F183E14A100B6A4B4 /* NSDate+RFC1123.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; name = "NSDate+RFC1123.h"; path = "OCWebDavClient/NSDate+RFC1123.h"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; }; EA7CC920183E14A100B6A4B4 /* NSDate+RFC1123.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; name = "NSDate+RFC1123.m"; path = "OCWebDavClient/NSDate+RFC1123.m"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objc; }; - EA7CC922183E14A100B6A4B4 /* OCHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; name = OCHTTPRequestOperation.h; path = OCWebDavClient/OCHTTPRequestOperation.h; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; }; - EA7CC923183E14A100B6A4B4 /* OCHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; name = OCHTTPRequestOperation.m; path = OCWebDavClient/OCHTTPRequestOperation.m; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objc; }; EA7CC924183E14A100B6A4B4 /* OCWebDAVClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; name = OCWebDAVClient.h; path = OCWebDavClient/OCWebDAVClient.h; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; }; EA7CC925183E14A100B6A4B4 /* OCWebDAVClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; lineEnding = 0; name = OCWebDAVClient.m; path = OCWebDavClient/OCWebDAVClient.m; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objc; }; EA7CC932183E150000B6A4B4 /* OCCommunication.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = OCCommunication.h; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; }; @@ -337,8 +333,6 @@ EA7CC91E183E14A100B6A4B4 /* NSDate+ISO8601.m */, EA7CC91F183E14A100B6A4B4 /* NSDate+RFC1123.h */, EA7CC920183E14A100B6A4B4 /* NSDate+RFC1123.m */, - EA7CC922183E14A100B6A4B4 /* OCHTTPRequestOperation.h */, - EA7CC923183E14A100B6A4B4 /* OCHTTPRequestOperation.m */, EA7CC924183E14A100B6A4B4 /* OCWebDAVClient.h */, EA7CC925183E14A100B6A4B4 /* OCWebDAVClient.m */, ); @@ -470,7 +464,6 @@ 59A5B722191907F100724BE3 /* AFURLRequestSerialization.m in Sources */, EA05999A1BB96D14002C2864 /* OCShareUser.m in Sources */, 59A5B723191907F100724BE3 /* AFURLResponseSerialization.m in Sources */, - EA7CC92C183E14A100B6A4B4 /* OCHTTPRequestOperation.m in Sources */, 7F6F496D1F46C70C009F8813 /* OCCredentialsDto.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -487,7 +480,6 @@ EAABAA33183E688900909831 /* OCFileDto.m in Sources */, EA7CC8B7183E11E600B6A4B4 /* OCCommunicationLibTests.m in Sources */, EA7CC929183E14A100B6A4B4 /* NSDate+ISO8601.m in Sources */, - EA7CC92D183E14A100B6A4B4 /* OCHTTPRequestOperation.m in Sources */, EAABAB2718585C5200909831 /* NSString+Encode.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; From feef0d982731bc1daddf83c829cf3ef5fd8c2691 Mon Sep 17 00:00:00 2001 From: nasli Date: Mon, 25 Sep 2017 12:26:12 +0200 Subject: [PATCH 35/50] Update store credentials method --- .../OCOAuth2Authentication/OCCredentialsStorage.h | 2 +- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h index bb4a67e4..e54b5834 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h @@ -33,6 +33,6 @@ @protocol OCCredentialsStorageDelegate -- (void)storeCredentials:(OCCredentialsDto *)credDto; +- (void)saveCredentials:(OCCredentialsDto *)credDto; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 320ac684..e12b21f0 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -139,7 +139,7 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; + [sharedOCCommunication.credentialsStorage saveCredentials:sharedOCCommunication.credDto]; } sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) @@ -209,7 +209,7 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; + [sharedOCCommunication.credentialsStorage saveCredentials:sharedOCCommunication.credDto]; } sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) @@ -412,7 +412,7 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; + [sharedOCCommunication.credentialsStorage saveCredentials:sharedOCCommunication.credDto]; } downloadTask = [self downloadTaskWithRequest:request @@ -527,7 +527,7 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; if (sharedOCCommunication.credentialsStorage != nil) { - [sharedOCCommunication.credentialsStorage storeCredentials:sharedOCCommunication.credDto]; + [sharedOCCommunication.credentialsStorage saveCredentials:sharedOCCommunication.credDto]; } uploadTask = [self uploadTaskWithRequest:request From b7452412309dc8350d676f0955c0b164619a5245 Mon Sep 17 00:00:00 2001 From: nasli Date: Tue, 26 Sep 2017 18:52:13 +0200 Subject: [PATCH 36/50] Move get auth data to the lib --- .../OCOAuth2Authentication/OCOAuth2Manager.h | 27 ++- .../OCOAuth2Authentication/OCOAuth2Manager.m | 195 ++++++++++++++++++ 2 files changed, 220 insertions(+), 2 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h index 089c6cd8..1bf93ed3 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -31,18 +31,41 @@ #import "OCOAuth2Configuration.h" #import "UtilsFramework.h" #import "OCFrameworkConstants.h" +#import "OCCredentialsDto.h" +//#import "SSLCertificateManager.h" + @interface OCOAuth2Manager : NSObject ++ (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + withServerPath:(NSString *)serverPath; + + +/** + * Method to get the auth data by the auth code + * + * @param baseURL -> NSString with the url of the path obteined from method getOAuth2URLToGetTokenByOAuth2Configuration:withServerPath: + * @param oauth2Configuration -> OCOAuth2Configuration with all the oauth parameters + * @param authCode -> NSString with the auth code + * @param userAgent -> NSString with the custom user agent or nil + * + **/ + ++ (void) authDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + withBaseURL:(NSString *)baseURL + authCode:(NSString *)authCode + userAgent:(NSString *)userAgent + withCompletion:(void(^)(OCCredentialsDto *userCredDto, NSError *error))completion; + /** * Method to get the new auth data by the oauth refresh token * - * @param url -> NSURL with the url of the path + * @param baseURL -> NSString with the url of the path * Ex: http://www.myowncloudserver.com/owncloud/remote.php/webdav/Music * - * @param oauth2Configuration -> OCOAuth2Configuration with all the oauth parameters * @param refreshToken -> NSString with the refreshToken + * @param oauth2Configuration -> OCOAuth2Configuration with all the oauth parameters * @param userAgent -> NSString with the custom user agent or nil * **/ diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index f6867eb5..0d409c3e 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -29,6 +29,143 @@ @implementation OCOAuth2Manager + + ++ (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + withServerPath:(NSString *)serverPath { + + NSString *oauth2RedirectUri = oauth2Configuration.redirectUri; + NSString *oauth2RedirectUriEncoded = [oauth2RedirectUri stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]; + + NSString *baseURL = [NSString stringWithFormat:@"%@%@",serverPath,oauth2Configuration.authorizationEndpoint]; + + NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:baseURL]; + NSDictionary *queryDictionary = @{ + @"response_type" : @"code", + @"redirect_uri" : oauth2RedirectUriEncoded, + @"client_id" : oauth2Configuration.clientId + }; + NSMutableArray *queryItems = [NSMutableArray array]; + for (NSString *key in queryDictionary) { + [queryItems addObject:[NSURLQueryItem queryItemWithName:key value:queryDictionary[key]]]; + } + urlComponents.queryItems = queryItems; + NSURL *fullOauthURL = urlComponents.URL; + + return fullOauthURL; +} + ++ (NSURL *) getOAuth2URLToGetTokenByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + withServerPath:(NSString *)serverPath { + + NSURL *serverPathURL = [[NSURL URLWithString:serverPath] URLByAppendingPathComponent:oauth2Configuration.tokenEndpoint]; + NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:serverPathURL.absoluteString]; + + NSURL *fullOAuthURL = urlComponents.URL; + + return fullOAuthURL; +} + + +#pragma mark - access token + ++ (void) authDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + withBaseURL:(NSString *)baseURL + authCode:(NSString *)authCode + userAgent:(NSString *)userAgent + withCompletion:(void(^)(OCCredentialsDto *userCredDto, NSError *error))completion { + + NSURL *urlToGetAuthData = [OCOAuth2Manager getOAuth2URLToGetTokenByOAuth2Configuration:oauth2Configuration withServerPath:baseURL]; + + [self authDataRequestByOAuth2Configuration:oauth2Configuration withURL:urlToGetAuthData authCode:authCode userAgent:userAgent withCompletion:^(NSData *data, NSHTTPURLResponse *httpResponse, NSError *error) { + + OCCredentialsDto *returnUserCredentials = nil; + NSError *returnError = nil; + + if (error != nil) { + returnError = error; + } else if (httpResponse != nil && (httpResponse.statusCode <200 || httpResponse.statusCode >= 300)) { + // errored HTTP response from server + returnError = [UtilsFramework getErrorByCodeId:OCErrorOAuth2Error]; //TODO: custom error message + } else if (httpResponse == nil || data == nil) { + // generic OAuth2 error, who knows what happened... + returnError = [UtilsFramework getErrorByCodeId:OCErrorOAuth2Error]; + + } else { + NSDictionary *dictJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; + if (dictJSON != nil ) { + NSString *errorInJSON = [dictJSON objectForKey:@"error"]; + if (errorInJSON) { + if ([errorInJSON isEqualToString:@"access_denied"]) { + returnError = [UtilsFramework getErrorByCodeId:OCErrorOAuth2ErrorAccessDenied]; + } else { + returnError = [UtilsFramework getErrorByCodeId:OCErrorOAuth2Error]; + } + } else { + returnUserCredentials = [[OCCredentialsDto alloc] init]; + returnUserCredentials.userName = [dictJSON objectForKey:@"user_id"]; + returnUserCredentials.accessToken = [dictJSON objectForKey:@"access_token"]; + returnUserCredentials.refreshToken = [dictJSON objectForKey:@"refresh_token"]; + returnUserCredentials.expiresIn = [dictJSON objectForKey:@"expires_in"]; + returnUserCredentials.tokenType = [dictJSON objectForKey:@"token_type"]; + returnUserCredentials.authenticationMethod = AuthenticationMethodBEARER_TOKEN; + } + } else { + returnError = [UtilsFramework getErrorByCodeId:OCErrorOAuth2Error]; + } + } + + completion(returnUserCredentials,returnError); + + }]; + +} + ++ (void) authDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration + withURL:(NSURL *)url + authCode:(NSString *)authCode + userAgent:(NSString *)userAgent + withCompletion:(void(^)(NSData *data,NSHTTPURLResponse *httpResponse, NSError *error))completion { + + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request setHTTPMethod:@"POST"]; + if (userAgent != nil) { + [request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + + [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + + NSString *authId = [NSString stringWithFormat:@"%@:%@",oauth2Configuration.clientId,oauth2Configuration.clientSecret]; + NSString *base64EncodedAuthId = [UtilsFramework AFBase64EncodedStringFromString:authId]; + NSString *authorizationValue = [NSString stringWithFormat:@"Basic %@",base64EncodedAuthId]; + [request setValue:authorizationValue forHTTPHeaderField:@"Authorization"]; + + + NSString *body = [NSString stringWithFormat:@"grant_type=authorization_code&code=%@&redirect_uri=%@",authCode,oauth2Configuration.clientId]; + + [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; + + NSURLSession *session = nil; + + session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; + + NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { + + if (data != nil) { + completion(data, (NSHTTPURLResponse*)response, error); + } else { + NSLog(@"Error %@",error.localizedDescription); + completion(nil, (NSHTTPURLResponse*)response, error); + } + }]; + + [task resume]; + +} + + +#pragma mark - Refresh token + + (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken @@ -131,4 +268,62 @@ + (void) refreshAuthDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oa [task resume]; } + +#pragma mark - methods from URLSessionDelegate + +// Delegate method called when the server responded with an authentication challenge. +// Since iOS is so great, it is also called when the server certificate is not trusted, so that the client +// can decide what to do about it. +// +// In this case we only expect to receive an authentication challenge if the server holds a certificate signed +// by an authority that is not trusted by iOS system. In this case, we need to check the list of certificates +// that were explicitly accepted by the user before, and allow the request to go on if the current one matches +// one of them (and not in other case). +// + +- (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler { + + // For the case that the call is due to server certificate not trusted by iOS, we compare the certificate in the + // authentication challenge with the certificates that were previously accepted by the user in the OC app. If + // it match any of them, we allow to go on. + + //SSLCertificateManager *sslCertificateManager = [[SSLCertificateManager alloc] init]; + BOOL trusted = YES;//TODO:->//[sslCertificateManager isTrustedServerCertificateIn:challenge]; + if (trusted) { + NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + completionHandler(NSURLSessionAuthChallengeUseCredential,credential); + } else { + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,nil); + } +} + + +/// MARK : methods from URLSessionTaskDelegate + +// Delegate method called when the server responsed with a redirection +// +// In this case we need to grant that redirections are just followed, but not with the request proposed by the system. +// The requests to access token endpoint are POSTs, and iOS proposes GETs for the redirections +// + +- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task + willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler { + + NSLog(@"DetectAuthenticationMethod: redirect detected in URLSessionTaskDelegate implementation"); + + // let's resuse the last request performed by the task (it's a POST) and set in it the redirected URL from the request proposed by the system + NSMutableURLRequest *newRequest; + + if (task.currentRequest) { + newRequest.URL = request.URL; + + completionHandler(newRequest); //follow + } else { + completionHandler(nil); // we don't know where to redirect, something was really wrong -> stop + } +} + + @end From 69d2c1dc81e3b1d1bd52ff846b501827958db90d Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Thu, 28 Sep 2017 14:50:55 +0200 Subject: [PATCH 37/50] Complete parameters of access token request, lost in traslation --- .../OCOAuth2Authentication/OCOAuth2Manager.m | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 0d409c3e..8b2de21a 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -141,7 +141,11 @@ + (void) authDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con [request setValue:authorizationValue forHTTPHeaderField:@"Authorization"]; - NSString *body = [NSString stringWithFormat:@"grant_type=authorization_code&code=%@&redirect_uri=%@",authCode,oauth2Configuration.clientId]; + NSString *body = [NSString stringWithFormat:@"grant_type=authorization_code&code=%@&redirect_uri=%@&client_id=%@", + authCode, + oauth2Configuration.redirectUri, + oauth2Configuration.clientId + ]; [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; From cc14f97803aac7ff771a9ab0fa45a5b5b0cfa619 Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Thu, 28 Sep 2017 15:03:41 +0200 Subject: [PATCH 38/50] Prevent cast of nil in completion handler --- .../OCOAuth2Authentication/OCOAuth2Manager.m | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 8b2de21a..13cd94bf 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -155,11 +155,12 @@ + (void) authDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { - if (data != nil) { - completion(data, (NSHTTPURLResponse*)response, error); - } else { + if (error != nil) { NSLog(@"Error %@",error.localizedDescription); - completion(nil, (NSHTTPURLResponse*)response, error); + completion(data, nil, error); + + } else { + completion(data, (NSHTTPURLResponse*)response, error); } }]; From 35a3801700ea8705ab0e0ea9e9076d3edfff77fc Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Thu, 28 Sep 2017 17:16:10 +0200 Subject: [PATCH 39/50] Fix delegate methods handling redirections and authentication challenges in OAuth2Manager --- .../OCOAuth2Authentication/OCOAuth2Manager.h | 6 ++--- .../OCOAuth2Authentication/OCOAuth2Manager.m | 22 +++++++++---------- .../OCWebDavClient/OCWebDAVClient.m | 12 ++++++---- 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h index 1bf93ed3..5607446b 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -38,7 +38,7 @@ @interface OCOAuth2Manager : NSObject -+ (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withServerPath:(NSString *)serverPath; @@ -52,7 +52,7 @@ * **/ -+ (void) authDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (void) authDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL authCode:(NSString *)authCode userAgent:(NSString *)userAgent @@ -70,7 +70,7 @@ * **/ -+ (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 13cd94bf..00b25712 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -31,7 +31,7 @@ @implementation OCOAuth2Manager -+ (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withServerPath:(NSString *)serverPath { NSString *oauth2RedirectUri = oauth2Configuration.redirectUri; @@ -69,7 +69,7 @@ + (NSURL *) getOAuth2URLToGetTokenByOAuth2Configuration:(OCOAuth2Configuration * #pragma mark - access token -+ (void) authDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (void) authDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL authCode:(NSString *)authCode userAgent:(NSString *)userAgent @@ -121,7 +121,7 @@ + (void) authDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configurat } -+ (void) authDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (void) authDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withURL:(NSURL *)url authCode:(NSString *)authCode userAgent:(NSString *)userAgent @@ -171,7 +171,7 @@ + (void) authDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con #pragma mark - Refresh token -+ (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent @@ -228,7 +228,7 @@ + (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con } -+ (void) refreshAuthDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration +- (void) refreshAuthDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withBaseURL:(NSString *)baseURL refreshToken:(NSString *)refreshToken userAgent:(NSString *)userAgent @@ -274,7 +274,7 @@ + (void) refreshAuthDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oa } -#pragma mark - methods from URLSessionDelegate +#pragma mark - methods from NSURLSessionDelegate // Delegate method called when the server responded with an authentication challenge. // Since iOS is so great, it is also called when the server certificate is not trusted, so that the client @@ -298,12 +298,14 @@ - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthentica NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,credential); } else { + // If this method was called due to untrusted server certificate and this was not accepted by the user before, + // or if it was called due to a different authentication challenge, default handling will lead the task to fail. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,nil); } } -/// MARK : methods from URLSessionTaskDelegate +/// MARK : methods from NSURLSessionTaskDelegate // Delegate method called when the server responsed with a redirection // @@ -318,11 +320,9 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task NSLog(@"DetectAuthenticationMethod: redirect detected in URLSessionTaskDelegate implementation"); - // let's resuse the last request performed by the task (it's a POST) and set in it the redirected URL from the request proposed by the system - NSMutableURLRequest *newRequest; - if (task.currentRequest) { - newRequest.URL = request.URL; + NSMutableURLRequest *newRequest = [task.currentRequest mutableCopy]; // let's resuse the last request performed by the task (it's a POST) ... + newRequest.URL = request.URL; // ... and then override the URL with the redirected one proposed by the system completionHandler(newRequest); //follow } else { diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index e12b21f0..9e426aab 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -123,7 +123,8 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request } else { //get refresh token - [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent @@ -195,7 +196,8 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request } else { //get refresh token - [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent @@ -397,7 +399,8 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req } } else { //get refresh token - [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent @@ -512,7 +515,8 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request } } else { //get refresh token - [OCOAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration + OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken userAgent:sharedOCCommunication.userAgent From eed53c5d31163f1052f7a34ab5ab4a362a9a4a7b Mon Sep 17 00:00:00 2001 From: "David A. Velasco" Date: Thu, 28 Sep 2017 18:18:57 +0200 Subject: [PATCH 40/50] Add protocol for optional check of user-accepted server certificates --- .../OCCommunicationLib/OCCommunication.h | 4 ++ .../OCCommunicationLib/OCCommunication.m | 4 ++ .../OCCredentialsStorage.h | 1 - .../OCOAuth2Authentication/OCOAuth2Manager.h | 6 ++- .../OCOAuth2Authentication/OCOAuth2Manager.m | 5 +- .../OCTrustedCertificatesStore.h | 48 +++++++++++++++++++ .../OCWebDavClient/OCWebDAVClient.m | 4 ++ .../project.pbxproj | 2 + 8 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 OCCommunicationLib/OCCommunicationLib/OCTrustedCertificatesStore.h diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 77c1b55d..2e83c541 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -28,6 +28,7 @@ #import "OCCredentialsDto.h" #import "OCOAuth2Configuration.h" #import "OCCredentialsStorage.h" +#import "OCTrustedCertificatesStore.h" @class AFURLSessionManager; @class AFSecurityPolicy; @@ -63,6 +64,7 @@ typedef enum { @property (nonatomic, strong) OCOAuth2Configuration *oauth2Configuration; @property (nonatomic, strong) id credentialsStorage; +@property (nonatomic, strong) id trustedCertificatesStore; //Public properties @@ -144,6 +146,8 @@ typedef enum { - (void) setValueCredentialsStorage:(id)credentialsStorage; +- (void) setValueTrustedCertificatesStore:(id)trustedCertificatesStore; + /* * Method to update the a request with the current credentials */ diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 64d07e72..16176670 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -170,6 +170,10 @@ - (void) setValueCredentialsStorage:(id)credential self.credentialsStorage = credentialsStorage; } +- (void) setValueTrustedCertificatesStore:(id)trustedCertificatesStore { + self.trustedCertificatesStore = trustedCertificatesStore; +} + ///----------------------------------- /// @name getRequestWithCredentials ///----------------------------------- diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h index e54b5834..e6493b3e 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCCredentialsStorage.h @@ -26,7 +26,6 @@ // #import -#import "OCCommunication.h" @class OCCredentialsDto; diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h index 5607446b..9ee05e4f 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.h @@ -32,12 +32,15 @@ #import "UtilsFramework.h" #import "OCFrameworkConstants.h" #import "OCCredentialsDto.h" -//#import "SSLCertificateManager.h" +#import "OCTrustedCertificatesStore.h" @interface OCOAuth2Manager : NSObject +@property (nonatomic, strong) id trustedCertificatesStore; + + - (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withServerPath:(NSString *)serverPath; @@ -78,4 +81,5 @@ failure:(void(^)(NSError *error))failure; + @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 00b25712..fcc1376e 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -292,9 +292,8 @@ - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthentica // authentication challenge with the certificates that were previously accepted by the user in the OC app. If // it match any of them, we allow to go on. - //SSLCertificateManager *sslCertificateManager = [[SSLCertificateManager alloc] init]; - BOOL trusted = YES;//TODO:->//[sslCertificateManager isTrustedServerCertificateIn:challenge]; - if (trusted) { + if (self.trustedCertificatesStore != nil && [self.trustedCertificatesStore isTrustedServerCertificateIn:challenge]) { + // trusted NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,credential); } else { diff --git a/OCCommunicationLib/OCCommunicationLib/OCTrustedCertificatesStore.h b/OCCommunicationLib/OCCommunicationLib/OCTrustedCertificatesStore.h new file mode 100644 index 00000000..fdfe5d7a --- /dev/null +++ b/OCCommunicationLib/OCCommunicationLib/OCTrustedCertificatesStore.h @@ -0,0 +1,48 @@ +// +// OCTrustedCertificatesStore.h +// ownCloud iOS library +// +// Created by David A. Velasco on 28/9/17. +// +// Copyright (C) 2017, ownCloud GmbH. ( http://www.owncloud.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + + +#ifndef OCTrustedCertificatesStore_h +#define OCTrustedCertificatesStore_h + +#import + +@protocol OCTrustedCertificatesStore + + +/* + * Checks if the challenge passed as a parameter corresponds to server certificate not trusted by iOS system, + * and if it is trusted by the user anyway, searching for it in the app-level store of certificates that + * were previously approved by her. + */ +- (BOOL) isTrustedServerCertificateIn:(NSURLAuthenticationChallenge *) challenge; + +@end + +#endif /* OCTrustedCertificatesStore_h */ + + diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 9e426aab..2b51eaaf 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -124,6 +124,7 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request //get refresh token OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + oAuth2Manager.trustedCertificatesStore = sharedOCCommunication.trustedCertificatesStore; [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken @@ -197,6 +198,7 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request //get refresh token OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + oAuth2Manager.trustedCertificatesStore = sharedOCCommunication.trustedCertificatesStore; [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken @@ -400,6 +402,7 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req } else { //get refresh token OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + oAuth2Manager.trustedCertificatesStore = sharedOCCommunication.trustedCertificatesStore; [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken @@ -516,6 +519,7 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request } else { //get refresh token OCOAuth2Manager* oAuth2Manager = [OCOAuth2Manager new]; + oAuth2Manager.trustedCertificatesStore = sharedOCCommunication.trustedCertificatesStore; [oAuth2Manager refreshAuthDataByOAuth2Configuration:sharedOCCommunication.oauth2Configuration withBaseURL:sharedOCCommunication.credDto.baseURL refreshToken:sharedOCCommunication.credDto.refreshToken diff --git a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj index 7c055c54..d668b06e 100644 --- a/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj +++ b/OCCommunicationLib/ownCloud iOS library.xcodeproj/project.pbxproj @@ -105,6 +105,7 @@ 59A5B719191907F100724BE3 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLResponseSerialization.m; path = ExternalLibs/AFNetworking/AFURLResponseSerialization.m; sourceTree = ""; }; 59A5B71A191907F100724BE3 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLSessionManager.h; path = ExternalLibs/AFNetworking/AFURLSessionManager.h; sourceTree = ""; }; 59A5B71B191907F100724BE3 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLSessionManager.m; path = ExternalLibs/AFNetworking/AFURLSessionManager.m; sourceTree = ""; }; + 7F4E820F1F7D4DFA00C20454 /* OCTrustedCertificatesStore.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OCTrustedCertificatesStore.h; sourceTree = ""; }; 7F6F496B1F46C6EB009F8813 /* OCCredentialsDto.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OCCredentialsDto.h; sourceTree = ""; }; 7F6F496C1F46C70C009F8813 /* OCCredentialsDto.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCCredentialsDto.m; sourceTree = ""; }; EA0599981BB96D14002C2864 /* OCShareUser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OCShareUser.h; sourceTree = ""; }; @@ -247,6 +248,7 @@ EA7CC932183E150000B6A4B4 /* OCCommunication.h */, EA7CC933183E150000B6A4B4 /* OCCommunication.m */, EAABAB1218574A7C00909831 /* OCErrorMsg.h */, + 7F4E820F1F7D4DFA00C20454 /* OCTrustedCertificatesStore.h */, EAABAB171858593500909831 /* UploadSupport */, EA7CC91C183E147C00B6A4B4 /* OCWebDavClient */, EA7CC8E7183E133800B6A4B4 /* Utils */, From 15ce0f103af648cfd3d7ae3f3c32dbc5b192a4aa Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 4 Oct 2017 17:05:12 +0200 Subject: [PATCH 41/50] Not encode uri --- .../OCOAuth2Authentication/OCOAuth2Manager.m | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index fcc1376e..26e202a8 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -34,15 +34,12 @@ @implementation OCOAuth2Manager - (NSURL *) getOAuth2URLToGetAuthCodeByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Configuration withServerPath:(NSString *)serverPath { - NSString *oauth2RedirectUri = oauth2Configuration.redirectUri; - NSString *oauth2RedirectUriEncoded = [oauth2RedirectUri stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]; - NSString *baseURL = [NSString stringWithFormat:@"%@%@",serverPath,oauth2Configuration.authorizationEndpoint]; NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:baseURL]; NSDictionary *queryDictionary = @{ @"response_type" : @"code", - @"redirect_uri" : oauth2RedirectUriEncoded, + @"redirect_uri" : oauth2Configuration.redirectUri, @"client_id" : oauth2Configuration.clientId }; NSMutableArray *queryItems = [NSMutableArray array]; From f6cbe663af5ef62779e3cbb7645394439d806336 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 6 Oct 2017 14:26:19 +0200 Subject: [PATCH 42/50] Retry any request after it was cancelled by the system --- .../OCWebDavClient/OCWebDAVClient.m | 59 +++++++++++++++++-- 1 file changed, 53 insertions(+), 6 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 2b51eaaf..542c9661 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -40,8 +40,7 @@ #define k_server_information_json @"status.php" #define k_api_header_request @"OCS-APIREQUEST" #define k_group_sharee_type 1 -#define k_retry_ntimes 2 //Retry ntimes request - +#define k_retry_ntimes 5 //Retry ntimes request NSString const *OCWebDAVContentTypeKey = @"getcontenttype"; NSString const *OCWebDAVETagKey = @"getetag"; @@ -115,7 +114,8 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request if (!error) { success((NSHTTPURLResponse*)response,responseObject, token); } else { - if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) { + if (((NSHTTPURLResponse*)response).statusCode == 401 && + sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) { if (ntimes <= 0) { if (failure) { failure((NSHTTPURLResponse*)response, responseObject, error, token); @@ -143,8 +143,8 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request if (sharedOCCommunication.credentialsStorage != nil) { [sharedOCCommunication.credentialsStorage saveCredentials:sharedOCCommunication.credDto]; } - - sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + + sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes -1) onCommunication:sharedOCCommunication withUserSessionToken:token success:success @@ -158,6 +158,17 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request }]; } + } else if (error.code == kCFURLErrorCancelled) { + + sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes -1) + onCommunication:sharedOCCommunication + withUserSessionToken:token + success:success + failure:failure + ]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; + [sessionDataTask resume]; + } else { failure((NSHTTPURLResponse*)response, responseObject, error, token); } @@ -228,6 +239,14 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request failure(nil,nil,error); }]; } + } else if (error.code == kCFURLErrorCancelled){ + sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) + onCommunication:sharedOCCommunication + success:success + failure:failure + ]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; + [sessionDataTask resume]; } else { failure((NSHTTPURLResponse*)response, responseObject, error); @@ -437,6 +456,22 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req failure(response, error); }]; } + + + } else if (error.code == kCFURLErrorCancelled) { + + downloadTask = [self downloadTaskWithRequest:request + toPath:localDestination + defaultPriority:defaultPriority + retryingNumberOfTimes:(ntimes -1) + onCommunication:sharedOCCommunication + progress:downloadProgress + success:success + failure:failure]; + + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.downloadSessionManager]; + [downloadTask resume]; + } else { failure(response, error); } @@ -545,13 +580,25 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request progress:uploadProgress success:success failure:failure]; - [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.uploadSessionManager]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.uploadSessionManager]; [uploadTask resume]; } failure:^(NSError *error) { failure(response, responseObject, error); }]; } + } else if (error.code == kCFURLErrorCancelled ) { + + uploadTask = [self uploadTaskWithRequest:request + fromFileURL:fileURL + retryingNumberOfTimes:(ntimes -1) + onCommunication:sharedOCCommunication + progress:uploadProgress + success:success + failure:failure]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.uploadSessionManager]; + [uploadTask resume]; + } else { failure(response, responseObject, error); } From c8a6a27ea29e387b62f42e35728452562bf08cfc Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 6 Oct 2017 15:11:39 +0200 Subject: [PATCH 43/50] Test cancelled request --- .../OCWebDavClient/OCWebDAVClient.m | 48 +------------------ 1 file changed, 2 insertions(+), 46 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index 542c9661..bbd2bb5f 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -158,17 +158,6 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request }]; } - } else if (error.code == kCFURLErrorCancelled) { - - sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes -1) - onCommunication:sharedOCCommunication - withUserSessionToken:token - success:success - failure:failure - ]; - [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [sessionDataTask resume]; - } else { failure((NSHTTPURLResponse*)response, responseObject, error, token); } @@ -239,14 +228,6 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request failure(nil,nil,error); }]; } - } else if (error.code == kCFURLErrorCancelled){ - sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:(ntimes - 1) - onCommunication:sharedOCCommunication - success:success - failure:failure - ]; - [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; - [sessionDataTask resume]; } else { failure((NSHTTPURLResponse*)response, responseObject, error); @@ -458,20 +439,6 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req } - } else if (error.code == kCFURLErrorCancelled) { - - downloadTask = [self downloadTaskWithRequest:request - toPath:localDestination - defaultPriority:defaultPriority - retryingNumberOfTimes:(ntimes -1) - onCommunication:sharedOCCommunication - progress:downloadProgress - success:success - failure:failure]; - - [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.downloadSessionManager]; - [downloadTask resume]; - } else { failure(response, error); } @@ -546,7 +513,8 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request if (!error) { success(response,responseObject); } else { - if (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) { + if ( (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) || + error.code == kCFURLErrorCancelled ){ if (ntimes <= 0) { if (failure) { failure(response, responseObject, error); @@ -587,18 +555,6 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request failure(response, responseObject, error); }]; } - } else if (error.code == kCFURLErrorCancelled ) { - - uploadTask = [self uploadTaskWithRequest:request - fromFileURL:fileURL - retryingNumberOfTimes:(ntimes -1) - onCommunication:sharedOCCommunication - progress:uploadProgress - success:success - failure:failure]; - [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.uploadSessionManager]; - [uploadTask resume]; - } else { failure(response, responseObject, error); } From 077b3e5e7c0787229918e3ec9382f4787924bf00 Mon Sep 17 00:00:00 2001 From: nasli Date: Fri, 6 Oct 2017 15:35:20 +0200 Subject: [PATCH 44/50] remove detect cancelled error code --- .../OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index bbd2bb5f..ceadb4fa 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -40,7 +40,7 @@ #define k_server_information_json @"status.php" #define k_api_header_request @"OCS-APIREQUEST" #define k_group_sharee_type 1 -#define k_retry_ntimes 5 //Retry ntimes request +#define k_retry_ntimes 3 //Retry ntimes request NSString const *OCWebDAVContentTypeKey = @"getcontenttype"; NSString const *OCWebDAVETagKey = @"getetag"; @@ -513,8 +513,8 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request if (!error) { success(response,responseObject); } else { - if ( (((NSHTTPURLResponse*)response).statusCode == 401 && sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN) || - error.code == kCFURLErrorCancelled ){ + if ( ((NSHTTPURLResponse*)response).statusCode == 401 && + sharedOCCommunication.credDto.authenticationMethod == AuthenticationMethodBEARER_TOKEN ){ if (ntimes <= 0) { if (failure) { failure(response, responseObject, error); From 88447df9f68d319ca7707c5a6c3986950fd1cb05 Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 11 Oct 2017 17:30:51 +0200 Subject: [PATCH 45/50] Fix for server OAuth refresh token responses without required data --- .../OCOAuth2Authentication/OCOAuth2Manager.m | 20 +++++++++---------- .../OCCommunicationLib/Utils/UtilsFramework.m | 4 ++-- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 26e202a8..0d76c036 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -192,18 +192,10 @@ - (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con options:kNilOptions error:&errorJSON]; if (errorJSON == nil) { - if (dictJSON[@"error"] != nil && ![dictJSON[@"error"] isEqual:[NSNull null]] ) { + if (dictJSON[@"user_id"] != nil && + dictJSON[@"access_token"] != nil && + dictJSON[@"refresh_token"] != nil ) { - NSString *message = (NSString*)[dictJSON objectForKey:@"error"]; - - if ([message isKindOfClass:[NSNull class]]) { - message = @""; - } - - NSError *error = [UtilsFramework getErrorByCodeId:OCErrorOAuth2Error]; - - failure(error); - } else { userCredDto.userName = dictJSON[@"user_id"]; userCredDto.accessToken = dictJSON[@"access_token"]; userCredDto.refreshToken = dictJSON[@"refresh_token"]; @@ -212,6 +204,12 @@ - (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con userCredDto.authenticationMethod = AuthenticationMethodBEARER_TOKEN; success(userCredDto); + + } else { + + NSError *error = [UtilsFramework getErrorByCodeId:OCErrorOAuth2Error]; + + failure(error); } } diff --git a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m index 13dfd03f..564a3a99 100644 --- a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m +++ b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m @@ -263,7 +263,7 @@ + (NSError *) getErrorByCodeId:(int) errorCode { NSMutableDictionary* details = [NSMutableDictionary dictionary]; [details setValue:NSLocalizedString(@"oauth2_error_access_denied", nil) forKey:NSLocalizedDescriptionKey]; - error = [NSError errorWithDomain:k_domain_error_code code:OCErrorForbiddenUnknown userInfo:details]; + error = [NSError errorWithDomain:k_domain_error_code code:OCErrorOAuth2ErrorAccessDenied userInfo:details]; break; } @@ -272,7 +272,7 @@ + (NSError *) getErrorByCodeId:(int) errorCode { NSMutableDictionary* details = [NSMutableDictionary dictionary]; [details setValue:NSLocalizedString(@"oauth2_error", nil) forKey:NSLocalizedDescriptionKey]; - error = [NSError errorWithDomain:k_domain_error_code code:OCErrorForbiddenUnknown userInfo:details]; + error = [NSError errorWithDomain:k_domain_error_code code:OCErrorOAuth2Error userInfo:details]; break; } From 6993f5b962910c0131380400f60bee57b321156b Mon Sep 17 00:00:00 2001 From: nasli Date: Mon, 16 Oct 2017 14:40:48 +0200 Subject: [PATCH 46/50] Refactor get user data and display name. Add displayName to credentials. Deprecate old methods. --- .../OCCommunicationLib/OCCommunication.h | 41 ++++++++++++- .../OCCommunicationLib/OCCommunication.m | 61 +++++++++++++++++++ .../OCCommunicationLib/OCCredentialsDto.h | 2 + .../OCCommunicationLib/OCCredentialsDto.m | 5 ++ .../OCCommunicationLib/OCFrameworkConstants.h | 6 ++ .../OCWebDavClient/OCWebDAVClient.h | 21 ++++++- .../OCWebDavClient/OCWebDAVClient.m | 36 +++++++++-- 7 files changed, 162 insertions(+), 10 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h index 2e83c541..2c9756bb 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.h @@ -484,11 +484,44 @@ typedef enum { successRequest:(void(^)(NSHTTPURLResponse *response, NSString *serverVersion, NSString *redirectedServer)) success failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failure; +///----------------------------------- +/// @name getUserDataOfServer +///----------------------------------- + +/** + * Method to get the User data. + * + * @param path -> NSString server path + * + * @param sharedOCCommunication -> OCCommunication Singleton of communication to add the operation on the queue. + */ +- (void) getUserDataOfServer:(NSString *)path onCommunication:(OCCommunication *)sharedOCCommunication + success:(void(^)(NSHTTPURLResponse *response, NSData *responseData, NSString *redirectedServer))success + failure:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failureRequest; + +///----------------------------------- +/// @name getUserDisplayNameOfServer +///----------------------------------- + +/** + * Method to get the User display name. + * + * @param path -> NSString server path + * + * @param sharedOCCommunication -> OCCommunication Singleton of communication to add the operation on the queue. + */ +- (void) getUserDisplayNameOfServer:(NSString *)path onCommunication:(OCCommunication *)sharedOCCommunication + success:(void(^)(NSHTTPURLResponse *response, NSString *displayName, NSString *redirectedServer))success + failure:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failureRequest; + + ///----------------------------------- /// @name requestForUserNameByCookie ///----------------------------------- /** + * DEPRECATED use - getUserDataOfServer:onCommunication: or getUserDisplayNameOfServer:onCommunication: instead + * * Method to get the User name by the cookie of the session. Used with SAML servers. * * @param cookieString -> NSString The cookie of the session @@ -501,14 +534,15 @@ typedef enum { - (void) getUserNameByCookie:(NSString *) cookieString ofServerPath:(NSString *)path onCommunication: (OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *response, NSData *responseData, NSString *redirectedServer))success - failure:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failure; + failure:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failure +__deprecated_msg("Use - getUserDataOfServer:onCommunication: or getUserDisplayNameOfServer:onCommunication: instead"); ///----------------------------------- /// @name Get Features Supported By Server ///----------------------------------- /** - * DEPRECATED use + getFeaturesSupportedByServerForVersion: instead + * DEPRECATED use - getFeaturesSupportedByServerForVersion: instead * * Method get the features supported by the path server using the version string. * @@ -530,7 +564,8 @@ typedef enum { - (void) getFeaturesSupportedByServer:(NSString*) path onCommunication:(OCCommunication *)sharedOCCommunication successRequest:(void(^)(NSHTTPURLResponse *response, BOOL hasShareSupport, BOOL hasShareeSupport, BOOL hasCookiesSupport, BOOL hasForbiddenCharactersSupport, BOOL hasCapabilitiesSupport, BOOL hasFedSharesOptionShareSupport, NSString *redirectedServer)) success - failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failure __deprecated_msg("Use + getFeaturesSupportedByServerForVersion: instead"); + failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failure +__deprecated_msg("Use - getFeaturesSupportedByServerForVersion: instead"); ///----------------------------------- diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 16176670..0ac9f877 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -627,6 +627,67 @@ - (void) getServerVersionWithPath:(NSString*) path onCommunication:(OCCommunicat } + +///----------------------------------- +/// @name Get UserData +///----------------------------------- + +- (void) getUserDataOfServer:(NSString *)path onCommunication:(OCCommunication *)sharedOCCommunication + success:(void(^)(NSHTTPURLResponse *response, NSData *responseData, NSString *redirectedServer))success + failure:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failureRequest { + + OCWebDAVClient *request = [OCWebDAVClient new]; + request = [self getRequestWithCredentials:request]; + + + [request requestUserDataOfServer:path onCommunication:sharedOCCommunication + success:^(NSHTTPURLResponse *response, id responseObject) { + success(response, responseObject, request.redirectedServer); + } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) { + [self returnErrorWithResponse:response andResponseData:responseData andError:error failureRequest:failureRequest andRequest:request]; + }]; +} + +///----------------------------------- +/// @name Get User Display Name +///----------------------------------- + +- (void) getUserDisplayNameOfServer:(NSString *)path onCommunication:(OCCommunication *)sharedOCCommunication + success:(void(^)(NSHTTPURLResponse *response, NSString *displayName, NSString *redirectedServer))success + failure:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer))failureRequest { + + OCWebDAVClient *request = [OCWebDAVClient new]; + request = [self getRequestWithCredentials:request]; + + [request requestUserDataOfServer:path onCommunication:sharedOCCommunication + success:^(NSHTTPURLResponse *response, id responseObject) { + + NSError *jsonError = nil; + NSString *displayName = @""; + + NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&jsonError]; + + if (!jsonDict) { + + NSLog(@"json error: %@", jsonError); + } else { + + NSDictionary *ocsDict = [jsonDict objectForKey:k_json_ocs]; + + NSDictionary *userDataDict = [ocsDict objectForKey:k_json_ocs_data]; + + displayName = [userDataDict objectForKey:k_json_ocs_data_display_name]; + } + + success(response, displayName, request.redirectedServer); + + } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) { + + [self returnErrorWithResponse:response andResponseData:responseData andError:error failureRequest:failureRequest andRequest:request]; + }]; +} + + ///----------------------------------- /// @name Get UserName by cookie ///----------------------------------- diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h index 02035a47..4df82de2 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.h @@ -49,6 +49,8 @@ typedef NS_ENUM (NSUInteger, AuthenticationMethod){ @property (nonatomic, copy) NSString *expiresIn; @property (nonatomic, copy) NSString *tokenType; +@property (nonatomic, copy) NSString *userDisplayName; + - (void)encodeWithCoder:(NSCoder *)aCoder; - (id)initWithCoder:(NSCoder *)aDecoder; diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m index 8fc85baf..466d8d08 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m @@ -42,6 +42,7 @@ - (id)initWithCredentialsDto:(OCCredentialsDto *)oCredDto{ _expiresIn = oCredDto.expiresIn; _tokenType = oCredDto.tokenType; _authenticationMethod = oCredDto.authenticationMethod; + _userDisplayName = oCredDto.userDisplayName; } return self; @@ -57,6 +58,7 @@ -(id) copyWithZone:(NSZone *)zone { credDtoCopy.expiresIn = self.expiresIn; credDtoCopy.tokenType = self.tokenType; credDtoCopy.authenticationMethod = self.authenticationMethod; + credDtoCopy.userDisplayName = self.userDisplayName; return credDtoCopy; } @@ -71,6 +73,7 @@ - (void)encodeWithCoder:(NSCoder *)aCoder [aCoder encodeObject:self.expiresIn forKey:@"expiresIn"]; [aCoder encodeObject:self.tokenType forKey:@"tokenType"]; [aCoder encodeInteger:self.authenticationMethod forKey:@"authenticationMethod"]; + [aCoder encodeObject:self.userDisplayName forKey:@"userDisplayName"]; } - (id)initWithCoder:(NSCoder *)aDecoder @@ -84,6 +87,8 @@ - (id)initWithCoder:(NSCoder *)aDecoder self.expiresIn = [aDecoder decodeObjectForKey:@"tokenType"]; self.tokenType = [aDecoder decodeObjectForKey:@"tokenType"]; self.authenticationMethod = [aDecoder decodeIntegerForKey:@"authenticationMethod"]; + self.userDisplayName = [aDecoder decodeObjectForKey:@"userDisplayName"]; + } return self; } diff --git a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h index de890dd3..c640d781 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h +++ b/OCCommunicationLib/OCCommunicationLib/OCFrameworkConstants.h @@ -45,6 +45,12 @@ //URL path for list of files in web interface #define k_url_path_list_of_files_in_web @"index.php/apps/files" +//URL to access user data API +#define k_api_user_url_json @"ocs/v1.php/cloud/user?format=json" +#define k_json_ocs @"ocs" +#define k_json_ocs_data @"data" +#define k_json_ocs_data_display_name @"display-name" + //Url to access to Shared API to create #define k_url_acces_shared_api @"ocs/v1.php/apps/files_sharing/api/v1/shares" diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h index bc40c135..429d04ff 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h @@ -215,11 +215,29 @@ extern NSString * _Nullable OCWebDAVModificationDateKey; */ - (NSURLSessionUploadTask * _Nonnull)putWithSessionLocalPath:(NSString * _Nonnull)localSource atRemotePath:(NSString * _Nonnull)remoteDestination onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication progress:(void(^ _Nonnull)(NSProgress * _Nonnull progress))uploadProgress success:(void(^ _Nonnull)(NSURLResponse * _Nonnull, NSString * _Nonnull))success failure:(void(^ _Nonnull)(NSURLResponse * _Nonnull, id _Nonnull, NSError * _Nonnull))failure failureBeforeRequest:(void(^ _Nonnull)(NSError * _Nonnull)) failureBeforeRequest; + +///----------------------------------- +/// @name requestUserData +///----------------------------------- + +/** + * Method to obtain the User data of server + * + * + */ +- (void) requestUserDataOfServer:(NSString * _Nonnull) path + onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication + success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success + failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure; + + ///----------------------------------- /// @name requestForUserNameByCookie ///----------------------------------- /** + * DEPRECATED use - requestUserDataOfServer:onCommunication: instead + * * Method to obtain the User name by the cookie of the session * * @param NSString the cookie of the session @@ -227,7 +245,8 @@ extern NSString * _Nullable OCWebDAVModificationDateKey; */ - (void) requestUserNameOfServer:(NSString * _Nonnull) path byCookie:(NSString * _Nonnull) cookieString onCommunication: (OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success - failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure; + failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure +__deprecated_msg("Use - requestUserDataOfServer:onCommunication: instead"); ///----------------------------------- diff --git a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m index ceadb4fa..a1f9bd4a 100755 --- a/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m +++ b/OCCommunicationLib/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m @@ -36,11 +36,11 @@ #import "OCConstants.h" #import "OCOAuth2Manager.h" -#define k_api_user_url_json @"ocs/v1.php/cloud/user?format=json" #define k_server_information_json @"status.php" #define k_api_header_request @"OCS-APIREQUEST" + #define k_group_sharee_type 1 -#define k_retry_ntimes 3 //Retry ntimes request +#define k_retry_ntimes 2 //Retry ntimes request NSString const *OCWebDAVContentTypeKey = @"getcontenttype"; NSString const *OCWebDAVETagKey = @"getetag"; @@ -135,6 +135,7 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request userCredDto.userId = sharedOCCommunication.credDto.userId; userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; + userCredDto.userDisplayName = sharedOCCommunication.credDto.userDisplayName; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; @@ -209,6 +210,7 @@ - (NSURLSessionDataTask *)mr_operationWithRequest:(NSMutableURLRequest *)request userCredDto.userId = sharedOCCommunication.credDto.userId; userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; + userCredDto.userDisplayName = sharedOCCommunication.credDto.userDisplayName; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; @@ -413,6 +415,7 @@ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSMutableURLRequest *)req userCredDto.userId = sharedOCCommunication.credDto.userId; userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; + userCredDto.userDisplayName = sharedOCCommunication.credDto.userDisplayName; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; @@ -533,6 +536,7 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSMutableURLRequest *)request userCredDto.userId = sharedOCCommunication.credDto.userId; userCredDto.baseURL = sharedOCCommunication.credDto.baseURL; + userCredDto.userDisplayName = sharedOCCommunication.credDto.userDisplayName; [sharedOCCommunication setCredentials:userCredDto]; [request setValue:[NSString stringWithFormat:@"Bearer %@", userCredDto.accessToken] forHTTPHeaderField:@"Authorization"]; @@ -621,14 +625,34 @@ - (NSURLSessionUploadTask *)putWithSessionLocalPath:(NSString *)localSource } } -- (void) requestUserNameOfServer:(NSString * _Nonnull) path byCookie:(NSString * _Nonnull) cookieString onCommunication: -(OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success - failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure { + +- (void) requestUserDataOfServer:(NSString * _Nonnull) path + onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication + success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success + failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure { NSString *apiUserUrl = nil; apiUserUrl = [NSString stringWithFormat:@"%@%@", path, k_api_user_url_json]; - NSLog(@"api user name call: %@", apiUserUrl); + _requestMethod = @"GET"; + + NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path: apiUserUrl parameters: nil]; + [request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"]; + + NSURLSessionDataTask *sessionDataTask = [self mr_operationWithRequest:request retryingNumberOfTimes:k_retry_ntimes onCommunication:sharedOCCommunication success:success failure:failure]; + [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager]; + [sessionDataTask resume]; +} + + +- (void) requestUserNameOfServer:(NSString * _Nonnull) path + byCookie:(NSString * _Nonnull) cookieString + onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication + success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success + failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nullable responseObject, NSError * _Nonnull))failure { + + NSString *apiUserUrl = nil; + apiUserUrl = [NSString stringWithFormat:@"%@%@", path, k_api_user_url_json]; _requestMethod = @"GET"; From d57639d9b2e42f794c4aa7b7cef7a455febd154e Mon Sep 17 00:00:00 2001 From: nasli Date: Mon, 23 Oct 2017 11:48:23 +0200 Subject: [PATCH 47/50] Not use handle error class in display name requests --- .../OCCommunicationLib/OCCommunication.m | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 0ac9f877..7e98481a 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -644,7 +644,7 @@ - (void) getUserDataOfServer:(NSString *)path onCommunication:(OCCommunication * success:^(NSHTTPURLResponse *response, id responseObject) { success(response, responseObject, request.redirectedServer); } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) { - [self returnErrorWithResponse:response andResponseData:responseData andError:error failureRequest:failureRequest andRequest:request]; + failureRequest(response,error, request.redirectedServer); }]; } @@ -667,7 +667,7 @@ - (void) getUserDisplayNameOfServer:(NSString *)path onCommunication:(OCCommunic NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&jsonError]; - if (!jsonDict) { + if (jsonError) { NSLog(@"json error: %@", jsonError); } else { @@ -679,11 +679,15 @@ - (void) getUserDisplayNameOfServer:(NSString *)path onCommunication:(OCCommunic displayName = [userDataDict objectForKey:k_json_ocs_data_display_name]; } + for(NSString *key in [jsonDict allKeys]) { + NSLog(@"%@",[jsonDict objectForKey:key]); + } + success(response, displayName, request.redirectedServer); } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) { - - [self returnErrorWithResponse:response andResponseData:responseData andError:error failureRequest:failureRequest andRequest:request]; + failureRequest(response,error, request.redirectedServer); + NSLog(@"Display name not updated"); }]; } From b434c573e68a1e229924319b9b2a50e5e26fc0cf Mon Sep 17 00:00:00 2001 From: nasli Date: Mon, 30 Oct 2017 09:55:27 +0100 Subject: [PATCH 48/50] Fix return request --- OCCommunicationLib/OCCommunicationLib/OCCommunication.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m index 7e98481a..184c770a 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCommunication.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCommunication.m @@ -243,7 +243,7 @@ - (id) getRequestWithCredentials:(id) request { [myRequest setUserAgent:self.userAgent]; } - return request; + return myRequest; } else { NSLog(@"We do not know witch kind of object is"); From 53ea3ed426c3f01e1a99814e66f3b504ee2ba64f Mon Sep 17 00:00:00 2001 From: nasli Date: Mon, 30 Oct 2017 09:56:51 +0100 Subject: [PATCH 49/50] Add NSCopying protocol into capabilities class --- .../OCCommunicationLib/OCCapabilities.h | 5 +- .../OCCommunicationLib/OCCapabilities.m | 119 ++++++++++++++++++ .../OCCommunicationLib/OCCredentialsDto.m | 11 +- .../OCCommunicationLib/Utils/UtilsFramework.m | 3 + 4 files changed, 135 insertions(+), 3 deletions(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCCapabilities.h b/OCCommunicationLib/OCCommunicationLib/OCCapabilities.h index bb8d6042..05a810f6 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCapabilities.h +++ b/OCCommunicationLib/OCCommunicationLib/OCCapabilities.h @@ -27,7 +27,7 @@ #import -@interface OCCapabilities : NSObject +@interface OCCapabilities : NSObject /*VERSION*/ @property (nonatomic) NSInteger versionMajor; @@ -76,6 +76,7 @@ @property (nonatomic) BOOL isFileUndeleteEnabled; @property (nonatomic) BOOL isFileVersioningEnabled; - +- (void)encodeWithCoder:(NSCoder *)aCoder; +- (id)initWithCoder:(NSCoder *)aDecoder; @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCCapabilities.m b/OCCommunicationLib/OCCommunicationLib/OCCapabilities.m index ce69b333..c31782d6 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCapabilities.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCapabilities.m @@ -44,6 +44,125 @@ - (id)init { return self; } +#pragma mark - NSCopying +-(id) copyWithZone:(NSZone *)zone { + OCCapabilities *capCopy = [[OCCapabilities alloc]init]; + capCopy.versionMajor = self.versionMajor; + capCopy.versionMinor = self.versionMinor; + capCopy.versionMicro = self.versionMicro; + capCopy.versionString = self.versionString; + capCopy.versionEdition = self.versionEdition; + + capCopy.corePollInterval = self.corePollInterval; + + capCopy.isFilesSharingAPIEnabled = self.isFilesSharingAPIEnabled; + + capCopy.isFilesSharingShareLinkEnabled = self.isFilesSharingShareLinkEnabled; + + capCopy.isFilesSharingPasswordEnforcedEnabled = self.isFilesSharingPasswordEnforcedEnabled; + + capCopy.isFilesSharingExpireDateByDefaultEnabled = self.isFilesSharingExpireDateByDefaultEnabled; + capCopy.isFilesSharingExpireDateEnforceEnabled = self.isFilesSharingExpireDateEnforceEnabled; + capCopy.filesSharingExpireDateDaysNumber = self.filesSharingExpireDateDaysNumber; + + capCopy.isFilesSharingAllowUserSendMailNotificationAboutShareLinkEnabled = self.isFilesSharingAllowUserSendMailNotificationAboutShareLinkEnabled; + capCopy.isFilesSharingAllowPublicUploadsEnabled = self.isFilesSharingAllowPublicUploadsEnabled; + capCopy.isFilesSharingSupportsUploadOnlyEnabled = self.isFilesSharingSupportsUploadOnlyEnabled; + capCopy.isFilesSharingAllowUserCreateMultiplePublicLinksEnabled = self.isFilesSharingAllowUserCreateMultiplePublicLinksEnabled; + + capCopy.isFilesSharingAllowUserSendMailNotificationAboutOtherUsersEnabled = self.isFilesSharingAllowUserSendMailNotificationAboutOtherUsersEnabled; + capCopy.isFilesSharingReSharingEnabled = self.isFilesSharingReSharingEnabled; + + capCopy.isFilesSharingAllowUserSendSharesToOtherServersEnabled = self.isFilesSharingAllowUserSendSharesToOtherServersEnabled; + capCopy.isFilesSharingAllowUserReceiveSharesToOtherServersEnabled = self.isFilesSharingAllowUserReceiveSharesToOtherServersEnabled; + + capCopy.isFileBigFileChunkingEnabled = self.isFileBigFileChunkingEnabled; + capCopy.isFileUndeleteEnabled = self.isFileUndeleteEnabled; + capCopy.isFileVersioningEnabled = self.isFileVersioningEnabled; + + return capCopy; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder +{ + [aCoder encodeInteger:self.versionMajor forKey:@"versionMajor"]; + [aCoder encodeInteger:self.versionMinor forKey:@"versionMinor"]; + [aCoder encodeInteger:self.versionMicro forKey:@"versionMicro"]; + [aCoder encodeObject:self.versionString forKey:@"versionString"]; + [aCoder encodeObject:self.versionEdition forKey:@"versionEdition"]; + + [aCoder encodeInteger:self.corePollInterval forKey:@"corePollInterval"]; + + [aCoder encodeBool:self.isFilesSharingAPIEnabled forKey:@"isFilesSharingAPIEnabled"]; + + [aCoder encodeBool:self.isFilesSharingShareLinkEnabled forKey:@"isFilesSharingShareLinkEnabled"]; + + [aCoder encodeBool:self.isFilesSharingPasswordEnforcedEnabled forKey:@"isFilesSharingPasswordEnforcedEnabled"]; + + [aCoder encodeBool:self.isFilesSharingExpireDateByDefaultEnabled forKey:@"isFilesSharingExpireDateByDefaultEnabled"]; + [aCoder encodeBool:self.isFilesSharingExpireDateEnforceEnabled forKey:@"isFilesSharingExpireDateEnforceEnabled"]; + [aCoder encodeInteger:self.filesSharingExpireDateDaysNumber forKey:@"filesSharingExpireDateDaysNumber"]; + + [aCoder encodeBool:self.isFilesSharingAllowUserSendMailNotificationAboutShareLinkEnabled forKey:@"isFilesSharingAllowUserSendMailNotificationAboutShareLinkEnabled"]; + [aCoder encodeBool:self.isFilesSharingAllowPublicUploadsEnabled forKey:@"isFilesSharingAllowPublicUploadsEnabled"]; + [aCoder encodeBool:self.isFilesSharingSupportsUploadOnlyEnabled forKey:@"isFilesSharingSupportsUploadOnlyEnabled"]; + [aCoder encodeBool:self.isFilesSharingAllowUserCreateMultiplePublicLinksEnabled forKey:@"isFilesSharingAllowUserCreateMultiplePublicLinksEnabled"]; + + [aCoder encodeBool:self.isFilesSharingAllowUserSendMailNotificationAboutOtherUsersEnabled forKey:@"isFilesSharingAllowUserSendMailNotificationAboutOtherUsersEnabled"]; + [aCoder encodeBool:self.isFilesSharingReSharingEnabled forKey:@"isFilesSharingReSharingEnabled"]; + + [aCoder encodeBool:self.isFilesSharingAllowUserSendSharesToOtherServersEnabled forKey:@"isFilesSharingAllowUserSendSharesToOtherServersEnabled"]; + [aCoder encodeBool:self.isFilesSharingAllowUserReceiveSharesToOtherServersEnabled forKey:@"isFilesSharingAllowUserReceiveSharesToOtherServersEnabled"]; + + [aCoder encodeBool:self.isFileBigFileChunkingEnabled forKey:@"isFileBigFileChunkingEnabled"]; + [aCoder encodeBool:self.isFileUndeleteEnabled forKey:@"isFileUndeleteEnabled"]; + [aCoder encodeBool:self.isFileVersioningEnabled forKey:@"isFileVersioningEnabled"]; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + if (self = [self init]) { + self.versionMajor = [aDecoder decodeIntegerForKey:@"versionMajor"]; + self.versionMinor = [aDecoder decodeIntegerForKey:@"versionMinor"]; + self.versionMicro = [aDecoder decodeIntegerForKey:@"versionMicro"]; + self.versionString = [aDecoder decodeObjectForKey:@"versionString"]; + self.versionEdition = [aDecoder decodeObjectForKey:@"versionEdition"]; + + self.corePollInterval = [aDecoder decodeIntegerForKey:@"corePollInterval"]; + + self.isFilesSharingAPIEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingAPIEnabled"]; + + self.isFilesSharingShareLinkEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingShareLinkEnabled"]; + + self.isFilesSharingPasswordEnforcedEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingPasswordEnforcedEnabled"]; + + self.isFilesSharingExpireDateByDefaultEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingExpireDateByDefaultEnabled"]; + self.isFilesSharingExpireDateEnforceEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingExpireDateEnforceEnabled"]; + self.filesSharingExpireDateDaysNumber = [aDecoder decodeIntegerForKey:@"filesSharingExpireDateDaysNumber"]; + + self.isFilesSharingAllowUserSendMailNotificationAboutShareLinkEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingAllowUserSendMailNotificationAboutShareLinkEnabled"]; + self.isFilesSharingAllowPublicUploadsEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingAllowPublicUploadsEnabled"]; + self.isFilesSharingSupportsUploadOnlyEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingSupportsUploadOnlyEnabled"]; + self.isFilesSharingAllowUserCreateMultiplePublicLinksEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingAllowUserCreateMultiplePublicLinksEnabled"]; + + self.isFilesSharingAllowUserSendMailNotificationAboutOtherUsersEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingAllowUserSendMailNotificationAboutOtherUsersEnabled"]; + self.isFilesSharingReSharingEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingReSharingEnabled"]; + + self.isFilesSharingAllowUserSendSharesToOtherServersEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingAllowUserSendSharesToOtherServersEnabled"]; + self.isFilesSharingAllowUserReceiveSharesToOtherServersEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingAllowUserReceiveSharesToOtherServersEnabled"]; + + self.isFileBigFileChunkingEnabled = [aDecoder decodeBoolForKey:@"isFilesSharingReSharingEnabled"]; + self.isFileUndeleteEnabled = [aDecoder decodeBoolForKey:@"isFileUndeleteEnabled"]; + self.isFileVersioningEnabled = [aDecoder decodeBoolForKey:@"isFileVersioningEnabled"]; + } + return self; +} @end diff --git a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m index 466d8d08..764b7b7f 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m +++ b/OCCommunicationLib/OCCommunicationLib/OCCredentialsDto.m @@ -48,6 +48,9 @@ - (id)initWithCredentialsDto:(OCCredentialsDto *)oCredDto{ return self; } + +#pragma mark - NSCopying + -(id) copyWithZone:(NSZone *)zone { OCCredentialsDto *credDtoCopy = [[OCCredentialsDto alloc]init]; credDtoCopy.userId = self.userId; @@ -63,6 +66,12 @@ -(id) copyWithZone:(NSZone *)zone { return credDtoCopy; } +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.userId forKey:@"userId"]; @@ -76,7 +85,7 @@ - (void)encodeWithCoder:(NSCoder *)aCoder [aCoder encodeObject:self.userDisplayName forKey:@"userDisplayName"]; } -- (id)initWithCoder:(NSCoder *)aDecoder +- (instancetype)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { self.userId = [aDecoder decodeObjectForKey:@"userId"]; diff --git a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m index 564a3a99..ecedbfec 100644 --- a/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m +++ b/OCCommunicationLib/OCCommunicationLib/Utils/UtilsFramework.m @@ -495,7 +495,10 @@ + (NSMutableURLRequest *) getRequestWithCookiesByRequest: (NSMutableURLRequest * * */ + (void) deleteAllCookies { + NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; + NSLog(@"Deleting cookie storage: %@", cookieStorage); + for (NSHTTPCookie *each in cookieStorage.cookies) { [cookieStorage deleteCookie:each]; } From 9cb56fbcc3711f6693d6a15eb3ffaf6bc30056de Mon Sep 17 00:00:00 2001 From: nasli Date: Wed, 18 Oct 2017 17:02:02 +0200 Subject: [PATCH 50/50] Test adding cookies to avoid reject from F5 --- .../OCOAuth2Authentication/OCOAuth2Manager.m | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m index 0d76c036..88bbf653 100644 --- a/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m +++ b/OCCommunicationLib/OCCommunicationLib/OCOAuth2Authentication/OCOAuth2Manager.m @@ -125,6 +125,9 @@ - (void) authDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con withCompletion:(void(^)(NSData *data,NSHTTPURLResponse *httpResponse, NSError *error))completion { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + + request = [UtilsFramework getRequestWithCookiesByRequest:request andOriginalUrlServer:url.absoluteString]; + [request setHTTPMethod:@"POST"]; if (userAgent != nil) { [request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; @@ -175,7 +178,7 @@ - (void) refreshAuthDataByOAuth2Configuration:(OCOAuth2Configuration *)oauth2Con success:(void(^)(OCCredentialsDto *userCredDto))success failure:(void(^)(NSError *error))failure { - [UtilsFramework deleteAllCookies]; + //[UtilsFramework deleteAllCookies]; [self refreshAuthDataRequestByOAuth2Configuration:oauth2Configuration withBaseURL:baseURL refreshToken:refreshToken userAgent:userAgent @@ -235,6 +238,8 @@ - (void) refreshAuthDataRequestByOAuth2Configuration:(OCOAuth2Configuration *)oa NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlToGetToken]; + request = [UtilsFramework getRequestWithCookiesByRequest:request andOriginalUrlServer:baseURL]; + [request setHTTPMethod:@"POST"]; if (userAgent != nil) { [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];