From b6235fb76ce82f96503cda83eebe8106320b2a0d Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Sat, 26 Nov 2022 20:22:45 +0100 Subject: [PATCH] Sign out --- Cargo.lock | 443 +++++++++++++++----------- TODO.md | 14 +- backend/Cargo.toml | 4 +- backend/src/db.rs | 56 +++- backend/src/hash.rs | 3 +- backend/src/main.rs | 329 +++++++++++++------ backend/src/model.rs | 4 +- backend/src/user.rs | 2 +- backend/templates/base.html | 10 +- backend/templates/base_with_list.html | 2 +- backend/templates/sign_in_form.html | 3 +- backend/templates/view_recipe.html | 10 +- 12 files changed, 561 insertions(+), 319 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 51e1d16..313d08d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -311,6 +311,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf722b94118a07fcbc6640190f247334027685d4e218b794dbfe17c32bf38ed0" dependencies = [ "askama_escape", + "comrak", "humansize", "mime", "mime_guess", @@ -444,7 +445,7 @@ dependencies = [ "js-sys", "num-integer", "num-traits", - "time 0.1.44", + "time 0.1.45", "wasm-bindgen", "winapi", ] @@ -504,6 +505,24 @@ dependencies = [ "regex", ] +[[package]] +name = "comrak" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff3c476e1a33eb4df1212a02db79d0f788bbd760901f34f5897644623e0e4e74" +dependencies = [ + "entities", + "lazy_static", + "pest", + "pest_derive", + "regex", + "shell-words", + "twoway", + "typed-arena", + "unicode_categories", + "xdg", +] + [[package]] name = "convert_case" version = "0.4.0" @@ -521,16 +540,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "core-foundation" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "core-foundation-sys" version = "0.8.3" @@ -633,6 +642,26 @@ dependencies = [ "subtle", ] +[[package]] +name = "dirs" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + [[package]] name = "either" version = "1.8.0" @@ -664,6 +693,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "entities" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca" + [[package]] name = "env_logger" version = "0.9.3" @@ -735,21 +770,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "form_urlencoded" version = "1.1.0" @@ -1053,7 +1073,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e394faa0efb47f9f227f1cd89978f854542b318a6f64fa695489c9c993056656" dependencies = [ "libc", - "windows-sys 0.42.0", + "windows-sys", ] [[package]] @@ -1065,7 +1085,7 @@ dependencies = [ "hermit-abi 0.2.6", "io-lifetimes", "rustix", - "windows-sys 0.42.0", + "windows-sys", ] [[package]] @@ -1128,11 +1148,13 @@ dependencies = [ "httpdate", "idna 0.2.3", "mime", - "native-tls", "nom", "once_cell", "quoted_printable", + "rustls", + "rustls-pemfile", "socket2", + "webpki-roots", ] [[package]] @@ -1262,25 +1284,7 @@ dependencies = [ "libc", "log", "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.42.0", -] - -[[package]] -name = "native-tls" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" -dependencies = [ - "lazy_static", - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", + "windows-sys", ] [[package]] @@ -1328,51 +1332,6 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" -[[package]] -name = "openssl" -version = "0.10.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "020433887e44c27ff16365eaa2d380547a94544ad509aff6eb5b6e3e0b27b376" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "openssl-probe" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" - -[[package]] -name = "openssl-sys" -version = "0.9.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07d5c8cb6e57b3a3612064d7b18b117912b4ce70955c2504d4b741c9e244b132" -dependencies = [ - "autocfg", - "cc", - "libc", - "pkg-config", - "vcpkg", -] - [[package]] name = "os_str_bytes" version = "6.4.1" @@ -1399,7 +1358,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-sys 0.42.0", + "windows-sys", ] [[package]] @@ -1425,6 +1384,50 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" +[[package]] +name = "pest" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f400b0f7905bf702f9f3dc3df5a121b16c54e9e8012c082905fdf09a931861a" +dependencies = [ + "thiserror", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "423c2ba011d6e27b02b482a3707c773d19aec65cc024637aec44e19652e66f63" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e64e6c2c85031c02fdbd9e5c72845445ca0a724d419aa0bc068ac620c9935c1" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pest_meta" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57959b91f0a133f89a68be874a5c88ed689c19cd729ecdb5d762ebf16c64d662" +dependencies = [ + "once_cell", + "pest", + "sha1", +] + [[package]] name = "pin-project-lite" version = "0.2.9" @@ -1582,6 +1585,17 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_users" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" +dependencies = [ + "getrandom", + "redox_syscall", + "thiserror", +] + [[package]] name = "regex" version = "1.7.0" @@ -1600,11 +1614,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" [[package]] -name = "remove_dir_all" -version = "0.5.3" +name = "ring" +version = "0.16.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted", + "web-sys", "winapi", ] @@ -1654,25 +1674,36 @@ dependencies = [ "io-lifetimes", "libc", "linux-raw-sys", - "windows-sys 0.42.0", + "windows-sys", ] [[package]] -name = "ryu" -version = "1.0.11" +name = "rustls" +version = "0.20.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" +checksum = "539a2bfe908f471bfa933876bd1eb6a19cf2176d375f82ef7f99530a40e48c2c" +dependencies = [ + "log", + "ring", + "sct", + "webpki", +] [[package]] -name = "schannel" -version = "0.1.20" +name = "rustls-pemfile" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2" +checksum = "0864aeff53f8c05aa08d86e5ef839d3dfcf07aeba2db32f12db0ef716e87bd55" dependencies = [ - "lazy_static", - "windows-sys 0.36.1", + "base64", ] +[[package]] +name = "ryu" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" + [[package]] name = "scheduled-thread-pool" version = "0.2.6" @@ -1695,26 +1726,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8132065adcfd6e02db789d9285a0deb2f3fcb04002865ab67d5fb103533898" [[package]] -name = "security-framework" -version = "2.7.0" +name = "sct" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bc1bb97804af6631813c55739f771071e0f2ed33ee20b68c86ec505d906356c" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556" -dependencies = [ - "core-foundation-sys", - "libc", + "ring", + "untrusted", ] [[package]] @@ -1777,6 +1795,12 @@ dependencies = [ "digest", ] +[[package]] +name = "shell-words" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" + [[package]] name = "signal-hook-registry" version = "1.4.0" @@ -1811,6 +1835,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + [[package]] name = "strsim" version = "0.10.0" @@ -1835,33 +1865,39 @@ dependencies = [ ] [[package]] -name = "tempfile" -version = "3.3.0" +name = "termcolor" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" dependencies = [ - "cfg-if", - "fastrand", - "libc", - "redox_syscall", - "remove_dir_all", - "winapi", + "winapi-util", ] [[package]] -name = "termcolor" -version = "1.1.3" +name = "thiserror" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" dependencies = [ - "winapi-util", + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", ] [[package]] name = "time" -version = "0.1.44" +version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" dependencies = [ "libc", "wasi 0.10.0+wasi-snapshot-preview1", @@ -1972,12 +2008,40 @@ dependencies = [ "once_cell", ] +[[package]] +name = "twoway" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c57ffb460d7c24cd6eda43694110189030a3d1dfe418416d9468fd1c1d290b47" +dependencies = [ + "memchr", + "unchecked-index", +] + +[[package]] +name = "typed-arena" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9b2228007eba4120145f785df0f6c92ea538f5a3635a612ecf4e334c8c1446d" + [[package]] name = "typenum" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" +[[package]] +name = "ucd-trie" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" + +[[package]] +name = "unchecked-index" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeba86d422ce181a719445e51872fa30f1f7413b62becb52e95ec91aa262d85c" + [[package]] name = "unicase" version = "2.6.0" @@ -2014,6 +2078,18 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + [[package]] name = "url" version = "2.3.1" @@ -2103,6 +2179,35 @@ version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" +[[package]] +name = "web-sys" +version = "0.3.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "webpki-roots" +version = "0.22.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368bfe657969fb01238bb756d351dcade285e0f6fcbd36dcb23359a5169975be" +dependencies = [ + "webpki", +] + [[package]] name = "winapi" version = "0.3.9" @@ -2134,19 +2239,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows-sys" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" -dependencies = [ - "windows_aarch64_msvc 0.36.1", - "windows_i686_gnu 0.36.1", - "windows_i686_msvc 0.36.1", - "windows_x86_64_gnu 0.36.1", - "windows_x86_64_msvc 0.36.1", -] - [[package]] name = "windows-sys" version = "0.42.0" @@ -2154,12 +2246,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" dependencies = [ "windows_aarch64_gnullvm", - "windows_aarch64_msvc 0.42.0", - "windows_i686_gnu 0.42.0", - "windows_i686_msvc 0.42.0", - "windows_x86_64_gnu 0.42.0", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", "windows_x86_64_gnullvm", - "windows_x86_64_msvc 0.42.0", + "windows_x86_64_msvc", ] [[package]] @@ -2168,48 +2260,24 @@ version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" -[[package]] -name = "windows_aarch64_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" - [[package]] name = "windows_aarch64_msvc" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" -[[package]] -name = "windows_i686_gnu" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" - [[package]] name = "windows_i686_gnu" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" -[[package]] -name = "windows_i686_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" - [[package]] name = "windows_i686_msvc" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" -[[package]] -name = "windows_x86_64_gnu" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" - [[package]] name = "windows_x86_64_gnu" version = "0.42.0" @@ -2224,15 +2292,18 @@ checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" [[package]] name = "windows_x86_64_msvc" -version = "0.36.1" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" +checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" [[package]] -name = "windows_x86_64_msvc" -version = "0.42.0" +name = "xdg" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" +checksum = "0c4583db5cbd4c4c0303df2d15af80f0539db703fa1c68802d4cbbd2dd0f88f6" +dependencies = [ + "dirs", +] [[package]] name = "zstd" diff --git a/TODO.md b/TODO.md index bb596f4..2120205 100644 --- a/TODO.md +++ b/TODO.md @@ -1,9 +1,13 @@ -* (WIP) Enable Logging to file. +* Asynchonous email sending and database requests +* Try using WASM for all the client logic (test on signup page) * Describe the use cases. -* Define the recipes model (SYSML). -* Implement the model as relational with SQLite. - * Create and update functions. * Define the UI (mockups). * Two CSS: one for desktop and one for mobile * Define the logic behind each page and action. -* Try using WASM for all the client logic \ No newline at end of file + +[ok] Sign out +[ok] Read all the askama doc and see if the current approach is good +[ok] Handle 404 +[ok] Enable Logging to file. +[ok] Implement the model as relational with SQLite. + [ok] Create and update functions. \ No newline at end of file diff --git a/backend/Cargo.toml b/backend/Cargo.toml index c443e9b..1cb217c 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -25,7 +25,7 @@ rusqlite = {version = "0.28", features = ["bundled", "chrono"]} futures = "0.3" # Needed by askam with the feature 'with-actix-web'. -askama = {version = "0.11", features = ["with-actix-web", "mime", "mime_guess"]} +askama = {version = "0.11", features = ["with-actix-web", "mime", "mime_guess", "markdown"]} askama_actix = "0.13" argon2 = {version = "0.4", features = ["default", "std"]} @@ -33,4 +33,4 @@ rand_core = {version = "0.6", features = ["std"]} rand = "0.8" -lettre = "0.10" \ No newline at end of file +lettre = {version = "0.10", default-features = false, features = ["smtp-transport", "pool", "hostname", "builder", "rustls-tls"]} \ No newline at end of file diff --git a/backend/src/db.rs b/backend/src/db.rs index bae57d0..e38aae7 100644 --- a/backend/src/db.rs +++ b/backend/src/db.rs @@ -7,7 +7,7 @@ use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use rand::distributions::{Alphanumeric, DistString}; -use crate::consts; +use crate::{consts, user}; use crate::hash::{hash, verify_password}; use crate::model; use crate::user::*; @@ -67,7 +67,8 @@ pub enum ValidationResult { #[derive(Debug)] pub enum SignInResult { UserNotFound, - PasswordsDontMatch, + WrongPassword, + AccountNotValidated, Ok(String, i32), // Returns token and user id. } @@ -197,8 +198,8 @@ impl Connection { pub fn get_recipe(&self, id: i32) -> Result { let con = self.pool.get()?; - con.query_row("SELECT [id], [title] FROM [Recipe] WHERE [id] = ?1", [id], |row| { - Ok(model::Recipe::new(row.get(0)?, row.get(1)?)) + con.query_row("SELECT [id], [title], [description] FROM [Recipe] WHERE [id] = ?1", [id], |row| { + Ok(model::Recipe::new(row.get("id")?, row.get("title")?, row.get("description")?)) }).map_err(DBError::from) } @@ -213,6 +214,15 @@ impl Connection { }).map_err(DBError::from) } + pub fn load_user(&self, user_id: i32) -> Result { + let con = self.pool.get()?; + con.query_row("SELECT [email] FROM [User] WHERE [id] = ?1", [user_id], |r| { + Ok(User { + email: r.get("email")?, + }) + }).map_err(DBError::from) + } + /// pub fn sign_up(&self, email: &str, password: &str) -> Result { self.sign_up_with_given_time(email, password, Utc::now()) @@ -268,19 +278,21 @@ impl Connection { Ok(ValidationResult::Ok(token, user_id)) } - pub fn sign_in(&self, password: &str, email: &str, ip: &str, user_agent: &str) -> Result { + pub fn sign_in(&self, email: &str, password: &str, ip: &str, user_agent: &str) -> Result { let mut con = self.pool.get()?; let tx = con.transaction()?; - match tx.query_row("SELECT [id], [password] FROM [User] WHERE [email] = ?1", [email], |r| { - Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?)) + match tx.query_row("SELECT [id], [password], [validation_token] FROM [User] WHERE [email] = ?1", [email], |r| { + Ok((r.get::<&str, i32>("id")?, r.get::<&str, String>("password")?, r.get::<&str, Option>("validation_token")?)) }).optional()? { - Some((id, stored_password)) => { - if verify_password(password, &stored_password).map_err(DBError::from_dyn_error)? { + Some((id, stored_password, validation_token)) => { + if validation_token.is_some() { + Ok(SignInResult::AccountNotValidated) + } else if verify_password(password, &stored_password).map_err(DBError::from_dyn_error)? { let token = Connection::create_login_token(&tx, id, ip, user_agent)?; tx.commit()?; Ok(SignInResult::Ok(token, id)) } else { - Ok(SignInResult::PasswordsDontMatch) + Ok(SignInResult::WrongPassword) } }, None => { @@ -387,6 +399,26 @@ mod tests { Ok(()) } + #[test] + fn sign_up_and_sign_in_without_validation() -> Result<()> { + let connection = Connection::new_in_memory()?; + + let email = "paul@test.org"; + let password = "12345"; + + match connection.sign_up(email, password)? { + SignUpResult::UserCreatedWaitingForValidation(_) => (), // Nominal case. + other => panic!("{:?}", other), + } + + match connection.sign_in(email, password, "127.0.0.1", "Mozilla/5.0")? { + SignInResult::AccountNotValidated => (), // Nominal case. + other => panic!("{:?}", other), + } + + Ok(()) + } + #[test] fn sign_up_to_an_unvalidated_already_existing_user() -> Result<()> { let connection = Connection::new_in_memory()?; @@ -475,7 +507,7 @@ mod tests { }; // Sign in. - match connection.sign_in(password, email, "127.0.0.1", "Mozilla/5.0")? { + match connection.sign_in(email, password, "127.0.0.1", "Mozilla/5.0")? { SignInResult::Ok(_, _) => (), // Nominal case. other => panic!("{:?}", other), } @@ -554,7 +586,7 @@ mod tests { // Sign in. let (authentication_token_2, user_id_2) = - match connection.sign_in(password, email, "192.168.1.1", "Chrome")? { + match connection.sign_in(email, password, "192.168.1.1", "Chrome")? { SignInResult::Ok(token, user_id) => (token, user_id), other => panic!("{:?}", other), }; diff --git a/backend/src/hash.rs b/backend/src/hash.rs index ecdaf45..8002ac7 100644 --- a/backend/src/hash.rs +++ b/backend/src/hash.rs @@ -1,8 +1,7 @@ -use std::{string::String, env::consts::OS}; +use std::{string::String}; use argon2::{ password_hash::{ - Error, rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString }, diff --git a/backend/src/main.rs b/backend/src/main.rs index 141c87f..91b8d32 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1,13 +1,14 @@ -use std::{collections::HashMap, net::ToSocketAddrs}; +use std::collections::HashMap; use actix_files as fs; -use actix_web::{http::header, get, post, web, Responder, middleware, App, HttpServer, HttpRequest, HttpResponse}; +use actix_web::{http::header, get, post, web, Responder, middleware, App, HttpServer, HttpRequest, HttpResponse, cookie::Cookie}; use askama_actix::{Template, TemplateToResponse}; use chrono::{prelude::*, Duration}; use clap::Parser; use serde::Deserialize; use config::Config; +use user::User; mod consts; mod db; @@ -17,65 +18,114 @@ mod user; mod email; mod config; +const COOKIE_AUTH_TOKEN_NAME: &str = "auth_token"; + +///// UTILS ///// + +fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) { + let user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default().to_string(); + let ip = req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default(); + (ip, user_agent) +} + +fn get_current_user(req: &HttpRequest, connection: &web::Data) -> Option { + let (client_ip, client_user_agent) = get_ip_and_user_agent(req); + + match req.cookie(COOKIE_AUTH_TOKEN_NAME) { + Some(token_cookie) => + match connection.authentication(token_cookie.value(), &client_ip, &client_user_agent) { + Ok(db::AuthenticationResult::NotValidToken) => + // TODO: remove cookie? + None, + Ok(db::AuthenticationResult::Ok(user_id)) => + match connection.load_user(user_id) { + Ok(user) => + Some(user), + Err(error) => { + eprintln!("Error during authentication: {:?}", error); + None + } + }, + Err(error) => { + eprintln!("Error during authentication: {:?}", error); + None + }, + }, + None => None + } +} + +///// HOME ///// + #[derive(Template)] #[template(path = "home.html")] struct HomeTemplate { + user: Option, recipes: Vec<(i32, String)>, } -#[derive(Template)] -#[template(path = "sign_in_form.html")] -struct SignInFormTemplate { +#[get("/")] +async fn home_page(req: HttpRequest, connection: web::Data) -> impl Responder { + HomeTemplate { user: get_current_user(&req, &connection), recipes: connection.get_all_recipe_titles().unwrap_or_default() } } +///// VIEW RECIPE ///// + #[derive(Template)] #[template(path = "view_recipe.html")] struct ViewRecipeTemplate { + user: Option, recipes: Vec<(i32, String)>, current_recipe: model::Recipe, } +#[get("/recipe/view/{id}")] +async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data) -> impl Responder { + let (id,)= path.into_inner(); + let recipes = connection.get_all_recipe_titles().unwrap_or_default(); + let user = get_current_user(&req, &connection); + + match connection.get_recipe(id) { + Ok(recipe) => + ViewRecipeTemplate { + user, + recipes, + current_recipe: recipe, + }.to_response(), + Err(_error) => + MessageTemplate { + user, + recipes, + message: format!("Unable to get recipe #{}", id), + }.to_response(), + } +} + +///// MESSAGE ///// + #[derive(Template)] #[template(path = "message.html")] struct MessageTemplate { + user: Option, recipes: Vec<(i32, String)>, message: String, } -#[get("/")] -async fn home_page(req: HttpRequest, connection: web::Data) -> impl Responder { - HomeTemplate { recipes: connection.get_all_recipe_titles().unwrap_or_default() } -} - //// SIGN UP ///// #[derive(Template)] #[template(path = "sign_up_form.html")] struct SignUpFormTemplate { + user: Option, email: String, message: String, message_email: String, message_password: String, } -impl SignUpFormTemplate { - fn new() -> Self { - SignUpFormTemplate { email: String::new(), message: String::new(), message_email: String::new(), message_password: String::new() } - } -} - -enum SignUpError { - InvalidEmail, - PasswordsNotEqual, - InvalidPassword, - UserAlreadyExists, - DatabaseError, - UnableSendEmail, -} - #[get("/signup")] async fn sign_up_get(req: HttpRequest, query: web::Query>, connection: web::Data) -> impl Responder { - SignUpFormTemplate::new() + SignUpFormTemplate { user: get_current_user(&req, &connection), email: String::new(), message: String::new(), message_email: String::new(), message_password: String::new() } } #[derive(Deserialize)] @@ -85,12 +135,22 @@ struct SignUpFormData { password_2: String, } +enum SignUpError { + InvalidEmail, + PasswordsNotEqual, + InvalidPassword, + UserAlreadyExists, + DatabaseError, + UnableSendEmail, +} + #[post("/signup")] async fn sign_up_post(req: HttpRequest, form: web::Form, connection: web::Data, config: web::Data) -> impl Responder { - println!("Sign Up, email: {}, passwords: {}/{}", form.email, form.password_1, form.password_2); + println!("Sign up, email: {}, passwords: {}/{}", form.email, form.password_1, form.password_2); - fn error_response(error: SignUpError, form: &web::Form) -> HttpResponse { + fn error_response(error: SignUpError, form: &web::Form, user: Option) -> HttpResponse { SignUpFormTemplate { + user, email: form.email.clone(), message_email: match error { @@ -113,22 +173,24 @@ async fn sign_up_post(req: HttpRequest, form: web::Form, connect }.to_response() } + let user = get_current_user(&req, &connection); + // Validation of email and password. if let common::utils::EmailValidation::NotValid = common::utils::validate_email(&form.email) { - return error_response(SignUpError::InvalidEmail, &form); + return error_response(SignUpError::InvalidEmail, &form, user); } if form.password_1 != form.password_2 { - return error_response(SignUpError::PasswordsNotEqual, &form); + return error_response(SignUpError::PasswordsNotEqual, &form, user); } if let common::utils::PasswordValidation::TooShort = common::utils::validate_password(&form.password_1) { - return error_response(SignUpError::InvalidPassword, &form); + return error_response(SignUpError::InvalidPassword, &form, user); } match connection.sign_up(&form.email, &form.password_1) { Ok(db::SignUpResult::UserAlreadyExists) => { - error_response(SignUpError::UserAlreadyExists, &form) + error_response(SignUpError::UserAlreadyExists, &form, user) }, Ok(db::SignUpResult::UserCreatedWaitingForValidation(token)) => { let url = { @@ -151,21 +213,22 @@ async fn sign_up_post(req: HttpRequest, form: web::Form, connect .finish(), Err(error) => { eprintln!("Email validation error: {:?}", error); - error_response(SignUpError::UnableSendEmail, &form) + error_response(SignUpError::UnableSendEmail, &form, user) }, } }, Err(error) => { eprintln!("Signup database error: {:?}", error); - error_response(SignUpError::DatabaseError, &form) + error_response(SignUpError::DatabaseError, &form, user) }, } } #[get("/signup_check_email")] -async fn sign_up_check_email(connection: web::Data) -> impl Responder { +async fn sign_up_check_email(req: HttpRequest, connection: web::Data) -> impl Responder { let recipes = connection.get_all_recipe_titles().unwrap_or_default(); MessageTemplate { + user: get_current_user(&req, &connection), recipes, message: "An email has been sent, follow the link to validate your account.".to_string(), } @@ -173,89 +236,166 @@ async fn sign_up_check_email(connection: web::Data) -> impl Resp #[get("/validation")] async fn sign_up_validation(req: HttpRequest, query: web::Query>, connection: web::Data) -> impl Responder { - - println!("req:\n{:#?}", req); - - let client_user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default(); - let client_ip = req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default(); + let (client_ip, client_user_agent) = get_ip_and_user_agent(&req); + let user = get_current_user(&req, &connection); let recipes = connection.get_all_recipe_titles().unwrap_or_default(); match query.get("token") { Some(token) => { - match connection.validation(token, Duration::seconds(consts::VALIDATION_TOKEN_DURATION), &client_ip, client_user_agent).unwrap() { - db::ValidationResult::Ok(token, user_id) => - // TODO: set token to cookie. - MessageTemplate { - recipes, - message: "Email validation successful, your account has been created".to_string(), - }, + match connection.validation(token, Duration::seconds(consts::VALIDATION_TOKEN_DURATION), &client_ip, &client_user_agent).unwrap() { + db::ValidationResult::Ok(token, user_id) => { + let cookie = Cookie::new(COOKIE_AUTH_TOKEN_NAME, token); + let user = + match connection.load_user(user_id) { + Ok(user) => + Some(user), + Err(error) => { + eprintln!("Error retrieving user by id: {}", error); + None + } + }; + + let mut response = + MessageTemplate { + user, + recipes, + message: "Email validation successful, your account has been created".to_string(), + }.to_response(); + + if let Err(error) = response.add_cookie(&cookie) { + eprintln!("Unable to set cookie after validation: {:?}", error); + }; + + response + }, db::ValidationResult::ValidationExpired => MessageTemplate { + user, recipes, message: "The validation has expired. Try to sign up again.".to_string(), - }, + }.to_response(), db::ValidationResult::UnknownUser => - MessageTemplate { - recipes, - message: "Validation error.".to_string(), - }, + MessageTemplate { + user, + recipes, + message: "Validation error.".to_string(), + }.to_response(), } }, None => { MessageTemplate { + user, recipes, message: format!("No token provided"), - } + }.to_response() }, } } ///// SIGN IN ///// -#[get("/signinform")] -async fn sign_in_form(req: HttpRequest, connection: web::Data) -> impl Responder { +#[derive(Template)] +#[template(path = "sign_in_form.html")] +struct SignInFormTemplate { + user: Option, + email: String, + message: String, +} + +#[get("/signin")] +async fn sign_in_get(req: HttpRequest, connection: web::Data) -> impl Responder { SignInFormTemplate { + user: get_current_user(&req, &connection), + email: String::new(), + message: String::new(), } } -#[post("/signin")] -async fn sign_in(req: HttpRequest) -> impl Responder { - "todo" +#[derive(Deserialize)] +struct SignInFormData { + email: String, + password: String, } -#[get("/recipe/view/{id}")] -async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data) -> impl Responder { - let (id,)= path.into_inner(); - let recipes = connection.get_all_recipe_titles().unwrap_or_default(); - println!("{:?}", recipes); - match connection.get_recipe(id) { - Ok(recipe) => - ViewRecipeTemplate { - recipes, - current_recipe: recipe, - }.to_response(), - Err(_error) => - MessageTemplate { - recipes, - message: format!("Unable to get recipe #{}", id), - }.to_response(), +enum SignInError { + AccountNotValidated, + AuthenticationFailed, +} + +#[post("/signin")] +async fn sign_in_post(req: HttpRequest, form: web::Form, connection: web::Data) -> impl Responder { + println!("Sign in, email: {}, password: {}", form.email, form.password); + + fn error_response(error: SignInError, form: &web::Form, user: Option) -> HttpResponse { + SignInFormTemplate { + user, + email: form.email.clone(), + message: + match error { + SignInError::AccountNotValidated => "This account must be validated first", + SignInError::AuthenticationFailed => "Wrong email or password", + }.to_string(), + }.to_response() } + + let user = get_current_user(&req, &connection); + let (client_ip, client_user_agent) = get_ip_and_user_agent(&req); + + match connection.sign_in(&form.email, &form.password, &client_ip, &client_user_agent) { + Ok(db::SignInResult::AccountNotValidated) => + error_response(SignInError::AccountNotValidated, &form, user), + Ok(db::SignInResult::UserNotFound) | Ok(db::SignInResult::WrongPassword) => { + error_response(SignInError::AuthenticationFailed, &form, user) + }, + Ok(db::SignInResult::Ok(token, user_id)) => { + let cookie = Cookie::new(COOKIE_AUTH_TOKEN_NAME, token); + let mut response = + HttpResponse::Found() + .insert_header((header::LOCATION, "/")) + .finish(); + if let Err(error) = response.add_cookie(&cookie) { + eprintln!("Unable to set cookie after sign in: {:?}", error); + }; + response + }, + Err(error) => { + eprintln!("Signin error: {:?}", error); + error_response(SignInError::AuthenticationFailed, &form, user) + }, + } +} + + +///// SIGN OUT ///// + +#[get("/signout")] +async fn sign_out(req: HttpRequest, connection: web::Data) -> impl Responder { + let mut response = + HttpResponse::Found() + .insert_header((header::LOCATION, "/")) + .finish(); + + if let Some(token_cookie) = req.cookie(COOKIE_AUTH_TOKEN_NAME) { + if let Err(error) = connection.sign_out(token_cookie.value()) { + eprintln!("Unable to sign out: {:?}", error); + }; + + if let Err(error) = response.add_removal_cookie(&Cookie::new(COOKIE_AUTH_TOKEN_NAME, "")) { + eprintln!("Unable to set a removal cookie after sign out: {:?}", error); + }; + }; + response } async fn not_found(req: HttpRequest, connection: web::Data) -> impl Responder { let recipes = connection.get_all_recipe_titles().unwrap_or_default(); MessageTemplate { + user: get_current_user(&req, &connection), recipes, message: "404: Not found".to_string(), } } -fn get_exe_name() -> String { - let first_arg = std::env::args().nth(0).unwrap(); - let sep: &[_] = &['\\', '/']; - first_arg[first_arg.rfind(sep).unwrap()+1..].to_string() -} - #[actix_web::main] async fn main() -> std::io::Result<()> { if process_args() { return Ok(()) } @@ -286,12 +426,12 @@ async fn main() -> std::io::Result<()> { .service(sign_up_post) .service(sign_up_check_email) .service(sign_up_validation) - .service(sign_in_form) - .service(sign_in) + .service(sign_in_get) + .service(sign_in_post) + .service(sign_out) .service(view_recipe) .service(fs::Files::new("/static", "static")) .default_service(web::to(not_found)) - //.default_service(not_found) }); server.bind(&format!("0.0.0.0:{}", port))?.run().await @@ -324,27 +464,4 @@ fn process_args() -> bool { } false - - /* - - - fn print_usage() { - println!("Usage:"); - println!(" {} [--help] [--test]", get_exe_name()); - } - - let args: Vec = args().collect(); - - if args.iter().any(|arg| arg == "--help") { - print_usage(); - return true - } else if args.iter().any(|arg| arg == "--test") { - match db::Connection::new() { - Ok(_) => (), - Err(error) => println!("Error: {:?}", error) - } - return true - } - false - */ } diff --git a/backend/src/model.rs b/backend/src/model.rs index 4984cdd..719ed21 100644 --- a/backend/src/model.rs +++ b/backend/src/model.rs @@ -1,6 +1,7 @@ pub struct Recipe { pub id: i32, pub title: String, + pub description: Option, pub estimate_time: Option, // [min]. pub difficulty: Option, @@ -9,10 +10,11 @@ pub struct Recipe { } impl Recipe { - pub fn new(id: i32, title: String) -> Recipe { + pub fn new(id: i32, title: String, description: Option) -> Recipe { Recipe { id, title, + description, estimate_time: None, difficulty: None, process: Vec::new(), diff --git a/backend/src/user.rs b/backend/src/user.rs index f6b308f..d9825ae 100644 --- a/backend/src/user.rs +++ b/backend/src/user.rs @@ -1,7 +1,7 @@ use chrono::prelude::*; pub struct User { - + pub email: String, } pub struct UserLoginInfo { diff --git a/backend/templates/base.html b/backend/templates/base.html index 2ca77df..c6fbf69 100644 --- a/backend/templates/base.html +++ b/backend/templates/base.html @@ -8,7 +8,15 @@ - +
+

~~ Recettes de cuisine ~~

+ {% match user %} + {% when Some with (user) %} +
{{ user.email }} / Sign out
+ {% when None %} + + {% endmatch %} +
{% block main_container %}{% endblock %}
diff --git a/backend/templates/base_with_list.html b/backend/templates/base_with_list.html index fb008aa..7e2e679 100644 --- a/backend/templates/base_with_list.html +++ b/backend/templates/base_with_list.html @@ -4,7 +4,7 @@
diff --git a/backend/templates/sign_in_form.html b/backend/templates/sign_in_form.html index d41b3cd..6b682d0 100644 --- a/backend/templates/sign_in_form.html +++ b/backend/templates/sign_in_form.html @@ -4,12 +4,13 @@
- +
+ {{ message }}
{% endblock %} diff --git a/backend/templates/view_recipe.html b/backend/templates/view_recipe.html index e355c52..1a5ba52 100644 --- a/backend/templates/view_recipe.html +++ b/backend/templates/view_recipe.html @@ -2,6 +2,14 @@ {% block content %} -{{ current_recipe.title }} +

{{ current_recipe.title }}

+ +{% match current_recipe.description %} + {% when Some with (description) %} +
+ {{ description|markdown }} +
+ {% when None %} +{% endmatch %} {% endblock %} \ No newline at end of file -- 2.45.2