From 031f112eb3b89472599ce282cf9589a6ae435208 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Mon, 9 Aug 2021 06:19:44 +0900 Subject: [PATCH] divive HTTP::Cookie --- src/mechanize/cookie.cr | 38 +++++++++++++++++++++++++++++++++++++ src/mechanize/http/agent.cr | 38 +------------------------------------ 2 files changed, 39 insertions(+), 37 deletions(-) create mode 100644 src/mechanize/cookie.cr diff --git a/src/mechanize/cookie.cr b/src/mechanize/cookie.cr new file mode 100644 index 0000000..b82cb22 --- /dev/null +++ b/src/mechanize/cookie.cr @@ -0,0 +1,38 @@ +# TODO: want to add methods with safe way like Ruby's refinement. + +# open HTTP::Cookie class to add origin property. +# origin property represents the origin of the resource. +# if cookie's domain attribute isn't designated, +# this property is used to send cookies to same origin resource. +class ::HTTP::Cookie + property origin : String? + def initialize(name : String, value : String, @path : String? = nil, + @expires : Time? = nil, @domain : String? = nil, + @secure : Bool = false, @http_only : Bool = false, + @samesite : SameSite? = nil, @extension : String? = nil, + @origin : String? = nil) + validate_name(name) + @name = name + validate_value(value) + @value = value + @origin = origin + end + + def valid_cookie?(uri) + host = uri.host + if path + bool = uri.path.try &.=~(/^#{path}.*/) + return false if bool.nil? + end + + if secure + return false if uri.scheme == "http" + end + + if domain + host.try &.=~(/.*#{domain.try &.gsub(".", "\.")}$/) + else + origin == host + end + end +end diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index e02b551..10dc306 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -1,5 +1,6 @@ require "uri" require "http/client" +require "../cookie" module MechanizeCr module HTTP @@ -138,40 +139,3 @@ module MechanizeCr end end end - -# open HTTP::Cookie class to add origin property. -# origin property represents the origin of the resource. -# if cookie's domain attribute isn't designated, -# this property is used to send cookies to same origin resource. -class HTTP::Cookie - property origin : String? - def initialize(name : String, value : String, @path : String? = nil, - @expires : Time? = nil, @domain : String? = nil, - @secure : Bool = false, @http_only : Bool = false, - @samesite : SameSite? = nil, @extension : String? = nil, - @origin : String? = nil) - validate_name(name) - @name = name - validate_value(value) - @value = value - @origin = origin - end - - def valid_cookie?(uri) - host = uri.host - if path - bool = uri.path.try &.=~(/^#{path}.*/) - return false if bool.nil? - end - - if secure - return false if uri.scheme == "http" - end - - if domain - host.try &.=~(/.*#{domain.try &.gsub(".", "\.")}$/) - else - origin == host - end - end -end