Validation.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. //
  2. // Validation.swift
  3. //
  4. // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. extension Request {
  26. /// Used to represent whether validation was successful or encountered an error resulting in a failure.
  27. ///
  28. /// - success: The validation was successful.
  29. /// - failure: The validation failed encountering the provided error.
  30. public enum ValidationResult {
  31. case success
  32. case failure(NSError)
  33. }
  34. /// A closure used to validate a request that takes a URL request and URL response, and returns whether the
  35. /// request was valid.
  36. public typealias Validation = (URLRequest?, HTTPURLResponse) -> ValidationResult
  37. /// Validates the request, using the specified closure.
  38. ///
  39. /// If validation fails, subsequent calls to response handlers will have an associated error.
  40. ///
  41. /// - parameter validation: A closure to validate the request.
  42. ///
  43. /// - returns: The request.
  44. @discardableResult
  45. public func validate(_ validation: Validation) -> Self {
  46. delegate.queue.addOperation {
  47. if
  48. let response = self.response,
  49. self.delegate.error == nil,
  50. case let .failure(error) = validation(self.request, response)
  51. {
  52. self.delegate.error = error
  53. }
  54. }
  55. return self
  56. }
  57. // MARK: - Status Code
  58. /// Validates that the response has a status code in the specified range.
  59. ///
  60. /// If validation fails, subsequent calls to response handlers will have an associated error.
  61. ///
  62. /// - parameter range: The range of acceptable status codes.
  63. ///
  64. /// - returns: The request.
  65. @discardableResult
  66. public func validate<S: Sequence where S.Iterator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  67. return validate { _, response in
  68. if acceptableStatusCode.contains(response.statusCode) {
  69. return .success
  70. } else {
  71. let failureReason = "Response status code was unacceptable: \(response.statusCode)"
  72. let error = NSError(
  73. domain: ErrorDomain,
  74. code: ErrorCode.statusCodeValidationFailed.rawValue,
  75. userInfo: [
  76. NSLocalizedFailureReasonErrorKey: failureReason,
  77. ErrorUserInfoKeys.StatusCode: response.statusCode
  78. ]
  79. )
  80. return .failure(error)
  81. }
  82. }
  83. }
  84. // MARK: - Content-Type
  85. private struct MIMEType {
  86. let type: String
  87. let subtype: String
  88. init?(_ string: String) {
  89. let components: [String] = {
  90. let stripped = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  91. let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
  92. return split.components(separatedBy: "/")
  93. }()
  94. if let type = components.first, let subtype = components.last {
  95. self.type = type
  96. self.subtype = subtype
  97. } else {
  98. return nil
  99. }
  100. }
  101. func matches(_ mime: MIMEType) -> Bool {
  102. switch (type, subtype) {
  103. case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
  104. return true
  105. default:
  106. return false
  107. }
  108. }
  109. }
  110. /// Validates that the response has a content type in the specified array.
  111. ///
  112. /// If validation fails, subsequent calls to response handlers will have an associated error.
  113. ///
  114. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  115. ///
  116. /// - returns: The request.
  117. @discardableResult
  118. public func validate<S: Sequence where S.Iterator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  119. return validate { _, response in
  120. guard let validData = self.delegate.data, validData.count > 0 else { return .success }
  121. if let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) {
  122. for contentType in acceptableContentTypes {
  123. if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
  124. return .success
  125. }
  126. }
  127. } else {
  128. for contentType in acceptableContentTypes {
  129. if let mimeType = MIMEType(contentType), mimeType.type == "*" && mimeType.subtype == "*" {
  130. return .success
  131. }
  132. }
  133. }
  134. let contentType: String
  135. let failureReason: String
  136. if let responseContentType = response.mimeType {
  137. contentType = responseContentType
  138. failureReason = (
  139. "Response content type \"\(responseContentType)\" does not match any acceptable " +
  140. "content types: \(acceptableContentTypes)"
  141. )
  142. } else {
  143. contentType = ""
  144. failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
  145. }
  146. let error = NSError(
  147. domain: ErrorDomain,
  148. code: ErrorCode.contentTypeValidationFailed.rawValue,
  149. userInfo: [
  150. NSLocalizedFailureReasonErrorKey: failureReason,
  151. ErrorUserInfoKeys.ContentType: contentType
  152. ]
  153. )
  154. return .failure(error)
  155. }
  156. }
  157. // MARK: - Automatic
  158. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  159. /// type matches any specified in the Accept HTTP header field.
  160. ///
  161. /// If validation fails, subsequent calls to response handlers will have an associated error.
  162. ///
  163. /// - returns: The request.
  164. @discardableResult
  165. public func validate() -> Self {
  166. let acceptableStatusCodes: CountableRange<Int> = 200..<300
  167. let acceptableContentTypes: [String] = {
  168. if let accept = request?.value(forHTTPHeaderField: "Accept") {
  169. return accept.components(separatedBy: ",")
  170. }
  171. return ["*/*"]
  172. }()
  173. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  174. }
  175. }