├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── dependabot.yml └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── cookie_store.rs ├── lib.rs ├── memory_store.rs ├── session.rs └── session_store.rs └── tests └── test.rs /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, 10 | education, socio-economic status, nationality, personal appearance, race, 11 | religion, or sexual identity and orientation. 12 | 13 | ## Our Standards 14 | 15 | Examples of behavior that contributes to creating a positive environment 16 | include: 17 | 18 | - Using welcoming and inclusive language 19 | - Being respectful of differing viewpoints and experiences 20 | - Gracefully accepting constructive criticism 21 | - Focusing on what is best for the community 22 | - Showing empathy towards other community members 23 | 24 | Examples of unacceptable behavior by participants include: 25 | 26 | - The use of sexualized language or imagery and unwelcome sexual attention or 27 | advances 28 | - Trolling, insulting/derogatory comments, and personal or political attacks 29 | - Public or private harassment 30 | - Publishing others' private information, such as a physical or electronic 31 | address, without explicit permission 32 | - Other conduct which could reasonably be considered inappropriate in a 33 | professional setting 34 | 35 | 36 | ## Our Responsibilities 37 | 38 | Project maintainers are responsible for clarifying the standards of acceptable 39 | behavior and are expected to take appropriate and fair corrective action in 40 | response to any instances of unacceptable behavior. 41 | 42 | Project maintainers have the right and responsibility to remove, edit, or 43 | reject comments, commits, code, wiki edits, issues, and other contributions 44 | that are not aligned to this Code of Conduct, or to ban temporarily or 45 | permanently any contributor for other behaviors that they deem inappropriate, 46 | threatening, offensive, or harmful. 47 | 48 | ## Scope 49 | 50 | This Code of Conduct applies both within project spaces and in public spaces 51 | when an individual is representing the project or its community. Examples of 52 | representing a project or community include using an official project e-mail 53 | address, posting via an official social media account, or acting as an appointed 54 | representative at an online or offline event. Representation of a project may be 55 | further defined and clarified by project maintainers. 56 | 57 | ## Enforcement 58 | 59 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 60 | reported by contacting the project team at yoshuawuyts@gmail.com, or through 61 | IRC. All complaints will be reviewed and investigated and will result in a 62 | response that is deemed necessary and appropriate to the circumstances. The 63 | project team is obligated to maintain confidentiality with regard to the 64 | reporter of an incident. 65 | Further details of specific enforcement policies may be posted separately. 66 | 67 | Project maintainers who do not follow or enforce the Code of Conduct in good 68 | faith may face temporary or permanent repercussions as determined by other 69 | members of the project's leadership. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 74 | available at 75 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Contributions include code, documentation, answering user questions, running the 3 | project's infrastructure, and advocating for all types of users. 4 | 5 | The project welcomes all contributions from anyone willing to work in good faith 6 | with other contributors and the community. No contribution is too small and all 7 | contributions are valued. 8 | 9 | This guide explains the process for contributing to the project's GitHub 10 | Repository. 11 | 12 | - [Code of Conduct](#code-of-conduct) 13 | - [Bad Actors](#bad-actors) 14 | 15 | ## Code of Conduct 16 | The project has a [Code of Conduct](./CODE_OF_CONDUCT.md) that *all* 17 | contributors are expected to follow. This code describes the *minimum* behavior 18 | expectations for all contributors. 19 | 20 | As a contributor, how you choose to act and interact towards your 21 | fellow contributors, as well as to the community, will reflect back not only 22 | on yourself but on the project as a whole. The Code of Conduct is designed and 23 | intended, above all else, to help establish a culture within the project that 24 | allows anyone and everyone who wants to contribute to feel safe doing so. 25 | 26 | Should any individual act in any way that is considered in violation of the 27 | [Code of Conduct](./CODE_OF_CONDUCT.md), corrective actions will be taken. It is 28 | possible, however, for any individual to *act* in such a manner that is not in 29 | violation of the strict letter of the Code of Conduct guidelines while still 30 | going completely against the spirit of what that Code is intended to accomplish. 31 | 32 | Open, diverse, and inclusive communities live and die on the basis of trust. 33 | Contributors can disagree with one another so long as they trust that those 34 | disagreements are in good faith and everyone is working towards a common 35 | goal. 36 | 37 | ## Bad Actors 38 | All contributors to tacitly agree to abide by both the letter and 39 | spirit of the [Code of Conduct](./CODE_OF_CONDUCT.md). Failure, or 40 | unwillingness, to do so will result in contributions being respectfully 41 | declined. 42 | 43 | A *bad actor* is someone who repeatedly violates the *spirit* of the Code of 44 | Conduct through consistent failure to self-regulate the way in which they 45 | interact with other contributors in the project. In doing so, bad actors 46 | alienate other contributors, discourage collaboration, and generally reflect 47 | poorly on the project as a whole. 48 | 49 | Being a bad actor may be intentional or unintentional. Typically, unintentional 50 | bad behavior can be easily corrected by being quick to apologize and correct 51 | course *even if you are not entirely convinced you need to*. Giving other 52 | contributors the benefit of the doubt and having a sincere willingness to admit 53 | that you *might* be wrong is critical for any successful open collaboration. 54 | 55 | Don't be a bad actor. 56 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "cargo" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - staging 8 | - trying 9 | 10 | env: 11 | RUSTFLAGS: -Dwarnings 12 | 13 | jobs: 14 | build_and_test: 15 | name: Build and test 16 | runs-on: ${{ matrix.os }} 17 | strategy: 18 | matrix: 19 | os: [ubuntu-latest, macOS-latest] 20 | rust: [nightly] 21 | 22 | steps: 23 | - uses: actions/checkout@master 24 | 25 | - name: Install ${{ matrix.rust }} 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | toolchain: ${{ matrix.rust }} 29 | override: true 30 | 31 | - name: check 32 | uses: actions-rs/cargo@v1 33 | with: 34 | command: check 35 | args: --all --bins --examples 36 | 37 | - name: check unstable 38 | uses: actions-rs/cargo@v1 39 | with: 40 | command: check 41 | args: --all --benches --bins --examples --tests 42 | 43 | - name: tests 44 | uses: actions-rs/cargo@v1 45 | with: 46 | command: test 47 | args: --all 48 | 49 | check_fmt_and_docs: 50 | name: Checking fmt and docs 51 | runs-on: ubuntu-latest 52 | steps: 53 | - uses: actions/checkout@master 54 | - uses: actions-rs/toolchain@v1 55 | with: 56 | toolchain: nightly 57 | components: rustfmt, clippy 58 | override: true 59 | 60 | - name: fmt 61 | run: cargo fmt --all -- --check 62 | 63 | - name: Docs 64 | run: cargo doc 65 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | tmp/ 3 | Cargo.lock 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async-session" 3 | version = "3.0.0" 4 | license = "MIT OR Apache-2.0" 5 | repository = "https://github.com/http-rs/async-session" 6 | documentation = "https://docs.rs/async-session" 7 | description = "Async session support with pluggable stores" 8 | readme = "README.md" 9 | edition = "2021" 10 | keywords = [] 11 | categories = [] 12 | authors = [ 13 | "Yoshua Wuyts ", 14 | "Jacob Rothstein " 15 | ] 16 | 17 | [dependencies] 18 | async-trait = "0.1.59" 19 | rand = "0.8.5" 20 | base64 = "0.20.0" 21 | sha2 = "0.10.6" 22 | hmac = "0.12.1" 23 | serde_json = "1.0.89" 24 | bincode = "1.3.3" 25 | anyhow = "1.0.66" 26 | blake3 = "1.3.3" 27 | async-lock = "2.6.0" 28 | log = "0.4.17" 29 | 30 | [dependencies.serde] 31 | version = "1.0.150" 32 | features = ["rc", "derive"] 33 | 34 | [dependencies.time] 35 | version = "0.3.17" 36 | features = ["serde"] 37 | 38 | [dev-dependencies.async-std] 39 | version = "1.12.0" 40 | features = ["attributes"] 41 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2020 Yoshua Wuyts 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Yoshua Wuyts 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

async-session

2 |
3 | 4 | Async session support with pluggable middleware 5 | 6 |
7 | 8 |
9 | 10 |
11 | 12 | 13 | Crates.io version 15 | 16 | 17 | 18 | Download 20 | 21 | 22 | 23 | docs.rs docs 25 | 26 |
27 | 28 |
29 |

30 | 31 | API Docs 32 | 33 | | 34 | 35 | Releases 36 | 37 | | 38 | 39 | Contributing 40 | 41 |

42 |
43 | 44 | ## Available session stores 45 | 46 | * [async-sqlx-session](https://crates.io/crates/async-sqlx-session) postgres, mysql & sqlite 47 | * [async-redis-session](https://crates.io/crates/async-redis-session) 48 | * [async-mongodb-session](https://crates.io/crates/async-mongodb-session) 49 | * [async-session-r2d2](https://crates.io/crates/async-session-r2d2) - sqlite only 50 | 51 | ## Framework implementations 52 | 53 | * [`tide::sessions`](https://docs.rs/tide/latest/tide/sessions/index.html) 54 | * [warp-sessions](https://docs.rs/warp-sessions/latest/warp_sessions/) 55 | * [trillium-sessions](https://docs.trillium.rs/trillium_sessions) 56 | * [axum-sessions](https://docs.rs/axum_sessions) 57 | * [salvo-sessions](https://docs.rs/salvo_extra/latest/salvo_extra/session/index.html) 58 | 59 | ## Safety 60 | This crate uses ``#![deny(unsafe_code)]`` to ensure everything is implemented in 61 | 100% Safe Rust. 62 | 63 | ## Contributing 64 | Want to join us? Check out our ["Contributing" guide][contributing] and take a 65 | look at some of these issues: 66 | 67 | - [Issues labeled "good first issue"][good-first-issue] 68 | - [Issues labeled "help wanted"][help-wanted] 69 | 70 | [contributing]: https://github.com/http-rs/async-session/blob/main/.github/CONTRIBUTING.md 71 | [good-first-issue]: https://github.com/http-rs/async-session/labels/good%20first%20issue 72 | [help-wanted]: https://github.com/http-rs/async-session/labels/help%20wanted 73 | 74 | ## Acknowledgements 75 | 76 | This work is based on the work initiated by 77 | [@chrisdickinson](https://github.com/chrisdickinson) in 78 | [tide#266](https://github.com/http-rs/tide/pull/266). 79 | 80 | ## License 81 | 82 | 83 | Licensed under either of Apache License, Version 84 | 2.0 or MIT license at your option. 85 | 86 | 87 |
88 | 89 | 90 | Unless you explicitly state otherwise, any contribution intentionally submitted 91 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 92 | be dual licensed as above, without any additional terms or conditions. 93 | 94 | -------------------------------------------------------------------------------- /src/cookie_store.rs: -------------------------------------------------------------------------------- 1 | use crate::{async_trait, Result, Session, SessionStore}; 2 | 3 | /// A session store that serializes the entire session into a Cookie. 4 | /// 5 | /// # ***This is not recommended for most production deployments.*** 6 | /// 7 | /// This implementation uses [`bincode`](::bincode) to serialize the 8 | /// Session to decrease the size of the cookie. Note: There is a 9 | /// maximum of 4093 cookie bytes allowed _per domain_, so the cookie 10 | /// store is limited in capacity. 11 | /// 12 | /// **Note:** Currently, the data in the cookie is only signed, but *not 13 | /// encrypted*. If the contained session data is sensitive and 14 | /// should not be read by a user, the cookie store is not an 15 | /// appropriate choice. 16 | /// 17 | /// Expiry: `SessionStore::destroy_session` and 18 | /// `SessionStore::clear_store` are not meaningful for the 19 | /// CookieStore, and noop. Destroying a session must be done at the 20 | /// cookie setting level, which is outside of the scope of this crate. 21 | 22 | #[derive(Default, Debug, Clone, Copy)] 23 | pub struct CookieStore; 24 | 25 | impl CookieStore { 26 | /// constructs a new CookieStore 27 | pub fn new() -> Self { 28 | Self 29 | } 30 | } 31 | 32 | #[async_trait] 33 | impl SessionStore for CookieStore { 34 | async fn load_session(&self, cookie_value: String) -> Result> { 35 | let serialized = base64::decode(cookie_value)?; 36 | let session: Session = bincode::deserialize(&serialized)?; 37 | Ok(session.validate()) 38 | } 39 | 40 | async fn store_session(&self, session: Session) -> Result> { 41 | let serialized = bincode::serialize(&session)?; 42 | Ok(Some(base64::encode(serialized))) 43 | } 44 | 45 | async fn destroy_session(&self, _session: Session) -> Result { 46 | Ok(()) 47 | } 48 | 49 | async fn clear_store(&self) -> Result { 50 | Ok(()) 51 | } 52 | } 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | use async_std::task; 58 | use std::time::Duration; 59 | #[async_std::test] 60 | async fn creating_a_new_session_with_no_expiry() -> Result { 61 | let store = CookieStore::new(); 62 | let mut session = Session::new(); 63 | session.insert("key", "Hello")?; 64 | let cloned = session.clone(); 65 | let cookie_value = store.store_session(session).await?.unwrap(); 66 | let loaded_session = store.load_session(cookie_value).await?.unwrap(); 67 | assert_eq!(cloned.id(), loaded_session.id()); 68 | assert_eq!("Hello", &loaded_session.get::("key").unwrap()); 69 | assert!(!loaded_session.is_expired()); 70 | assert!(loaded_session.validate().is_some()); 71 | Ok(()) 72 | } 73 | 74 | #[async_std::test] 75 | async fn updating_a_session() -> Result { 76 | let store = CookieStore::new(); 77 | let mut session = Session::new(); 78 | 79 | session.insert("key", "value")?; 80 | let cookie_value = store.store_session(session).await?.unwrap(); 81 | 82 | let mut session = store.load_session(cookie_value.clone()).await?.unwrap(); 83 | session.insert("key", "other value")?; 84 | 85 | let new_cookie_value = store.store_session(session).await?.unwrap(); 86 | let session = store.load_session(new_cookie_value).await?.unwrap(); 87 | assert_eq!(&session.get::("key").unwrap(), "other value"); 88 | 89 | Ok(()) 90 | } 91 | 92 | #[async_std::test] 93 | async fn updating_a_session_extending_expiry() -> Result { 94 | let store = CookieStore::new(); 95 | let mut session = Session::new(); 96 | session.expire_in(Duration::from_secs(1)); 97 | let original_expires = session.expiry().unwrap().clone(); 98 | let cookie_value = store.store_session(session).await?.unwrap(); 99 | 100 | let mut session = store.load_session(cookie_value.clone()).await?.unwrap(); 101 | 102 | assert_eq!(session.expiry().unwrap(), &original_expires); 103 | session.expire_in(Duration::from_secs(3)); 104 | let new_expires = session.expiry().unwrap().clone(); 105 | let cookie_value = store.store_session(session).await?.unwrap(); 106 | 107 | let session = store.load_session(cookie_value.clone()).await?.unwrap(); 108 | assert_eq!(session.expiry().unwrap(), &new_expires); 109 | 110 | task::sleep(Duration::from_secs(3)).await; 111 | assert_eq!(None, store.load_session(cookie_value).await?); 112 | 113 | Ok(()) 114 | } 115 | 116 | #[async_std::test] 117 | async fn creating_a_new_session_with_expiry() -> Result { 118 | let store = CookieStore::new(); 119 | let mut session = Session::new(); 120 | session.expire_in(Duration::from_secs(3)); 121 | session.insert("key", "value")?; 122 | let cloned = session.clone(); 123 | 124 | let cookie_value = store.store_session(session).await?.unwrap(); 125 | 126 | let loaded_session = store.load_session(cookie_value.clone()).await?.unwrap(); 127 | assert_eq!(cloned.id(), loaded_session.id()); 128 | assert_eq!("value", &*loaded_session.get::("key").unwrap()); 129 | 130 | assert!(!loaded_session.is_expired()); 131 | 132 | task::sleep(Duration::from_secs(3)).await; 133 | assert_eq!(None, store.load_session(cookie_value).await?); 134 | 135 | Ok(()) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Async HTTP sessions. 2 | //! 3 | //! This crate provides a generic interface between cookie values and 4 | //! storage backends to create a concept of sessions. It provides an 5 | //! interface that can be used to encode and store sessions, and 6 | //! decode and load sessions generating cookies in the process. 7 | //! 8 | //! # Example 9 | //! 10 | //! ``` 11 | //! use async_session::{Session, SessionStore, MemoryStore}; 12 | //! 13 | //! # fn main() -> async_session::Result { 14 | //! # async_std::task::block_on(async { 15 | //! # 16 | //! // Init a new session store we can persist sessions to. 17 | //! let mut store = MemoryStore::new(); 18 | //! 19 | //! // Create a new session. 20 | //! let mut session = Session::new(); 21 | //! session.insert("user_id", 1)?; 22 | //! assert!(session.data_changed()); 23 | //! 24 | //! // retrieve the cookie value to store in a session cookie 25 | //! let cookie_value = store.store_session(session).await?.unwrap(); 26 | //! 27 | //! // Retrieve the session using the cookie. 28 | //! let session = store.load_session(cookie_value).await?.unwrap(); 29 | //! assert_eq!(session.get::("user_id").unwrap(), 1); 30 | //! assert!(!session.data_changed()); 31 | //! # 32 | //! # Ok(()) }) } 33 | //! ``` 34 | 35 | // #![forbid(unsafe_code, future_incompatible)] 36 | // #![deny(missing_debug_implementations, nonstandard_style)] 37 | // #![warn(missing_docs, missing_doc_code_examples, unreachable_pub)] 38 | #![forbid(unsafe_code)] 39 | #![deny( 40 | future_incompatible, 41 | missing_debug_implementations, 42 | nonstandard_style, 43 | missing_docs, 44 | unreachable_pub, 45 | missing_copy_implementations, 46 | unused_qualifications 47 | )] 48 | 49 | pub use anyhow::Error; 50 | /// An anyhow::Result with default return type of () 51 | pub type Result = std::result::Result; 52 | 53 | mod cookie_store; 54 | mod memory_store; 55 | mod session; 56 | mod session_store; 57 | 58 | pub use cookie_store::CookieStore; 59 | pub use memory_store::MemoryStore; 60 | pub use session::Session; 61 | pub use session_store::SessionStore; 62 | 63 | pub use async_trait::async_trait; 64 | pub use base64; 65 | pub use blake3; 66 | pub use hmac; 67 | pub use log; 68 | pub use serde; 69 | pub use serde_json; 70 | pub use sha2; 71 | pub use time; 72 | -------------------------------------------------------------------------------- /src/memory_store.rs: -------------------------------------------------------------------------------- 1 | use crate::{async_trait, log, Result, Session, SessionStore}; 2 | use async_lock::RwLock; 3 | use std::{collections::HashMap, sync::Arc}; 4 | 5 | /// # in-memory session store 6 | /// Because there is no external 7 | /// persistance, this session store is ephemeral and will be cleared 8 | /// on server restart. 9 | /// 10 | /// # ***READ THIS BEFORE USING IN A PRODUCTION DEPLOYMENT*** 11 | /// 12 | /// Storing sessions only in memory brings the following problems: 13 | /// 14 | /// 1. All sessions must fit in available memory (important for high load services) 15 | /// 2. Sessions stored in memory are cleared only if a client calls [MemoryStore::destroy_session] or [MemoryStore::clear_store]. 16 | /// If sessions are not cleaned up properly it might result in OOM 17 | /// 3. All sessions will be lost on shutdown 18 | /// 4. If the service is clustered particular session will be stored only on a single instance. 19 | /// This might be solved by using load balancers with sticky sessions. 20 | /// Unfortunately, this solution brings additional complexity especially if the connection is 21 | /// using secure transport since the load balancer has to perform SSL termination to understand 22 | /// where should it forward packets to 23 | /// 24 | /// Example crates providing alternative implementations: 25 | /// - [async-sqlx-session](https://crates.io/crates/async-sqlx-session) postgres & sqlite 26 | /// - [async-redis-session](https://crates.io/crates/async-redis-session) 27 | /// - [async-mongodb-session](https://crates.io/crates/async-mongodb-session) 28 | /// 29 | #[derive(Default, Debug, Clone)] 30 | pub struct MemoryStore { 31 | inner: Arc>>, 32 | } 33 | 34 | #[async_trait] 35 | impl SessionStore for MemoryStore { 36 | async fn load_session(&self, cookie_value: String) -> Result> { 37 | let id = Session::id_from_cookie_value(&cookie_value)?; 38 | log::trace!("loading session by id `{}`", id); 39 | Ok(self 40 | .inner 41 | .read() 42 | .await 43 | .get(&id) 44 | .cloned() 45 | .and_then(Session::validate)) 46 | } 47 | 48 | async fn store_session(&self, session: Session) -> Result> { 49 | log::trace!("storing session by id `{}`", session.id()); 50 | self.inner 51 | .write() 52 | .await 53 | .insert(session.id().to_string(), session.clone()); 54 | 55 | session.reset_data_changed(); 56 | Ok(session.into_cookie_value()) 57 | } 58 | 59 | async fn destroy_session(&self, session: Session) -> Result { 60 | log::trace!("destroying session by id `{}`", session.id()); 61 | self.inner.write().await.remove(session.id()); 62 | Ok(()) 63 | } 64 | 65 | async fn clear_store(&self) -> Result { 66 | log::trace!("clearing memory store"); 67 | self.inner.write().await.clear(); 68 | Ok(()) 69 | } 70 | } 71 | 72 | impl MemoryStore { 73 | /// Create a new instance of MemoryStore 74 | pub fn new() -> Self { 75 | Self::default() 76 | } 77 | 78 | /// Performs session cleanup. This should be run on an 79 | /// intermittent basis if this store is run for long enough that 80 | /// memory accumulation is a concern 81 | pub async fn cleanup(&self) -> Result { 82 | log::trace!("cleaning up memory store..."); 83 | let ids_to_delete: Vec<_> = self 84 | .inner 85 | .read() 86 | .await 87 | .values() 88 | .filter_map(|session| { 89 | if session.is_expired() { 90 | Some(session.id().to_owned()) 91 | } else { 92 | None 93 | } 94 | }) 95 | .collect(); 96 | 97 | log::trace!("found {} expired sessions", ids_to_delete.len()); 98 | for id in ids_to_delete { 99 | self.inner.write().await.remove(&id); 100 | } 101 | Ok(()) 102 | } 103 | 104 | /// returns the number of elements in the memory store 105 | /// # Example 106 | /// ```rust 107 | /// # use async_session::{MemoryStore, Session, SessionStore}; 108 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 109 | /// let mut store = MemoryStore::new(); 110 | /// assert_eq!(store.count().await, 0); 111 | /// store.store_session(Session::new()).await?; 112 | /// assert_eq!(store.count().await, 1); 113 | /// # Ok(()) }) } 114 | /// ``` 115 | pub async fn count(&self) -> usize { 116 | let data = self.inner.read().await; 117 | data.len() 118 | } 119 | } 120 | 121 | #[cfg(test)] 122 | mod tests { 123 | use super::*; 124 | use async_std::task; 125 | use std::time::Duration; 126 | #[async_std::test] 127 | async fn creating_a_new_session_with_no_expiry() -> Result { 128 | let store = MemoryStore::new(); 129 | let mut session = Session::new(); 130 | session.insert("key", "Hello")?; 131 | let cloned = session.clone(); 132 | let cookie_value = store.store_session(session).await?.unwrap(); 133 | let loaded_session = store.load_session(cookie_value).await?.unwrap(); 134 | assert_eq!(cloned.id(), loaded_session.id()); 135 | assert_eq!("Hello", &loaded_session.get::("key").unwrap()); 136 | assert!(!loaded_session.is_expired()); 137 | assert!(loaded_session.validate().is_some()); 138 | Ok(()) 139 | } 140 | 141 | #[async_std::test] 142 | async fn updating_a_session() -> Result { 143 | let store = MemoryStore::new(); 144 | let mut session = Session::new(); 145 | 146 | session.insert("key", "value")?; 147 | let cookie_value = store.store_session(session).await?.unwrap(); 148 | 149 | let mut session = store.load_session(cookie_value.clone()).await?.unwrap(); 150 | session.insert("key", "other value")?; 151 | 152 | assert_eq!(store.store_session(session).await?, None); 153 | let session = store.load_session(cookie_value).await?.unwrap(); 154 | assert_eq!(&session.get::("key").unwrap(), "other value"); 155 | 156 | Ok(()) 157 | } 158 | 159 | #[async_std::test] 160 | async fn updating_a_session_extending_expiry() -> Result { 161 | let store = MemoryStore::new(); 162 | let mut session = Session::new(); 163 | session.expire_in(Duration::from_secs(1)); 164 | let original_expires = session.expiry().unwrap().clone(); 165 | let cookie_value = store.store_session(session).await?.unwrap(); 166 | 167 | let mut session = store.load_session(cookie_value.clone()).await?.unwrap(); 168 | 169 | assert_eq!(session.expiry().unwrap(), &original_expires); 170 | session.expire_in(Duration::from_secs(3)); 171 | let new_expires = session.expiry().unwrap().clone(); 172 | assert_eq!(None, store.store_session(session).await?); 173 | 174 | let session = store.load_session(cookie_value.clone()).await?.unwrap(); 175 | assert_eq!(session.expiry().unwrap(), &new_expires); 176 | 177 | task::sleep(Duration::from_secs(3)).await; 178 | assert_eq!(None, store.load_session(cookie_value).await?); 179 | 180 | Ok(()) 181 | } 182 | 183 | #[async_std::test] 184 | async fn creating_a_new_session_with_expiry() -> Result { 185 | let store = MemoryStore::new(); 186 | let mut session = Session::new(); 187 | session.expire_in(Duration::from_secs(3)); 188 | session.insert("key", "value")?; 189 | let cloned = session.clone(); 190 | 191 | let cookie_value = store.store_session(session).await?.unwrap(); 192 | 193 | let loaded_session = store.load_session(cookie_value.clone()).await?.unwrap(); 194 | assert_eq!(cloned.id(), loaded_session.id()); 195 | assert_eq!("value", &*loaded_session.get::("key").unwrap()); 196 | 197 | assert!(!loaded_session.is_expired()); 198 | 199 | task::sleep(Duration::from_secs(3)).await; 200 | assert_eq!(None, store.load_session(cookie_value).await?); 201 | 202 | Ok(()) 203 | } 204 | 205 | #[async_std::test] 206 | async fn destroying_a_single_session() -> Result { 207 | let store = MemoryStore::new(); 208 | for _ in 0..3i8 { 209 | store.store_session(Session::new()).await?; 210 | } 211 | 212 | let cookie = store.store_session(Session::new()).await?.unwrap(); 213 | assert_eq!(4, store.count().await); 214 | let session = store.load_session(cookie.clone()).await?.unwrap(); 215 | store.destroy_session(session.clone()).await?; 216 | assert_eq!(None, store.load_session(cookie).await?); 217 | assert_eq!(3, store.count().await); 218 | 219 | // attempting to destroy the session again is not an error 220 | assert!(store.destroy_session(session).await.is_ok()); 221 | Ok(()) 222 | } 223 | 224 | #[async_std::test] 225 | async fn clearing_the_whole_store() -> Result { 226 | let store = MemoryStore::new(); 227 | for _ in 0..3i8 { 228 | store.store_session(Session::new()).await?; 229 | } 230 | 231 | assert_eq!(3, store.count().await); 232 | store.clear_store().await.unwrap(); 233 | assert_eq!(0, store.count().await); 234 | 235 | Ok(()) 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /src/session.rs: -------------------------------------------------------------------------------- 1 | use rand::RngCore; 2 | use serde::{Deserialize, Serialize}; 3 | use std::{ 4 | collections::HashMap, 5 | convert::TryFrom, 6 | sync::{ 7 | atomic::{AtomicBool, Ordering}, 8 | Arc, RwLock, 9 | }, 10 | }; 11 | use time::OffsetDateTime as DateTime; 12 | 13 | /// # The main session type. 14 | /// 15 | /// ## Cloning and Serialization 16 | /// 17 | /// The `cookie_value` field is not cloned or serialized, and it can 18 | /// only be read through `into_cookie_value`. The intent of this field 19 | /// is that it is set either by initialization or by a session store, 20 | /// and read exactly once in order to set the cookie value. 21 | /// 22 | /// ## Change tracking session tracks whether any of its inner data 23 | /// was changed since it was last serialized. Any session store that 24 | /// does not undergo a serialization-deserialization cycle must call 25 | /// [`Session::reset_data_changed`] in order to reset the change tracker on 26 | /// an individual record. 27 | /// 28 | /// ### Change tracking example 29 | /// ```rust 30 | /// # use async_session::Session; 31 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 32 | /// let mut session = Session::new(); 33 | /// assert!(!session.data_changed()); 34 | /// 35 | /// session.insert("key", 1)?; 36 | /// assert!(session.data_changed()); 37 | /// 38 | /// session.reset_data_changed(); 39 | /// assert_eq!(session.get::("key").unwrap(), 1); 40 | /// assert!(!session.data_changed()); 41 | /// 42 | /// session.insert("key", 2)?; 43 | /// assert!(session.data_changed()); 44 | /// assert_eq!(session.get::("key").unwrap(), 2); 45 | /// 46 | /// session.insert("key", 1)?; 47 | /// assert!(session.data_changed(), "reverting the data still counts as a change"); 48 | /// 49 | /// session.reset_data_changed(); 50 | /// assert!(!session.data_changed()); 51 | /// session.remove("nonexistent key"); 52 | /// assert!(!session.data_changed()); 53 | /// session.remove("key"); 54 | /// assert!(session.data_changed()); 55 | /// # Ok(()) }) } 56 | /// ``` 57 | #[derive(Debug, Serialize, Deserialize)] 58 | pub struct Session { 59 | id: String, 60 | expiry: Option, 61 | data: Arc>>, 62 | 63 | #[serde(skip)] 64 | cookie_value: Option, 65 | #[serde(skip)] 66 | data_changed: Arc, 67 | #[serde(skip)] 68 | destroy: Arc, 69 | } 70 | 71 | impl Clone for Session { 72 | fn clone(&self) -> Self { 73 | Self { 74 | cookie_value: None, 75 | id: self.id.clone(), 76 | data: self.data.clone(), 77 | expiry: self.expiry, 78 | destroy: self.destroy.clone(), 79 | data_changed: self.data_changed.clone(), 80 | } 81 | } 82 | } 83 | 84 | impl Default for Session { 85 | fn default() -> Self { 86 | Self::new() 87 | } 88 | } 89 | 90 | /// generates a random cookie value 91 | fn generate_cookie(len: usize) -> String { 92 | let mut key = vec![0u8; len]; 93 | rand::thread_rng().fill_bytes(&mut key); 94 | base64::encode(key) 95 | } 96 | 97 | impl Session { 98 | /// Create a new session. Generates a random id and matching 99 | /// cookie value. Does not set an expiry by default 100 | /// 101 | /// # Example 102 | /// 103 | /// ```rust 104 | /// # use async_session::Session; 105 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 106 | /// let session = Session::new(); 107 | /// assert_eq!(None, session.expiry()); 108 | /// assert!(session.into_cookie_value().is_some()); 109 | /// # Ok(()) }) } 110 | pub fn new() -> Self { 111 | let cookie_value = generate_cookie(64); 112 | let id = Session::id_from_cookie_value(&cookie_value).unwrap(); 113 | 114 | Self { 115 | data_changed: Arc::new(AtomicBool::new(false)), 116 | expiry: None, 117 | data: Arc::new(RwLock::new(HashMap::default())), 118 | cookie_value: Some(cookie_value), 119 | id, 120 | destroy: Arc::new(AtomicBool::new(false)), 121 | } 122 | } 123 | 124 | /// applies a cryptographic hash function on a cookie value 125 | /// returned by [`Session::into_cookie_value`] to obtain the 126 | /// session id for that cookie. Returns an error if the cookie 127 | /// format is not recognized 128 | /// 129 | /// # Example 130 | /// 131 | /// ```rust 132 | /// # use async_session::Session; 133 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 134 | /// let session = Session::new(); 135 | /// let id = session.id().to_string(); 136 | /// let cookie_value = session.into_cookie_value().unwrap(); 137 | /// assert_eq!(id, Session::id_from_cookie_value(&cookie_value)?); 138 | /// # Ok(()) }) } 139 | /// ``` 140 | pub fn id_from_cookie_value(string: &str) -> Result { 141 | let decoded = base64::decode(string)?; 142 | let hash = blake3::hash(&decoded); 143 | Ok(base64::encode(hash.as_bytes())) 144 | } 145 | 146 | /// mark this session for destruction. the actual session record 147 | /// is not destroyed until the end of this response cycle. 148 | /// 149 | /// # Example 150 | /// 151 | /// ```rust 152 | /// # use async_session::Session; 153 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 154 | /// let mut session = Session::new(); 155 | /// assert!(!session.is_destroyed()); 156 | /// session.destroy(); 157 | /// assert!(session.is_destroyed()); 158 | /// # Ok(()) }) } 159 | pub fn destroy(&mut self) { 160 | self.destroy.store(true, Ordering::SeqCst); 161 | } 162 | 163 | /// returns true if this session is marked for destruction 164 | /// 165 | /// # Example 166 | /// 167 | /// ```rust 168 | /// # use async_session::Session; 169 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 170 | /// let mut session = Session::new(); 171 | /// assert!(!session.is_destroyed()); 172 | /// session.destroy(); 173 | /// assert!(session.is_destroyed()); 174 | /// # Ok(()) }) } 175 | 176 | pub fn is_destroyed(&self) -> bool { 177 | self.destroy.load(Ordering::SeqCst) 178 | } 179 | 180 | /// Gets the session id 181 | /// 182 | /// # Example 183 | /// 184 | /// ```rust 185 | /// # use async_session::Session; 186 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 187 | /// let session = Session::new(); 188 | /// let id = session.id().to_owned(); 189 | /// let cookie_value = session.into_cookie_value().unwrap(); 190 | /// assert_eq!(id, Session::id_from_cookie_value(&cookie_value)?); 191 | /// # Ok(()) }) } 192 | pub fn id(&self) -> &str { 193 | &self.id 194 | } 195 | 196 | /// inserts a serializable value into the session hashmap. returns 197 | /// an error if the serialization was unsuccessful. 198 | /// 199 | /// # Example 200 | /// 201 | /// ```rust 202 | /// # use serde::{Serialize, Deserialize}; 203 | /// # use async_session::Session; 204 | /// #[derive(Serialize, Deserialize)] 205 | /// struct User { 206 | /// name: String, 207 | /// legs: u8 208 | /// } 209 | /// let mut session = Session::new(); 210 | /// session.insert("user", User { name: "chashu".into(), legs: 4 }).expect("serializable"); 211 | /// assert_eq!(r#"{"name":"chashu","legs":4}"#, session.get_raw("user").unwrap()); 212 | /// ``` 213 | pub fn insert(&mut self, key: &str, value: impl Serialize) -> Result<(), serde_json::Error> { 214 | self.insert_raw(key, serde_json::to_string(&value)?); 215 | Ok(()) 216 | } 217 | 218 | /// inserts a string into the session hashmap 219 | /// 220 | /// # Example 221 | /// 222 | /// ```rust 223 | /// # use async_session::Session; 224 | /// let mut session = Session::new(); 225 | /// session.insert_raw("ten", "10".to_string()); 226 | /// let ten: usize = session.get("ten").unwrap(); 227 | /// assert_eq!(ten, 10); 228 | /// ``` 229 | pub fn insert_raw(&mut self, key: &str, value: String) { 230 | let mut data = self.data.write().unwrap(); 231 | if data.get(key) != Some(&value) { 232 | data.insert(key.to_string(), value); 233 | self.data_changed.store(true, Ordering::Release); 234 | } 235 | } 236 | 237 | /// deserializes a type T out of the session hashmap 238 | /// 239 | /// # Example 240 | /// 241 | /// ```rust 242 | /// # use async_session::Session; 243 | /// let mut session = Session::new(); 244 | /// session.insert("key", vec![1, 2, 3]); 245 | /// let numbers: Vec = session.get("key").unwrap(); 246 | /// assert_eq!(vec![1, 2, 3], numbers); 247 | /// ``` 248 | pub fn get(&self, key: &str) -> Option { 249 | let data = self.data.read().unwrap(); 250 | let string = data.get(key)?; 251 | serde_json::from_str(string).ok() 252 | } 253 | 254 | /// returns the String value contained in the session hashmap 255 | /// 256 | /// # Example 257 | /// 258 | /// ```rust 259 | /// # use async_session::Session; 260 | /// let mut session = Session::new(); 261 | /// session.insert("key", vec![1, 2, 3]); 262 | /// assert_eq!("[1,2,3]", session.get_raw("key").unwrap()); 263 | /// ``` 264 | pub fn get_raw(&self, key: &str) -> Option { 265 | let data = self.data.read().unwrap(); 266 | data.get(key).cloned() 267 | } 268 | 269 | /// removes an entry from the session hashmap 270 | /// 271 | /// # Example 272 | /// 273 | /// ```rust 274 | /// # use async_session::Session; 275 | /// let mut session = Session::new(); 276 | /// session.insert("key", "value"); 277 | /// session.remove("key"); 278 | /// assert!(session.get_raw("key").is_none()); 279 | /// assert_eq!(session.len(), 0); 280 | /// ``` 281 | pub fn remove(&mut self, key: &str) { 282 | let mut data = self.data.write().unwrap(); 283 | if data.remove(key).is_some() { 284 | self.data_changed.store(true, Ordering::Release); 285 | } 286 | } 287 | 288 | /// returns the number of elements in the session hashmap 289 | /// 290 | /// # Example 291 | /// 292 | /// ```rust 293 | /// # use async_session::Session; 294 | /// let mut session = Session::new(); 295 | /// assert_eq!(session.len(), 0); 296 | /// session.insert("key", 0); 297 | /// assert_eq!(session.len(), 1); 298 | /// ``` 299 | pub fn len(&self) -> usize { 300 | self.data.read().unwrap().len() 301 | } 302 | 303 | /// returns a boolean indicating whether there are zero elements in the session hashmap 304 | /// 305 | /// # Example 306 | /// 307 | /// ```rust 308 | /// # use async_session::Session; 309 | /// let mut session = Session::new(); 310 | /// assert!(session.is_empty()); 311 | /// session.insert("key", 0); 312 | /// assert!(!session.is_empty()); 313 | pub fn is_empty(&self) -> bool { 314 | return self.data.read().unwrap().is_empty(); 315 | } 316 | 317 | /// Generates a new id and cookie for this session 318 | /// 319 | /// # Example 320 | /// 321 | /// ```rust 322 | /// # use async_session::Session; 323 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 324 | /// let mut session = Session::new(); 325 | /// let old_id = session.id().to_string(); 326 | /// session.regenerate(); 327 | /// assert!(session.id() != &old_id); 328 | /// let new_id = session.id().to_string(); 329 | /// let cookie_value = session.into_cookie_value().unwrap(); 330 | /// assert_eq!(new_id, Session::id_from_cookie_value(&cookie_value)?); 331 | /// # Ok(()) }) } 332 | /// ``` 333 | pub fn regenerate(&mut self) { 334 | let cookie_value = generate_cookie(64); 335 | self.id = Session::id_from_cookie_value(&cookie_value).unwrap(); 336 | self.cookie_value = Some(cookie_value); 337 | } 338 | 339 | /// sets the cookie value that this session will use to serialize 340 | /// itself. this should only be called by cookie stores. any other 341 | /// uses of this method will result in the cookie not getting 342 | /// correctly deserialized on subsequent requests. 343 | /// 344 | /// # Example 345 | /// 346 | /// ```rust 347 | /// # use async_session::Session; 348 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 349 | /// let mut session = Session::new(); 350 | /// session.set_cookie_value("hello".to_owned()); 351 | /// let cookie_value = session.into_cookie_value().unwrap(); 352 | /// assert_eq!(cookie_value, "hello".to_owned()); 353 | /// # Ok(()) }) } 354 | /// ``` 355 | pub fn set_cookie_value(&mut self, cookie_value: String) { 356 | self.cookie_value = Some(cookie_value) 357 | } 358 | 359 | /// returns the expiry timestamp of this session, if there is one 360 | /// 361 | /// # Example 362 | /// 363 | /// ```rust 364 | /// # use async_session::Session; 365 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 366 | /// let mut session = Session::new(); 367 | /// assert_eq!(None, session.expiry()); 368 | /// session.expire_in(std::time::Duration::from_secs(1)); 369 | /// assert!(session.expiry().is_some()); 370 | /// # Ok(()) }) } 371 | /// ``` 372 | pub fn expiry(&self) -> Option<&DateTime> { 373 | self.expiry.as_ref() 374 | } 375 | 376 | /// assigns an expiry timestamp to this session 377 | /// 378 | /// # Example 379 | /// 380 | /// ```rust 381 | /// # use async_session::Session; 382 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 383 | /// let mut session = Session::new(); 384 | /// assert_eq!(None, session.expiry()); 385 | /// session.set_expiry(time::OffsetDateTime::now_utc()); 386 | /// assert!(session.expiry().is_some()); 387 | /// # Ok(()) }) } 388 | /// ``` 389 | pub fn set_expiry(&mut self, expiry: DateTime) { 390 | self.expiry = Some(expiry); 391 | } 392 | 393 | /// assigns the expiry timestamp to a duration from the current time. 394 | /// 395 | /// # Example 396 | /// 397 | /// ```rust 398 | /// # use async_session::Session; 399 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 400 | /// let mut session = Session::new(); 401 | /// assert_eq!(None, session.expiry()); 402 | /// session.expire_in(std::time::Duration::from_secs(1)); 403 | /// assert!(session.expiry().is_some()); 404 | /// # Ok(()) }) } 405 | /// ``` 406 | pub fn expire_in(&mut self, ttl: std::time::Duration) { 407 | self.expiry = Some(DateTime::now_utc() + ttl); 408 | } 409 | 410 | /// predicate function to determine if this session is 411 | /// expired. returns false if there is no expiry set, or if it is 412 | /// in the past. 413 | /// 414 | /// # Example 415 | /// 416 | /// ```rust 417 | /// # use async_session::Session; 418 | /// # use std::time::Duration; 419 | /// # use async_std::task; 420 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 421 | /// let mut session = Session::new(); 422 | /// assert_eq!(None, session.expiry()); 423 | /// assert!(!session.is_expired()); 424 | /// session.expire_in(Duration::from_secs(1)); 425 | /// assert!(!session.is_expired()); 426 | /// task::sleep(Duration::from_secs(2)).await; 427 | /// assert!(session.is_expired()); 428 | /// # Ok(()) }) } 429 | /// ``` 430 | pub fn is_expired(&self) -> bool { 431 | match self.expiry { 432 | Some(expiry) => expiry < DateTime::now_utc(), 433 | None => false, 434 | } 435 | } 436 | 437 | /// Ensures that this session is not expired. Returns None if it is expired 438 | /// 439 | /// # Example 440 | /// 441 | /// ```rust 442 | /// # use async_session::Session; 443 | /// # use std::time::Duration; 444 | /// # use async_std::task; 445 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 446 | /// let session = Session::new(); 447 | /// let mut session = session.validate().unwrap(); 448 | /// session.expire_in(Duration::from_secs(1)); 449 | /// let session = session.validate().unwrap(); 450 | /// task::sleep(Duration::from_secs(2)).await; 451 | /// assert_eq!(None, session.validate()); 452 | /// # Ok(()) }) } 453 | /// ``` 454 | pub fn validate(self) -> Option { 455 | if self.is_expired() { 456 | None 457 | } else { 458 | Some(self) 459 | } 460 | } 461 | 462 | /// Checks if the data has been modified. This is based on the 463 | /// implementation of [`PartialEq`] for the inner data type. 464 | /// 465 | /// # Example 466 | /// 467 | /// ```rust 468 | /// # use async_session::Session; 469 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 470 | /// let mut session = Session::new(); 471 | /// assert!(!session.data_changed(), "new session is not changed"); 472 | /// session.insert("key", 1); 473 | /// assert!(session.data_changed()); 474 | /// 475 | /// session.reset_data_changed(); 476 | /// assert!(!session.data_changed()); 477 | /// session.remove("key"); 478 | /// assert!(session.data_changed()); 479 | /// # Ok(()) }) } 480 | /// ``` 481 | pub fn data_changed(&self) -> bool { 482 | self.data_changed.load(Ordering::Acquire) 483 | } 484 | 485 | /// Resets `data_changed` dirty tracking. This is unnecessary for 486 | /// any session store that serializes the data to a string on 487 | /// storage. 488 | /// 489 | /// # Example 490 | /// 491 | /// ```rust 492 | /// # use async_session::Session; 493 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 494 | /// let mut session = Session::new(); 495 | /// assert!(!session.data_changed(), "new session is not changed"); 496 | /// session.insert("key", 1); 497 | /// assert!(session.data_changed()); 498 | /// 499 | /// session.reset_data_changed(); 500 | /// assert!(!session.data_changed()); 501 | /// session.remove("key"); 502 | /// assert!(session.data_changed()); 503 | /// # Ok(()) }) } 504 | /// ``` 505 | pub fn reset_data_changed(&self) { 506 | self.data_changed.store(false, Ordering::SeqCst); 507 | } 508 | 509 | /// Ensures that this session is not expired. Returns None if it is expired 510 | /// 511 | /// # Example 512 | /// 513 | /// ```rust 514 | /// # use async_session::Session; 515 | /// # use std::time::Duration; 516 | /// # use async_std::task; 517 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 518 | /// let mut session = Session::new(); 519 | /// session.expire_in(Duration::from_secs(123)); 520 | /// let expires_in = session.expires_in().unwrap(); 521 | /// assert!(123 - expires_in.as_secs() < 2); 522 | /// # Ok(()) }) } 523 | /// ``` 524 | /// Duration from now to the expiry time of this session 525 | pub fn expires_in(&self) -> Option { 526 | let dur = self.expiry? - DateTime::now_utc(); 527 | if dur.is_negative() { 528 | None 529 | } else { 530 | std::time::Duration::try_from(dur).ok() 531 | } 532 | } 533 | 534 | /// takes the cookie value and consume this session. 535 | /// this is generally only performed by the session store 536 | /// 537 | /// # Example 538 | /// 539 | /// ```rust 540 | /// # use async_session::Session; 541 | /// # fn main() -> async_session::Result { async_std::task::block_on(async { 542 | /// let mut session = Session::new(); 543 | /// session.set_cookie_value("hello".to_owned()); 544 | /// let cookie_value = session.into_cookie_value().unwrap(); 545 | /// assert_eq!(cookie_value, "hello".to_owned()); 546 | /// # Ok(()) }) } 547 | /// ``` 548 | pub fn into_cookie_value(mut self) -> Option { 549 | self.cookie_value.take() 550 | } 551 | } 552 | 553 | impl PartialEq for Session { 554 | fn eq(&self, other: &Self) -> bool { 555 | other.id == self.id 556 | } 557 | } 558 | -------------------------------------------------------------------------------- /src/session_store.rs: -------------------------------------------------------------------------------- 1 | use crate::{async_trait, Result, Session}; 2 | 3 | /// An async session backend. 4 | #[async_trait] 5 | pub trait SessionStore { 6 | /// Get a session from the storage backend. 7 | /// 8 | /// The input is expected to be the value of an identifying 9 | /// cookie. This will then be parsed by the session middleware 10 | /// into a session if possible 11 | async fn load_session(&self, cookie_value: String) -> Result>; 12 | 13 | /// Store a session on the storage backend. 14 | /// 15 | /// The return value is the value of the cookie to store for the 16 | /// user that represents this session 17 | async fn store_session(&self, session: Session) -> Result>; 18 | 19 | /// Remove a session from the session store 20 | async fn destroy_session(&self, session: Session) -> Result; 21 | 22 | /// Empties the entire store, destroying all sessions 23 | async fn clear_store(&self) -> Result; 24 | } 25 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------