GIDEMMErrorHandler.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 = [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 (@available(iOS 15, *)) {
  139. for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
  140. if ([scene isKindOfClass:[UIWindowScene class]] &&
  141. scene.activationState == UISceneActivationStateForegroundActive) {
  142. return ((UIWindowScene *)scene).keyWindow;
  143. }
  144. }
  145. } else {
  146. #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0
  147. if (@available(iOS 13, *)) {
  148. for (UIWindow *window in UIApplication.sharedApplication.windows) {
  149. if (window.isKeyWindow) {
  150. return window;
  151. }
  152. }
  153. } else {
  154. #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_13_0
  155. return UIApplication.sharedApplication.keyWindow;
  156. #endif // __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_13_0
  157. }
  158. #endif // __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0
  159. }
  160. return nil;
  161. }
  162. #pragma mark - Alerts
  163. // Returns an alert controller for device not compliant error.
  164. - (UIAlertController *)deviceNotCompliantAlertWithCompletion:(void (^)(void))completion {
  165. UIAlertController *alert =
  166. [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  167. message:[self deviceNotCompliantString]
  168. preferredStyle:UIAlertControllerStyleAlert];
  169. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  170. style:UIAlertActionStyleDefault
  171. handler:^(UIAlertAction *action) {
  172. completion();
  173. }]];
  174. return alert;
  175. };
  176. // Returns an alert controller for passcode required error.
  177. - (UIAlertController *)passcodeRequiredAlertWithCompletion:(void (^)(void))completion {
  178. UIAlertController *alert =
  179. [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  180. message:[self passcodeRequiredString]
  181. preferredStyle:UIAlertControllerStyleAlert];
  182. BOOL canOpenSettings = YES;
  183. if ([[UIDevice currentDevice].systemVersion hasPrefix:@"10."]) {
  184. // In iOS 10, `UIApplicationOpenSettingsURLString` fails to open the Settings app if the
  185. // opening app does not have Setting bundle.
  186. NSString* mainBundlePath = [[NSBundle mainBundle] resourcePath];
  187. NSString* settingsBundlePath = [mainBundlePath
  188. stringByAppendingPathComponent:@"Settings.bundle"];
  189. if (![NSBundle bundleWithPath:settingsBundlePath]) {
  190. canOpenSettings = NO;
  191. }
  192. }
  193. if (canOpenSettings) {
  194. [alert addAction:[UIAlertAction actionWithTitle:[self cancelString]
  195. style:UIAlertActionStyleCancel
  196. handler:^(UIAlertAction *action) {
  197. completion();
  198. }]];
  199. [alert addAction:[UIAlertAction actionWithTitle:[self settingsString]
  200. style:UIAlertActionStyleDefault
  201. handler:^(UIAlertAction *action) {
  202. completion();
  203. [self openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  204. }]];
  205. } else {
  206. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  207. style:UIAlertActionStyleCancel
  208. handler:^(UIAlertAction *action) {
  209. completion();
  210. }]];
  211. }
  212. return alert;
  213. };
  214. // Returns an alert controller for app verification required error.
  215. - (UIAlertController *)appVerificationRequiredAlertWithURL:(nullable NSURL *)url
  216. completion:(void (^)(void))completion {
  217. UIAlertController *alert;
  218. if (url) {
  219. // If the URL is provided, prompt user to open this URL or cancel.
  220. alert = [UIAlertController alertControllerWithTitle:[self appVerificationTitleString]
  221. message:[self appVerificationTextString]
  222. preferredStyle:UIAlertControllerStyleAlert];
  223. [alert addAction:[UIAlertAction actionWithTitle:[self cancelString]
  224. style:UIAlertActionStyleCancel
  225. handler:^(UIAlertAction *action) {
  226. completion();
  227. }]];
  228. [alert addAction:[UIAlertAction actionWithTitle:[self appVerificationActionString]
  229. style:UIAlertActionStyleDefault
  230. handler:^(UIAlertAction *action) {
  231. completion();
  232. [self openURL:url];
  233. }]];
  234. } else {
  235. // If the URL is not provided, simple let user acknowledge the issue. This is not supposed to
  236. // happen but just to fail gracefully.
  237. alert = [UIAlertController alertControllerWithTitle:[self unableToAccessString]
  238. message:[self appVerificationTextString]
  239. preferredStyle:UIAlertControllerStyleAlert];
  240. [alert addAction:[UIAlertAction actionWithTitle:[self okayString]
  241. style:UIAlertActionStyleDefault
  242. handler:^(UIAlertAction *action) {
  243. completion();
  244. }]];
  245. }
  246. return alert;
  247. }
  248. - (void)openURL:(NSURL *)url {
  249. if (@available(iOS 10, *)) {
  250. [UIApplication.sharedApplication openURL:url options:@{} completionHandler:nil];
  251. } else {
  252. #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
  253. [UIApplication.sharedApplication openURL:url];
  254. #endif // __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
  255. }
  256. }
  257. #pragma mark - Localization
  258. // The English version of the strings are used as back-up in case the bundle resource is missing
  259. // from the third-party app. Please keep them in sync with the strings in the bundle.
  260. // Returns a localized string for unable to access the account.
  261. - (NSString *)unableToAccessString {
  262. return [GIDSignInStrings localizedStringForKey:@"EmmErrorTitle"
  263. text:@"Unable to sign in to account"];
  264. }
  265. // Returns a localized string for device passcode required error.
  266. - (NSString *)passcodeRequiredString {
  267. NSString *defaultText =
  268. @"Your administrator requires you to set a passcode on this device to access this account. "
  269. "Please set a passcode and try again.";
  270. return [GIDSignInStrings localizedStringForKey:@"EmmPasscodeRequired" text:defaultText];
  271. }
  272. // Returns a localized string for app verification error dialog title.
  273. - (NSString *)appVerificationTitleString {
  274. return [GIDSignInStrings localizedStringForKey:@"EmmConnectTitle"
  275. text:@"Connect with Device Policy App?"];
  276. }
  277. // Returns a localized string for app verification error dialog message.
  278. - (NSString *)appVerificationTextString {
  279. NSString *defaultText = @"In order to protect your organization's data, "
  280. "you must connect with the Device Policy app before logging in.";
  281. return [GIDSignInStrings localizedStringForKey:@"EmmConnectText" text:defaultText];
  282. }
  283. // Returns a localized string for app verification error dialog action button label.
  284. - (NSString *)appVerificationActionString {
  285. return [GIDSignInStrings localizedStringForKey:@"EmmConnectLabel" text:@"Connect"];
  286. }
  287. // Returns a localized string for general device non-compliance error.
  288. - (NSString *)deviceNotCompliantString {
  289. NSString *defaultText =
  290. @"The device is not compliant with the security policy set by your administrator.";
  291. return [GIDSignInStrings localizedStringForKey:@"EmmGeneralError" text:defaultText];
  292. }
  293. // Returns a localized string for "Settings".
  294. - (NSString *)settingsString {
  295. return [GIDSignInStrings localizedStringForKey:@"SettingsAppName" text:@"Settings"];
  296. }
  297. // Returns a localized string for "OK".
  298. - (NSString *)okayString {
  299. return [GIDSignInStrings localizedStringForKey:@"OK" text:@"OK"];
  300. }
  301. // Returns a localized string for "Cancel".
  302. - (NSString *)cancelString {
  303. return [GIDSignInStrings localizedStringForKey:@"Cancel" text:@"Cancel"];
  304. }
  305. @end
  306. NS_ASSUME_NONNULL_END
  307. #endif