Validation.swift 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. /**
  27. Used to represent whether validation was successful or encountered an error resulting in a failure.
  28. - Success: The validation was successful.
  29. - Failure: The validation failed encountering the provided error.
  30. */
  31. public enum ValidationResult {
  32. case success
  33. case failure(NSError)
  34. }
  35. /**
  36. A closure used to validate a request that takes a URL request and URL response, and returns whether the
  37. request was valid.
  38. */
  39. public typealias Validation = (Foundation.URLRequest?, HTTPURLResponse) -> ValidationResult
  40. /**
  41. Validates the request, using the specified closure.
  42. If validation fails, subsequent calls to response handlers will have an associated error.
  43. - parameter validation: A closure to validate the request.
  44. - returns: The request.
  45. */
  46. public func validate(_ validation: Validation) -> Self {
  47. delegate.queue.addOperation {
  48. if let response = self.response, self.delegate.error == nil,
  49. case let .failure(error) = validation(self.request, response)
  50. {
  51. self.delegate.error = error
  52. }
  53. }
  54. return self
  55. }
  56. // MARK: - Status Code
  57. /**
  58. Validates that the response has a status code in the specified range.
  59. If validation fails, subsequent calls to response handlers will have an associated error.
  60. - parameter range: The range of acceptable status codes.
  61. - returns: The request.
  62. */
  63. public func validate<S: Sequence where S.Iterator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  64. return validate { _, response in
  65. if acceptableStatusCode.contains(response.statusCode) {
  66. return .success
  67. } else {
  68. let failureReason = "Response status code was unacceptable: \(response.statusCode)"
  69. let error = NSError(
  70. domain: Error.Domain,
  71. code: Error.Code.statusCodeValidationFailed.rawValue,
  72. userInfo: [
  73. NSLocalizedFailureReasonErrorKey: failureReason,
  74. Error.UserInfoKeys.StatusCode: response.statusCode
  75. ]
  76. )
  77. return .failure(error)
  78. }
  79. }
  80. }
  81. // MARK: - Content-Type
  82. private struct MIMEType {
  83. let type: String
  84. let subtype: String
  85. init?(_ string: String) {
  86. let components: [String] = {
  87. let stripped = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  88. let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
  89. return split.components(separatedBy: "/")
  90. }()
  91. if let type = components.first,
  92. let subtype = components.last
  93. {
  94. self.type = type
  95. self.subtype = subtype
  96. } else {
  97. return nil
  98. }
  99. }
  100. func matches(_ mime: MIMEType) -> Bool {
  101. switch (type, subtype) {
  102. case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
  103. return true
  104. default:
  105. return false
  106. }
  107. }
  108. }
  109. /**
  110. Validates that the response has a content type in the specified array.
  111. If validation fails, subsequent calls to response handlers will have an associated error.
  112. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  113. - returns: The request.
  114. */
  115. public func validate<S : Sequence where S.Iterator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  116. return validate { _, response in
  117. guard let validData = self.delegate.data, validData.count > 0 else { return .success }
  118. if let responseContentType = response.mimeType,
  119. let responseMIMEType = MIMEType(responseContentType)
  120. {
  121. for contentType in acceptableContentTypes {
  122. if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
  123. return .success
  124. }
  125. }
  126. } else {
  127. for contentType in acceptableContentTypes {
  128. if let mimeType = MIMEType(contentType), mimeType.type == "*" && mimeType.subtype == "*" {
  129. return .success
  130. }
  131. }
  132. }
  133. let contentType: String
  134. let failureReason: String
  135. if let responseContentType = response.mimeType {
  136. contentType = responseContentType
  137. failureReason = (
  138. "Response content type \"\(responseContentType)\" does not match any acceptable " +
  139. "content types: \(acceptableContentTypes)"
  140. )
  141. } else {
  142. contentType = ""
  143. failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
  144. }
  145. let error = NSError(
  146. domain: Error.Domain,
  147. code: Error.Code.contentTypeValidationFailed.rawValue,
  148. userInfo: [
  149. NSLocalizedFailureReasonErrorKey: failureReason,
  150. Error.UserInfoKeys.ContentType: contentType
  151. ]
  152. )
  153. return .failure(error)
  154. }
  155. }
  156. // MARK: - Automatic
  157. /**
  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. If validation fails, subsequent calls to response handlers will have an associated error.
  161. - returns: The request.
  162. */
  163. public func validate() -> Self {
  164. let acceptableStatusCodes: CountableRange<Int> = 200..<300
  165. let acceptableContentTypes: [String] = {
  166. if let accept = request?.value(forHTTPHeaderField: "Accept") {
  167. return accept.components(separatedBy: ",")
  168. }
  169. return ["*/*"]
  170. }()
  171. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  172. }
  173. }