GIDEMMErrorHandler.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 && !TARGET_OS_MACCATALYST
  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 = [self keyWindow];
  85. if (!keyWindow) {
  86. // Shouldn't happen, just in case.
  87. completion();
  88. return;
  89. }
  90. UIWindow *alertWindow;
  91. if (@available(iOS 13, *)) {
  92. if (keyWindow.windowScene) {
  93. alertWindow = [[UIWindow alloc] initWithWindowScene:keyWindow.windowScene];
  94. }
  95. }
  96. if (!alertWindow) {
  97. CGRect keyWindowBounds = CGRectIsEmpty(keyWindow.bounds) ?
  98. keyWindow.bounds : [UIScreen mainScreen].bounds;
  99. alertWindow = [[UIWindow alloc] initWithFrame:keyWindowBounds];
  100. }
  101. alertWindow.backgroundColor = [UIColor clearColor];
  102. alertWindow.rootViewController = [[UIViewController alloc] init];
  103. alertWindow.rootViewController.view.backgroundColor = [UIColor clearColor];
  104. alertWindow.windowLevel = UIWindowLevelAlert;
  105. [alertWindow makeKeyAndVisible];
  106. void (^finish)(void) = ^{
  107. alertWindow.hidden = YES;
  108. alertWindow.rootViewController = nil;
  109. [keyWindow makeKeyAndVisible];
  110. self->_pendingDialog = NO;
  111. completion();
  112. };
  113. UIAlertController *alert;
  114. switch (errorCode) {
  115. case ErrorCodeNone:
  116. break;
  117. case ErrorCodeScreenlockRequired:
  118. alert = [self passcodeRequiredAlertWithCompletion:finish];
  119. break;
  120. case ErrorCodeAppVerificationRequired:
  121. alert = [self appVerificationRequiredAlertWithURL:appVerificationURL completion:finish];
  122. break;
  123. case ErrorCodeDeviceNotCompliant:
  124. alert = [self deviceNotCompliantAlertWithCompletion:finish];
  125. break;
  126. }
  127. if (alert) {
  128. [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  129. } else {
  130. // Should not happen but just in case.
  131. finish();
  132. }
  133. });
  134. return YES;
  135. }
  136. // This method is exposed to the unit test.
  137. - (nullable UIWindow *)keyWindow {
  138. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000
  139. if (@available(iOS 15, *)) {
  140. for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
  141. if ([scene isKindOfClass:[UIWindowScene class]] &&
  142. scene.activationState == UISceneActivationStateForegroundActive) {
  143. return ((UIWindowScene *)scene).keyWindow;
  144. }
  145. }
  146. } else
  147. #endif // __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000
  148. {
  149. #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0
  150. if (@available(iOS 13, *)) {
  151. for (UIWindow *window in UIApplication.sharedApplication.windows) {
  152. if (window.isKeyWindow) {
  153. return window;
  154. }
  155. }
  156. } else {
  157. #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_13_0
  158. return UIApplication.sharedApplication.keyWindow;
  159. #endif // __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_13_0
  160. }
  161. #endif // __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0
  162. }
  163. return nil;
  164. }
  165. #pragma mark - Alerts
  166. // Returns an alert controller for device not compliant error.
  167. - (UIAlertController *)deviceNotCompliantAlertWithCompletion:(void (^)(void))completion {
  168. UIAlertController *alert =
  169. [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  170. message:[self deviceNotCompliantString]
  171. preferredStyle:UIAlertControllerStyleAlert];
  172. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  173. style:UIAlertActionStyleDefault
  174. handler:^(UIAlertAction *action) {
  175. completion();
  176. }]];
  177. return alert;
  178. };
  179. // Returns an alert controller for passcode required error.
  180. - (UIAlertController *)passcodeRequiredAlertWithCompletion:(void (^)(void))completion {
  181. UIAlertController *alert =
  182. [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  183. message:[self passcodeRequiredString]
  184. preferredStyle:UIAlertControllerStyleAlert];
  185. BOOL canOpenSettings = YES;
  186. if ([[UIDevice currentDevice].systemVersion hasPrefix:@"10."]) {
  187. // In iOS 10, `UIApplicationOpenSettingsURLString` fails to open the Settings app if the
  188. // opening app does not have Setting bundle.
  189. NSString* mainBundlePath = [[NSBundle mainBundle] resourcePath];
  190. NSString* settingsBundlePath = [mainBundlePath
  191. stringByAppendingPathComponent:@"Settings.bundle"];
  192. if (![NSBundle bundleWithPath:settingsBundlePath]) {
  193. canOpenSettings = NO;
  194. }
  195. }
  196. if (canOpenSettings) {
  197. [alert addAction:[UIAlertAction actionWithTitle:[self cancelString]
  198. style:UIAlertActionStyleCancel
  199. handler:^(UIAlertAction *action) {
  200. completion();
  201. }]];
  202. [alert addAction:[UIAlertAction actionWithTitle:[self settingsString]
  203. style:UIAlertActionStyleDefault
  204. handler:^(UIAlertAction *action) {
  205. completion();
  206. [self openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  207. }]];
  208. } else {
  209. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  210. style:UIAlertActionStyleCancel
  211. handler:^(UIAlertAction *action) {
  212. completion();
  213. }]];
  214. }
  215. return alert;
  216. };
  217. // Returns an alert controller for app verification required error.
  218. - (UIAlertController *)appVerificationRequiredAlertWithURL:(nullable NSURL *)url
  219. completion:(void (^)(void))completion {
  220. UIAlertController *alert;
  221. if (url) {
  222. // If the URL is provided, prompt user to open this URL or cancel.
  223. alert = [UIAlertController alertControllerWithTitle:[self appVerificationTitleString]
  224. message:[self appVerificationTextString]
  225. preferredStyle:UIAlertControllerStyleAlert];
  226. [alert addAction:[UIAlertAction actionWithTitle:[self cancelString]
  227. style:UIAlertActionStyleCancel
  228. handler:^(UIAlertAction *action) {
  229. completion();
  230. }]];
  231. [alert addAction:[UIAlertAction actionWithTitle:[self appVerificationActionString]
  232. style:UIAlertActionStyleDefault
  233. handler:^(UIAlertAction *action) {
  234. completion();
  235. [self openURL:url];
  236. }]];
  237. } else {
  238. // If the URL is not provided, simple let user acknowledge the issue. This is not supposed to
  239. // happen but just to fail gracefully.
  240. alert = [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  241. message:[self appVerificationTextString]
  242. preferredStyle:UIAlertControllerStyleAlert];
  243. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  244. style:UIAlertActionStyleDefault
  245. handler:^(UIAlertAction *action) {
  246. completion();
  247. }]];
  248. }
  249. return alert;
  250. }
  251. - (void)openURL:(NSURL *)url {
  252. if (@available(iOS 10, *)) {
  253. [UIApplication.sharedApplication openURL:url options:@{} completionHandler:nil];
  254. } else {
  255. #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
  256. [UIApplication.sharedApplication openURL:url];
  257. #endif // __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
  258. }
  259. }
  260. #pragma mark - Localization
  261. // The English version of the strings are used as back-up in case the bundle resource is missing
  262. // from the third-party app. Please keep them in sync with the strings in the bundle.
  263. // Returns a localized string for unable to access the account.
  264. - (NSString *)unableToAccessString {
  265. return [GIDSignInStrings localizedStringForKey:@"EmmErrorTitle"
  266. text:@"Unable to sign in to account"];
  267. }
  268. // Returns a localized string for device passcode required error.
  269. - (NSString *)passcodeRequiredString {
  270. NSString *defaultText =
  271. @"Your administrator requires you to set a passcode on this device to access this account. "
  272. "Please set a passcode and try again.";
  273. return [GIDSignInStrings localizedStringForKey:@"EmmPasscodeRequired" text:defaultText];
  274. }
  275. // Returns a localized string for app verification error dialog title.
  276. - (NSString *)appVerificationTitleString {
  277. return [GIDSignInStrings localizedStringForKey:@"EmmConnectTitle"
  278. text:@"Connect with Device Policy App?"];
  279. }
  280. // Returns a localized string for app verification error dialog message.
  281. - (NSString *)appVerificationTextString {
  282. NSString *defaultText = @"In order to protect your organization's data, "
  283. "you must connect with the Device Policy app before logging in.";
  284. return [GIDSignInStrings localizedStringForKey:@"EmmConnectText" text:defaultText];
  285. }
  286. // Returns a localized string for app verification error dialog action button label.
  287. - (NSString *)appVerificationActionString {
  288. return [GIDSignInStrings localizedStringForKey:@"EmmConnectLabel" text:@"Connect"];
  289. }
  290. // Returns a localized string for general device non-compliance error.
  291. - (NSString *)deviceNotCompliantString {
  292. NSString *defaultText =
  293. @"The device is not compliant with the security policy set by your administrator.";
  294. return [GIDSignInStrings localizedStringForKey:@"EmmGeneralError" text:defaultText];
  295. }
  296. // Returns a localized string for "Settings".
  297. - (NSString *)settingsString {
  298. return [GIDSignInStrings localizedStringForKey:@"SettingsAppName" text:@"Settings"];
  299. }
  300. // Returns a localized string for "OK".
  301. - (NSString *)okayString {
  302. return [GIDSignInStrings localizedStringForKey:@"OK" text:@"OK"];
  303. }
  304. // Returns a localized string for "Cancel".
  305. - (NSString *)cancelString {
  306. return [GIDSignInStrings localizedStringForKey:@"Cancel" text:@"Cancel"];
  307. }
  308. @end
  309. NS_ASSUME_NONNULL_END
  310. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST