MyCookieManager.swift 9.81 KB
Newer Older
1 2
//
//  MyCookieManager.swift
3
//  flutter_inappwebview
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
//
//  Created by Lorenzo on 26/10/18.
//

import Foundation
import WebKit

@available(iOS 11.0, *)
class MyCookieManager: NSObject, FlutterPlugin {

    static var registrar: FlutterPluginRegistrar?
    static var channel: FlutterMethodChannel?
    static var httpCookieStore: WKHTTPCookieStore?
    
    static func register(with registrar: FlutterPluginRegistrar) {
        
    }
    
    init(registrar: FlutterPluginRegistrar) {
        super.init()
        MyCookieManager.registrar = registrar
        MyCookieManager.httpCookieStore = WKWebsiteDataStore.default().httpCookieStore
        
27
        MyCookieManager.channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappwebview_cookiemanager", binaryMessenger: registrar.messenger())
28 29 30 31 32 33 34 35 36 37 38 39
        registrar.addMethodCallDelegate(self, channel: MyCookieManager.channel!)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let arguments = call.arguments as? NSDictionary
        switch call.method {
            case "setCookie":
                let url = arguments!["url"] as! String
                let name = arguments!["name"] as! String
                let value = arguments!["value"] as! String
                let domain = arguments!["domain"] as! String
                let path = arguments!["path"] as! String
40 41 42 43 44 45 46
                
                var expiresDate: Int64?
                if let expiresDateString = arguments!["expiresDate"] as? String {
                    expiresDate = Int64(expiresDateString)
                }
                
                let maxAge = arguments!["maxAge"] as? Int64
47
                let isSecure = arguments!["isSecure"] as? Bool
48 49
                let isHttpOnly = arguments!["isHttpOnly"] as? Bool
                let sameSite = arguments!["sameSite"] as? String
50
                
51 52 53 54 55 56 57 58 59 60 61
                MyCookieManager.setCookie(url: url,
                                          name: name,
                                          value: value,
                                          domain: domain,
                                          path: path,
                                          expiresDate: expiresDate,
                                          maxAge: maxAge,
                                          isSecure: isSecure,
                                          isHttpOnly: isHttpOnly,
                                          sameSite: sameSite,
                                          result: result)
62 63 64 65 66 67 68 69 70 71
                break
            case "getCookies":
                let url = arguments!["url"] as! String
                MyCookieManager.getCookies(url: url, result: result)
                break
            case "deleteCookie":
                let url = arguments!["url"] as! String
                let name = arguments!["name"] as! String
                let domain = arguments!["domain"] as! String
                let path = arguments!["path"] as! String
72
                MyCookieManager.deleteCookie(url: url, name: name, domain: domain, path: path, result: result)
73 74 75 76 77
                break;
            case "deleteCookies":
                let url = arguments!["url"] as! String
                let domain = arguments!["domain"] as! String
                let path = arguments!["path"] as! String
78
                MyCookieManager.deleteCookies(url: url, domain: domain, path: path, result: result)
79 80
                break;
            case "deleteAllCookies":
81 82
                MyCookieManager.deleteAllCookies(result: result)
                break
83 84 85 86 87 88 89 90 91 92 93
            default:
                result(FlutterMethodNotImplemented)
                break
        }
    }
    
    public static func setCookie(url: String,
                          name: String,
                          value: String,
                          domain: String,
                          path: String,
94 95
                          expiresDate: Int64?,
                          maxAge: Int64?,
96
                          isSecure: Bool?,
97 98
                          isHttpOnly: Bool?,
                          sameSite: String?,
99 100 101 102 103 104 105 106
                          result: @escaping FlutterResult) {
        var properties: [HTTPCookiePropertyKey: Any] = [:]
        properties[.originURL] = url
        properties[.name] = name
        properties[.value] = value
        properties[.domain] = domain
        properties[.path] = path
        if expiresDate != nil {
107
            // convert from milliseconds
108
            properties[.expires] = Date(timeIntervalSince1970: TimeInterval(Double(expiresDate!)/1000))
109 110 111 112
        }
        if maxAge != nil {
            properties[.maximumAge] = String(maxAge!)
        }
113 114 115
        if isSecure != nil && isSecure! {
            properties[.secure] = "TRUE"
        }
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        if isHttpOnly != nil && isHttpOnly! {
            properties[.init("HttpOnly")] = "YES"
        }
        if sameSite != nil {
            if #available(iOS 13.0, *) {
                var sameSiteValue = HTTPCookieStringPolicy(rawValue: "None")
                switch sameSite {
                case "Lax":
                    sameSiteValue = HTTPCookieStringPolicy.sameSiteLax
                case "Strict":
                    sameSiteValue = HTTPCookieStringPolicy.sameSiteStrict
                default:
                    break
                }
                properties[.sameSitePolicy] = sameSiteValue
            } else {
                properties[.init("SameSite")] = sameSite
            }
        }
135 136
        
        let cookie = HTTPCookie(properties: properties)!
137
        
138 139 140
        MyCookieManager.httpCookieStore!.setCookie(cookie, completionHandler: {() in
            result(true)
        })
141 142 143
    }
    
    public static func getCookies(url: String, result: @escaping FlutterResult) {
144
        var cookieList: [[String: Any?]] = []
145 146 147 148 149 150 151 152 153 154
        
        if let urlHost = URL(string: url)?.host {
            MyCookieManager.httpCookieStore!.getAllCookies { (cookies) in
                for cookie in cookies {
                    if cookie.domain.contains(urlHost) {
                        var sameSite: String? = nil
                        if #available(iOS 13.0, *) {
                            if let sameSiteValue = cookie.sameSitePolicy?.rawValue {
                                sameSite = sameSiteValue.prefix(1).capitalized + sameSiteValue.dropFirst()
                            }
155
                        }
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
                        
                        var expiresDateTimestamp: Int64 = -1
                        if let expiresDate = cookie.expiresDate?.timeIntervalSince1970 {
                            // convert to milliseconds
                            expiresDateTimestamp = Int64(expiresDate * 1000)
                        }
                        
                        cookieList.append([
                            "name": cookie.name,
                            "value": cookie.value,
                            "expiresDate": expiresDateTimestamp != -1 ? expiresDateTimestamp : nil,
                            "isSessionOnly": cookie.isSessionOnly,
                            "domain": cookie.domain,
                            "sameSite": sameSite,
                            "isSecure": cookie.isSecure,
                            "isHttpOnly": cookie.isHTTPOnly,
                            "path": cookie.path,
                        ])
174
                    }
175
                }
176
                result(cookieList)
177
            }
178 179 180
            return
        } else {
            print("Cannot get WebView cookies. No HOST found for URL: \(url)")
181
        }
182 183
        
        result(cookieList)
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    }
    
    public static func deleteCookie(url: String, name: String, domain: String, path: String, result: @escaping FlutterResult) {
        MyCookieManager.httpCookieStore!.getAllCookies { (cookies) in
            for cookie in cookies {
                var originURL = ""
                if cookie.properties![.originURL] is String {
                    originURL = cookie.properties![.originURL] as! String
                }
                else if cookie.properties![.originURL] is URL {
                    originURL = (cookie.properties![.originURL] as! URL).absoluteString
                }
                if (!originURL.isEmpty && originURL != url) {
                    continue
                }
                if cookie.domain.contains(domain) && cookie.name == name && cookie.path == path {
                    MyCookieManager.httpCookieStore!.delete(cookie, completionHandler: {
                        result(true)
                    })
                    return
                }
            }
            result(false)
        }
    }
    
    public static func deleteCookies(url: String, domain: String, path: String, result: @escaping FlutterResult) {
        MyCookieManager.httpCookieStore!.getAllCookies { (cookies) in
            for cookie in cookies {
                var originURL = ""
                if cookie.properties![.originURL] is String {
                    originURL = cookie.properties![.originURL] as! String
                }
                else if cookie.properties![.originURL] is URL{
                    originURL = (cookie.properties![.originURL] as! URL).absoluteString
                }
                if (!originURL.isEmpty && originURL != url) {
                    continue
                }
                if cookie.domain.contains(domain) && cookie.path == path {
                    MyCookieManager.httpCookieStore!.delete(cookie, completionHandler: nil)
                }
            }
            result(true)
        }
    }
    
    public static func deleteAllCookies(result: @escaping FlutterResult) {
        let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeCookies])
        let date = NSDate(timeIntervalSince1970: 0)
        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{
            result(true)
        })
    }
}