e38aae7f2715174855c435c992ae7201d5eb8d7e
1 use std
::{fmt
, fs
::{self, File
}, path
::Path
, io
::Read
};
3 use itertools
::Itertools
;
4 use chrono
::{prelude
::*, Duration
};
5 use rusqlite
::{named_params
, OptionalExtension
, params
, Params
};
7 use r2d2_sqlite
::SqliteConnectionManager
;
8 use rand
::distributions
::{Alphanumeric
, DistString
};
10 use crate::{consts
, user
};
11 use crate::hash
::{hash
, verify_password
};
15 const CURRENT_DB_VERSION
: u32 = 1;
19 SqliteError(rusqlite
::Error
),
20 R2d2Error(r2d2
::Error
),
21 UnsupportedVersion(u32),
25 impl fmt
::Display
for DBError
{
26 fn fmt(&self, f
: &mut fmt
::Formatter
) -> std
::result
::Result
<(), fmt
::Error
> {
27 write!(f
, "{:?}", self)
31 impl std
::error
::Error
for DBError
{ }
33 impl From
<rusqlite
::Error
> for DBError
{
34 fn from(error
: rusqlite
::Error
) -> Self {
35 DBError
::SqliteError(error
)
39 impl From
<r2d2
::Error
> for DBError
{
40 fn from(error
: r2d2
::Error
) -> Self {
41 DBError
::R2d2Error(error
)
45 // TODO: Is there a better solution?
47 fn from_dyn_error(error
: Box
<dyn std
::error
::Error
>) -> Self {
48 DBError
::Other(error
.to_string())
52 type Result
<T
> = std
::result
::Result
<T
, DBError
>;
55 pub enum SignUpResult
{
57 UserCreatedWaitingForValidation(String
), // Validation token.
61 pub enum ValidationResult
{
64 Ok(String
, i32), // Returns token and user id.
68 pub enum SignInResult
{
72 Ok(String
, i32), // Returns token and user id.
76 pub enum AuthenticationResult
{
78 Ok(i32), // Returns user id.
82 pub struct Connection
{
83 //con: rusqlite::Connection
84 pool
: Pool
<SqliteConnectionManager
>
88 pub fn new() -> Result
<Connection
> {
89 let path
= Path
::new(consts
::DB_DIRECTORY
).join(consts
::DB_FILENAME
);
90 Self::new_from_file(path
)
93 pub fn new_in_memory() -> Result
<Connection
> {
94 Self::create_connection(SqliteConnectionManager
::memory())
97 pub fn new_from_file
<P
: AsRef
<Path
>>(file
: P
) -> Result
<Connection
> {
98 if let Some(data_dir
) = file
.as_ref().parent() {
99 if !data_dir
.exists() {
100 fs
::DirBuilder
::new().create(data_dir
).unwrap();
104 Self::create_connection(SqliteConnectionManager
::file(file
))
107 fn create_connection(manager
: SqliteConnectionManager
) -> Result
<Connection
> {
108 let pool
= r2d2
::Pool
::new(manager
).unwrap();
109 let connection
= Connection
{ pool
};
110 connection
.create_or_update()?
;
114 /// Called after the connection has been established for creating or updating the database.
115 /// The 'Version' table tracks the current state of the database.
116 fn create_or_update(&self) -> Result
<()> {
117 // Check the Database version.
118 let mut con
= self.pool
.get()?
;
119 let tx
= con
.transaction()?
;
121 // Version 0 corresponds to an empty database.
124 "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",
126 |row
| row
.get
::<usize, String
>(0)
128 Ok(_
) => tx
.query_row("SELECT [version] FROM [Version] ORDER BY [id] DESC", [], |row
| row
.get(0)).unwrap_or_default(),
133 while Self::update_to_next_version(version
, &tx
)?
{
142 fn update_to_next_version(current_version
: u32, tx
: &rusqlite
::Transaction
) -> Result
<bool
> {
143 let next_version
= current_version
+ 1;
145 if next_version
<= CURRENT_DB_VERSION
{
146 println!("Update to version {}...", next_version
);
149 fn update_version(to_version
: u32, tx
: &rusqlite
::Transaction
) -> Result
<()> {
150 tx
.execute("INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", [to_version
]).map(|_
| ()).map_err(DBError
::from
)
153 fn ok(updated
: bool
) -> Result
<bool
> {
155 println!("Version updated");
162 let sql_file
= consts
::SQL_FILENAME
.replace("{VERSION}", &next_version
.to_string());
163 tx
.execute_batch(&load_sql_file(&sql_file
)?
)?
;
164 update_version(next_version
, tx
)?
;
169 // Version 1 doesn't exist yet.
174 Err(DBError
::UnsupportedVersion(v
)),
178 pub fn get_all_recipe_titles(&self) -> Result
<Vec
<(i32, String
)>> {
179 let con
= self.pool
.get()?
;
180 let mut stmt
= con
.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?
;
182 stmt
.query_map([], |row
| {
183 Ok((row
.get(0)?
, row
.get(1)?
))
184 })?
.map(|r
| r
.unwrap()).collect_vec(); // TODO: remove unwrap.
188 /* Not used for the moment.
189 pub fn get_all_recipes(&self) -> Result<Vec<model::Recipe>> {
190 let con = self.pool.get()?;
191 let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;
193 stmt.query_map([], |row| {
194 Ok(model::Recipe::new(row.get(0)?, row.get(1)?))
195 })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.
199 pub fn get_recipe(&self, id
: i32) -> Result
<model
::Recipe
> {
200 let con
= self.pool
.get()?
;
201 con
.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id
], |row
| {
202 Ok(model
::Recipe
::new(row
.get("id")?
, row
.get("title")?
, row
.get("description")?
))
203 }).map_err(DBError
::from
)
206 pub fn get_user_login_info(&self, token
: &str) -> Result
<UserLoginInfo
> {
207 let con
= self.pool
.get()?
;
208 con
.query_row("SELECT [last_login_datetime], [ip], [user_agent] FROM [UserLoginToken] WHERE [token] = ?1", [token
], |r
| {
210 last_login_datetime
: r
.get("last_login_datetime")?
,
212 user_agent
: r
.get("user_agent")?
,
214 }).map_err(DBError
::from
)
217 pub fn load_user(&self, user_id
: i32) -> Result
<User
> {
218 let con
= self.pool
.get()?
;
219 con
.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id
], |r
| {
221 email
: r
.get("email")?
,
223 }).map_err(DBError
::from
)
227 pub fn sign_up(&self, email
: &str, password
: &str) -> Result
<SignUpResult
> {
228 self.sign_up_with_given_time(email
, password
, Utc
::now())
231 fn sign_up_with_given_time(&self, email
: &str, password
: &str, datetime
: DateTime
<Utc
>) -> Result
<SignUpResult
> {
232 let mut con
= self.pool
.get()?
;
233 let tx
= con
.transaction()?
;
235 match tx
.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email
], |r
| {
236 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, Option
<String
>>("validation_token")?
))
238 Some((id
, validation_token
)) => {
239 if validation_token
.is_none() {
240 return Ok(SignUpResult
::UserAlreadyExists
)
242 let token
= generate_token();
243 let hashed_password
= hash(password
).map_err(|e
| DBError
::from_dyn_error(e
))?
;
244 tx
.execute("UPDATE [User] SET [validation_token] = ?2, [creation_datetime] = ?3, [password] = ?4 WHERE [id] = ?1", params
![id
, token
, datetime
, hashed_password
])?
;
248 let token
= generate_token();
249 let hashed_password
= hash(password
).map_err(|e
| DBError
::from_dyn_error(e
))?
;
250 tx
.execute("INSERT INTO [User] ([email], [validation_token], [creation_datetime], [password]) VALUES (?1, ?2, ?3, ?4)", params
![email
, token
, datetime
, hashed_password
])?
;
255 Ok(SignUpResult
::UserCreatedWaitingForValidation(token
))
258 pub fn validation(&self, token
: &str, validation_time
: Duration
, ip
: &str, user_agent
: &str) -> Result
<ValidationResult
> {
259 let mut con
= self.pool
.get()?
;
260 let tx
= con
.transaction()?
;
262 match tx
.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token
], |r
| {
263 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, DateTime
<Utc
>>("creation_datetime")?
))
265 Some((id
, creation_datetime
)) => {
266 if Utc
::now() - creation_datetime
> validation_time
{
267 return Ok(ValidationResult
::ValidationExpired
)
269 tx
.execute("UPDATE [User] SET [validation_token] = NULL WHERE [id] = ?1", [id
])?
;
273 return Ok(ValidationResult
::UnknownUser
)
276 let token
= Connection
::create_login_token(&tx
, user_id
, ip
, user_agent
)?
;
278 Ok(ValidationResult
::Ok(token
, user_id
))
281 pub fn sign_in(&self, email
: &str, password
: &str, ip
: &str, user_agent
: &str) -> Result
<SignInResult
> {
282 let mut con
= self.pool
.get()?
;
283 let tx
= con
.transaction()?
;
284 match tx
.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email
], |r
| {
285 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, String
>("password")?
, r
.get
::<&str, Option
<String
>>("validation_token")?
))
287 Some((id
, stored_password
, validation_token
)) => {
288 if validation_token
.is_some() {
289 Ok(SignInResult
::AccountNotValidated
)
290 } else if verify_password(password
, &stored_password
).map_err(DBError
::from_dyn_error
)?
{
291 let token
= Connection
::create_login_token(&tx
, id
, ip
, user_agent
)?
;
293 Ok(SignInResult
::Ok(token
, id
))
295 Ok(SignInResult
::WrongPassword
)
299 Ok(SignInResult
::UserNotFound
)
304 pub fn authentication(&self, token
: &str, ip
: &str, user_agent
: &str) -> Result
<AuthenticationResult
> {
305 let mut con
= self.pool
.get()?
;
306 let tx
= con
.transaction()?
;
307 match tx
.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token
], |r
| {
308 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, i32>("user_id")?
))
310 Some((login_id
, user_id
)) => {
311 tx
.execute("UPDATE [UserLoginToken] SET [last_login_datetime] = ?2, [ip] = ?3, [user_agent] = ?4 WHERE [id] = ?1", params
![login_id
, Utc
::now(), ip
, user_agent
])?
;
313 Ok(AuthenticationResult
::Ok(user_id
))
316 Ok(AuthenticationResult
::NotValidToken
)
320 pub fn sign_out(&self, token
: &str) -> Result
<()> {
321 let mut con
= self.pool
.get()?
;
322 let tx
= con
.transaction()?
;
323 match tx
.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token
], |r
| {
324 Ok(r
.get
::<&str, i32>("id")?
)
327 tx
.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params
![login_id
])?
;
335 /// Execute a given SQL file.
336 pub fn execute_file
<P
: AsRef
<Path
> + fmt
::Display
>(&self, file
: P
) -> Result
<()> {
337 let con
= self.pool
.get()?
;
338 let sql
= load_sql_file(file
)?
;
339 con
.execute_batch(&sql
).map_err(DBError
::from
)
342 /// Execute any SQL statement.
343 /// Mainly used for testing.
344 pub fn execute_sql
<P
: Params
>(&self, sql
: &str, params
: P
) -> Result
<usize> {
345 let con
= self.pool
.get()?
;
346 con
.execute(sql
, params
).map_err(DBError
::from
)
350 fn create_login_token(tx
: &rusqlite
::Transaction
, user_id
: i32, ip
: &str, user_agent
: &str) -> Result
<String
> {
351 let token
= generate_token();
352 tx
.execute("INSERT INTO [UserLoginToken] ([user_id], [last_login_datetime], [token], [ip], [user_agent]) VALUES (?1, ?2, ?3, ?4, ?5)", params
![user_id
, Utc
::now(), token
, ip
, user_agent
])?
;
357 fn load_sql_file
<P
: AsRef
<Path
> + fmt
::Display
>(sql_file
: P
) -> Result
<String
> {
358 let mut file
= File
::open(&sql_file
).map_err(|err
| DBError
::Other(format!("Cannot open SQL file ({}): {}", &sql_file
, err
.to_string())))?
;
359 let mut sql
= String
::new();
360 file
.read_to_string(&mut sql
).map_err(|err
| DBError
::Other(format!("Cannot read SQL file ({}) : {}", &sql_file
, err
.to_string())))?
;
364 fn generate_token() -> String
{
365 Alphanumeric
.sample_string(&mut rand
::thread_rng(), 24)
373 fn sign_up() -> Result
<()> {
374 let connection
= Connection
::new_in_memory()?
;
375 match connection
.sign_up("paul@test.org", "12345")?
{
376 SignUpResult
::UserCreatedWaitingForValidation(_
) => (), // Nominal case.
377 other
=> panic!("{:?}", other
),
383 fn sign_up_to_an_already_existing_user() -> Result
<()> {
384 let connection
= Connection
::new_in_memory()?
;
385 connection
.execute_sql("
386 INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
391 '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
395 match connection
.sign_up("paul@test.org", "12345")?
{
396 SignUpResult
::UserAlreadyExists
=> (), // Nominal case.
397 other
=> panic!("{:?}", other
),
403 fn sign_up_and_sign_in_without_validation() -> Result
<()> {
404 let connection
= Connection
::new_in_memory()?
;
406 let email
= "paul@test.org";
407 let password
= "12345";
409 match connection
.sign_up(email
, password
)?
{
410 SignUpResult
::UserCreatedWaitingForValidation(_
) => (), // Nominal case.
411 other
=> panic!("{:?}", other
),
414 match connection
.sign_in(email
, password
, "127.0.0.1", "Mozilla/5.0")?
{
415 SignInResult
::AccountNotValidated
=> (), // Nominal case.
416 other
=> panic!("{:?}", other
),
423 fn sign_up_to_an_unvalidated_already_existing_user() -> Result
<()> {
424 let connection
= Connection
::new_in_memory()?
;
425 let token
= generate_token();
426 connection
.execute_sql("
427 INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
432 '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
435 );", named_params
! { ":token": token
})?
;
436 match connection
.sign_up("paul@test.org", "12345")?
{
437 SignUpResult
::UserCreatedWaitingForValidation(_
) => (), // Nominal case.
438 other
=> panic!("{:?}", other
),
444 fn sign_up_then_send_validation_at_time() -> Result
<()> {
445 let connection
= Connection
::new_in_memory()?
;
446 let validation_token
=
447 match connection
.sign_up("paul@test.org", "12345")?
{
448 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
449 other
=> panic!("{:?}", other
),
451 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
452 ValidationResult
::Ok(_
, _
) => (), // Nominal case.
453 other
=> panic!("{:?}", other
),
459 fn sign_up_then_send_validation_too_late() -> Result
<()> {
460 let connection
= Connection
::new_in_memory()?
;
461 let validation_token
=
462 match connection
.sign_up_with_given_time("paul@test.org", "12345", Utc
::now() - Duration
::days(1))?
{
463 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
464 other
=> panic!("{:?}", other
),
466 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
467 ValidationResult
::ValidationExpired
=> (), // Nominal case.
468 other
=> panic!("{:?}", other
),
474 fn sign_up_then_send_validation_with_bad_token() -> Result
<()> {
475 let connection
= Connection
::new_in_memory()?
;
476 let _validation_token
=
477 match connection
.sign_up("paul@test.org", "12345")?
{
478 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
479 other
=> panic!("{:?}", other
),
481 let random_token
= generate_token();
482 match connection
.validation(&random_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
483 ValidationResult
::UnknownUser
=> (), // Nominal case.
484 other
=> panic!("{:?}", other
),
490 fn sign_up_then_send_validation_then_sign_in() -> Result
<()> {
491 let connection
= Connection
::new_in_memory()?
;
493 let email
= "paul@test.org";
494 let password
= "12345";
497 let validation_token
=
498 match connection
.sign_up(email
, password
)?
{
499 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
500 other
=> panic!("{:?}", other
),
504 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
505 ValidationResult
::Ok(_
, _
) => (),
506 other
=> panic!("{:?}", other
),
510 match connection
.sign_in(email
, password
, "127.0.0.1", "Mozilla/5.0")?
{
511 SignInResult
::Ok(_
, _
) => (), // Nominal case.
512 other
=> panic!("{:?}", other
),
519 fn sign_up_then_send_validation_then_authentication() -> Result
<()> {
520 let connection
= Connection
::new_in_memory()?
;
522 let email
= "paul@test.org";
523 let password
= "12345";
526 let validation_token
=
527 match connection
.sign_up(email
, password
)?
{
528 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
529 other
=> panic!("{:?}", other
),
533 let (authentication_token
, user_id
) = match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla")?
{
534 ValidationResult
::Ok(token
, user_id
) => (token
, user_id
),
535 other
=> panic!("{:?}", other
),
538 // Check user login information.
539 let user_login_info_1
= connection
.get_user_login_info(&authentication_token
)?
;
540 assert_eq!(user_login_info_1
.ip
, "127.0.0.1");
541 assert_eq!(user_login_info_1
.user_agent
, "Mozilla");
545 match connection
.authentication(&authentication_token
, "192.168.1.1", "Chrome")?
{
546 AuthenticationResult
::Ok(user_id
) => user_id
, // Nominal case.
547 other
=> panic!("{:?}", other
),
550 // Check user login information.
551 let user_login_info_2
= connection
.get_user_login_info(&authentication_token
)?
;
552 assert_eq!(user_login_info_2
.ip
, "192.168.1.1");
553 assert_eq!(user_login_info_2
.user_agent
, "Chrome");
559 fn sign_up_then_send_validation_then_sign_out_then_sign_in() -> Result
<()> {
560 let connection
= Connection
::new_in_memory()?
;
562 let email
= "paul@test.org";
563 let password
= "12345";
566 let validation_token
=
567 match connection
.sign_up(email
, password
)?
{
568 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
569 other
=> panic!("{:?}", other
),
573 let (authentication_token_1
, user_id_1
) =
574 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla")?
{
575 ValidationResult
::Ok(token
, user_id
) => (token
, user_id
),
576 other
=> panic!("{:?}", other
),
579 // Check user login information.
580 let user_login_info_1
= connection
.get_user_login_info(&authentication_token_1
)?
;
581 assert_eq!(user_login_info_1
.ip
, "127.0.0.1");
582 assert_eq!(user_login_info_1
.user_agent
, "Mozilla");
585 connection
.sign_out(&authentication_token_1
)?
;
588 let (authentication_token_2
, user_id_2
) =
589 match connection
.sign_in(email
, password
, "192.168.1.1", "Chrome")?
{
590 SignInResult
::Ok(token
, user_id
) => (token
, user_id
),
591 other
=> panic!("{:?}", other
),
594 assert_eq!(user_id_1
, user_id_2
);
595 assert_ne!(authentication_token_1
, authentication_token_2
);
597 // Check user login information.
598 let user_login_info_2
= connection
.get_user_login_info(&authentication_token_2
)?
;
600 assert_eq!(user_login_info_2
.ip
, "192.168.1.1");
601 assert_eq!(user_login_info_2
.user_agent
, "Chrome");