-
Notifications
You must be signed in to change notification settings - Fork 643
/
Copy pathpersistent_session.rs
177 lines (159 loc) · 5.41 KB
/
persistent_session.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use chrono::NaiveDateTime;
use cookie::{Cookie, SameSite};
use diesel::prelude::*;
use std::num::ParseIntError;
use std::str::FromStr;
use thiserror::Error;
use crate::schema::persistent_sessions;
use crate::util::token::NewSecureToken;
use crate::util::token::SecureToken;
use crate::util::token::SecureTokenKind;
/// A persistent session model (as is stored in the database).
///
/// The sessions table works by maintaining a `hashed_token`. In order for a user to securely
/// demonstrate authenticity, the user provides us with the token (stored as part of a cookie). We
/// hash the token and search in the database for matches. If we find one and the token hasn't
/// been revoked, then we update the session with the latest values and authorize the user.
#[derive(Clone, Debug, PartialEq, Eq, Identifiable, Queryable)]
#[table_name = "persistent_sessions"]
pub struct PersistentSession {
/// The id of this session.
pub id: i64,
/// The user id associated with this session.
pub user_id: i32,
/// The token (hashed) that identifies the session.
pub hashed_token: SecureToken,
/// Datetime the session was created.
pub created_at: NaiveDateTime,
/// Whether the session is revoked.
pub revoked: bool,
}
impl PersistentSession {
/// Creates a `NewPersistentSession` for the `user_id` and the token associated with it.
pub fn create(user_id: i32) -> NewPersistentSession {
let token = SecureToken::generate(SecureTokenKind::Session);
NewPersistentSession { user_id, token }
}
/// Finds the session with the ID.
///
/// # Returns
///
/// * `Ok(Some(...))` if a session matches the id.
/// * `Ok(None)` if no session matches the id.
/// * `Err(...)` for other errors..
pub fn find(id: i64, conn: &PgConnection) -> Result<Option<Self>, diesel::result::Error> {
persistent_sessions::table
.find(id)
.get_result(conn)
.optional()
}
/// Updates the session in the database.
pub fn update(&self, conn: &PgConnection) -> Result<(), diesel::result::Error> {
diesel::update(persistent_sessions::table.find(self.id))
.set((
persistent_sessions::user_id.eq(&self.user_id),
persistent_sessions::hashed_token.eq(&self.hashed_token),
persistent_sessions::revoked.eq(&self.revoked),
))
.get_result::<Self>(conn)
.map(|_| ())
}
pub fn is_authorized(&self, token: &str) -> bool {
if let Some(hashed_token) = SecureToken::parse(SecureTokenKind::Session, token) {
!self.revoked && self.hashed_token == hashed_token
} else {
false
}
}
/// Revokes the session (needs update).
pub fn revoke(&mut self) -> &mut Self {
self.revoked = true;
self
}
}
/// A new, insertable persistent session.
pub struct NewPersistentSession {
user_id: i32,
token: NewSecureToken,
}
impl NewPersistentSession {
/// Inserts the session into the database.
///
/// # Returns
///
/// The
pub fn insert(
self,
conn: &PgConnection,
) -> Result<(PersistentSession, SessionCookie), diesel::result::Error> {
let session: PersistentSession = diesel::insert_into(persistent_sessions::table)
.values((
persistent_sessions::user_id.eq(&self.user_id),
persistent_sessions::hashed_token.eq(&*self.token),
))
.get_result(conn)?;
let id = session.id;
Ok((
session,
SessionCookie::new(id, self.token.plaintext().to_string()),
))
}
}
/// Holds the information needed for the session cookie.
#[derive(Debug, PartialEq, Eq)]
pub struct SessionCookie {
/// The session ID in the database.
id: i64,
/// The token
token: String,
}
impl SessionCookie {
/// Name of the cookie used for session-based authentication.
pub const SESSION_COOKIE_NAME: &'static str = "__Host-auth";
/// Creates a new `SessionCookie`.
pub fn new(id: i64, token: String) -> Self {
Self { id, token }
}
/// Returns the `[Cookie]`.
pub fn build(&self, secure: bool) -> Cookie<'static> {
Cookie::build(
Self::SESSION_COOKIE_NAME,
format!("{}:{}", self.id, &self.token),
)
.http_only(true)
.secure(secure)
.same_site(SameSite::Strict)
.path("/")
.finish()
}
pub fn session_id(&self) -> i64 {
self.id
}
pub fn token(&self) -> &str {
&self.token
}
}
/// Error returned when the session cookie couldn't be parsed.
#[derive(Error, Debug, PartialEq)]
pub enum ParseSessionCookieError {
#[error("The session id wasn't in the cookie.")]
MissingSessionId,
#[error("The session id couldn't be parsed from the cookie.")]
IdParseError(#[from] ParseIntError),
#[error("The session token wasn't in the cookie.")]
MissingToken,
}
impl FromStr for SessionCookie {
type Err = ParseSessionCookieError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut id_and_token = s.split(':');
let id: i64 = id_and_token
.next()
.ok_or(ParseSessionCookieError::MissingSessionId)?
.parse()?;
let token = id_and_token
.next()
.ok_or(ParseSessionCookieError::MissingToken)?;
Ok(Self::new(id, token.to_string()))
}
}