diff --git a/OAuth2.xcodeproj/project.pbxproj b/OAuth2.xcodeproj/project.pbxproj index bb9bdf5..5333d04 100644 --- a/OAuth2.xcodeproj/project.pbxproj +++ b/OAuth2.xcodeproj/project.pbxproj @@ -9,6 +9,10 @@ /* Begin PBXBuildFile section */ 0C2F5E5B1DE2DB8500F621E0 /* OAuth2CodeGrantAzure.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C2F5E5A1DE2DB8500F621E0 /* OAuth2CodeGrantAzure.swift */; }; 19C919DD1E51CC8000BFC834 /* OAuth2CustomAuthorizer+macOS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19C919DC1E51CC8000BFC834 /* OAuth2CustomAuthorizer+macOS.swift */; }; + 5EA7ED3A2E6ED86100124A26 /* Logging in Frameworks */ = {isa = PBXBuildFile; productRef = 5EA7ED392E6ED86100124A26 /* Logging */; }; + 5EA7ED3C2E6ED87300124A26 /* Logging in Frameworks */ = {isa = PBXBuildFile; productRef = 5EA7ED3B2E6ED87300124A26 /* Logging */; }; + 5EA7ED3E2E6ED87900124A26 /* Logging in Frameworks */ = {isa = PBXBuildFile; productRef = 5EA7ED3D2E6ED87900124A26 /* Logging */; }; + 5EA7ED402E6ED87E00124A26 /* Logging in Frameworks */ = {isa = PBXBuildFile; productRef = 5EA7ED3F2E6ED87E00124A26 /* Logging */; }; 6598544E1C5B3C9500237D39 /* OAuth2Authorizer+tvOS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6598543F1C5B3B4000237D39 /* OAuth2Authorizer+tvOS.swift */; }; 6598544F1C5B3C9C00237D39 /* OAuth2Base.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEDB8640193FAB9200C4EEA1 /* OAuth2Base.swift */; }; 659854501C5B3C9C00237D39 /* OAuth2Requestable.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEF47D2A1B1E3FDD0057D838 /* OAuth2Requestable.swift */; }; @@ -118,9 +122,6 @@ EEACE1DD1A7E8DF7009BF3A7 /* extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEDB864B19421DAD00C4EEA1 /* extensions.swift */; }; EEACE1DF1A7E8FC1009BF3A7 /* OAuth2CodeGrantFacebook.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEACE1DE1A7E8FC1009BF3A7 /* OAuth2CodeGrantFacebook.swift */; }; EEACE1E01A7E8FC5009BF3A7 /* OAuth2CodeGrantFacebook.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEACE1DE1A7E8FC1009BF3A7 /* OAuth2CodeGrantFacebook.swift */; }; - EEAEF10B1CDBCF28001A1C6F /* OAuth2Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEAEF10A1CDBCF28001A1C6F /* OAuth2Logger.swift */; }; - EEAEF10C1CDBCF28001A1C6F /* OAuth2Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEAEF10A1CDBCF28001A1C6F /* OAuth2Logger.swift */; }; - EEAEF10D1CDBCF28001A1C6F /* OAuth2Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEAEF10A1CDBCF28001A1C6F /* OAuth2Logger.swift */; }; EEB9A97C1D86C34E0022EF66 /* OAuth2Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEB9A97B1D86C34E0022EF66 /* OAuth2Response.swift */; }; EEB9A97D1D86C34E0022EF66 /* OAuth2Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEB9A97B1D86C34E0022EF66 /* OAuth2Response.swift */; }; EEB9A97E1D86C34E0022EF66 /* OAuth2Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEB9A97B1D86C34E0022EF66 /* OAuth2Response.swift */; }; @@ -239,7 +240,6 @@ EE9EBF1A1D775F74003263FC /* OAuth2Securable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuth2Securable.swift; sourceTree = ""; }; EEAC17A01CAA69110025F84B /* CONTRIBUTORS.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CONTRIBUTORS.md; sourceTree = ""; }; EEACE1DE1A7E8FC1009BF3A7 /* OAuth2CodeGrantFacebook.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuth2CodeGrantFacebook.swift; sourceTree = ""; }; - EEAEF10A1CDBCF28001A1C6F /* OAuth2Logger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuth2Logger.swift; sourceTree = ""; }; EEB9A97B1D86C34E0022EF66 /* OAuth2Response.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuth2Response.swift; sourceTree = ""; }; EEB9A97F1D86CD4A0022EF66 /* OAuth2DataLoaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuth2DataLoaderTests.swift; sourceTree = ""; }; EEB9A9821D86D36A0022EF66 /* OAuth2RequestPerformer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuth2RequestPerformer.swift; sourceTree = ""; }; @@ -263,6 +263,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 5EA7ED3E2E6ED87900124A26 /* Logging in Frameworks */, 871279812DB152B300A5AF72 /* SwiftKeychain in Frameworks */, 8760AE602E16C78000020465 /* Semaphore in Frameworks */, ); @@ -272,6 +273,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 5EA7ED3C2E6ED87300124A26 /* Logging in Frameworks */, 8712797F2DB152AE00A5AF72 /* SwiftKeychain in Frameworks */, 8760AE5E2E16C77C00020465 /* Semaphore in Frameworks */, ); @@ -281,6 +283,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 5EA7ED3A2E6ED86100124A26 /* Logging in Frameworks */, 8712797D2DB152A800A5AF72 /* SwiftKeychain in Frameworks */, 8760AE5C2E16C77700020465 /* Semaphore in Frameworks */, ); @@ -290,6 +293,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 5EA7ED402E6ED87E00124A26 /* Logging in Frameworks */, 871279832DB152BB00A5AF72 /* SwiftKeychain in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -355,7 +359,6 @@ EEB9A9821D86D36A0022EF66 /* OAuth2RequestPerformer.swift */, EEB9A97B1D86C34E0022EF66 /* OAuth2Response.swift */, EE79F6591BFAA36900746243 /* OAuth2Error.swift */, - EEAEF10A1CDBCF28001A1C6F /* OAuth2Logger.swift */, 65EC05DF1C9050CB00DE9186 /* OAuth2KeychainAccount.swift */, EE29EABB195A0DB2008882C8 /* OAuth2DebugURLSessionDelegate.swift */, EE2983741D40BE7600933CDD /* OAuth2AuthorizerUI.swift */, @@ -661,6 +664,7 @@ packageReferences = ( 8712797A2DB151ED00A5AF72 /* XCRemoteSwiftPackageReference "SwiftKeychain" */, 8760AE5A2E16C5E800020465 /* XCRemoteSwiftPackageReference "Semaphore" */, + 5EA7ED382E6ED86100124A26 /* XCRemoteSwiftPackageReference "swift-log" */, ); productRefGroup = EEDB8625193FAAE500C4EEA1 /* Products */; projectDirPath = ""; @@ -739,7 +743,6 @@ EE9EBF151D775A21003263FC /* OAuth2DataLoader.swift in Sources */, EE1070361E5C7A4200250586 /* OAuth2CustomAuthorizerUI.swift in Sources */, 87FABDDE2DC9F2DF00E0C67B /* OAuth2Actor.swift in Sources */, - EEAEF10D1CDBCF28001A1C6F /* OAuth2Logger.swift in Sources */, EE9EBF1D1D775F74003263FC /* OAuth2Securable.swift in Sources */, 659854521C5B3C9C00237D39 /* OAuth2AuthConfig.swift in Sources */, EEC49F331C9BF22400989A18 /* OAuth2AuthRequest.swift in Sources */, @@ -754,7 +757,6 @@ buildActionMask = 2147483647; files = ( EEACE1DD1A7E8DF7009BF3A7 /* extensions.swift in Sources */, - EEAEF10C1CDBCF28001A1C6F /* OAuth2Logger.swift in Sources */, EE20118D1E44D0BD00913FA7 /* OAuth2DataLoaderSessionTaskDelegate.swift in Sources */, 65EC05E11C9050CB00DE9186 /* OAuth2KeychainAccount.swift in Sources */, 87FABDDF2DC9F2DF00E0C67B /* OAuth2Actor.swift in Sources */, @@ -798,7 +800,6 @@ buildActionMask = 2147483647; files = ( EEACE1DC1A7E8DF6009BF3A7 /* extensions.swift in Sources */, - EEAEF10B1CDBCF28001A1C6F /* OAuth2Logger.swift in Sources */, 65EC05E01C9050CB00DE9186 /* OAuth2KeychainAccount.swift in Sources */, 0C2F5E5B1DE2DB8500F621E0 /* OAuth2CodeGrantAzure.swift in Sources */, DD0CCBAD1C4DC83A0044C4E3 /* OAuth2WebViewController+macOS.swift in Sources */, @@ -1273,6 +1274,14 @@ /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ + 5EA7ED382E6ED86100124A26 /* XCRemoteSwiftPackageReference "swift-log" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/apple/swift-log.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.6.4; + }; + }; 8712797A2DB151ED00A5AF72 /* XCRemoteSwiftPackageReference "SwiftKeychain" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/slidoapp/SwiftKeychain"; @@ -1292,6 +1301,26 @@ /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ + 5EA7ED392E6ED86100124A26 /* Logging */ = { + isa = XCSwiftPackageProductDependency; + package = 5EA7ED382E6ED86100124A26 /* XCRemoteSwiftPackageReference "swift-log" */; + productName = Logging; + }; + 5EA7ED3B2E6ED87300124A26 /* Logging */ = { + isa = XCSwiftPackageProductDependency; + package = 5EA7ED382E6ED86100124A26 /* XCRemoteSwiftPackageReference "swift-log" */; + productName = Logging; + }; + 5EA7ED3D2E6ED87900124A26 /* Logging */ = { + isa = XCSwiftPackageProductDependency; + package = 5EA7ED382E6ED86100124A26 /* XCRemoteSwiftPackageReference "swift-log" */; + productName = Logging; + }; + 5EA7ED3F2E6ED87E00124A26 /* Logging */ = { + isa = XCSwiftPackageProductDependency; + package = 5EA7ED382E6ED86100124A26 /* XCRemoteSwiftPackageReference "swift-log" */; + productName = Logging; + }; 8712797C2DB152A800A5AF72 /* SwiftKeychain */ = { isa = XCSwiftPackageProductDependency; package = 8712797A2DB151ED00A5AF72 /* XCRemoteSwiftPackageReference "SwiftKeychain" */; diff --git a/OAuth2.xcworkspace/xcshareddata/swiftpm/Package.resolved b/OAuth2.xcworkspace/xcshareddata/swiftpm/Package.resolved index f1734d5..20428c5 100644 --- a/OAuth2.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/OAuth2.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "3e7272bf7c98b4cdae60d2d8850e4e38300f88987738046a1365a9dcd95802c5", + "originHash" : "fe7b4843235867ca5bcafabf451a1f0b14c19f4d6cc03f3a18bba0edfcb15b4f", "pins" : [ { "identity" : "semaphore", @@ -10,6 +10,15 @@ "version" : "0.1.0" } }, + { + "identity" : "swift-log", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-log.git", + "state" : { + "revision" : "ce592ae52f982c847a4efc0dd881cc9eb32d29f2", + "version" : "1.6.4" + } + }, { "identity" : "swiftkeychain", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 8f610f7..d2d1375 100644 --- a/Package.swift +++ b/Package.swift @@ -31,12 +31,13 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/slidoapp/SwiftKeychain.git", .upToNextMinor(from: "2.1.0")), - .package(url: "https://github.com/groue/Semaphore.git", .upToNextMinor(from: "0.1.0")) + .package(url: "https://github.com/groue/Semaphore.git", .upToNextMinor(from: "0.1.0")), + .package(url: "https://github.com/apple/swift-log.git", .upToNextMinor(from: "1.6.4")) ], targets: [ .target(name: "OAuth2", dependencies: ["Base", "Flows", "DataLoader"]), - .target(name: "Base", dependencies: ["SwiftKeychain", "Semaphore"]), + .target(name: "Base", dependencies: ["SwiftKeychain", "Semaphore", .product(name: "Logging", package: "swift-log")]), .target(name: "macOS", dependencies: [.target(name: "Base")]), .target(name: "iOS", dependencies: [.target(name: "Base")]), .target(name: "tvOS", dependencies: [.target(name: "Base")]), diff --git a/README.md b/README.md index fa5fd59..63af889 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ Need to specify a separate refresh token URI? You can set the `refresh_uri` in t Need to debug? Use a `.debug` or even a `.trace` logger: ```swift -oauth2.logger = OAuth2DebugLogger(.trace) +oauth2.logger?.logLevel = .trace ``` For more see [advanced settings](#advanced-settings) below. @@ -554,6 +554,10 @@ These three steps are needed to: 2. Link the framework into your app 3. Embed the framework in your app when distributing +Swift Logging +------------- + +This library uses the [Swift logging system](https://swiftpackageindex.com/apple/swift-log) for internal logging. You can adjust the log level and configure the logger as needed for your application. License ------- diff --git a/Sources/Base/OAuth2AuthRequest.swift b/Sources/Base/OAuth2AuthRequest.swift index da5751f..882fff0 100644 --- a/Sources/Base/OAuth2AuthRequest.swift +++ b/Sources/Base/OAuth2AuthRequest.swift @@ -189,14 +189,14 @@ open class OAuth2AuthRequest { // add to request body if oauth2.clientConfig.secretInBody { - oauth2.logger?.debug("OAuth2", msg: "Adding “client_id” and “client_secret” to request body") + oauth2.logger?.debug("Adding “client_id” and “client_secret” to request body") finalParams["client_id"] = clientId finalParams["client_secret"] = secret } // add Authorization header (if not in body) else { - oauth2.logger?.debug("OAuth2", msg: "Adding “Authorization” header as “Basic client-key:client-secret”") + oauth2.logger?.debug("Adding “Authorization” header as “Basic client-key:client-secret”") let pw = "\(clientId.wwwFormURLEncodedString):\(secret.wwwFormURLEncodedString)" if let utf8 = pw.data(using: oauth2.clientConfig.authStringEncoding) { req.setValue("Basic \(utf8.base64EncodedString())", forHTTPHeaderField: "Authorization") @@ -212,13 +212,13 @@ open class OAuth2AuthRequest { // add custom headers, first from our OAuth2 instance, then our custom ones if let headers = oauth2.authHeaders { for (key, val) in headers { - oauth2.logger?.trace("OAuth2", msg: "Overriding “\(key)” header") + oauth2.logger?.trace("Overriding “\(key)” header") req.setValue(val, forHTTPHeaderField: key) } } if let headers = headers { for (key, val) in headers { - oauth2.logger?.trace("OAuth2", msg: "Adding custom “\(key)” header") + oauth2.logger?.trace("Adding custom “\(key)” header") req.setValue(val, forHTTPHeaderField: key) } } diff --git a/Sources/Base/OAuth2Base.swift b/Sources/Base/OAuth2Base.swift index 7f19781..9111c2a 100644 --- a/Sources/Base/OAuth2Base.swift +++ b/Sources/Base/OAuth2Base.swift @@ -201,7 +201,7 @@ open class OAuth2Base: OAuth2Securable { override open func updateFromKeychainItems(_ items: [String: any Sendable]) { for message in clientConfig.updateFromStorableItems(items) { - logger?.debug("OAuth2", msg: message) + logger?.debug("\(message)") } clientConfig.secretInBody = (clientConfig.endpointAuthMethod == OAuth2EndpointAuthMethod.clientSecretPost) } @@ -298,7 +298,7 @@ open class OAuth2Base: OAuth2Securable { public final func didFail(with error: OAuth2Error?) { var finalError = error if let error = finalError { - logger?.debug("OAuth2", msg: "\(error)") + logger?.debug("\(error)") } else { finalError = OAuth2Error.requestCancelled @@ -319,7 +319,7 @@ open class OAuth2Base: OAuth2Securable { */ open func abortAuthorization() { if !abortTask() { - logger?.debug("OAuth2", msg: "Aborting authorization") + logger?.debug("Aborting authorization") didFail(with: nil) } } @@ -472,7 +472,7 @@ open class OAuth2Base: OAuth2Securable { guard let state = params["state"] as? String, !state.isEmpty else { throw OAuth2Error.missingState } - logger?.trace("OAuth2", msg: "Checking state, got “\(state)”, expecting “\(context.state)”") + logger?.trace("Checking state, got “\(state)”, expecting “\(context.state)”") if !context.matchesState(state) { throw OAuth2Error.invalidState } diff --git a/Sources/Base/OAuth2Logger.swift b/Sources/Base/OAuth2Logger.swift deleted file mode 100644 index 68c735c..0000000 --- a/Sources/Base/OAuth2Logger.swift +++ /dev/null @@ -1,132 +0,0 @@ -// -// OAuth2Logger.swift -// OAuth2 -// -// Created by Pascal Pfiffner on 05/05/16. -// Copyright © 2016 Pascal Pfiffner. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - - -/** -Logging levels -*/ -public enum OAuth2LogLevel: Int, CustomStringConvertible { - - /// If you want the logger to log everything. - case trace = 0 - - /// Only log debug messages. - case debug - - /// Only warning messages. - case warn - - /// Don't log anything. - case off - - public var description: String { - switch self { - case .trace: - return "Trace" - case .debug: - return "Debug" - case .warn: - return "Warn!" - case .off: - return "-/-" - } - } -} - -extension OAuth2LogLevel: Comparable { - - static public func <(lh: OAuth2LogLevel, rh: OAuth2LogLevel) -> Bool { - return lh.rawValue < rh.rawValue - } -} - - -/** -A simple protocol for loggers used in OAuth2. - -The `OAuth2DebugLogger` is a simple implementation that logs to stdout. If you need more sophisticated logging, just adapt this protocol -and set your logger on the `OAuth2` instance you're using. -*/ -@OAuth2Actor -public protocol OAuth2Logger { - - /// The logger's logging level. - var level: OAuth2LogLevel { get } - - /** This is made a protocol method so it can be implemented in `extension OAuth2Logger` **and** you're able to create your own class - that overrides this method so you can write your own implementation. */ - func log(_ atLevel: OAuth2LogLevel, module: String?, filename: String?, line: Int?, function: String?, msg: @autoclosure() -> String) - - /** Log a message at the trace level. */ - func trace(_ module: String?, filename: String?, line: Int?, function: String?, msg: @autoclosure() -> String) - - /** Standard debug logging. */ - func debug(_ module: String?, filename: String?, line: Int?, function: String?, msg: @autoclosure() -> String) - - /** Log warning messages. */ - func warn(_ module: String?, filename: String?, line: Int?, function: String?, msg: @autoclosure() -> String) -} - -extension OAuth2Logger { - - /** - The main log method, figures out whether to log the given message based on the receiver's logging level, then just uses `print`. Ignores - filename, line and function. - If you override this method in your own logger there's no need to override the `trace`, `debug` and `warn` methods implemented below as - they all call out to this one. - */ - public func log(_ atLevel: OAuth2LogLevel, module: String?, filename: String?, line: Int?, function: String?, msg: @autoclosure() -> String) { - if level != .off && atLevel.rawValue >= level.rawValue { - print("[\(atLevel)] \(module ?? ""): \(msg())") - } - } - - /** Log a message at the trace level. */ - public func trace(_ module: String? = "OAuth2", filename: String? = #file, line: Int? = #line, function: String? = #function, msg: @autoclosure() -> String) { - log(.trace, module: module, filename: filename, line: line, function: function, msg: msg()) - } - - /** Standard debug logging. */ - public func debug(_ module: String? = "OAuth2", filename: String? = #file, line: Int? = #line, function: String? = #function, msg: @autoclosure() -> String) { - log(.debug, module: module, filename: filename, line: line, function: function, msg: msg()) - } - - /** Log warning messages. */ - public func warn(_ module: String? = "OAuth2", filename: String? = #file, line: Int? = #line, function: String? = #function, msg: @autoclosure() -> String) { - log(.warn, module: module, filename: filename, line: line, function: function, msg: msg()) - } -} - - -/** -Basic logger that just prints to stdout. -*/ -open class OAuth2DebugLogger: OAuth2Logger { - - /// The logger's logging level, set to `Debug` by default. - open var level = OAuth2LogLevel.debug - - - /** Designated initializer. */ - public init(_ level: OAuth2LogLevel = OAuth2LogLevel.debug) { - self.level = level - } -} - diff --git a/Sources/Base/OAuth2Requestable.swift b/Sources/Base/OAuth2Requestable.swift index c7489b7..31291fa 100644 --- a/Sources/Base/OAuth2Requestable.swift +++ b/Sources/Base/OAuth2Requestable.swift @@ -19,6 +19,7 @@ // import Foundation +import Logging /// Typealias to ease working with JSON dictionaries. @@ -40,12 +41,13 @@ open class OAuth2Requestable { /// Set to `true` to log all the things. `false` by default. Use `"verbose": bool` in settings or assign `logger` yourself. open var verbose = false { didSet { - logger = verbose ? OAuth2DebugLogger() : nil + logger = verbose ? Logger(label: "OAuth2") : nil + logger?.logLevel = .debug // make debug logger } } /// The logger being used. Auto-assigned to a debug logger if you set `verbose` to true or false. - open var logger: OAuth2Logger? + open var logger: Logger? /** @@ -53,19 +55,20 @@ open class OAuth2Requestable { */ public init(verbose: Bool) { self.verbose = verbose - logger = verbose ? OAuth2DebugLogger() : nil - logger?.debug("OAuth2", msg: "Initialization finished") + logger = verbose ? Logger(label: "OAuth2") : nil + logger?.logLevel = .debug // make debug logger + logger?.debug("Initialization finished") } /** Designated initializer. - - parameter logger: An optional `OAuth2Logger` instance to use + - parameter logger: An optional `Logger` (swift-log) instance to use */ - public init(logger: OAuth2Logger?) { + public init(logger: Logger?) { self.logger = logger self.verbose = (nil != logger) - logger?.debug("OAuth2", msg: "Initialization finished") + logger?.debug("Initialization finished") } @@ -116,14 +119,14 @@ open class OAuth2Requestable { - returns : OAuth2 response */ open func perform(request: URLRequest) async -> OAuth2Response { - self.logger?.trace("OAuth2", msg: "REQUEST\n\(request.debugDescription)\n---") + self.logger?.trace("REQUEST\n\(request.debugDescription)\n---") let performer = requestPerformer ?? OAuth2DataTaskRequestPerformer(session: session) requestPerformer = performer do { // TODO: add support for aborting the request, see https://www.hackingwithswift.com/quick-start/concurrency/how-to-cancel-a-task let (sessData, sessResponse) = try await performer.perform(request: request) - self.logger?.trace("OAuth2", msg: "RESPONSE\n\(sessResponse.debugDescription)\n\n\(String(data: sessData ?? Data(), encoding: String.Encoding.utf8) ?? "no data")\n---") + self.logger?.trace("RESPONSE\n\(sessResponse.debugDescription)\n\n\(String(data: sessData ?? Data(), encoding: String.Encoding.utf8) ?? "no data")\n---") guard let response = sessResponse as? HTTPURLResponse else { throw CommonError.castError( @@ -135,7 +138,7 @@ open class OAuth2Requestable { return OAuth2Response(data: sessData, request: request, response: response, error: nil) } catch { - self.logger?.trace("OAuth2", msg: "RESPONSE\nno response\n\nno data\n---") + self.logger?.trace("RESPONSE\nno response\n\nno data\n---") let http = HTTPURLResponse(url: request.url!, statusCode: 499, httpVersion: nil, headerFields: nil)! return OAuth2Response(data: nil, request: request, response: http, error: error) @@ -154,7 +157,7 @@ open class OAuth2Requestable { guard let task = abortableTask else { return false } - logger?.debug("OAuth2", msg: "Aborting request") + logger?.debug("Aborting request") task.cancel() return true } @@ -175,13 +178,13 @@ open class OAuth2Requestable { return json } if let str = String(data: data, encoding: String.Encoding.utf8) { - logger?.warn("OAuth2", msg: "JSON did not resolve to a dictionary, was: \(str)") + logger?.warning("JSON did not resolve to a dictionary, was: \(str)") } throw OAuth2Error.jsonParserError } catch let error where NSCocoaErrorDomain == error._domain && 3840 == error._code { // JSON parser error if let str = String(data: data, encoding: String.Encoding.utf8) { - logger?.warn("OAuth2", msg: "Unparsable JSON was: \(str)") + logger?.warning("Unparsable JSON was: \(str)") } throw OAuth2Error.jsonParserError } diff --git a/Sources/Base/OAuth2Securable.swift b/Sources/Base/OAuth2Securable.swift index 3a82ae2..afc5944 100644 --- a/Sources/Base/OAuth2Securable.swift +++ b/Sources/Base/OAuth2Securable.swift @@ -110,26 +110,26 @@ open class OAuth2Securable: OAuth2Requestable { /** Queries the keychain for tokens stored for the receiver's authorize URL, and updates the token properties accordingly. */ private func updateFromKeychain() { - logger?.debug("OAuth2", msg: "Looking for items in keychain") + logger?.debug("Looking for items in keychain") do { var creds = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials, classes: storableCredentialClasses()) let creds_data = try creds.fetchedFromKeychain() updateFromKeychainItems(creds_data) - logger?.trace("OAuth2", msg: "Client credentials updated from keychain: \(creds_data)") + logger?.trace("Client credentials updated from keychain: \(creds_data)") } catch { - logger?.warn("OAuth2", msg: "Failed to load client credentials from keychain: \(error)") + logger?.warning("Failed to load client credentials from keychain: \(error)") } do { var toks = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens, classes: storableTokenClasses()) let toks_data = try toks.fetchedFromKeychain() updateFromKeychainItems(toks_data) - logger?.trace("OAuth2", msg: "Tokens updated from keychain: \(toks_data)") + logger?.trace("Tokens updated from keychain: \(toks_data)") } catch { - logger?.warn("OAuth2", msg: "Failed to load tokens from keychain: \(error)") + logger?.warning("Failed to load tokens from keychain: \(error)") } } @@ -153,14 +153,14 @@ open class OAuth2Securable: OAuth2Requestable { /** Stores our client credentials in the keychain. */ open func storeClientToKeychain() { if let items = storableCredentialItems() { - logger?.debug("OAuth2", msg: "Storing client credentials to keychain") + logger?.debug("Storing client credentials to keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials, data: items, classes: storableCredentialClasses()) do { try keychain.saveInKeychain() - logger?.trace("OAuth2", msg: "Client credentials stored to keychain: \(items)") + logger?.trace("Client credentials stored to keychain: \(items)") } catch { - logger?.warn("OAuth2", msg: "Failed to store client credentials to keychain: \(error)") + logger?.warning("Failed to store client credentials to keychain: \(error)") } } } @@ -181,40 +181,40 @@ open class OAuth2Securable: OAuth2Requestable { /** Stores our current token(s) in the keychain. */ public func storeTokensToKeychain() { if let items = storableTokenItems() { - logger?.debug("OAuth2", msg: "Storing tokens to keychain") + logger?.debug("Storing tokens to keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens, data: items, classes: storableTokenClasses()) do { try keychain.saveInKeychain() - logger?.trace("OAuth2", msg: "Tokens stored to keychain: \(items)") + logger?.trace("Tokens stored to keychain: \(items)") } catch let error { - logger?.warn("OAuth2", msg: "Failed to store tokens to keychain: \(error)") + logger?.warning("Failed to store tokens to keychain: \(error)") } } } /** Unsets the client credentials and deletes them from the keychain. */ open func forgetClient() { - logger?.debug("OAuth2", msg: "Forgetting client credentials and removing them from keychain") + logger?.debug("Forgetting client credentials and removing them from keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials) do { try keychain.removeFromKeychain() } catch { - logger?.warn("OAuth2", msg: "Failed to delete credentials from keychain: \(error)") + logger?.warning("Failed to delete credentials from keychain: \(error)") } } /** Unsets the tokens and deletes them from the keychain. */ open func forgetTokens() { - logger?.debug("OAuth2", msg: "Forgetting tokens and removing them from keychain") + logger?.debug("Forgetting tokens and removing them from keychain") let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens) do { try keychain.removeFromKeychain() } catch { - logger?.warn("OAuth2", msg: "Failed to delete tokens from keychain: \(error)") + logger?.warning("Failed to delete tokens from keychain: \(error)") } } } diff --git a/Sources/DataLoader/OAuth2DataLoaderSessionTaskDelegate.swift b/Sources/DataLoader/OAuth2DataLoaderSessionTaskDelegate.swift index 88d393b..5b1cd48 100644 --- a/Sources/DataLoader/OAuth2DataLoaderSessionTaskDelegate.swift +++ b/Sources/DataLoader/OAuth2DataLoaderSessionTaskDelegate.swift @@ -54,7 +54,7 @@ final class OAuth2DataLoaderSessionTaskDelegate: NSObject, URLSessionTaskDelegat func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { guard request.url?.host == host else { - loader?.logger?.warn("OAuth2", msg: "Redirected to «\(request.url?.host ?? "nil")» but only approving HTTP redirection on «\(host)», not following redirect: \(request)") + loader?.logger?.warning("Redirected to «\(request.url?.host ?? "nil")» but only approving HTTP redirection on «\(host)», not following redirect: \(request)") completionHandler(nil) return } @@ -63,11 +63,11 @@ final class OAuth2DataLoaderSessionTaskDelegate: NSObject, URLSessionTaskDelegat throw OAuth2Error.generic("no loader instance, cannot re-sign") } let newRequest = try request.signed(with: loader.oauth2) - loader.logger?.debug("OAuth2", msg: "Following HTTP redirection to «\(request.url?.description ?? "nil")»") + loader.logger?.debug("Following HTTP redirection to «\(request.url?.description ?? "nil")»") completionHandler(newRequest) } catch { - loader?.logger?.warn("OAuth2", msg: "Failed to re-sign request after HTTP redirection: \(error)") + loader?.logger?.warning("Failed to re-sign request after HTTP redirection: \(error)") completionHandler(request) } } diff --git a/Sources/Flows/OAuth2.swift b/Sources/Flows/OAuth2.swift index 8c39dd2..bc0424c 100644 --- a/Sources/Flows/OAuth2.swift +++ b/Sources/Flows/OAuth2.swift @@ -115,7 +115,7 @@ open class OAuth2: OAuth2Base { } self.isAuthorizing = true - logger?.debug("OAuth2", msg: "Starting authorization") + logger?.debug("Starting authorization") do { if let successParams = try await tryToObtainAccessTokenIfNeeded(params: params) { @@ -162,15 +162,15 @@ open class OAuth2: OAuth2Base { */ open func tryToObtainAccessTokenIfNeeded(params: OAuth2StringDict? = nil) async throws -> OAuth2JSON? { if hasUnexpiredAccessToken() { - logger?.debug("OAuth2", msg: "Have an apparently unexpired access token") + logger?.debug("Have an apparently unexpired access token") return OAuth2JSON() } else { - logger?.debug("OAuth2", msg: "No access token, checking if a refresh token is available") + logger?.debug("No access token, checking if a refresh token is available") do { return try await self.doRefreshToken(params: params) } catch { - self.logger?.debug("OAuth2", msg: "Error refreshing token: \(error)") + self.logger?.debug("Error refreshing token: \(error)") switch error.asOAuth2Error { case .noRefreshToken, .noClientId, .unauthorizedClient: @@ -217,7 +217,7 @@ open class OAuth2: OAuth2Base { */ final func doOpenAuthorizeURLInBrowser(params: OAuth2StringDict? = nil) throws { let url = try authorizeURL(params: params) - logger?.debug("OAuth2", msg: "Opening authorize URL in system browser: \(url)") + logger?.debug("Opening authorize URL in system browser: \(url)") try authorizer.openAuthorizeURLInBrowser(url) } @@ -233,7 +233,7 @@ open class OAuth2: OAuth2Base { */ final func doAuthorizeEmbedded(with config: OAuth2AuthConfig, params: OAuth2StringDict? = nil) async throws { let url = try authorizeURL(params: params) - logger?.debug("OAuth2", msg: "Opening authorize URL embedded: \(url)") + logger?.debug("Opening authorize URL embedded: \(url)") try await authorizer.authorizeEmbedded(with: config, at: url) } @@ -356,7 +356,7 @@ open class OAuth2: OAuth2Base { do { let post = try tokenRequestForTokenRefresh(params: params).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Using refresh token to receive access token from \(post.url?.description ?? "nil")") + logger?.debug("Using refresh token to receive access token from \(post.url?.description ?? "nil")") let response = await perform(request: post) let data = try response.responseData() @@ -365,7 +365,7 @@ open class OAuth2: OAuth2Base { self.clientConfig.refreshToken = nil throw OAuth2Error.generic("Failed with status \(response.response.statusCode)") } - self.logger?.debug("OAuth2", msg: "Did use refresh token for access token [\(nil != self.clientConfig.accessToken)]") + self.logger?.debug("Did use refresh token for access token [\(nil != self.clientConfig.accessToken)]") if (self.useKeychain) { self.storeTokensToKeychain() } @@ -424,7 +424,7 @@ open class OAuth2: OAuth2Base { do { let post = try tokenRequestForExchangeRefreshToken(audienceClientId: audienceClientId, params: params).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Exchanging refresh token for client with ID \(audienceClientId) from \(post.url?.description ?? "nil") [trace=\(traceId)]") + logger?.debug("Exchanging refresh token for client with ID \(audienceClientId) from \(post.url?.description ?? "nil") [trace=\(traceId)]") let response = await perform(request: post) let data = try response.responseData() @@ -445,15 +445,15 @@ open class OAuth2: OAuth2Base { guard let exchangedRefreshToken = json["access_token"] as? String else { throw OAuth2Error.generic("Exchange refresh token didn't return exchanged refresh token (response.access_token) [trace=\(traceId)]") } - self.logger?.debug("OAuth2", msg: "Did use refresh token for exchanging refresh token [trace=\(traceId)]") - self.logger?.trace("OAuth2", msg: "Exchanged refresh token in [trace=\(traceId)] is [\(exchangedRefreshToken)]") + self.logger?.debug("Did use refresh token for exchanging refresh token [trace=\(traceId)]") + self.logger?.trace("Exchanged refresh token in [trace=\(traceId)] is [\(exchangedRefreshToken)]") if self.useKeychain { self.storeTokensToKeychain() } debugPrint("[doExchangeRefreshToken] Ended for \(audienceClientId)") return exchangedRefreshToken } catch { - self.logger?.debug("OAuth2", msg: "Error exchanging refresh in [trace=\(traceId)] token: \(error)") + self.logger?.debug("Error exchanging refresh in [trace=\(traceId)] token: \(error)") throw error.asOAuth2Error } } @@ -507,7 +507,7 @@ open class OAuth2: OAuth2Base { } let post = try tokenRequestForExchangeAccessTokenForResource(params: params).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Exchanging access token for resource(s) \(resourceURIs) from \(post.url?.description ?? "nil")") + logger?.debug("Exchanging access token for resource(s) \(resourceURIs) from \(post.url?.description ?? "nil")") let response = await perform(request: post) let data = try response.responseData() @@ -521,7 +521,7 @@ open class OAuth2: OAuth2Base { } return exchangedAccessToken } catch let error { - self.logger?.debug("OAuth2", msg: "Error exchanging access token for resource(s): \(error)") + self.logger?.debug("Error exchanging access token for resource(s): \(error)") throw error.asOAuth2Error } } diff --git a/Sources/Flows/OAuth2ClientCredentials.swift b/Sources/Flows/OAuth2ClientCredentials.swift index f93515c..cd66c94 100644 --- a/Sources/Flows/OAuth2ClientCredentials.swift +++ b/Sources/Flows/OAuth2ClientCredentials.swift @@ -77,12 +77,12 @@ open class OAuth2ClientCredentials: OAuth2 { public func obtainAccessToken(params: OAuth2StringDict? = nil) async throws -> OAuth2JSON { do { let post = try accessTokenRequest(params: params).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Requesting new access token from \(post.url?.description ?? "nil")") + logger?.debug("Requesting new access token from \(post.url?.description ?? "nil")") let response = await perform(request: post) let data = try response.responseData() let params = try self.parseAccessTokenResponse(data: data) - self.logger?.debug("OAuth2", msg: "Did get access token [\(nil != self.clientConfig.accessToken)]") + self.logger?.debug("Did get access token [\(nil != self.clientConfig.accessToken)]") return params } catch { diff --git a/Sources/Flows/OAuth2CodeGrant.swift b/Sources/Flows/OAuth2CodeGrant.swift index 803f2f4..d7344f2 100644 --- a/Sources/Flows/OAuth2CodeGrant.swift +++ b/Sources/Flows/OAuth2CodeGrant.swift @@ -82,7 +82,7 @@ open class OAuth2CodeGrant: OAuth2 { Extracts the code from the redirect URL and exchanges it for a token. */ override open func handleRedirectURL(_ redirect: URL) async throws -> OAuth2JSON { - logger?.debug("OAuth2", msg: "Handling redirect URL \(redirect.description)") + logger?.debug("Handling redirect URL \(redirect.description)") do { let code = try validateRedirectURL(redirect) return try await exchangeCodeForToken(code) @@ -105,7 +105,7 @@ open class OAuth2CodeGrant: OAuth2 { } let post = try accessTokenRequest(with: code).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Exchanging code \(code) for access token at \(post.url!)") + logger?.debug("Exchanging code \(code) for access token at \(post.url!)") let response = await perform(request: post) let data = try response.responseData() @@ -113,7 +113,7 @@ open class OAuth2CodeGrant: OAuth2 { if response.response.statusCode >= 400 { throw OAuth2Error.generic("Failed with status \(response.response.statusCode)") } - self.logger?.debug("OAuth2", msg: "Did exchange code for access [\(nil != self.clientConfig.accessToken)] and refresh [\(nil != self.clientConfig.refreshToken)] tokens") + self.logger?.debug("Did exchange code for access [\(nil != self.clientConfig.accessToken)] and refresh [\(nil != self.clientConfig.refreshToken)] tokens") self.didAuthorize(withParameters: params) return params } catch { diff --git a/Sources/Flows/OAuth2CodeGrantBasicAuth.swift b/Sources/Flows/OAuth2CodeGrantBasicAuth.swift index 32f9ae3..a48fe22 100644 --- a/Sources/Flows/OAuth2CodeGrantBasicAuth.swift +++ b/Sources/Flows/OAuth2CodeGrantBasicAuth.swift @@ -55,11 +55,11 @@ open class OAuth2CodeGrantBasicAuth: OAuth2CodeGrant { override open func accessTokenRequest(with code: String, params: OAuth2StringDict? = nil) throws -> OAuth2AuthRequest { let req = try super.accessTokenRequest(with: code, params: params) if let basic = basicToken { - logger?.debug("OAuth2", msg: "Overriding “Basic” authorization header, as specified during client initialization") + logger?.debug("Overriding “Basic” authorization header, as specified during client initialization") req.set(header: "Authorization", to: "Basic \(basic)") } else { - logger?.warn("OAuth2", msg: "Using extended code grant, but “basicToken” is not actually specified. Using standard code grant.") + logger?.warning("Using extended code grant, but “basicToken” is not actually specified. Using standard code grant.") } return req } diff --git a/Sources/Flows/OAuth2DeviceGrant.swift b/Sources/Flows/OAuth2DeviceGrant.swift index 233aa55..7d073ab 100644 --- a/Sources/Flows/OAuth2DeviceGrant.swift +++ b/Sources/Flows/OAuth2DeviceGrant.swift @@ -124,7 +124,7 @@ open class OAuth2DeviceGrant: OAuth2 { ) } catch { - self.logger?.warn("OAuth2", msg: "Unable to get device code: \(error)") // TODO improve message to cover different scenarios + self.logger?.warning("Unable to get device code: \(error)") // TODO improve message to cover different scenarios throw error } } @@ -132,7 +132,7 @@ open class OAuth2DeviceGrant: OAuth2 { private func authorizeDevice(params: OAuth2StringDict?) async throws -> OAuth2JSON { do { let post = try deviceAuthorizationRequest(params: params).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Obtaining device code from \(post.url!)") + logger?.debug("Obtaining device code from \(post.url!)") let response = await self.perform(request: post) let data = try response.responseData() @@ -147,7 +147,7 @@ open class OAuth2DeviceGrant: OAuth2 { private func getDeviceAccessToken(deviceCode: String, interval: TimeInterval) async throws -> OAuth2JSON { do { let post = try deviceAccessTokenRequest(with: deviceCode).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Obtaining access token for device with code \(deviceCode) from \(post.url!)") + logger?.debug("Obtaining access token for device with code \(deviceCode) from \(post.url!)") let response = await self.perform(request: post) let data = try response.responseData() @@ -157,12 +157,12 @@ open class OAuth2DeviceGrant: OAuth2 { let oaerror = error.asOAuth2Error if oaerror == .authorizationPending(nil) { - self.logger?.debug("OAuth2", msg: "AuthorizationPending, repeating in \(interval) seconds.") + self.logger?.debug("AuthorizationPending, repeating in \(interval) seconds.") try await Task.sleep(seconds: interval) return try await self.getDeviceAccessToken(deviceCode: deviceCode, interval: interval) } else if oaerror == .slowDown(nil) { let updatedInterval = interval + 5 // The 5 seconds increase is required by the RFC8628 standard (https://www.rfc-editor.org/rfc/rfc8628#section-3.5) - self.logger?.debug("OAuth2", msg: "SlowDown, repeating in \(updatedInterval) seconds.") + self.logger?.debug("SlowDown, repeating in \(updatedInterval) seconds.") try await Task.sleep(seconds: updatedInterval) return try await self.getDeviceAccessToken(deviceCode: deviceCode, interval: updatedInterval) } diff --git a/Sources/Flows/OAuth2DynReg.swift b/Sources/Flows/OAuth2DynReg.swift index 8fae5cd..80daadd 100644 --- a/Sources/Flows/OAuth2DynReg.swift +++ b/Sources/Flows/OAuth2DynReg.swift @@ -58,14 +58,14 @@ open class OAuth2DynReg { open func register(client: OAuth2) async throws -> OAuth2JSON { do { let req = try registrationRequest(for: client) - client.logger?.debug("OAuth2", msg: "Registering client at \(req.url!) with scopes “\(client.scope ?? "(none)")”") + client.logger?.debug("Registering client at \(req.url!) with scopes “\(client.scope ?? "(none)")”") let response = await client.perform(request: req) let data = try response.responseData() let dict = try self.parseRegistrationResponse(data: data, client: client) try client.assureNoErrorInResponse(dict) if response.response.statusCode >= 400 { - client.logger?.warn("OAuth2", msg: "Registration failed with \(response.response.statusCode)") + client.logger?.warning("Registration failed with \(response.response.statusCode)") } else { self.didRegisterWith(json: dict, client: client) } @@ -99,7 +99,7 @@ open class OAuth2DynReg { } } let body = registrationBody(for: client) - client.logger?.debug("OAuth2", msg: "Registration parameters: \(body)") + client.logger?.debug("Registration parameters: \(body)") req.httpBody = try JSONSerialization.data(withJSONObject: body, options: []) return req @@ -159,15 +159,15 @@ open class OAuth2DynReg { open func didRegisterWith(json: OAuth2JSON, client: OAuth2) { if let id = json["client_id"] as? String { client.clientId = id - client.logger?.debug("OAuth2", msg: "Did register with client-id “\(id)”, params: \(json)") + client.logger?.debug("Did register with client-id “\(id)”, params: \(json)") } else { - client.logger?.debug("OAuth2", msg: "Did register but did not get a client-id. Params: \(json)") + client.logger?.debug("Did register but did not get a client-id. Params: \(json)") } if let secret = json["client_secret"] as? String { client.clientSecret = secret if let expires = json["client_secret_expires_at"] as? Double, 0 != expires { - client.logger?.debug("OAuth2", msg: "Client secret will expire on \(Date(timeIntervalSince1970: expires))") + client.logger?.debug("Client secret will expire on \(Date(timeIntervalSince1970: expires))") } } if let methodName = json["token_endpoint_auth_method"] as? String, let method = OAuth2EndpointAuthMethod(rawValue: methodName) { diff --git a/Sources/Flows/OAuth2ImplicitGrant.swift b/Sources/Flows/OAuth2ImplicitGrant.swift index c77115f..625fede 100644 --- a/Sources/Flows/OAuth2ImplicitGrant.swift +++ b/Sources/Flows/OAuth2ImplicitGrant.swift @@ -40,7 +40,7 @@ open class OAuth2ImplicitGrant: OAuth2 { } override open func handleRedirectURL(_ redirect: URL) async throws -> OAuth2JSON { - logger?.debug("OAuth2", msg: "Handling redirect URL \(redirect.description)") + logger?.debug("Handling redirect URL \(redirect.description)") do { // token should be in the URL fragment let comp = URLComponents(url: redirect, resolvingAgainstBaseURL: true) @@ -50,7 +50,7 @@ open class OAuth2ImplicitGrant: OAuth2 { let params = type(of: self).params(fromQuery: fragment) let dict = try parseAccessTokenResponse(params: params) - logger?.debug("OAuth2", msg: "Successfully extracted access token") + logger?.debug("Successfully extracted access token") didAuthorize(withParameters: dict) return dict } diff --git a/Sources/Flows/OAuth2ImplicitGrantWithQueryParams.swift b/Sources/Flows/OAuth2ImplicitGrantWithQueryParams.swift index 6c2cd24..a134352 100644 --- a/Sources/Flows/OAuth2ImplicitGrantWithQueryParams.swift +++ b/Sources/Flows/OAuth2ImplicitGrantWithQueryParams.swift @@ -32,7 +32,7 @@ import Base open class OAuth2ImplicitGrantWithQueryParams: OAuth2ImplicitGrant { override open func handleRedirectURL(_ redirect: URL) async throws -> OAuth2JSON { - logger?.debug("OAuth2", msg: "Handling redirect URL \(redirect.description)") + logger?.debug("Handling redirect URL \(redirect.description)") do { // token should be in the URL query let comp = URLComponents(url: redirect, resolvingAgainstBaseURL: true) @@ -42,7 +42,7 @@ open class OAuth2ImplicitGrantWithQueryParams: OAuth2ImplicitGrant { let params = type(of: self).params(fromQuery: query) let dict = try parseAccessTokenResponse(params: params) - logger?.debug("OAuth2", msg: "Successfully extracted access token") + logger?.debug("Successfully extracted access token") didAuthorize(withParameters: dict) return dict } diff --git a/Sources/Flows/OAuth2PasswordGrant.swift b/Sources/Flows/OAuth2PasswordGrant.swift index 53152b7..a129cc5 100644 --- a/Sources/Flows/OAuth2PasswordGrant.swift +++ b/Sources/Flows/OAuth2PasswordGrant.swift @@ -126,7 +126,7 @@ open class OAuth2PasswordGrant: OAuth2 { - parameter params: Optional key/value pairs to pass during authorization */ private func askForCredentials(params: OAuth2StringDict? = nil) async throws { - logger?.debug("OAuth2", msg: "Presenting the login controller") + logger?.debug("Presenting the login controller") guard let delegate = delegate else { throw OAuth2Error.noPasswordGrantDelegate } @@ -178,7 +178,7 @@ open class OAuth2PasswordGrant: OAuth2 { - parameter animated: Whether dismissal should be animated */ open func dismissLoginController(animated: Bool = true) { - logger?.debug("OAuth2", msg: "Dismissing the login controller") + logger?.debug("Dismissing the login controller") customAuthorizer.dismissLoginController(animated: animated) if isAuthorizing { didFail(with: nil) @@ -227,7 +227,7 @@ open class OAuth2PasswordGrant: OAuth2 { public func obtainAccessToken(params: OAuth2StringDict? = nil) async throws -> OAuth2JSON { do { let post = try accessTokenRequest(params: params).asURLRequest(for: self) - logger?.debug("OAuth2", msg: "Requesting new access token from \(post.url?.description ?? "nil")") + logger?.debug("Requesting new access token from \(post.url?.description ?? "nil")") let response = await self.perform(request: post) let data = try response.responseData() @@ -235,7 +235,7 @@ open class OAuth2PasswordGrant: OAuth2 { if response.response.statusCode >= 400 { throw OAuth2Error.generic("Failed with status \(response.response.statusCode)") } - self.logger?.debug("OAuth2", msg: "Did get access token [\(nil != self.clientConfig.accessToken)]") + self.logger?.debug("Did get access token [\(nil != self.clientConfig.accessToken)]") return dict } catch OAuth2Error.unauthorizedClient { // TODO: which one is it? @@ -245,7 +245,7 @@ open class OAuth2PasswordGrant: OAuth2 { throw OAuth2Error.wrongUsernamePassword } catch { - self.logger?.debug("OAuth2", msg: "Error obtaining access token: \(error)") + self.logger?.debug("Error obtaining access token: \(error)") throw error } } diff --git a/Sources/iOS/OAuth2Authorizer+iOS.swift b/Sources/iOS/OAuth2Authorizer+iOS.swift index 5cee559..476bbb2 100644 --- a/Sources/iOS/OAuth2Authorizer+iOS.swift +++ b/Sources/iOS/OAuth2Authorizer+iOS.swift @@ -72,7 +72,7 @@ open class OAuth2Authorizer: OAuth2AuthorizerUI { await UIApplication.shared.open(url) { didOpen in if !didOpen { Task { @OAuth2Actor in - self.oauth2.logger?.warn("OAuth2", msg: "Unable to open authorize URL") + self.oauth2.logger?.warning("Unable to open authorize URL") } } } @@ -148,7 +148,7 @@ open class OAuth2Authorizer: OAuth2AuthorizerUI { @discardableResult public func authenticationSessionEmbedded(at url: URL, withRedirect redirect: String, prefersEphemeralWebBrowserSession: Bool = false) -> Bool { guard let redirectURL = URL(string: redirect) else { - oauth2.logger?.warn("OAuth2", msg: "Unable to parse redirect URL ”(redirect)“") + oauth2.logger?.warning("Unable to parse redirect URL ”(redirect)“") return false } let completionHandler: (URL?, Error?) -> Void = { url, error in @@ -158,7 +158,7 @@ open class OAuth2Authorizer: OAuth2AuthorizerUI { try await self.oauth2.handleRedirectURL(url as URL) } catch { - self.oauth2.logger?.warn("OAuth2", msg: "Cannot intercept redirect URL: \(error)") + self.oauth2.logger?.warning("Cannot intercept redirect URL: \(error)") } } } else { diff --git a/Sources/iOS/OAuth2WebViewController+iOS.swift b/Sources/iOS/OAuth2WebViewController+iOS.swift index 8c53a03..3659b3a 100644 --- a/Sources/iOS/OAuth2WebViewController+iOS.swift +++ b/Sources/iOS/OAuth2WebViewController+iOS.swift @@ -56,7 +56,7 @@ open class OAuth2WebViewController: UIViewController, WKNavigationDelegate { interceptComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) } else { - oauth?.logger?.debug("OAuth2", msg: "Failed to parse URL \(interceptURLString), discarding") + oauth?.logger?.debug("Failed to parse URL \(interceptURLString), discarding") self.interceptURLString = nil } } @@ -237,13 +237,13 @@ open class OAuth2WebViewController: UIViewController, WKNavigationDelegate { if let scheme = interceptComponents?.scheme, "urn" == scheme { if let path = interceptComponents?.path, path.hasPrefix("ietf:wg:oauth:2.0:oob") { if let title = await webView.title, title.hasPrefix("Success ") { - oauth?.logger?.debug("OAuth2", msg: "Creating redirect URL from document.title") + oauth?.logger?.debug("Creating redirect URL from document.title") let qry = title.replacingOccurrences(of: "Success ", with: "") if let url = URL(string: "http://localhost/?\(qry)") { _ = onIntercept?(url) return } - oauth?.logger?.warn("OAuth2", msg: "Failed to create a URL with query parts \"\(qry)\"") + oauth?.logger?.warning("Failed to create a URL with query parts \"\(qry)\"") } } } diff --git a/Sources/macOS/OAuth2Authorizer+macOS.swift b/Sources/macOS/OAuth2Authorizer+macOS.swift index d43dc4b..9a394a8 100644 --- a/Sources/macOS/OAuth2Authorizer+macOS.swift +++ b/Sources/macOS/OAuth2Authorizer+macOS.swift @@ -136,7 +136,7 @@ open class OAuth2Authorizer: OAuth2AuthorizerUI { do { try await self.oauth2.handleRedirectURL(url) } catch let err { - self.oauth2.logger?.warn("OAuth2", msg: "Cannot intercept redirect URL: \(err)") + self.oauth2.logger?.warning("Cannot intercept redirect URL: \(err)") } } } else { @@ -227,7 +227,7 @@ open class OAuth2Authorizer: OAuth2AuthorizerUI { return true } catch let error { - self.oauth2.logger?.warn("OAuth2", msg: "Cannot intercept redirect URL: \(error)") + self.oauth2.logger?.warning("Cannot intercept redirect URL: \(error)") } return false } diff --git a/Sources/macOS/OAuth2WebViewController+macOS.swift b/Sources/macOS/OAuth2WebViewController+macOS.swift index a46ad42..8c42e3e 100644 --- a/Sources/macOS/OAuth2WebViewController+macOS.swift +++ b/Sources/macOS/OAuth2WebViewController+macOS.swift @@ -68,7 +68,7 @@ public class OAuth2WebViewController: NSViewController, WKNavigationDelegate, NS interceptComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) } else { - oauth?.logger?.warn("OAuth2", msg: "Failed to parse URL \(interceptURLString!), discarding") + oauth?.logger?.warning("Failed to parse URL \(interceptURLString!), discarding") interceptURLString = nil } } @@ -283,14 +283,14 @@ public class OAuth2WebViewController: NSViewController, WKNavigationDelegate, NS if let scheme = interceptComponents?.scheme, "urn" == scheme { if let path = interceptComponents?.path, path.hasPrefix("ietf:wg:oauth:2.0:oob") { if let title = await webView.title, title.hasPrefix("Success ") { - oauth?.logger?.debug("OAuth2", msg: "Creating redirect URL from document.title") + oauth?.logger?.debug("Creating redirect URL from document.title") let qry = title.replacingOccurrences(of: "Success ", with: "") if let url = URL(string: "http://localhost/?\(qry)") { _ = await onIntercept?(url) return } - oauth?.logger?.warn("OAuth2", msg: "Failed to create a URL with query parts \"\(qry)\"") + oauth?.logger?.warning("Failed to create a URL with query parts \"\(qry)\"") } } } diff --git a/Tests/DataLoaderTests/OAuth2DataLoaderTests.swift b/Tests/DataLoaderTests/OAuth2DataLoaderTests.swift index 851be87..806eb8d 100644 --- a/Tests/DataLoaderTests/OAuth2DataLoaderTests.swift +++ b/Tests/DataLoaderTests/OAuth2DataLoaderTests.swift @@ -19,6 +19,7 @@ // import XCTest +import Logging #if !NO_MODULE_IMPORT @testable @@ -52,7 +53,7 @@ class OAuth2DataLoaderTests: XCTestCase { "authorize_url": "https://oauth.io/authorize", "keychain": false ] as OAuth2JSON) - oauth2!.logger = OAuth2DebugLogger(.debug) + oauth2!.logger = Logger(label: "OAuth2DataLoaderTests") oauth2!.username = "p2" oauth2!.password = "test" oauth2!.requestPerformer = OAuth2MockPerformer(response)