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
};
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
{
71 Ok(String
, i32), // Returns token and user id.
75 pub enum AuthenticationResult
{
77 Ok(i32), // Returns user id.
81 pub struct Connection
{
82 //con: rusqlite::Connection
83 pool
: Pool
<SqliteConnectionManager
>
87 pub fn new() -> Result
<Connection
> {
88 let path
= Path
::new(consts
::DB_DIRECTORY
).join(consts
::DB_FILENAME
);
89 Self::new_from_file(path
)
92 pub fn new_in_memory() -> Result
<Connection
> {
93 Self::create_connection(SqliteConnectionManager
::memory())
96 pub fn new_from_file
<P
: AsRef
<Path
>>(file
: P
) -> Result
<Connection
> {
97 if let Some(data_dir
) = file
.as_ref().parent() {
98 if !data_dir
.exists() {
99 fs
::DirBuilder
::new().create(data_dir
).unwrap();
103 Self::create_connection(SqliteConnectionManager
::file(file
))
106 fn create_connection(manager
: SqliteConnectionManager
) -> Result
<Connection
> {
107 let pool
= r2d2
::Pool
::new(manager
).unwrap();
108 let connection
= Connection
{ pool
};
109 connection
.create_or_update()?
;
113 /// Called after the connection has been established for creating or updating the database.
114 /// The 'Version' table tracks the current state of the database.
115 fn create_or_update(&self) -> Result
<()> {
116 // Check the Database version.
117 let mut con
= self.pool
.get()?
;
118 let tx
= con
.transaction()?
;
120 // Version 0 corresponds to an empty database.
123 "SELECT [name] FROM [sqlite_master] WHERE [type] = 'table' AND [name] = 'Version'",
125 |row
| row
.get
::<usize, String
>(0)
127 Ok(_
) => tx
.query_row("SELECT [version] FROM [Version] ORDER BY [id] DESC", [], |row
| row
.get(0)).unwrap_or_default(),
132 while Self::update_to_next_version(version
, &tx
)?
{
141 fn update_to_next_version(current_version
: u32, tx
: &rusqlite
::Transaction
) -> Result
<bool
> {
142 let next_version
= current_version
+ 1;
144 if next_version
<= CURRENT_DB_VERSION
{
145 println!("Update to version {}...", next_version
);
148 fn update_version(to_version
: u32, tx
: &rusqlite
::Transaction
) -> Result
<()> {
149 tx
.execute("INSERT INTO [Version] ([version], [datetime]) VALUES (?1, datetime('now'))", [to_version
]).map(|_
| ()).map_err(DBError
::from
)
152 fn ok(updated
: bool
) -> Result
<bool
> {
154 println!("Version updated");
161 let sql_file
= consts
::SQL_FILENAME
.replace("{VERSION}", &next_version
.to_string());
162 tx
.execute_batch(&load_sql_file(&sql_file
)?
)?
;
163 update_version(next_version
, tx
)?
;
168 // Version 1 doesn't exist yet.
173 Err(DBError
::UnsupportedVersion(v
)),
177 pub fn get_all_recipe_titles(&self) -> Result
<Vec
<(i32, String
)>> {
178 let con
= self.pool
.get()?
;
179 let mut stmt
= con
.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?
;
181 stmt
.query_map([], |row
| {
182 Ok((row
.get(0)?
, row
.get(1)?
))
183 })?
.map(|r
| r
.unwrap()).collect_vec(); // TODO: remove unwrap.
187 /* Not used for the moment.
188 pub fn get_all_recipes(&self) -> Result<Vec<model::Recipe>> {
189 let con = self.pool.get()?;
190 let mut stmt = con.prepare("SELECT [id], [title] FROM [Recipe] ORDER BY [title]")?;
192 stmt.query_map([], |row| {
193 Ok(model::Recipe::new(row.get(0)?, row.get(1)?))
194 })?.map(|r| r.unwrap()).collect_vec(); // TODO: remove unwrap.
198 pub fn get_recipe(&self, id
: i32) -> Result
<model
::Recipe
> {
199 let con
= self.pool
.get()?
;
200 con
.query_row("SELECT [id], [title] FROM [Recipe] WHERE [id] = ?1", [id
], |row
| {
201 Ok(model
::Recipe
::new(row
.get(0)?
, row
.get(1)?
))
202 }).map_err(DBError
::from
)
205 pub fn get_user_login_info(&self, token
: &str) -> Result
<UserLoginInfo
> {
206 let con
= self.pool
.get()?
;
207 con
.query_row("SELECT [last_login_datetime], [ip], [user_agent] FROM [UserLoginToken] WHERE [token] = ?1", [token
], |r
| {
209 last_login_datetime
: r
.get("last_login_datetime")?
,
211 user_agent
: r
.get("user_agent")?
,
213 }).map_err(DBError
::from
)
217 pub fn sign_up(&self, email
: &str, password
: &str) -> Result
<SignUpResult
> {
218 self.sign_up_with_given_time(email
, password
, Utc
::now())
221 fn sign_up_with_given_time(&self, email
: &str, password
: &str, datetime
: DateTime
<Utc
>) -> Result
<SignUpResult
> {
222 let mut con
= self.pool
.get()?
;
223 let tx
= con
.transaction()?
;
225 match tx
.query_row("SELECT [id], [validation_token] FROM [User] WHERE [email] = ?1", [email
], |r
| {
226 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, Option
<String
>>("validation_token")?
))
228 Some((id
, validation_token
)) => {
229 if validation_token
.is_none() {
230 return Ok(SignUpResult
::UserAlreadyExists
)
232 let token
= generate_token();
233 let hashed_password
= hash(password
).map_err(|e
| DBError
::from_dyn_error(e
))?
;
234 tx
.execute("UPDATE [User] SET [validation_token] = ?2, [creation_datetime] = ?3, [password] = ?4 WHERE [id] = ?1", params
![id
, token
, datetime
, hashed_password
])?
;
238 let token
= generate_token();
239 let hashed_password
= hash(password
).map_err(|e
| DBError
::from_dyn_error(e
))?
;
240 tx
.execute("INSERT INTO [User] ([email], [validation_token], [creation_datetime], [password]) VALUES (?1, ?2, ?3, ?4)", params
![email
, token
, datetime
, hashed_password
])?
;
245 Ok(SignUpResult
::UserCreatedWaitingForValidation(token
))
248 pub fn validation(&self, token
: &str, validation_time
: Duration
, ip
: &str, user_agent
: &str) -> Result
<ValidationResult
> {
249 let mut con
= self.pool
.get()?
;
250 let tx
= con
.transaction()?
;
252 match tx
.query_row("SELECT [id], [creation_datetime] FROM [User] WHERE [validation_token] = ?1", [token
], |r
| {
253 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, DateTime
<Utc
>>("creation_datetime")?
))
255 Some((id
, creation_datetime
)) => {
256 if Utc
::now() - creation_datetime
> validation_time
{
257 return Ok(ValidationResult
::ValidationExpired
)
259 tx
.execute("UPDATE [User] SET [validation_token] = NULL WHERE [id] = ?1", [id
])?
;
263 return Ok(ValidationResult
::UnknownUser
)
266 let token
= Connection
::create_login_token(&tx
, user_id
, ip
, user_agent
)?
;
268 Ok(ValidationResult
::Ok(token
, user_id
))
271 pub fn sign_in(&self, password
: &str, email
: &str, ip
: &str, user_agent
: &str) -> Result
<SignInResult
> {
272 let mut con
= self.pool
.get()?
;
273 let tx
= con
.transaction()?
;
274 match tx
.query_row("SELECT [id], [password] FROM [User] WHERE [email] = ?1", [email
], |r
| {
275 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, String
>("password")?
))
277 Some((id
, stored_password
)) => {
278 if verify_password(password
, &stored_password
).map_err(DBError
::from_dyn_error
)?
{
279 let token
= Connection
::create_login_token(&tx
, id
, ip
, user_agent
)?
;
281 Ok(SignInResult
::Ok(token
, id
))
283 Ok(SignInResult
::PasswordsDontMatch
)
287 Ok(SignInResult
::UserNotFound
)
292 pub fn authentication(&self, token
: &str, ip
: &str, user_agent
: &str) -> Result
<AuthenticationResult
> {
293 let mut con
= self.pool
.get()?
;
294 let tx
= con
.transaction()?
;
295 match tx
.query_row("SELECT [id], [user_id] FROM [UserLoginToken] WHERE [token] = ?1", [token
], |r
| {
296 Ok((r
.get
::<&str, i32>("id")?
, r
.get
::<&str, i32>("user_id")?
))
298 Some((login_id
, user_id
)) => {
299 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
])?
;
301 Ok(AuthenticationResult
::Ok(user_id
))
304 Ok(AuthenticationResult
::NotValidToken
)
308 pub fn sign_out(&self, token
: &str) -> Result
<()> {
309 let mut con
= self.pool
.get()?
;
310 let tx
= con
.transaction()?
;
311 match tx
.query_row("SELECT [id] FROM [UserLoginToken] WHERE [token] = ?1", [token
], |r
| {
312 Ok(r
.get
::<&str, i32>("id")?
)
315 tx
.execute("DELETE FROM [UserLoginToken] WHERE [id] = ?1", params
![login_id
])?
;
323 /// Execute a given SQL file.
324 pub fn execute_file
<P
: AsRef
<Path
> + fmt
::Display
>(&self, file
: P
) -> Result
<()> {
325 let con
= self.pool
.get()?
;
326 let sql
= load_sql_file(file
)?
;
327 con
.execute_batch(&sql
).map_err(DBError
::from
)
330 /// Execute any SQL statement.
331 /// Mainly used for testing.
332 pub fn execute_sql
<P
: Params
>(&self, sql
: &str, params
: P
) -> Result
<usize> {
333 let con
= self.pool
.get()?
;
334 con
.execute(sql
, params
).map_err(DBError
::from
)
338 fn create_login_token(tx
: &rusqlite
::Transaction
, user_id
: i32, ip
: &str, user_agent
: &str) -> Result
<String
> {
339 let token
= generate_token();
340 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
])?
;
345 fn load_sql_file
<P
: AsRef
<Path
> + fmt
::Display
>(sql_file
: P
) -> Result
<String
> {
346 let mut file
= File
::open(&sql_file
).map_err(|err
| DBError
::Other(format!("Cannot open SQL file ({}): {}", &sql_file
, err
.to_string())))?
;
347 let mut sql
= String
::new();
348 file
.read_to_string(&mut sql
).map_err(|err
| DBError
::Other(format!("Cannot read SQL file ({}) : {}", &sql_file
, err
.to_string())))?
;
352 fn generate_token() -> String
{
353 Alphanumeric
.sample_string(&mut rand
::thread_rng(), 24)
361 fn sign_up() -> Result
<()> {
362 let connection
= Connection
::new_in_memory()?
;
363 match connection
.sign_up("paul@test.org", "12345")?
{
364 SignUpResult
::UserCreatedWaitingForValidation(_
) => (), // Nominal case.
365 other
=> panic!("{:?}", other
),
371 fn sign_up_to_an_already_existing_user() -> Result
<()> {
372 let connection
= Connection
::new_in_memory()?
;
373 connection
.execute_sql("
374 INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
379 '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
383 match connection
.sign_up("paul@test.org", "12345")?
{
384 SignUpResult
::UserAlreadyExists
=> (), // Nominal case.
385 other
=> panic!("{:?}", other
),
391 fn sign_up_to_an_unvalidated_already_existing_user() -> Result
<()> {
392 let connection
= Connection
::new_in_memory()?
;
393 let token
= generate_token();
394 connection
.execute_sql("
395 INSERT INTO [User] ([id], [email], [name], [password], [creation_datetime], [validation_token])
400 '$argon2id$v=19$m=4096,t=3,p=1$1vtXcacYjUHZxMrN6b2Xng$wW8Z59MIoMcsIljnjHmxn3EBcc5ymEySZPUVXHlRxcY',
403 );", named_params
! { ":token": token
})?
;
404 match connection
.sign_up("paul@test.org", "12345")?
{
405 SignUpResult
::UserCreatedWaitingForValidation(_
) => (), // Nominal case.
406 other
=> panic!("{:?}", other
),
412 fn sign_up_then_send_validation_at_time() -> Result
<()> {
413 let connection
= Connection
::new_in_memory()?
;
414 let validation_token
=
415 match connection
.sign_up("paul@test.org", "12345")?
{
416 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
417 other
=> panic!("{:?}", other
),
419 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
420 ValidationResult
::Ok(_
, _
) => (), // Nominal case.
421 other
=> panic!("{:?}", other
),
427 fn sign_up_then_send_validation_too_late() -> Result
<()> {
428 let connection
= Connection
::new_in_memory()?
;
429 let validation_token
=
430 match connection
.sign_up_with_given_time("paul@test.org", "12345", Utc
::now() - Duration
::days(1))?
{
431 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
432 other
=> panic!("{:?}", other
),
434 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
435 ValidationResult
::ValidationExpired
=> (), // Nominal case.
436 other
=> panic!("{:?}", other
),
442 fn sign_up_then_send_validation_with_bad_token() -> Result
<()> {
443 let connection
= Connection
::new_in_memory()?
;
444 let _validation_token
=
445 match connection
.sign_up("paul@test.org", "12345")?
{
446 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
447 other
=> panic!("{:?}", other
),
449 let random_token
= generate_token();
450 match connection
.validation(&random_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
451 ValidationResult
::UnknownUser
=> (), // Nominal case.
452 other
=> panic!("{:?}", other
),
458 fn sign_up_then_send_validation_then_sign_in() -> Result
<()> {
459 let connection
= Connection
::new_in_memory()?
;
461 let email
= "paul@test.org";
462 let password
= "12345";
465 let validation_token
=
466 match connection
.sign_up(email
, password
)?
{
467 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
468 other
=> panic!("{:?}", other
),
472 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla/5.0")?
{
473 ValidationResult
::Ok(_
, _
) => (),
474 other
=> panic!("{:?}", other
),
478 match connection
.sign_in(password
, email
, "127.0.0.1", "Mozilla/5.0")?
{
479 SignInResult
::Ok(_
, _
) => (), // Nominal case.
480 other
=> panic!("{:?}", other
),
487 fn sign_up_then_send_validation_then_authentication() -> Result
<()> {
488 let connection
= Connection
::new_in_memory()?
;
490 let email
= "paul@test.org";
491 let password
= "12345";
494 let validation_token
=
495 match connection
.sign_up(email
, password
)?
{
496 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
497 other
=> panic!("{:?}", other
),
501 let (authentication_token
, user_id
) = match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla")?
{
502 ValidationResult
::Ok(token
, user_id
) => (token
, user_id
),
503 other
=> panic!("{:?}", other
),
506 // Check user login information.
507 let user_login_info_1
= connection
.get_user_login_info(&authentication_token
)?
;
508 assert_eq!(user_login_info_1
.ip
, "127.0.0.1");
509 assert_eq!(user_login_info_1
.user_agent
, "Mozilla");
513 match connection
.authentication(&authentication_token
, "192.168.1.1", "Chrome")?
{
514 AuthenticationResult
::Ok(user_id
) => user_id
, // Nominal case.
515 other
=> panic!("{:?}", other
),
518 // Check user login information.
519 let user_login_info_2
= connection
.get_user_login_info(&authentication_token
)?
;
520 assert_eq!(user_login_info_2
.ip
, "192.168.1.1");
521 assert_eq!(user_login_info_2
.user_agent
, "Chrome");
527 fn sign_up_then_send_validation_then_sign_out_then_sign_in() -> Result
<()> {
528 let connection
= Connection
::new_in_memory()?
;
530 let email
= "paul@test.org";
531 let password
= "12345";
534 let validation_token
=
535 match connection
.sign_up(email
, password
)?
{
536 SignUpResult
::UserCreatedWaitingForValidation(token
) => token
, // Nominal case.
537 other
=> panic!("{:?}", other
),
541 let (authentication_token_1
, user_id_1
) =
542 match connection
.validation(&validation_token
, Duration
::hours(1), "127.0.0.1", "Mozilla")?
{
543 ValidationResult
::Ok(token
, user_id
) => (token
, user_id
),
544 other
=> panic!("{:?}", other
),
547 // Check user login information.
548 let user_login_info_1
= connection
.get_user_login_info(&authentication_token_1
)?
;
549 assert_eq!(user_login_info_1
.ip
, "127.0.0.1");
550 assert_eq!(user_login_info_1
.user_agent
, "Mozilla");
553 connection
.sign_out(&authentication_token_1
)?
;
556 let (authentication_token_2
, user_id_2
) =
557 match connection
.sign_in(password
, email
, "192.168.1.1", "Chrome")?
{
558 SignInResult
::Ok(token
, user_id
) => (token
, user_id
),
559 other
=> panic!("{:?}", other
),
562 assert_eq!(user_id_1
, user_id_2
);
563 assert_ne!(authentication_token_1
, authentication_token_2
);
565 // Check user login information.
566 let user_login_info_2
= connection
.get_user_login_info(&authentication_token_2
)?
;
568 assert_eq!(user_login_info_2
.ip
, "192.168.1.1");
569 assert_eq!(user_login_info_2
.user_agent
, "Chrome");