O2AccessTokenAuthorizable.swift 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // O2AccessTokenAuthorizable.swift
  3. // O2OA_SDK_Framwork
  4. //
  5. // Created by FancyLou on 2018/11/7.
  6. //
  7. import Foundation
  8. import Moya
  9. public protocol O2APIContextCapable {
  10. var apiContextKey:String { get }
  11. }
  12. public protocol O2AccessTokenAuthorizable {
  13. var shouldAuthorize: Bool { get }
  14. }
  15. public class O2AccessTokenPlugin:PluginType {
  16. public init() {}
  17. var tokenVal:String {
  18. get {
  19. guard let myInfo = O2UserDefaults.shared.myInfo else {
  20. return ""
  21. }
  22. return myInfo.token ?? ""
  23. }
  24. }
  25. var clientVal:String {
  26. get {
  27. let version = ProcessInfo.processInfo.operatingSystemVersion
  28. let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
  29. return "iOS \(versionString)"
  30. }
  31. }
  32. public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
  33. var request = request
  34. //加上通用头
  35. request.addValue(clientVal, forHTTPHeaderField: "x-client")
  36. if let authorizable = target as? O2AccessTokenAuthorizable,authorizable.shouldAuthorize == false {
  37. return request
  38. }
  39. //加上token
  40. let tokenName = O2AuthSDK.shared.tokenName()
  41. request.addValue(tokenVal, forHTTPHeaderField: tokenName)
  42. return request
  43. }
  44. }