From a11cabb3563b775120ff0d5d952891a0ab891320 Mon Sep 17 00:00:00 2001 From: kinggo Date: Fri, 5 May 2023 14:54:39 +0800 Subject: [PATCH] optimize: provides an API to help users modify data using session_id (#9) * chore: add redis store vendor * feat: add SaveSessionWithoutContext and LoadSessionBySessionId * feat: add SaveSessionWithoutContext and LoadSessionBySessionId * feat: add SaveSessionWithoutContext and LoadSessionBySessionId * chore: upgrade hertz version * test: add unit test --- .github/workflows/pr-check.yml | 2 +- .licenserc.yaml | 27 +- _example/cookie/main.go | 63 +-- _example/redis/main.go | 63 +-- cookie/cookie.go | 63 +-- cookie/cookie_test.go | 63 +-- go.mod | 4 +- go.sum | 64 +-- licenses/LICENSE-securecookie | 27 ++ redis/redis.go | 74 ++-- redis/redis_test.go | 63 +-- redis/redistore.go | 426 +++++++++++++++++++ redis/redistore_test.go | 495 +++++++++++++++++++++++ session_options.go | 75 ++++ session_options_go1.10.go | 51 --- session_options_go1.11.go | 63 --- sessions.go | 63 +-- tester/tester.go | 63 +-- tester/tester_options_samesite.go | 79 ++++ tester/tester_options_samesite_go1.10.go | 39 -- tester/tester_options_samesite_go1.11.go | 67 --- 21 files changed, 1460 insertions(+), 474 deletions(-) create mode 100644 licenses/LICENSE-securecookie create mode 100644 redis/redistore.go create mode 100644 redis/redistore_test.go create mode 100644 session_options.go delete mode 100644 session_options_go1.10.go delete mode 100644 session_options_go1.11.go create mode 100644 tester/tester_options_samesite.go delete mode 100644 tester/tester_options_samesite_go1.10.go delete mode 100644 tester/tester_options_samesite_go1.11.go diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml index 9d397d0..51bb967 100644 --- a/.github/workflows/pr-check.yml +++ b/.github/workflows/pr-check.yml @@ -9,7 +9,7 @@ jobs: - uses: actions/checkout@v3 - name: Check License Header - uses: apache/skywalking-eyes@main + uses: apache/skywalking-eyes/header@501a28d2fb4a9b962661987e50cf0219631b32ff env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.licenserc.yaml b/.licenserc.yaml index 72afc4c..41e44dc 100644 --- a/.licenserc.yaml +++ b/.licenserc.yaml @@ -2,34 +2,9 @@ header: license: spdx-id: Apache-2.0 copyright-owner: CloudWeGo Authors - content: | - MIT License - - Copyright (c) 2019 Gin-Gonic - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - - This file may have been modified by CloudWeGo authors. All CloudWeGo - Modifications are Copyright 2022 CloudWeGo Authors. paths: - '**/*.go' - '**/*.s' - - + comment: on-failure diff --git a/_example/cookie/main.go b/_example/cookie/main.go index 41c60ee..9672684 100644 --- a/_example/cookie/main.go +++ b/_example/cookie/main.go @@ -1,27 +1,42 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package main diff --git a/_example/redis/main.go b/_example/redis/main.go index 0835adb..80c96e8 100644 --- a/_example/redis/main.go +++ b/_example/redis/main.go @@ -1,27 +1,42 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package main diff --git a/cookie/cookie.go b/cookie/cookie.go index f498f3f..1633b24 100644 --- a/cookie/cookie.go +++ b/cookie/cookie.go @@ -1,27 +1,42 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package cookie diff --git a/cookie/cookie_test.go b/cookie/cookie_test.go index 326ede9..4ef4d79 100644 --- a/cookie/cookie_test.go +++ b/cookie/cookie_test.go @@ -1,27 +1,42 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package cookie diff --git a/go.mod b/go.mod index 36df95b..be56070 100644 --- a/go.mod +++ b/go.mod @@ -3,9 +3,9 @@ module github.com/hertz-contrib/sessions go 1.16 require ( - github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff - github.com/cloudwego/hertz v0.3.0 + github.com/cloudwego/hertz v0.6.2 github.com/gomodule/redigo v2.0.0+incompatible github.com/gorilla/context v1.1.1 + github.com/gorilla/securecookie v1.1.1 github.com/gorilla/sessions v1.2.1 ) diff --git a/go.sum b/go.sum index 77bfc74..c7fbae4 100644 --- a/go.sum +++ b/go.sum @@ -1,24 +1,24 @@ -github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04= -github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw= github.com/bytedance/go-tagexpr/v2 v2.9.2 h1:QySJaAIQgOEDQBLS3x9BxOWrnhqu5sQ+f6HaZIxD39I= github.com/bytedance/go-tagexpr/v2 v2.9.2/go.mod h1:5qsx05dYOiUXOUgnQ7w3Oz8BYs2qtM/bJokdLb79wRM= github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7 h1:PtwsQyQJGxf8iaPptPNaduEIu9BnrNms+pcRdHAxZaM= github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q= -github.com/bytedance/sonic v1.3.0 h1:T2rlvNytw6bTmczlAXvGqmuMzIqGJBOsJKYwRPWR7Y8= -github.com/bytedance/sonic v1.3.0/go.mod h1:V973WhNhGmvHxW6nQmsHEfHaoU9F3zTF+93rH03hcUQ= -github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06 h1:1sDoSuDPWzhkdzNVxCxtIaKiAe96ESVPv8coGwc1gZ4= +github.com/bytedance/mockey v1.2.1 h1:g84ngI88hz1DR4wZTL3yOuqlEcq67MretBfQUdXwrmw= +github.com/bytedance/mockey v1.2.1/go.mod h1:+Jm/fzWZAuhEDrPXVjDf/jLM2BlLXJkwk94zf2JZ3X4= +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.8.1 h1:NqAHCaGaTzro0xMmnTCLUyRlbEP6r8MCA1cJUrH3Pu4= +github.com/bytedance/sonic v1.8.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= -github.com/cloudwego/hertz v0.2.1 h1:59q5azeMJisErOKTrxxxRURiUrGCjJ7gABgwOpejTkc= -github.com/cloudwego/hertz v0.2.1/go.mod h1:prTyExvsH/UmDkvfU3dp3EHsZFQISfT8R7BirvpTKdo= -github.com/cloudwego/hertz v0.3.0 h1:gyKaw/uc7I2YLuCzqWHD3G2W8MVKRZPZ5u8k8tiDBbk= -github.com/cloudwego/hertz v0.3.0/go.mod h1:GWWYlAVkq1gDu6vJd/XNciWsP6q0d4TrEKk5fpJYF04= -github.com/cloudwego/netpoll v0.2.4 h1:Kbo2HA1cXEgoy/bu1jSNrjcqZj2diENcJqLy6vKiROU= -github.com/cloudwego/netpoll v0.2.4/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/cloudwego/hertz v0.6.2 h1:8NM0yHbyv8B4dNYgICirk733S7monTNB+uR9as1It1Y= +github.com/cloudwego/hertz v0.6.2/go.mod h1:2em2hGREvCBawsTQcQxyWBGVlCeo+N1pp2q0HkkbwR0= +github.com/cloudwego/netpoll v0.3.1 h1:xByoORmCLIyKZ8gS+da06WDo3j+jvmhaqS2KeKejtBk= +github.com/cloudwego/netpoll v0.3.1/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/goccy/go-json v0.9.4 h1:L8MLKG2mvVXiQu07qB6hmfqeSYQdOnqPot2GhsIwIaI= -github.com/goccy/go-json v0.9.4/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0 h1:LUVKkCeviFUMKqHa4tXIIij/lbhnMbP7Fn5wKdKkRh4= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= @@ -26,12 +26,12 @@ github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNu github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= -github.com/gorilla/sessions v1.1.1/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/henrylee2cn/ameda v1.4.8/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= @@ -39,40 +39,49 @@ github.com/henrylee2cn/ameda v1.4.10 h1:JdvI2Ekq7tapdPsuhrc4CaFiqw6QXFvZIULWJgQy github.com/henrylee2cn/ameda v1.4.10/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8 h1:yE9ULgp02BhYIrO6sdV/FPe0xQM6fNHkVQW2IAymfM0= github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8/go.mod h1:Nhe/DM3671a5udlv2AdV2ni/MZzgfv2qrPL5nIi3EGQ= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/nyaruka/phonenumbers v1.0.55 h1:bj0nTO88Y68KeUQ/n3Lo2KgK7lM1hF7L9NFuwcCl3yg= github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.12.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.13.0 h1:3TFY9yxOQShrvmjdM76K+jc66zJeT6D3/VFFYCGQf7M= github.com/tidwall/gjson v1.13.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/sjson v1.2.4 h1:cuiLzLnaMeBhRmEv00Lpk3tkYrcxpmbU81tAY4Dw0tc= -github.com/tidwall/sjson v1.2.4/go.mod h1:098SZ494YoMWPmMO6ct4dcFnqxwj9r/gF0Etp19pSNM= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20220110181412-a018aaa089fe/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= @@ -80,6 +89,7 @@ google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+Rur google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/licenses/LICENSE-securecookie b/licenses/LICENSE-securecookie new file mode 100644 index 0000000..0e5fb87 --- /dev/null +++ b/licenses/LICENSE-securecookie @@ -0,0 +1,27 @@ +Copyright (c) 2012 Rodrigo Moraes. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/redis/redis.go b/redis/redis.go index 23c305a..2c4931d 100644 --- a/redis/redis.go +++ b/redis/redis.go @@ -1,34 +1,48 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package redis import ( "errors" - "github.com/boj/redistore" "github.com/gomodule/redigo/redis" "github.com/hertz-contrib/sessions" ) @@ -38,7 +52,7 @@ type Store interface { } type store struct { - *redistore.RediStore + *RediStore } func (s *store) Options(opts sessions.Options) { @@ -46,7 +60,7 @@ func (s *store) Options(opts sessions.Options) { } func NewStore(size int, network, addr, passwd string, keyPairs ...[]byte) (Store, error) { - s, err := redistore.NewRediStore(size, network, addr, passwd, keyPairs...) + s, err := NewRediStore(size, network, addr, passwd, keyPairs...) if err != nil { return nil, err } @@ -58,7 +72,7 @@ func NewStore(size int, network, addr, passwd string, keyPairs ...[]byte) (Store // // Ref: https://godoc.org/github.com/boj/redistore#NewRediStoreWithDB func NewStoreWithDB(size int, network, addr, passwd, DB string, keyPairs ...[]byte) (Store, error) { - s, err := redistore.NewRediStoreWithDB(size, network, addr, passwd, DB, keyPairs...) + s, err := NewRediStoreWithDB(size, network, addr, passwd, DB, keyPairs...) if err != nil { return nil, err } @@ -69,7 +83,7 @@ func NewStoreWithDB(size int, network, addr, passwd, DB string, keyPairs ...[]by // // Ref: https://godoc.org/github.com/boj/redistore#NewRediStoreWithPool func NewStoreWithPool(pool *redis.Pool, keyPairs ...[]byte) (Store, error) { - s, err := redistore.NewRediStoreWithPool(pool, keyPairs...) + s, err := NewRediStoreWithPool(pool, keyPairs...) if err != nil { return nil, err } @@ -89,7 +103,7 @@ func SetKeyPrefix(s Store, prefix string) error { // GetRedisStore get the actual working store. // Ref: https://godoc.org/github.com/boj/redistore#RediStore -func GetRedisStore(s Store) (rediStore *redistore.RediStore, err error) { +func GetRedisStore(s Store) (rediStore *RediStore, err error) { realStore, ok := s.(*store) if !ok { err = errors.New("unable to get the redis store: Store isn't *store") diff --git a/redis/redis_test.go b/redis/redis_test.go index afb112f..f78f592 100644 --- a/redis/redis_test.go +++ b/redis/redis_test.go @@ -1,27 +1,42 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package redis diff --git a/redis/redistore.go b/redis/redistore.go new file mode 100644 index 0000000..9fdfdd2 --- /dev/null +++ b/redis/redistore.go @@ -0,0 +1,426 @@ +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * Copyright (c) 2012 Rodrigo Moraes. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ + +package redis + +import ( + "bytes" + "encoding/base32" + "encoding/gob" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/cloudwego/hertz/pkg/common/hlog" + + "github.com/gomodule/redigo/redis" + "github.com/gorilla/securecookie" + "github.com/gorilla/sessions" +) + +// Amount of time for cookies/redis keys to expire. +var sessionExpire = 86400 * 30 + +// SessionSerializer provides an interface hook for alternative serializers +type SessionSerializer interface { + Deserialize(d []byte, ss *sessions.Session) error + Serialize(ss *sessions.Session) ([]byte, error) +} + +// JSONSerializer encode the session map to JSON. +type JSONSerializer struct{} + +// Serialize to JSON. Will err if there are unmarshalable key values +func (s JSONSerializer) Serialize(ss *sessions.Session) ([]byte, error) { + m := make(map[string]interface{}, len(ss.Values)) + for k, v := range ss.Values { + ks, ok := k.(string) + if !ok { + err := fmt.Errorf("non-string key value, cannot serialize session to JSON: %v", k) + hlog.Errorf("redistore.JSONSerializer.serialize() Error: %v", err) + return nil, err + } + m[ks] = v + } + return json.Marshal(m) +} + +// Deserialize back to map[string]interface{} +func (s JSONSerializer) Deserialize(d []byte, ss *sessions.Session) error { + m := make(map[string]interface{}) + err := json.Unmarshal(d, &m) + if err != nil { + hlog.Errorf("redistore.JSONSerializer.deserialize() Error: %v", err) + return err + } + for k, v := range m { + ss.Values[k] = v + } + return nil +} + +// GobSerializer uses gob package to encode the session map +type GobSerializer struct{} + +// Serialize using gob +func (s GobSerializer) Serialize(ss *sessions.Session) ([]byte, error) { + buf := new(bytes.Buffer) + enc := gob.NewEncoder(buf) + err := enc.Encode(ss.Values) + if err == nil { + return buf.Bytes(), nil + } + return nil, err +} + +// Deserialize back to map[interface{}]interface{} +func (s GobSerializer) Deserialize(d []byte, ss *sessions.Session) error { + dec := gob.NewDecoder(bytes.NewBuffer(d)) + return dec.Decode(&ss.Values) +} + +// RediStore stores sessions in a redis backend. +type RediStore struct { + Pool *redis.Pool + Codecs []securecookie.Codec + Options *sessions.Options // default configuration + DefaultMaxAge int // default Redis TTL for a MaxAge == 0 session + maxLength int + keyPrefix string + serializer SessionSerializer +} + +// SetMaxLength sets RediStore.maxLength if the `l` argument is greater or equal 0 +// maxLength restricts the maximum length of new sessions to l. +// If l is 0 there is no limit to the size of a session, use with caution. +// The default for a new RediStore is 4096. Redis allows for max. +// value sizes of up to 512MB (http://redis.io/topics/data-types) +// Default: 4096, +func (s *RediStore) SetMaxLength(l int) { + if l >= 0 { + s.maxLength = l + } +} + +// SetKeyPrefix set the prefix +func (s *RediStore) SetKeyPrefix(p string) { + s.keyPrefix = p +} + +// SetSerializer sets the serializer +func (s *RediStore) SetSerializer(ss SessionSerializer) { + s.serializer = ss +} + +// SetMaxAge restricts the maximum age, in seconds, of the session record +// both in database and a browser. This is to change session storage configuration. +// If you want just to remove session use your session `s` object and change it's +// `Options.MaxAge` to -1, as specified in +// +// http://godoc.org/github.com/gorilla/sessions#Options +// +// Default is the one provided by this package value - `sessionExpire`. +// Set it to 0 for no restriction. +// Because we use `MaxAge` also in SecureCookie crypting algorithm you should +// use this function to change `MaxAge` value. +func (s *RediStore) SetMaxAge(v int) { + var c *securecookie.SecureCookie + var ok bool + s.Options.MaxAge = v + for i := range s.Codecs { + if c, ok = s.Codecs[i].(*securecookie.SecureCookie); ok { + c.MaxAge(v) + } else { + hlog.Warnf("Can't change MaxAge on codec %v\n", s.Codecs[i]) + } + } +} + +func dial(network, address, password string) (redis.Conn, error) { + c, err := redis.Dial(network, address) + if err != nil { + return nil, err + } + if password != "" { + if _, err := c.Do("AUTH", password); err != nil { + c.Close() + return nil, err + } + } + return c, err +} + +// NewRediStore returns a new RediStore. +// size: maximum number of idle connections. +func NewRediStore(size int, network, address, password string, keyPairs ...[]byte) (*RediStore, error) { + return NewRediStoreWithPool(&redis.Pool{ + MaxIdle: size, + IdleTimeout: 240 * time.Second, + TestOnBorrow: func(c redis.Conn, t time.Time) error { + _, err := c.Do("PING") + return err + }, + Dial: func() (redis.Conn, error) { + return dial(network, address, password) + }, + }, keyPairs...) +} + +func dialWithDB(network, address, password, DB string) (redis.Conn, error) { + c, err := dial(network, address, password) + if err != nil { + return nil, err + } + if _, err := c.Do("SELECT", DB); err != nil { + c.Close() + return nil, err + } + return c, err +} + +// NewRediStoreWithDB - like NewRedisStore but accepts `DB` parameter to select +// redis DB instead of using the default one ("0") +func NewRediStoreWithDB(size int, network, address, password, DB string, keyPairs ...[]byte) (*RediStore, error) { + return NewRediStoreWithPool(&redis.Pool{ + MaxIdle: size, + IdleTimeout: 240 * time.Second, + TestOnBorrow: func(c redis.Conn, t time.Time) error { + _, err := c.Do("PING") + return err + }, + Dial: func() (redis.Conn, error) { + return dialWithDB(network, address, password, DB) + }, + }, keyPairs...) +} + +// NewRediStoreWithPool instantiates a RediStore with a *redis.Pool passed in. +func NewRediStoreWithPool(pool *redis.Pool, keyPairs ...[]byte) (*RediStore, error) { + rs := &RediStore{ + // http://godoc.org/github.com/gomodule/redigo/redis#Pool + Pool: pool, + Codecs: securecookie.CodecsFromPairs(keyPairs...), + Options: &sessions.Options{ + Path: "/", + MaxAge: sessionExpire, + }, + DefaultMaxAge: 60 * 20, // 20 minutes seems like a reasonable default + maxLength: 4096, + keyPrefix: "session_", + serializer: GobSerializer{}, + } + _, err := rs.ping() + return rs, err +} + +// Close closes the underlying *redis.Pool +func (s *RediStore) Close() error { + return s.Pool.Close() +} + +// Get returns a session for the given name after adding it to the registry. +// +// See gorilla/sessions FilesystemStore.Get(). +func (s *RediStore) Get(r *http.Request, name string) (*sessions.Session, error) { + return sessions.GetRegistry(r).Get(s, name) +} + +// New returns a session for the given name without adding it to the registry. +// +// See gorilla/sessions FilesystemStore.New(). +func (s *RediStore) New(r *http.Request, name string) (*sessions.Session, error) { + var ( + err error + ok bool + ) + session := sessions.NewSession(s, name) + // make a copy + options := *s.Options + session.Options = &options + session.IsNew = true + if c, errCookie := r.Cookie(name); errCookie == nil { + err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...) + if err == nil { + ok, err = s.load(session) + session.IsNew = !(err == nil && ok) // not new if no error and data available + } + } + return session, err +} + +// Save adds a single session to the response. +func (s *RediStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { + // Marked for deletion. + if session.Options.MaxAge <= 0 { + if err := s.delete(session); err != nil { + return err + } + http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options)) + } else { + // Build an alphanumeric key for the redis store. + if session.ID == "" { + session.ID = strings.TrimRight(base32.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)), "=") + } + if err := s.save(session); err != nil { + return err + } + encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, s.Codecs...) + if err != nil { + return err + } + http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options)) + } + return nil +} + +// Delete removes the session from redis, and sets the cookie to expire. +// +// WARNING: This method should be considered deprecated since it is not exposed via the gorilla/sessions interface. +// Set session.Options.MaxAge = -1 and call Save instead. - July 18th, 2013 +func (s *RediStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { + conn := s.Pool.Get() + defer conn.Close() + if _, err := conn.Do("DEL", s.keyPrefix+session.ID); err != nil { + return err + } + // Set cookie to expire. + options := *session.Options + options.MaxAge = -1 + http.SetCookie(w, sessions.NewCookie(session.Name(), "", &options)) + // Clear session values. + for k := range session.Values { + delete(session.Values, k) + } + return nil +} + +// ping does an internal ping against a server to check if it is alive. +func (s *RediStore) ping() (bool, error) { + conn := s.Pool.Get() + defer conn.Close() + data, err := conn.Do("PING") + if err != nil || data == nil { + return false, err + } + return (data == "PONG"), nil +} + +// save stores the session in redis. +func (s *RediStore) save(session *sessions.Session) error { + b, err := s.serializer.Serialize(session) + if err != nil { + return err + } + if s.maxLength != 0 && len(b) > s.maxLength { + return errors.New("SessionStore: the value to store is too big") + } + conn := s.Pool.Get() + defer conn.Close() + if err = conn.Err(); err != nil { + return err + } + age := session.Options.MaxAge + if age == 0 { + age = s.DefaultMaxAge + } + _, err = conn.Do("SETEX", s.keyPrefix+session.ID, age, b) + return err +} + +// load reads the session from redis. +// returns true if there is a sessoin data in DB +func (s *RediStore) load(session *sessions.Session) (bool, error) { + conn := s.Pool.Get() + defer conn.Close() + if err := conn.Err(); err != nil { + return false, err + } + data, err := conn.Do("GET", s.keyPrefix+session.ID) + if err != nil { + return false, err + } + if data == nil { + return false, nil // no data was associated with this key + } + b, err := redis.Bytes(data, err) + if err != nil { + return false, err + } + return true, s.serializer.Deserialize(b, session) +} + +// delete removes keys from redis if MaxAge<0 +func (s *RediStore) delete(session *sessions.Session) error { + conn := s.Pool.Get() + defer conn.Close() + if _, err := conn.Do("DEL", s.keyPrefix+session.ID); err != nil { + return err + } + return nil +} + +// LoadSessionBySessionId Get session using session_id even without a context +func LoadSessionBySessionId(s *RediStore, sessionId string) (*sessions.Session, error) { + var session sessions.Session + session.ID = sessionId + exist, err := s.load(&session) + if err != nil { + return nil, err + } + if !exist { + return nil, nil + } + return &session, nil +} + +// SaveSessionWithoutContext Save session even without a context +func SaveSessionWithoutContext(s *RediStore, sessionId string, session *sessions.Session) error { + session.ID = sessionId + return s.save(session) +} diff --git a/redis/redistore_test.go b/redis/redistore_test.go new file mode 100644 index 0000000..fb6133e --- /dev/null +++ b/redis/redistore_test.go @@ -0,0 +1,495 @@ +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * Copyright (c) 2012 Rodrigo Moraes. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ + +package redis + +import ( + "bytes" + "encoding/base64" + "encoding/gob" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gorilla/sessions" +) + +func setup() string { + return redisTestServer +} + +// ---------------------------------------------------------------------------- +// ResponseRecorder +// ---------------------------------------------------------------------------- +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// ResponseRecorder is an implementation of http.ResponseWriter that +// records its mutations for later inspection in tests. +type ResponseRecorder struct { + Code int // the HTTP response code from WriteHeader + HeaderMap http.Header // the HTTP response headers + Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to + Flushed bool +} + +// NewRecorder returns an initialized ResponseRecorder. +func NewRecorder() *ResponseRecorder { + return &ResponseRecorder{ + HeaderMap: make(http.Header), + Body: new(bytes.Buffer), + } +} + +// Header returns the response headers. +func (rw *ResponseRecorder) Header() http.Header { + return rw.HeaderMap +} + +// Write always succeeds and writes to rw.Body, if not nil. +func (rw *ResponseRecorder) Write(buf []byte) (int, error) { + if rw.Body != nil { + rw.Body.Write(buf) + } + if rw.Code == 0 { + rw.Code = http.StatusOK + } + return len(buf), nil +} + +// WriteHeader sets rw.Code. +func (rw *ResponseRecorder) WriteHeader(code int) { + rw.Code = code +} + +// Flush sets rw.Flushed to true. +func (rw *ResponseRecorder) Flush() { + rw.Flushed = true +} + +// ---------------------------------------------------------------------------- + +type FlashMessage struct { + Type int + Message string +} + +func TestRediStore(t *testing.T) { + var ( + req *http.Request + rsp *ResponseRecorder + hdr http.Header + ok bool + cookies []string + session *sessions.Session + flashes []interface{} + ) + + // Copyright 2012 The Gorilla Authors. All rights reserved. + // Use of this source code is governed by a BSD-style + // license that can be found in the LICENSE file. + + // Round 1 ---------------------------------------------------------------- + { + // RedisStore + addr := setup() + store, err := NewRediStore(10, "tcp", addr, "", []byte("secret-key")) + if err != nil { + t.Fatal(err.Error()) + } + defer store.Close() + + req, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + rsp = NewRecorder() + // Get a session. + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Get a flash. + flashes = session.Flashes() + if len(flashes) != 0 { + t.Errorf("Expected empty flashes; Got %v", flashes) + } + // Add some flashes. + session.AddFlash("foo") + session.AddFlash("bar") + // Custom key. + session.AddFlash("baz", "custom_key") + // Save. + if err = sessions.Save(req, rsp); err != nil { + t.Fatalf("Error saving session: %v", err) + } + hdr = rsp.Header() + cookies, ok = hdr["Set-Cookie"] + if !ok || len(cookies) != 1 { + t.Fatalf("No cookies. Header: %s", hdr) + } + } + + // Round 2 ---------------------------------------------------------------- + { + + addr := setup() + store, err := NewRediStore(10, "tcp", addr, "", []byte("secret-key")) + if err != nil { + t.Fatal(err.Error()) + } + defer store.Close() + + req, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + req.Header.Add("Cookie", cookies[0]) + rsp = NewRecorder() + // Get a session. + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Check all saved values. + flashes = session.Flashes() + if len(flashes) != 2 { + t.Fatalf("Expected flashes; Got %v", flashes) + } + if flashes[0] != "foo" || flashes[1] != "bar" { + t.Errorf("Expected foo,bar; Got %v", flashes) + } + flashes = session.Flashes() + if len(flashes) != 0 { + t.Errorf("Expected dumped flashes; Got %v", flashes) + } + // Custom key. + flashes = session.Flashes("custom_key") + if len(flashes) != 1 { + t.Errorf("Expected flashes; Got %v", flashes) + } else if flashes[0] != "baz" { + t.Errorf("Expected baz; Got %v", flashes) + } + flashes = session.Flashes("custom_key") + if len(flashes) != 0 { + t.Errorf("Expected dumped flashes; Got %v", flashes) + } + + // RediStore specific + // Set MaxAge to -1 to mark for deletion. + session.Options.MaxAge = -1 + // Save. + if err = sessions.Save(req, rsp); err != nil { + t.Fatalf("Error saving session: %v", err) + } + } + + // Round 3 ---------------------------------------------------------------- + // Custom type + + // RedisStore + { + addr := setup() + store, err := NewRediStore(10, "tcp", addr, "", []byte("secret-key")) + if err != nil { + t.Fatal(err.Error()) + } + defer store.Close() + + req, _ = http.NewRequest("GET", "http://localhost:8080/", nil) + rsp = NewRecorder() + // Get a session. + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Get a flash. + flashes = session.Flashes() + if len(flashes) != 0 { + t.Errorf("Expected empty flashes; Got %v", flashes) + } + // Add some flashes. + session.AddFlash(&FlashMessage{42, "foo"}) + // Save. + if err = sessions.Save(req, rsp); err != nil { + t.Fatalf("Error saving session: %v", err) + } + hdr = rsp.Header() + cookies, ok = hdr["Set-Cookie"] + if !ok || len(cookies) != 1 { + t.Fatalf("No cookies. Header: %s", hdr) + } + + sID := session.ID + s, err := LoadSessionBySessionId(store, sID) + if err != nil { + t.Fatalf("LoadSessionBySessionId Error: %v", err) + } + + if len(s.Values) == 0 { + t.Fatalf("No session value: %s", hdr) + } + } + + // Round 4 ---------------------------------------------------------------- + // Custom type + { + addr := setup() + store, err := NewRediStore(10, "tcp", addr, "", []byte("secret-key")) + if err != nil { + t.Fatal(err.Error()) + } + defer store.Close() + + req, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + req.Header.Add("Cookie", cookies[0]) + rsp = NewRecorder() + // Get a session. + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Check all saved values. + flashes = session.Flashes() + if len(flashes) != 1 { + t.Fatalf("Expected flashes; Got %v", flashes) + } + custom := flashes[0].(FlashMessage) + if custom.Type != 42 || custom.Message != "foo" { + t.Errorf("Expected %#v, got %#v", FlashMessage{42, "foo"}, custom) + } + + // RediStore specific + // Set MaxAge to -1 to mark for deletion. + session.Options.MaxAge = -1 + // Save. + if err = sessions.Save(req, rsp); err != nil { + t.Fatalf("Error saving session: %v", err) + } + } + + // Round 5 ---------------------------------------------------------------- + // RediStore Delete session (deprecated) + + //req, _ = http.NewRequest("GET", "http://localhost:8080/", nil) + //req.Header.Add("Cookie", cookies[0]) + //rsp = NewRecorder() + //// Get a session. + //if session, err = store.Get(req, "session-key"); err != nil { + // t.Fatalf("Error getting session: %v", err) + //} + //// Delete session. + //if err = store.Delete(req, rsp, session); err != nil { + // t.Fatalf("Error deleting session: %v", err) + //} + //// Get a flash. + //flashes = session.Flashes() + //if len(flashes) != 0 { + // t.Errorf("Expected empty flashes; Got %v", flashes) + //} + //hdr = rsp.Header() + //cookies, ok = hdr["Set-Cookie"] + //if !ok || len(cookies) != 1 { + // t.Fatalf("No cookies. Header:", hdr) + //} + + // Round 6 ---------------------------------------------------------------- + // RediStore change MaxLength of session + + { + addr := setup() + store, err := NewRediStore(10, "tcp", addr, "", []byte("secret-key")) + if err != nil { + t.Fatal(err.Error()) + } + req, err = http.NewRequest("GET", "http://www.example.com", nil) + if err != nil { + t.Fatal("failed to create request", err) + } + w := httptest.NewRecorder() + + session, err = store.New(req, "my session") + if err != nil { + t.Fatal("failed to New store", err) + } + session.Values["big"] = make([]byte, base64.StdEncoding.DecodedLen(4096*2)) + err = session.Save(req, w) + if err == nil { + t.Fatal("expected an error, got nil") + } + + store.SetMaxLength(4096 * 3) // A bit more than the value size to account for encoding overhead. + err = session.Save(req, w) + if err != nil { + t.Fatal("failed to Save:", err) + } + } + + // Round 7 ---------------------------------------------------------------- + + // RedisStoreWithDB + { + addr := setup() + store, err := NewRediStoreWithDB(10, "tcp", addr, "", "1", []byte("secret-key")) + if err != nil { + t.Fatal(err.Error()) + } + defer store.Close() + + req, _ = http.NewRequest("GET", "http://localhost:8080/", nil) + rsp = NewRecorder() + // Get a session. Using the same key as previously, but on different DB + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Get a flash. + flashes = session.Flashes() + if len(flashes) != 0 { + t.Errorf("Expected empty flashes; Got %v", flashes) + } + // Add some flashes. + session.AddFlash("foo") + // Save. + if err = sessions.Save(req, rsp); err != nil { + t.Fatalf("Error saving session: %v", err) + } + hdr = rsp.Header() + cookies, ok = hdr["Set-Cookie"] + if !ok || len(cookies) != 1 { + t.Fatalf("No cookies. Header: %s", hdr) + } + + // Get a session. + req.Header.Add("Cookie", cookies[0]) + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Check all saved values. + flashes = session.Flashes() + if len(flashes) != 1 { + t.Fatalf("Expected flashes; Got %v", flashes) + } + if flashes[0] != "foo" { + t.Errorf("Expected foo,bar; Got %v", flashes) + } + } + + // Round 8 ---------------------------------------------------------------- + // JSONSerializer + + // RedisStore + { + addr := setup() + store, err := NewRediStore(10, "tcp", addr, "", []byte("secret-key")) + store.SetSerializer(JSONSerializer{}) + if err != nil { + t.Fatal(err.Error()) + } + defer store.Close() + + req, _ = http.NewRequest("GET", "http://localhost:8080/", nil) + rsp = NewRecorder() + // Get a session. + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Get a flash. + flashes = session.Flashes() + if len(flashes) != 0 { + t.Errorf("Expected empty flashes; Got %v", flashes) + } + // Add some flashes. + session.AddFlash("foo") + // Save. + if err = sessions.Save(req, rsp); err != nil { + t.Fatalf("Error saving session: %v", err) + } + hdr = rsp.Header() + cookies, ok = hdr["Set-Cookie"] + if !ok || len(cookies) != 1 { + t.Fatalf("No cookies. Header: %s", hdr) + } + + // Get a session. + req.Header.Add("Cookie", cookies[0]) + if session, err = store.Get(req, "session-key"); err != nil { + t.Fatalf("Error getting session: %v", err) + } + // Check all saved values. + flashes = session.Flashes() + if len(flashes) != 1 { + t.Fatalf("Expected flashes; Got %v", flashes) + } + if flashes[0] != "foo" { + t.Errorf("Expected foo,bar; Got %v", flashes) + } + } +} + +func TestPingGoodPort(t *testing.T) { + store, _ := NewRediStore(10, "tcp", ":6379", "", []byte("secret-key")) + defer store.Close() + ok, err := store.ping() + if err != nil { + t.Error(err.Error()) + } + if !ok { + t.Error("Expected server to PONG") + } +} + +func TestPingBadPort(t *testing.T) { + store, _ := NewRediStore(10, "tcp", ":6378", "", []byte("secret-key")) + defer store.Close() + _, err := store.ping() + if err == nil { + t.Error("Expected error") + } +} + +func ExampleRediStore() { + // RedisStore + store, err := NewRediStore(10, "tcp", ":6379", "", []byte("secret-key")) + if err != nil { + panic(err) + } + defer store.Close() +} + +func init() { + gob.Register(FlashMessage{}) +} diff --git a/session_options.go b/session_options.go new file mode 100644 index 0000000..02eead8 --- /dev/null +++ b/session_options.go @@ -0,0 +1,75 @@ +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ + +package sessions + +import ( + "net/http" + + gsessions "github.com/gorilla/sessions" +) + +// Options stores configuration for a session or session store. +// Fields are a subset of http.Cookie fields. +type Options struct { + Path string + Domain string + // MaxAge=0 means no 'Max-Age' attribute specified. + // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. + // MaxAge>0 means Max-Age attribute present and given in seconds. + MaxAge int + Secure bool + HttpOnly bool + // rfc-draft to preventing CSRF: https://tools.ietf.org/html/draft-west-first-party-cookies-07 + // refer: https://godoc.org/net/http + // https://www.sjoerdlangkemper.nl/2016/04/14/preventing-csrf-with-samesite-cookie-attribute/ + SameSite http.SameSite +} + +func (o Options) ToGorillaOptions() *gsessions.Options { + return &gsessions.Options{ + Path: o.Path, + Domain: o.Domain, + MaxAge: o.MaxAge, + Secure: o.Secure, + HttpOnly: o.HttpOnly, + SameSite: o.SameSite, + } +} diff --git a/session_options_go1.10.go b/session_options_go1.10.go deleted file mode 100644 index 7ae9264..0000000 --- a/session_options_go1.10.go +++ /dev/null @@ -1,51 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. - -//go:build !go1.11 -// +build !go1.11 - -package sessions - -// Options stores configuration for a session or session store. -// Fields are a subset of http.Cookie fields. -type Options struct { - Path string - Domain string - // MaxAge=0 means no 'Max-Age' attribute specified. - // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. - // MaxAge>0 means Max-Age attribute present and given in seconds. - MaxAge int - Secure bool - HttpOnly bool -} - -func (o Options) ToGorillaOptions() *gsessions.Options { - return &gsessions.Options{ - Path: o.Path, - Domain: o.Domain, - MaxAge: o.MaxAge, - HttpOnly: o.HttpOnly, - } -} diff --git a/session_options_go1.11.go b/session_options_go1.11.go deleted file mode 100644 index c395578..0000000 --- a/session_options_go1.11.go +++ /dev/null @@ -1,63 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. - -//go:build go1.11 -// +build go1.11 - -package sessions - -import ( - "net/http" - - gsessions "github.com/gorilla/sessions" -) - -// Options stores configuration for a session or session store. -// Fields are a subset of http.Cookie fields. -type Options struct { - Path string - Domain string - // MaxAge=0 means no 'Max-Age' attribute specified. - // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. - // MaxAge>0 means Max-Age attribute present and given in seconds. - MaxAge int - Secure bool - HttpOnly bool - // rfc-draft to preventing CSRF: https://tools.ietf.org/html/draft-west-first-party-cookies-07 - // refer: https://godoc.org/net/http - // https://www.sjoerdlangkemper.nl/2016/04/14/preventing-csrf-with-samesite-cookie-attribute/ - SameSite http.SameSite -} - -func (o Options) ToGorillaOptions() *gsessions.Options { - return &gsessions.Options{ - Path: o.Path, - Domain: o.Domain, - MaxAge: o.MaxAge, - Secure: o.Secure, - HttpOnly: o.HttpOnly, - SameSite: o.SameSite, - } -} diff --git a/sessions.go b/sessions.go index 8cdaa7f..ff43c03 100644 --- a/sessions.go +++ b/sessions.go @@ -1,27 +1,42 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package sessions diff --git a/tester/tester.go b/tester/tester.go index 6b1dc29..736e624 100644 --- a/tester/tester.go +++ b/tester/tester.go @@ -1,27 +1,42 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ package tester diff --git a/tester/tester_options_samesite.go b/tester/tester_options_samesite.go new file mode 100644 index 0000000..f585951 --- /dev/null +++ b/tester/tester_options_samesite.go @@ -0,0 +1,79 @@ +/* + * Copyright 2023 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * The MIT License (MIT) + * + * Copyright (c) 2016 Bo-Yi Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * +* This file may have been modified by CloudWeGo authors. All CloudWeGo +* Modifications are Copyright 2022 CloudWeGo Authors. +*/ + +package tester + +import ( + "context" + "net/http" + "strings" + "testing" + + "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego/hertz/pkg/common/adaptor" + "github.com/cloudwego/hertz/pkg/common/ut" + "github.com/cloudwego/hertz/pkg/protocol/consts" + "github.com/cloudwego/hertz/pkg/route" + "github.com/hertz-contrib/sessions" +) + +func testOptionSameSitego(t *testing.T, r *route.Engine) { + r.GET("/sameSite", func(ctx context.Context, c *app.RequestContext) { + session := sessions.Default(c) + session.Set("key", ok) + session.Options(sessions.Options{ + SameSite: http.SameSiteStrictMode, + }) + _ = session.Save() + c.String(200, ok) + }) + + w1 := ut.PerformRequest(r, consts.MethodGet, "/sameSite", nil) + res3 := w1.Result() + resp3 := adaptor.GetCompatResponseWriter(res3) + // res3 := httptest.NewRecorder() + // req3, _ := http.NewRequest("GET", "/sameSite", nil) + // r.ServeHTTP(res3, req3) + + s := strings.Split(resp3.Header().Get("Set-Cookie"), ";") + if s[1] != " SameSite=Strict" { + t.Error("Error writing same site with options:", s[1]) + } +} diff --git a/tester/tester_options_samesite_go1.10.go b/tester/tester_options_samesite_go1.10.go deleted file mode 100644 index 0eb1f9d..0000000 --- a/tester/tester_options_samesite_go1.10.go +++ /dev/null @@ -1,39 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. - -//go:build !go1.11 -// +build !go1.11 - -package tester - -import ( - "testing" - - "github.com/cloudwego/hertz/pkg/route" -) - -func testOptionSameSitego(t *testing.T, r *route.Engine) { - // not supported -} diff --git a/tester/tester_options_samesite_go1.11.go b/tester/tester_options_samesite_go1.11.go deleted file mode 100644 index a05be6d..0000000 --- a/tester/tester_options_samesite_go1.11.go +++ /dev/null @@ -1,67 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2016 Bo-Yi Wu -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// This file may have been modified by CloudWeGo authors. All CloudWeGo -// Modifications are Copyright 2022 CloudWeGo Authors. - -//go:build go1.11 -// +build go1.11 - -package tester - -import ( - "context" - "net/http" - "strings" - "testing" - - "github.com/cloudwego/hertz/pkg/app" - "github.com/cloudwego/hertz/pkg/common/adaptor" - "github.com/cloudwego/hertz/pkg/common/ut" - "github.com/cloudwego/hertz/pkg/protocol/consts" - "github.com/cloudwego/hertz/pkg/route" - "github.com/hertz-contrib/sessions" -) - -func testOptionSameSitego(t *testing.T, r *route.Engine) { - r.GET("/sameSite", func(ctx context.Context, c *app.RequestContext) { - session := sessions.Default(c) - session.Set("key", ok) - session.Options(sessions.Options{ - SameSite: http.SameSiteStrictMode, - }) - _ = session.Save() - c.String(200, ok) - }) - - w1 := ut.PerformRequest(r, consts.MethodGet, "/sameSite", nil) - res3 := w1.Result() - resp3 := adaptor.GetCompatResponseWriter(res3) - // res3 := httptest.NewRecorder() - // req3, _ := http.NewRequest("GET", "/sameSite", nil) - // r.ServeHTTP(res3, req3) - - s := strings.Split(resp3.Header().Get("Set-Cookie"), ";") - if s[1] != " SameSite=Strict" { - t.Error("Error writing same site with options:", s[1]) - } -}