|
| 1 | +import AuthenticationServices |
| 2 | +import OSLog |
| 3 | +import UIKit |
| 4 | + |
| 5 | +/// Google sign-in delegate. |
| 6 | +public protocol OpenGoogleSignInDelegate: AnyObject { |
| 7 | + /// Indicates that sign-in flow has finished and retrieves `GoogleUser` if successful or `error`. |
| 8 | + func sign(didSignInFor user: GoogleUser?, withError error: GoogleSignInError?) |
| 9 | +} |
| 10 | + |
| 11 | +/// Signs the user in with Google using OAuth 2.0. |
| 12 | +public final class OpenGoogleSignIn: NSObject { |
| 13 | + |
| 14 | + // MARK: - Public properties |
| 15 | + |
| 16 | + public weak var delegate: OpenGoogleSignInDelegate? |
| 17 | + |
| 18 | + /// The client ID of the app. |
| 19 | + /// It is required for communication with Google API to work. |
| 20 | + public var clientID: String = "" |
| 21 | + |
| 22 | + /// Client secret. |
| 23 | + /// It is only used when exchanging the authorization code for an access token. |
| 24 | + public var clientSecret: String = "" |
| 25 | + |
| 26 | + /// `URLSession` used to perform data tasks. |
| 27 | + public var session: URLSession = URLSession.shared |
| 28 | + |
| 29 | + /// Shared `OpenGoogleSignIn` instance |
| 30 | + public static let shared: OpenGoogleSignIn = OpenGoogleSignIn() |
| 31 | + |
| 32 | + /// API scopes requested by the app |
| 33 | + public var scopes: Set<GoogleSignInScope> = [.email, .openID, .profile] |
| 34 | + |
| 35 | + /// View controller to present Google sign-in flow. |
| 36 | + /// Needs to be set for presenting to work correctly. |
| 37 | + public weak var presentingViewController: UIViewController? = nil |
| 38 | + |
| 39 | + // MARK: - Private properties |
| 40 | + |
| 41 | + /// Session used to authenticate a user with Google sign-in. |
| 42 | + private var authenticationSession: ASWebAuthenticationSession? = nil |
| 43 | + |
| 44 | + /// Google API OAuth 2.0 token url. |
| 45 | + private static let tokenURL: URL? = URL(string: "https://www.googleapis.com/oauth2/v4/token") |
| 46 | + |
| 47 | + /// The client's redirect URI, which is based on `clientID`. |
| 48 | + private var redirectURI: String { |
| 49 | + String( |
| 50 | + clientID |
| 51 | + .components(separatedBy: ".") |
| 52 | + .reversed() |
| 53 | + .joined(separator: ".") |
| 54 | + ) + ":/oauth2redirect/google" |
| 55 | + } |
| 56 | + |
| 57 | + /// Authorization `URL` based on parameters provided by the app. |
| 58 | + private var authURL: URL { |
| 59 | + let scopes = scopes.map { $0.rawValue }.joined(separator: "+") |
| 60 | + var components = URLComponents() |
| 61 | + |
| 62 | + components.scheme = "https" |
| 63 | + components.host = "accounts.google.com" |
| 64 | + components.path = "/o/oauth2/v2/auth" |
| 65 | + |
| 66 | + components.queryItems = [ |
| 67 | + URLQueryItem(name: "client_id", value: clientID), |
| 68 | + URLQueryItem(name: "redirect_uri", value: redirectURI), |
| 69 | + URLQueryItem(name: "response_type", value: "code"), |
| 70 | + URLQueryItem(name: "scope", value: scopes) |
| 71 | + ] |
| 72 | + |
| 73 | + return components.url! |
| 74 | + } |
| 75 | + |
| 76 | + // MARK: - Initialization |
| 77 | + |
| 78 | + private override init() { } |
| 79 | + |
| 80 | + // MARK: - Public helpers |
| 81 | + |
| 82 | + |
| 83 | + /// Handles token response. |
| 84 | + /// Calls `OpenGoogleSignInDelegate` with valid response or error. |
| 85 | + public func handle(_ url: URL) { |
| 86 | + handleTokenResponse(using: url) { [weak self] result in |
| 87 | + switch result { |
| 88 | + case .success(let response): |
| 89 | + self?.delegate?.sign(didSignInFor: response, withError: nil) |
| 90 | + case .failure(let error): |
| 91 | + self?.delegate?.sign(didSignInFor: nil, withError: error) |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + /// Starts Google sign-in flow. |
| 97 | + /// `OpenGoogleSignInDelegate` will be called on success/error. |
| 98 | + public func signIn() { |
| 99 | + guard !clientID.isEmpty else { |
| 100 | + os_log(.error, "You must specify clientID for Google sign-in to work correctly!") |
| 101 | + return |
| 102 | + } |
| 103 | + |
| 104 | + // Create authentication session with provided parameters |
| 105 | + authenticationSession = ASWebAuthenticationSession( |
| 106 | + url: authURL, |
| 107 | + callbackURLScheme: clientID |
| 108 | + ) { [weak self] callbackURL, error in |
| 109 | + guard let callbackURL = callbackURL else { return } |
| 110 | + |
| 111 | + if let error = error { |
| 112 | + // Throw error if received |
| 113 | + self?.delegate?.sign(didSignInFor: nil, withError: .authenticationError(error)) |
| 114 | + } else { |
| 115 | + // Handle received `callbackURL` on success |
| 116 | + self?.handle(callbackURL) |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // Set `presentationContextProvider` for iOS 13+ modals to work correctly |
| 121 | + if #available(iOS 13.0, *) { |
| 122 | + authenticationSession?.presentationContextProvider = self |
| 123 | + } |
| 124 | + |
| 125 | + // Start authentication session |
| 126 | + authenticationSession?.start() |
| 127 | + } |
| 128 | + |
| 129 | + // MARK: - Private helpers |
| 130 | + |
| 131 | + /// Decodes `GoogleUser` from OAuth 2.0 response. |
| 132 | + private func decodeUser(from data: Data) throws -> GoogleUser { |
| 133 | + let decoder = JSONDecoder() |
| 134 | + decoder.keyDecodingStrategy = .convertFromSnakeCase |
| 135 | + |
| 136 | + return try decoder.decode(GoogleUser.self, from: data) |
| 137 | + } |
| 138 | + |
| 139 | + /// Handles OAuth 2.0 token response. |
| 140 | + private func handleTokenResponse(using redirectUrl: URL, completion: @escaping (Result<GoogleUser, GoogleSignInError>) -> Void) { |
| 141 | + guard let code = self.parseCode(from: redirectUrl) else { |
| 142 | + completion(.failure(.invalidCode)) |
| 143 | + return |
| 144 | + } |
| 145 | + |
| 146 | + guard let tokenRequest = makeTokenRequest(with: code) else { |
| 147 | + completion(.failure(.invalidTokenRequest)) |
| 148 | + return |
| 149 | + } |
| 150 | + |
| 151 | + let task = session.dataTask(with: tokenRequest) { data, response, error in |
| 152 | + if let error = error { |
| 153 | + completion(.failure(.networkError(error))) |
| 154 | + return |
| 155 | + } |
| 156 | + |
| 157 | + guard let data = data else { |
| 158 | + completion(.failure(.invalidResponse)) |
| 159 | + return |
| 160 | + } |
| 161 | + |
| 162 | + do { |
| 163 | + completion(.success(try self.decodeUser(from: data))) |
| 164 | + } catch { |
| 165 | + completion(.failure(.tokenDecodingError(error))) |
| 166 | + } |
| 167 | + } |
| 168 | + task.resume() |
| 169 | + } |
| 170 | + |
| 171 | + /// Returns `code` parsed from provided `redirectURL`. |
| 172 | + private func parseCode(from redirectURL: URL) -> String? { |
| 173 | + let components = URLComponents(url: redirectURL, resolvingAgainstBaseURL: false) |
| 174 | + |
| 175 | + return components?.queryItems?.first(where: { $0.name == "code" })?.value |
| 176 | + } |
| 177 | + |
| 178 | + /// Returns `URLRequest` to retrieve Google sign-in OAuth 2.0 token using arameters provided by the app. |
| 179 | + private func makeTokenRequest(with code: String) -> URLRequest? { |
| 180 | + guard let tokenURL = OpenGoogleSignIn.tokenURL else { return nil } |
| 181 | + |
| 182 | + var request = URLRequest(url: tokenURL) |
| 183 | + request.httpMethod = "POST" |
| 184 | + request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") |
| 185 | + |
| 186 | + let parameters = [ |
| 187 | + "client_id": clientID, |
| 188 | + "client_secret": clientSecret, |
| 189 | + "code": code, |
| 190 | + "grant_type": "authorization_code", |
| 191 | + "redirect_uri": redirectURI |
| 192 | + ] |
| 193 | + |
| 194 | + let body = parameters |
| 195 | + .map { "\($0)=\($1)" } |
| 196 | + .joined(separator: "&") |
| 197 | + |
| 198 | + request.httpBody = body.data(using: .utf8) |
| 199 | + |
| 200 | + return request |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +// MARK: - ASWebAuthenticationPresentationContextProviding |
| 205 | + |
| 206 | +extension OpenGoogleSignIn: ASWebAuthenticationPresentationContextProviding { |
| 207 | + public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { |
| 208 | + UIApplication.shared.windows.first { $0.isKeyWindow } ?? ASPresentationAnchor() |
| 209 | + } |
| 210 | +} |
0 commit comments