GIDEMMErrorHandler.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import <TargetConditionals.h>
  15. #if TARGET_OS_IOS
  16. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  17. #import <UIKit/UIKit.h>
  18. #import "GoogleSignIn/Sources/GIDSignInStrings.h"
  19. NS_ASSUME_NONNULL_BEGIN
  20. // The error key in the server response.
  21. static NSString *const kErrorKey = @"error";
  22. // Error strings in the server response.
  23. static NSString *const kGeneralErrorPrefix = @"emm_";
  24. static NSString *const kScreenlockRequiredError = @"emm_passcode_required";
  25. static NSString *const kAppVerificationRequiredErrorPrefix = @"emm_app_verification_required";
  26. // Optional separator between error prefix and the payload.
  27. static NSString *const kErrorPayloadSeparator = @":";
  28. // A list for recognized error codes.
  29. typedef enum {
  30. ErrorCodeNone = 0,
  31. ErrorCodeDeviceNotCompliant,
  32. ErrorCodeScreenlockRequired,
  33. ErrorCodeAppVerificationRequired,
  34. } ErrorCode;
  35. @implementation GIDEMMErrorHandler {
  36. // Whether or not a dialog is pending user interaction.
  37. BOOL _pendingDialog;
  38. }
  39. + (instancetype)sharedInstance {
  40. static dispatch_once_t once;
  41. static GIDEMMErrorHandler *sharedInstance;
  42. dispatch_once(&once, ^{
  43. sharedInstance = [[self alloc] init];
  44. });
  45. return sharedInstance;
  46. }
  47. - (BOOL)handleErrorFromResponse:(NSDictionary<NSString *, id> *)response
  48. completion:(void (^)(void))completion {
  49. ErrorCode errorCode = ErrorCodeNone;
  50. NSURL *appVerificationURL;
  51. @synchronized(self) { // for accessing _pendingDialog
  52. if (!_pendingDialog && [UIAlertController class] &&
  53. [response isKindOfClass:[NSDictionary class]]) {
  54. id errorValue = response[kErrorKey];
  55. if ([errorValue isEqual:kScreenlockRequiredError]) {
  56. errorCode = ErrorCodeScreenlockRequired;
  57. } else if ([errorValue hasPrefix:kAppVerificationRequiredErrorPrefix]) {
  58. errorCode = ErrorCodeAppVerificationRequired;
  59. NSString *appVerificationString =
  60. [errorValue substringFromIndex:kAppVerificationRequiredErrorPrefix.length];
  61. if ([appVerificationString hasPrefix:kErrorPayloadSeparator]) {
  62. appVerificationString =
  63. [appVerificationString substringFromIndex:kErrorPayloadSeparator.length];
  64. }
  65. appVerificationString = [appVerificationString
  66. stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  67. if (appVerificationString.length) {
  68. appVerificationURL = [NSURL URLWithString:appVerificationString];
  69. }
  70. } else if ([errorValue hasPrefix:kGeneralErrorPrefix]) {
  71. errorCode = ErrorCodeDeviceNotCompliant;
  72. }
  73. if (errorCode) {
  74. _pendingDialog = YES;
  75. }
  76. }
  77. }
  78. if (!errorCode) {
  79. completion();
  80. return NO;
  81. }
  82. // All UI must happen in the main thread.
  83. dispatch_async(dispatch_get_main_queue(), ^() {
  84. UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
  85. CGRect keyWindowBounds = CGRectIsEmpty(keyWindow.bounds) ?
  86. keyWindow.bounds : [UIScreen mainScreen].bounds;
  87. UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:keyWindowBounds];
  88. alertWindow.backgroundColor = [UIColor clearColor];
  89. alertWindow.rootViewController = [[UIViewController alloc] init];
  90. alertWindow.rootViewController.view.backgroundColor = [UIColor clearColor];
  91. alertWindow.windowLevel = UIWindowLevelAlert;
  92. [alertWindow makeKeyAndVisible];
  93. void (^finish)(void) = ^{
  94. alertWindow.hidden = YES;
  95. alertWindow.rootViewController = nil;
  96. [keyWindow makeKeyAndVisible];
  97. self->_pendingDialog = NO;
  98. completion();
  99. };
  100. UIAlertController *alert;
  101. switch (errorCode) {
  102. case ErrorCodeNone:
  103. break;
  104. case ErrorCodeScreenlockRequired:
  105. alert = [self passcodeRequiredAlertWithCompletion:finish];
  106. break;
  107. case ErrorCodeAppVerificationRequired:
  108. alert = [self appVerificationRequiredAlertWithURL:appVerificationURL completion:finish];
  109. break;
  110. case ErrorCodeDeviceNotCompliant:
  111. alert = [self deviceNotCompliantAlertWithCompletion:finish];
  112. break;
  113. }
  114. if (alert) {
  115. [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  116. } else {
  117. // Should not happen but just in case.
  118. finish();
  119. }
  120. });
  121. return YES;
  122. }
  123. #pragma mark - Alerts
  124. // Returns an alert controller for device not compliant error.
  125. - (UIAlertController *)deviceNotCompliantAlertWithCompletion:(void (^)(void))completion {
  126. UIAlertController *alert =
  127. [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  128. message:[self deviceNotCompliantString]
  129. preferredStyle:UIAlertControllerStyleAlert];
  130. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  131. style:UIAlertActionStyleDefault
  132. handler:^(UIAlertAction *action) {
  133. completion();
  134. }]];
  135. return alert;
  136. };
  137. // Returns an alert controller for passcode required error.
  138. - (UIAlertController *)passcodeRequiredAlertWithCompletion:(void (^)(void))completion {
  139. UIAlertController *alert =
  140. [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  141. message:[self passcodeRequiredString]
  142. preferredStyle:UIAlertControllerStyleAlert];
  143. BOOL canOpenSettings = YES;
  144. if ([[UIDevice currentDevice].systemVersion hasPrefix:@"10."]) {
  145. // In iOS 10, `UIApplicationOpenSettingsURLString` fails to open the Settings app if the
  146. // opening app does not have Setting bundle.
  147. NSString* mainBundlePath = [[NSBundle mainBundle] resourcePath];
  148. NSString* settingsBundlePath = [mainBundlePath
  149. stringByAppendingPathComponent:@"Settings.bundle"];
  150. if (![NSBundle bundleWithPath:settingsBundlePath]) {
  151. canOpenSettings = NO;
  152. }
  153. }
  154. if (canOpenSettings) {
  155. [alert addAction:[UIAlertAction actionWithTitle:[self cancelString]
  156. style:UIAlertActionStyleCancel
  157. handler:^(UIAlertAction *action) {
  158. completion();
  159. }]];
  160. [alert addAction:[UIAlertAction actionWithTitle:[self settingsString]
  161. style:UIAlertActionStyleDefault
  162. handler:^(UIAlertAction *action) {
  163. completion();
  164. [[UIApplication sharedApplication]
  165. openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  166. }]];
  167. } else {
  168. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  169. style:UIAlertActionStyleCancel
  170. handler:^(UIAlertAction *action) {
  171. completion();
  172. }]];
  173. }
  174. return alert;
  175. };
  176. // Returns an alert controller for app verification required error.
  177. - (UIAlertController *)appVerificationRequiredAlertWithURL:(nullable NSURL *)url
  178. completion:(void (^)(void))completion {
  179. UIAlertController *alert;
  180. if (url) {
  181. // If the URL is provided, prompt user to open this URL or cancel.
  182. alert = [UIAlertController alertControllerWithTitle:[self appVerificationTitleString]
  183. message:[self appVerificationTextString]
  184. preferredStyle:UIAlertControllerStyleAlert];
  185. [alert addAction:[UIAlertAction actionWithTitle:[self cancelString]
  186. style:UIAlertActionStyleCancel
  187. handler:^(UIAlertAction *action) {
  188. completion();
  189. }]];
  190. [alert addAction:[UIAlertAction actionWithTitle:[self appVerificationActionString]
  191. style:UIAlertActionStyleDefault
  192. handler:^(UIAlertAction *action) {
  193. completion();
  194. [[UIApplication sharedApplication] openURL:url];
  195. }]];
  196. } else {
  197. // If the URL is not provided, simple let user acknowledge the issue. This is not supposed to
  198. // happen but just to fail gracefully.
  199. alert = [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  200. message:[self appVerificationTextString]
  201. preferredStyle:UIAlertControllerStyleAlert];
  202. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  203. style:UIAlertActionStyleDefault
  204. handler:^(UIAlertAction *action) {
  205. completion();
  206. }]];
  207. }
  208. return alert;
  209. }
  210. #pragma mark - Localization
  211. // The English version of the strings are used as back-up in case the bundle resource is missing
  212. // from the third-party app. Please keep them in sync with the strings in the bundle.
  213. // Returns a localized string for unable to access the account.
  214. - (NSString *)unableToAccessString {
  215. return [GIDSignInStrings localizedStringForKey:@"EmmErrorTitle"
  216. text:@"Unable to sign in to account"];
  217. }
  218. // Returns a localized string for device passcode required error.
  219. - (NSString *)passcodeRequiredString {
  220. NSString *defaultText =
  221. @"Your administrator requires you to set a passcode on this device to access this account. "
  222. "Please set a passcode and try again.";
  223. return [GIDSignInStrings localizedStringForKey:@"EmmPasscodeRequired" text:defaultText];
  224. }
  225. // Returns a localized string for app verification error dialog title.
  226. - (NSString *)appVerificationTitleString {
  227. return [GIDSignInStrings localizedStringForKey:@"EmmConnectTitle"
  228. text:@"Connect with Device Policy App?"];
  229. }
  230. // Returns a localized string for app verification error dialog message.
  231. - (NSString *)appVerificationTextString {
  232. NSString *defaultText = @"In order to protect your organization's data, "
  233. "you must connect with the Device Policy app before logging in.";
  234. return [GIDSignInStrings localizedStringForKey:@"EmmConnectText" text:defaultText];
  235. }
  236. // Returns a localized string for app verification error dialog action button label.
  237. - (NSString *)appVerificationActionString {
  238. return [GIDSignInStrings localizedStringForKey:@"EmmConnectLabel" text:@"Connect"];
  239. }
  240. // Returns a localized string for general device non-compliance error.
  241. - (NSString *)deviceNotCompliantString {
  242. NSString *defaultText =
  243. @"The device is not compliant with the security policy set by your administrator.";
  244. return [GIDSignInStrings localizedStringForKey:@"EmmGeneralError" text:defaultText];
  245. }
  246. // Returns a localized string for "Settings".
  247. - (NSString *)settingsString {
  248. return [GIDSignInStrings localizedStringForKey:@"SettingsAppName" text:@"Settings"];
  249. }
  250. // Returns a localized string for "OK".
  251. - (NSString *)okayString {
  252. return [GIDSignInStrings localizedStringForKey:@"OK" text:@"OK"];
  253. }
  254. // Returns a localized string for "Cancel".
  255. - (NSString *)cancelString {
  256. return [GIDSignInStrings localizedStringForKey:@"Cancel" text:@"Cancel"];
  257. }
  258. @end
  259. NS_ASSUME_NONNULL_END
  260. #endif