├── .env.test ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── db └── .keep ├── diesel.toml ├── docker └── Dockerfile ├── migrations ├── .gitkeep ├── 2020-02-20-085623_create_user │ ├── down.sql │ └── up.sql ├── 2020-02-21-011449_create_items │ ├── down.sql │ └── up.sql ├── 2020-02-21-102019_create_tokens │ ├── down.sql │ └── up.sql └── 2020-02-22-110735_initial_indices │ ├── down.sql │ └── up.sql ├── src ├── api.rs ├── db.rs ├── item.rs ├── lock.rs ├── main.rs ├── schema.rs ├── sync_tokens.rs ├── tests.rs ├── tokens.rs └── user.rs └── test.sh /.env.test: -------------------------------------------------------------------------------- 1 | SFRS_ENV=development 2 | DATABASE_URL=./db/database.test.db 3 | SYNC_TOKEN_SECRET=awesome_password 4 | SYNC_TOKEN_SALT=awesome_salt -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .env 3 | database.db 4 | database.test.db -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "aho-corasick" 5 | version = "0.6.10" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | checksum = "81ce3d38065e618af2d7b77e10c5ad9a069859b4be3c2250f674af3840d9c8a5" 8 | dependencies = [ 9 | "memchr", 10 | ] 11 | 12 | [[package]] 13 | name = "aho-corasick" 14 | version = "0.7.8" 15 | source = "registry+https://github.com/rust-lang/crates.io-index" 16 | checksum = "743ad5a418686aad3b87fd14c43badd828cf26e214a00f92a384291cf22e1811" 17 | dependencies = [ 18 | "memchr", 19 | ] 20 | 21 | [[package]] 22 | name = "atty" 23 | version = "0.2.14" 24 | source = "registry+https://github.com/rust-lang/crates.io-index" 25 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 26 | dependencies = [ 27 | "hermit-abi", 28 | "libc", 29 | "winapi 0.3.8", 30 | ] 31 | 32 | [[package]] 33 | name = "autocfg" 34 | version = "1.0.0" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" 37 | 38 | [[package]] 39 | name = "base64" 40 | version = "0.9.3" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "489d6c0ed21b11d038c31b6ceccca973e65d73ba3bd8ecb9a2babf5546164643" 43 | dependencies = [ 44 | "byteorder", 45 | "safemem", 46 | ] 47 | 48 | [[package]] 49 | name = "base64" 50 | version = "0.10.1" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" 53 | dependencies = [ 54 | "byteorder", 55 | ] 56 | 57 | [[package]] 58 | name = "bitflags" 59 | version = "1.2.1" 60 | source = "registry+https://github.com/rust-lang/crates.io-index" 61 | checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 62 | 63 | [[package]] 64 | name = "block-buffer" 65 | version = "0.7.3" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" 68 | dependencies = [ 69 | "block-padding", 70 | "byte-tools", 71 | "byteorder", 72 | "generic-array", 73 | ] 74 | 75 | [[package]] 76 | name = "block-padding" 77 | version = "0.1.5" 78 | source = "registry+https://github.com/rust-lang/crates.io-index" 79 | checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" 80 | dependencies = [ 81 | "byte-tools", 82 | ] 83 | 84 | [[package]] 85 | name = "byte-tools" 86 | version = "0.3.1" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" 89 | 90 | [[package]] 91 | name = "byteorder" 92 | version = "1.3.4" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" 95 | 96 | [[package]] 97 | name = "c2-chacha" 98 | version = "0.2.3" 99 | source = "registry+https://github.com/rust-lang/crates.io-index" 100 | checksum = "214238caa1bf3a496ec3392968969cab8549f96ff30652c9e56885329315f6bb" 101 | dependencies = [ 102 | "ppv-lite86", 103 | ] 104 | 105 | [[package]] 106 | name = "cc" 107 | version = "1.0.50" 108 | source = "registry+https://github.com/rust-lang/crates.io-index" 109 | checksum = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" 110 | 111 | [[package]] 112 | name = "cfg-if" 113 | version = "0.1.10" 114 | source = "registry+https://github.com/rust-lang/crates.io-index" 115 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 116 | 117 | [[package]] 118 | name = "chrono" 119 | version = "0.4.10" 120 | source = "registry+https://github.com/rust-lang/crates.io-index" 121 | checksum = "31850b4a4d6bae316f7a09e691c944c28299298837edc0a03f755618c23cbc01" 122 | dependencies = [ 123 | "num-integer", 124 | "num-traits", 125 | "time", 126 | ] 127 | 128 | [[package]] 129 | name = "cloudabi" 130 | version = "0.0.3" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" 133 | dependencies = [ 134 | "bitflags", 135 | ] 136 | 137 | [[package]] 138 | name = "cookie" 139 | version = "0.11.2" 140 | source = "registry+https://github.com/rust-lang/crates.io-index" 141 | checksum = "d9fac5e7bdefb6160fb181ee0eaa6f96704b625c70e6d61c465cb35750a4ea12" 142 | dependencies = [ 143 | "base64 0.9.3", 144 | "ring", 145 | "time", 146 | "url", 147 | ] 148 | 149 | [[package]] 150 | name = "crypto-mac" 151 | version = "0.7.0" 152 | source = "registry+https://github.com/rust-lang/crates.io-index" 153 | checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" 154 | dependencies = [ 155 | "generic-array", 156 | "subtle", 157 | ] 158 | 159 | [[package]] 160 | name = "devise" 161 | version = "0.2.0" 162 | source = "registry+https://github.com/rust-lang/crates.io-index" 163 | checksum = "74e04ba2d03c5fa0d954c061fc8c9c288badadffc272ebb87679a89846de3ed3" 164 | dependencies = [ 165 | "devise_codegen", 166 | "devise_core", 167 | ] 168 | 169 | [[package]] 170 | name = "devise_codegen" 171 | version = "0.2.0" 172 | source = "registry+https://github.com/rust-lang/crates.io-index" 173 | checksum = "066ceb7928ca93a9bedc6d0e612a8a0424048b0ab1f75971b203d01420c055d7" 174 | dependencies = [ 175 | "devise_core", 176 | "quote 0.6.13", 177 | ] 178 | 179 | [[package]] 180 | name = "devise_core" 181 | version = "0.2.0" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "cf41c59b22b5e3ec0ea55c7847e5f358d340f3a8d6d53a5cf4f1564967f96487" 184 | dependencies = [ 185 | "bitflags", 186 | "proc-macro2 0.4.30", 187 | "quote 0.6.13", 188 | "syn 0.15.44", 189 | ] 190 | 191 | [[package]] 192 | name = "diesel" 193 | version = "1.4.3" 194 | source = "registry+https://github.com/rust-lang/crates.io-index" 195 | checksum = "9d7cc03b910de9935007861dce440881f69102aaaedfd4bc5a6f40340ca5840c" 196 | dependencies = [ 197 | "byteorder", 198 | "chrono", 199 | "diesel_derives", 200 | "libsqlite3-sys", 201 | "r2d2", 202 | ] 203 | 204 | [[package]] 205 | name = "diesel_derives" 206 | version = "1.4.1" 207 | source = "registry+https://github.com/rust-lang/crates.io-index" 208 | checksum = "45f5098f628d02a7a0f68ddba586fb61e80edec3bdc1be3b921f4ceec60858d3" 209 | dependencies = [ 210 | "proc-macro2 1.0.8", 211 | "quote 1.0.2", 212 | "syn 1.0.14", 213 | ] 214 | 215 | [[package]] 216 | name = "diesel_migrations" 217 | version = "1.4.0" 218 | source = "registry+https://github.com/rust-lang/crates.io-index" 219 | checksum = "bf3cde8413353dc7f5d72fa8ce0b99a560a359d2c5ef1e5817ca731cd9008f4c" 220 | dependencies = [ 221 | "migrations_internals", 222 | "migrations_macros", 223 | ] 224 | 225 | [[package]] 226 | name = "digest" 227 | version = "0.8.1" 228 | source = "registry+https://github.com/rust-lang/crates.io-index" 229 | checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" 230 | dependencies = [ 231 | "generic-array", 232 | ] 233 | 234 | [[package]] 235 | name = "dotenv" 236 | version = "0.9.0" 237 | source = "registry+https://github.com/rust-lang/crates.io-index" 238 | checksum = "400b347fe65ccfbd8f545c9d9a75d04b0caf23fec49aaa838a9a05398f94c019" 239 | dependencies = [ 240 | "regex 0.2.11", 241 | ] 242 | 243 | [[package]] 244 | name = "either" 245 | version = "1.5.3" 246 | source = "registry+https://github.com/rust-lang/crates.io-index" 247 | checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" 248 | 249 | [[package]] 250 | name = "fake-simd" 251 | version = "0.1.2" 252 | source = "registry+https://github.com/rust-lang/crates.io-index" 253 | checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" 254 | 255 | [[package]] 256 | name = "filetime" 257 | version = "0.2.8" 258 | source = "registry+https://github.com/rust-lang/crates.io-index" 259 | checksum = "1ff6d4dab0aa0c8e6346d46052e93b13a16cf847b54ed357087c35011048cc7d" 260 | dependencies = [ 261 | "cfg-if", 262 | "libc", 263 | "redox_syscall", 264 | "winapi 0.3.8", 265 | ] 266 | 267 | [[package]] 268 | name = "fsevent" 269 | version = "0.4.0" 270 | source = "registry+https://github.com/rust-lang/crates.io-index" 271 | checksum = "5ab7d1bd1bd33cc98b0889831b72da23c0aa4df9cec7e0702f46ecea04b35db6" 272 | dependencies = [ 273 | "bitflags", 274 | "fsevent-sys", 275 | ] 276 | 277 | [[package]] 278 | name = "fsevent-sys" 279 | version = "2.0.1" 280 | source = "registry+https://github.com/rust-lang/crates.io-index" 281 | checksum = "f41b048a94555da0f42f1d632e2e19510084fb8e303b0daa2816e733fb3644a0" 282 | dependencies = [ 283 | "libc", 284 | ] 285 | 286 | [[package]] 287 | name = "fuchsia-cprng" 288 | version = "0.1.1" 289 | source = "registry+https://github.com/rust-lang/crates.io-index" 290 | checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" 291 | 292 | [[package]] 293 | name = "fuchsia-zircon" 294 | version = "0.3.3" 295 | source = "registry+https://github.com/rust-lang/crates.io-index" 296 | checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" 297 | dependencies = [ 298 | "bitflags", 299 | "fuchsia-zircon-sys", 300 | ] 301 | 302 | [[package]] 303 | name = "fuchsia-zircon-sys" 304 | version = "0.3.3" 305 | source = "registry+https://github.com/rust-lang/crates.io-index" 306 | checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" 307 | 308 | [[package]] 309 | name = "generic-array" 310 | version = "0.12.3" 311 | source = "registry+https://github.com/rust-lang/crates.io-index" 312 | checksum = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec" 313 | dependencies = [ 314 | "typenum", 315 | ] 316 | 317 | [[package]] 318 | name = "getrandom" 319 | version = "0.1.14" 320 | source = "registry+https://github.com/rust-lang/crates.io-index" 321 | checksum = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb" 322 | dependencies = [ 323 | "cfg-if", 324 | "libc", 325 | "wasi", 326 | ] 327 | 328 | [[package]] 329 | name = "hermit-abi" 330 | version = "0.1.7" 331 | source = "registry+https://github.com/rust-lang/crates.io-index" 332 | checksum = "e2c55f143919fbc0bc77e427fe2d74cf23786d7c1875666f2fde3ac3c659bb67" 333 | dependencies = [ 334 | "libc", 335 | ] 336 | 337 | [[package]] 338 | name = "hex" 339 | version = "0.4.2" 340 | source = "registry+https://github.com/rust-lang/crates.io-index" 341 | checksum = "644f9158b2f133fd50f5fb3242878846d9eb792e445c893805ff0e3824006e35" 342 | 343 | [[package]] 344 | name = "hmac" 345 | version = "0.7.1" 346 | source = "registry+https://github.com/rust-lang/crates.io-index" 347 | checksum = "5dcb5e64cda4c23119ab41ba960d1e170a774c8e4b9d9e6a9bc18aabf5e59695" 348 | dependencies = [ 349 | "crypto-mac", 350 | "digest", 351 | ] 352 | 353 | [[package]] 354 | name = "httparse" 355 | version = "1.3.4" 356 | source = "registry+https://github.com/rust-lang/crates.io-index" 357 | checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9" 358 | 359 | [[package]] 360 | name = "hyper" 361 | version = "0.10.16" 362 | source = "registry+https://github.com/rust-lang/crates.io-index" 363 | checksum = "0a0652d9a2609a968c14be1a9ea00bf4b1d64e2e1f53a1b51b6fff3a6e829273" 364 | dependencies = [ 365 | "base64 0.9.3", 366 | "httparse", 367 | "language-tags", 368 | "log 0.3.9", 369 | "mime", 370 | "num_cpus", 371 | "time", 372 | "traitobject", 373 | "typeable", 374 | "unicase 1.4.2", 375 | "url", 376 | ] 377 | 378 | [[package]] 379 | name = "idna" 380 | version = "0.1.5" 381 | source = "registry+https://github.com/rust-lang/crates.io-index" 382 | checksum = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" 383 | dependencies = [ 384 | "matches", 385 | "unicode-bidi", 386 | "unicode-normalization", 387 | ] 388 | 389 | [[package]] 390 | name = "indexmap" 391 | version = "1.3.2" 392 | source = "registry+https://github.com/rust-lang/crates.io-index" 393 | checksum = "076f042c5b7b98f31d205f1249267e12a6518c1481e9dae9764af19b707d2292" 394 | dependencies = [ 395 | "autocfg", 396 | ] 397 | 398 | [[package]] 399 | name = "inotify" 400 | version = "0.7.0" 401 | source = "registry+https://github.com/rust-lang/crates.io-index" 402 | checksum = "24e40d6fd5d64e2082e0c796495c8ef5ad667a96d03e5aaa0becfd9d47bcbfb8" 403 | dependencies = [ 404 | "bitflags", 405 | "inotify-sys", 406 | "libc", 407 | ] 408 | 409 | [[package]] 410 | name = "inotify-sys" 411 | version = "0.1.3" 412 | source = "registry+https://github.com/rust-lang/crates.io-index" 413 | checksum = "e74a1aa87c59aeff6ef2cc2fa62d41bc43f54952f55652656b18a02fd5e356c0" 414 | dependencies = [ 415 | "libc", 416 | ] 417 | 418 | [[package]] 419 | name = "iovec" 420 | version = "0.1.4" 421 | source = "registry+https://github.com/rust-lang/crates.io-index" 422 | checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" 423 | dependencies = [ 424 | "libc", 425 | ] 426 | 427 | [[package]] 428 | name = "itertools" 429 | version = "0.8.2" 430 | source = "registry+https://github.com/rust-lang/crates.io-index" 431 | checksum = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484" 432 | dependencies = [ 433 | "either", 434 | ] 435 | 436 | [[package]] 437 | name = "itoa" 438 | version = "0.4.5" 439 | source = "registry+https://github.com/rust-lang/crates.io-index" 440 | checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" 441 | 442 | [[package]] 443 | name = "kernel32-sys" 444 | version = "0.2.2" 445 | source = "registry+https://github.com/rust-lang/crates.io-index" 446 | checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" 447 | dependencies = [ 448 | "winapi 0.2.8", 449 | "winapi-build", 450 | ] 451 | 452 | [[package]] 453 | name = "language-tags" 454 | version = "0.2.2" 455 | source = "registry+https://github.com/rust-lang/crates.io-index" 456 | checksum = "a91d884b6667cd606bb5a69aa0c99ba811a115fc68915e7056ec08a46e93199a" 457 | 458 | [[package]] 459 | name = "lazy_static" 460 | version = "1.4.0" 461 | source = "registry+https://github.com/rust-lang/crates.io-index" 462 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 463 | 464 | [[package]] 465 | name = "lazycell" 466 | version = "1.2.1" 467 | source = "registry+https://github.com/rust-lang/crates.io-index" 468 | checksum = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" 469 | 470 | [[package]] 471 | name = "libc" 472 | version = "0.2.66" 473 | source = "registry+https://github.com/rust-lang/crates.io-index" 474 | checksum = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" 475 | 476 | [[package]] 477 | name = "libsqlite3-sys" 478 | version = "0.16.0" 479 | source = "registry+https://github.com/rust-lang/crates.io-index" 480 | checksum = "5e5b95e89c330291768dc840238db7f9e204fd208511ab6319b56193a7f2ae25" 481 | dependencies = [ 482 | "pkg-config", 483 | "vcpkg", 484 | ] 485 | 486 | [[package]] 487 | name = "lock_api" 488 | version = "0.3.3" 489 | source = "registry+https://github.com/rust-lang/crates.io-index" 490 | checksum = "79b2de95ecb4691949fea4716ca53cdbcfccb2c612e19644a8bad05edcf9f47b" 491 | dependencies = [ 492 | "scopeguard", 493 | ] 494 | 495 | [[package]] 496 | name = "log" 497 | version = "0.3.9" 498 | source = "registry+https://github.com/rust-lang/crates.io-index" 499 | checksum = "e19e8d5c34a3e0e2223db8e060f9e8264aeeb5c5fc64a4ee9965c062211c024b" 500 | dependencies = [ 501 | "log 0.4.8", 502 | ] 503 | 504 | [[package]] 505 | name = "log" 506 | version = "0.4.8" 507 | source = "registry+https://github.com/rust-lang/crates.io-index" 508 | checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" 509 | dependencies = [ 510 | "cfg-if", 511 | ] 512 | 513 | [[package]] 514 | name = "matches" 515 | version = "0.1.8" 516 | source = "registry+https://github.com/rust-lang/crates.io-index" 517 | checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" 518 | 519 | [[package]] 520 | name = "maybe-uninit" 521 | version = "2.0.0" 522 | source = "registry+https://github.com/rust-lang/crates.io-index" 523 | checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" 524 | 525 | [[package]] 526 | name = "memchr" 527 | version = "2.3.2" 528 | source = "registry+https://github.com/rust-lang/crates.io-index" 529 | checksum = "53445de381a1f436797497c61d851644d0e8e88e6140f22872ad33a704933978" 530 | 531 | [[package]] 532 | name = "migrations_internals" 533 | version = "1.4.0" 534 | source = "registry+https://github.com/rust-lang/crates.io-index" 535 | checksum = "8089920229070f914b9ce9b07ef60e175b2b9bc2d35c3edd8bf4433604e863b9" 536 | dependencies = [ 537 | "diesel", 538 | ] 539 | 540 | [[package]] 541 | name = "migrations_macros" 542 | version = "1.4.1" 543 | source = "registry+https://github.com/rust-lang/crates.io-index" 544 | checksum = "719ef0bc7f531428764c9b70661c14abd50a7f3d21f355752d9985aa21251c9e" 545 | dependencies = [ 546 | "migrations_internals", 547 | "proc-macro2 1.0.8", 548 | "quote 1.0.2", 549 | "syn 1.0.14", 550 | ] 551 | 552 | [[package]] 553 | name = "mime" 554 | version = "0.2.6" 555 | source = "registry+https://github.com/rust-lang/crates.io-index" 556 | checksum = "ba626b8a6de5da682e1caa06bdb42a335aee5a84db8e5046a3e8ab17ba0a3ae0" 557 | dependencies = [ 558 | "log 0.3.9", 559 | ] 560 | 561 | [[package]] 562 | name = "mio" 563 | version = "0.6.21" 564 | source = "registry+https://github.com/rust-lang/crates.io-index" 565 | checksum = "302dec22bcf6bae6dfb69c647187f4b4d0fb6f535521f7bc022430ce8e12008f" 566 | dependencies = [ 567 | "cfg-if", 568 | "fuchsia-zircon", 569 | "fuchsia-zircon-sys", 570 | "iovec", 571 | "kernel32-sys", 572 | "libc", 573 | "log 0.4.8", 574 | "miow", 575 | "net2", 576 | "slab", 577 | "winapi 0.2.8", 578 | ] 579 | 580 | [[package]] 581 | name = "mio-extras" 582 | version = "2.0.6" 583 | source = "registry+https://github.com/rust-lang/crates.io-index" 584 | checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" 585 | dependencies = [ 586 | "lazycell", 587 | "log 0.4.8", 588 | "mio", 589 | "slab", 590 | ] 591 | 592 | [[package]] 593 | name = "miow" 594 | version = "0.2.1" 595 | source = "registry+https://github.com/rust-lang/crates.io-index" 596 | checksum = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" 597 | dependencies = [ 598 | "kernel32-sys", 599 | "net2", 600 | "winapi 0.2.8", 601 | "ws2_32-sys", 602 | ] 603 | 604 | [[package]] 605 | name = "net2" 606 | version = "0.2.33" 607 | source = "registry+https://github.com/rust-lang/crates.io-index" 608 | checksum = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" 609 | dependencies = [ 610 | "cfg-if", 611 | "libc", 612 | "winapi 0.3.8", 613 | ] 614 | 615 | [[package]] 616 | name = "notify" 617 | version = "4.0.15" 618 | source = "registry+https://github.com/rust-lang/crates.io-index" 619 | checksum = "80ae4a7688d1fab81c5bf19c64fc8db920be8d519ce6336ed4e7efe024724dbd" 620 | dependencies = [ 621 | "bitflags", 622 | "filetime", 623 | "fsevent", 624 | "fsevent-sys", 625 | "inotify", 626 | "libc", 627 | "mio", 628 | "mio-extras", 629 | "walkdir", 630 | "winapi 0.3.8", 631 | ] 632 | 633 | [[package]] 634 | name = "num-integer" 635 | version = "0.1.42" 636 | source = "registry+https://github.com/rust-lang/crates.io-index" 637 | checksum = "3f6ea62e9d81a77cd3ee9a2a5b9b609447857f3d358704331e4ef39eb247fcba" 638 | dependencies = [ 639 | "autocfg", 640 | "num-traits", 641 | ] 642 | 643 | [[package]] 644 | name = "num-traits" 645 | version = "0.2.11" 646 | source = "registry+https://github.com/rust-lang/crates.io-index" 647 | checksum = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" 648 | dependencies = [ 649 | "autocfg", 650 | ] 651 | 652 | [[package]] 653 | name = "num_cpus" 654 | version = "1.12.0" 655 | source = "registry+https://github.com/rust-lang/crates.io-index" 656 | checksum = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" 657 | dependencies = [ 658 | "hermit-abi", 659 | "libc", 660 | ] 661 | 662 | [[package]] 663 | name = "opaque-debug" 664 | version = "0.2.3" 665 | source = "registry+https://github.com/rust-lang/crates.io-index" 666 | checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" 667 | 668 | [[package]] 669 | name = "parking_lot" 670 | version = "0.10.0" 671 | source = "registry+https://github.com/rust-lang/crates.io-index" 672 | checksum = "92e98c49ab0b7ce5b222f2cc9193fc4efe11c6d0bd4f648e374684a6857b1cfc" 673 | dependencies = [ 674 | "lock_api", 675 | "parking_lot_core", 676 | ] 677 | 678 | [[package]] 679 | name = "parking_lot_core" 680 | version = "0.7.0" 681 | source = "registry+https://github.com/rust-lang/crates.io-index" 682 | checksum = "7582838484df45743c8434fbff785e8edf260c28748353d44bc0da32e0ceabf1" 683 | dependencies = [ 684 | "cfg-if", 685 | "cloudabi", 686 | "libc", 687 | "redox_syscall", 688 | "smallvec 1.2.0", 689 | "winapi 0.3.8", 690 | ] 691 | 692 | [[package]] 693 | name = "pbkdf2" 694 | version = "0.3.0" 695 | source = "registry+https://github.com/rust-lang/crates.io-index" 696 | checksum = "006c038a43a45995a9670da19e67600114740e8511d4333bf97a56e66a7542d9" 697 | dependencies = [ 698 | "byteorder", 699 | "crypto-mac", 700 | ] 701 | 702 | [[package]] 703 | name = "pear" 704 | version = "0.1.2" 705 | source = "registry+https://github.com/rust-lang/crates.io-index" 706 | checksum = "c26d2b92e47063ffce70d3e3b1bd097af121a9e0db07ca38a6cc1cf0cc85ff25" 707 | dependencies = [ 708 | "pear_codegen", 709 | ] 710 | 711 | [[package]] 712 | name = "pear_codegen" 713 | version = "0.1.2" 714 | source = "registry+https://github.com/rust-lang/crates.io-index" 715 | checksum = "336db4a192cc7f54efeb0c4e11a9245394824cc3bcbd37ba3ff51240c35d7a6e" 716 | dependencies = [ 717 | "proc-macro2 0.4.30", 718 | "quote 0.6.13", 719 | "syn 0.15.44", 720 | "version_check 0.1.5", 721 | "yansi 0.4.0", 722 | ] 723 | 724 | [[package]] 725 | name = "percent-encoding" 726 | version = "1.0.1" 727 | source = "registry+https://github.com/rust-lang/crates.io-index" 728 | checksum = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" 729 | 730 | [[package]] 731 | name = "pkg-config" 732 | version = "0.3.17" 733 | source = "registry+https://github.com/rust-lang/crates.io-index" 734 | checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677" 735 | 736 | [[package]] 737 | name = "ppv-lite86" 738 | version = "0.2.6" 739 | source = "registry+https://github.com/rust-lang/crates.io-index" 740 | checksum = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b" 741 | 742 | [[package]] 743 | name = "proc-macro2" 744 | version = "0.4.30" 745 | source = "registry+https://github.com/rust-lang/crates.io-index" 746 | checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" 747 | dependencies = [ 748 | "unicode-xid 0.1.0", 749 | ] 750 | 751 | [[package]] 752 | name = "proc-macro2" 753 | version = "1.0.8" 754 | source = "registry+https://github.com/rust-lang/crates.io-index" 755 | checksum = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" 756 | dependencies = [ 757 | "unicode-xid 0.2.0", 758 | ] 759 | 760 | [[package]] 761 | name = "quote" 762 | version = "0.6.13" 763 | source = "registry+https://github.com/rust-lang/crates.io-index" 764 | checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" 765 | dependencies = [ 766 | "proc-macro2 0.4.30", 767 | ] 768 | 769 | [[package]] 770 | name = "quote" 771 | version = "1.0.2" 772 | source = "registry+https://github.com/rust-lang/crates.io-index" 773 | checksum = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" 774 | dependencies = [ 775 | "proc-macro2 1.0.8", 776 | ] 777 | 778 | [[package]] 779 | name = "r2d2" 780 | version = "0.8.8" 781 | source = "registry+https://github.com/rust-lang/crates.io-index" 782 | checksum = "1497e40855348e4a8a40767d8e55174bce1e445a3ac9254ad44ad468ee0485af" 783 | dependencies = [ 784 | "log 0.4.8", 785 | "parking_lot", 786 | "scheduled-thread-pool", 787 | ] 788 | 789 | [[package]] 790 | name = "rand" 791 | version = "0.5.6" 792 | source = "registry+https://github.com/rust-lang/crates.io-index" 793 | checksum = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" 794 | dependencies = [ 795 | "cloudabi", 796 | "fuchsia-cprng", 797 | "libc", 798 | "rand_core 0.3.1", 799 | "winapi 0.3.8", 800 | ] 801 | 802 | [[package]] 803 | name = "rand" 804 | version = "0.7.3" 805 | source = "registry+https://github.com/rust-lang/crates.io-index" 806 | checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" 807 | dependencies = [ 808 | "getrandom", 809 | "libc", 810 | "rand_chacha", 811 | "rand_core 0.5.1", 812 | "rand_hc", 813 | ] 814 | 815 | [[package]] 816 | name = "rand_chacha" 817 | version = "0.2.1" 818 | source = "registry+https://github.com/rust-lang/crates.io-index" 819 | checksum = "03a2a90da8c7523f554344f921aa97283eadf6ac484a6d2a7d0212fa7f8d6853" 820 | dependencies = [ 821 | "c2-chacha", 822 | "rand_core 0.5.1", 823 | ] 824 | 825 | [[package]] 826 | name = "rand_core" 827 | version = "0.3.1" 828 | source = "registry+https://github.com/rust-lang/crates.io-index" 829 | checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" 830 | dependencies = [ 831 | "rand_core 0.4.2", 832 | ] 833 | 834 | [[package]] 835 | name = "rand_core" 836 | version = "0.4.2" 837 | source = "registry+https://github.com/rust-lang/crates.io-index" 838 | checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" 839 | 840 | [[package]] 841 | name = "rand_core" 842 | version = "0.5.1" 843 | source = "registry+https://github.com/rust-lang/crates.io-index" 844 | checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" 845 | dependencies = [ 846 | "getrandom", 847 | ] 848 | 849 | [[package]] 850 | name = "rand_hc" 851 | version = "0.2.0" 852 | source = "registry+https://github.com/rust-lang/crates.io-index" 853 | checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" 854 | dependencies = [ 855 | "rand_core 0.5.1", 856 | ] 857 | 858 | [[package]] 859 | name = "redox_syscall" 860 | version = "0.1.56" 861 | source = "registry+https://github.com/rust-lang/crates.io-index" 862 | checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" 863 | 864 | [[package]] 865 | name = "regex" 866 | version = "0.2.11" 867 | source = "registry+https://github.com/rust-lang/crates.io-index" 868 | checksum = "9329abc99e39129fcceabd24cf5d85b4671ef7c29c50e972bc5afe32438ec384" 869 | dependencies = [ 870 | "aho-corasick 0.6.10", 871 | "memchr", 872 | "regex-syntax 0.5.6", 873 | "thread_local 0.3.6", 874 | "utf8-ranges", 875 | ] 876 | 877 | [[package]] 878 | name = "regex" 879 | version = "1.3.4" 880 | source = "registry+https://github.com/rust-lang/crates.io-index" 881 | checksum = "322cf97724bea3ee221b78fe25ac9c46114ebb51747ad5babd51a2fc6a8235a8" 882 | dependencies = [ 883 | "aho-corasick 0.7.8", 884 | "memchr", 885 | "regex-syntax 0.6.14", 886 | "thread_local 1.0.1", 887 | ] 888 | 889 | [[package]] 890 | name = "regex-syntax" 891 | version = "0.5.6" 892 | source = "registry+https://github.com/rust-lang/crates.io-index" 893 | checksum = "7d707a4fa2637f2dca2ef9fd02225ec7661fe01a53623c1e6515b6916511f7a7" 894 | dependencies = [ 895 | "ucd-util", 896 | ] 897 | 898 | [[package]] 899 | name = "regex-syntax" 900 | version = "0.6.14" 901 | source = "registry+https://github.com/rust-lang/crates.io-index" 902 | checksum = "b28dfe3fe9badec5dbf0a79a9cccad2cfc2ab5484bdb3e44cbd1ae8b3ba2be06" 903 | 904 | [[package]] 905 | name = "ring" 906 | version = "0.13.5" 907 | source = "registry+https://github.com/rust-lang/crates.io-index" 908 | checksum = "2c4db68a2e35f3497146b7e4563df7d4773a2433230c5e4b448328e31740458a" 909 | dependencies = [ 910 | "cc", 911 | "lazy_static", 912 | "libc", 913 | "untrusted", 914 | ] 915 | 916 | [[package]] 917 | name = "rocket" 918 | version = "0.4.2" 919 | source = "registry+https://github.com/rust-lang/crates.io-index" 920 | checksum = "42c1e9deb3ef4fa430d307bfccd4231434b707ca1328fae339c43ad1201cc6f7" 921 | dependencies = [ 922 | "atty", 923 | "base64 0.10.1", 924 | "log 0.4.8", 925 | "memchr", 926 | "num_cpus", 927 | "pear", 928 | "rocket_codegen", 929 | "rocket_http", 930 | "state", 931 | "time", 932 | "toml", 933 | "version_check 0.9.1", 934 | "yansi 0.5.0", 935 | ] 936 | 937 | [[package]] 938 | name = "rocket_codegen" 939 | version = "0.4.2" 940 | source = "registry+https://github.com/rust-lang/crates.io-index" 941 | checksum = "79aa1366f9b2eccddc05971e17c5de7bb75a5431eb12c2b5c66545fd348647f4" 942 | dependencies = [ 943 | "devise", 944 | "indexmap", 945 | "quote 0.6.13", 946 | "rocket_http", 947 | "version_check 0.9.1", 948 | "yansi 0.5.0", 949 | ] 950 | 951 | [[package]] 952 | name = "rocket_contrib" 953 | version = "0.4.2" 954 | source = "registry+https://github.com/rust-lang/crates.io-index" 955 | checksum = "e0fa5c1392135adc0f96a02ba150ac4c765e27c58dbfd32aa40678e948f6e56f" 956 | dependencies = [ 957 | "diesel", 958 | "log 0.4.8", 959 | "notify", 960 | "r2d2", 961 | "rocket", 962 | "rocket_contrib_codegen", 963 | "serde", 964 | "serde_json", 965 | ] 966 | 967 | [[package]] 968 | name = "rocket_contrib_codegen" 969 | version = "0.4.2" 970 | source = "registry+https://github.com/rust-lang/crates.io-index" 971 | checksum = "343da6694fc3cfd901242fd6efafc823e7a3a7f4948017a7dda7311775055092" 972 | dependencies = [ 973 | "devise", 974 | "quote 0.6.13", 975 | "version_check 0.9.1", 976 | "yansi 0.5.0", 977 | ] 978 | 979 | [[package]] 980 | name = "rocket_cors" 981 | version = "0.5.1" 982 | source = "registry+https://github.com/rust-lang/crates.io-index" 983 | checksum = "270a960cba5a0b7928ad74268db7773ce932da6b550478383cefebe9f46c4e13" 984 | dependencies = [ 985 | "log 0.3.9", 986 | "regex 1.3.4", 987 | "rocket", 988 | "serde", 989 | "serde_derive", 990 | "unicase 2.6.0", 991 | "unicase_serde", 992 | "url", 993 | ] 994 | 995 | [[package]] 996 | name = "rocket_http" 997 | version = "0.4.2" 998 | source = "registry+https://github.com/rust-lang/crates.io-index" 999 | checksum = "b1391457ee4e80b40d4b57fa5765c0f2836b20d73bcbee4e3f35d93cf3b80817" 1000 | dependencies = [ 1001 | "cookie", 1002 | "hyper", 1003 | "indexmap", 1004 | "pear", 1005 | "percent-encoding", 1006 | "smallvec 0.6.13", 1007 | "state", 1008 | "time", 1009 | "unicode-xid 0.1.0", 1010 | ] 1011 | 1012 | [[package]] 1013 | name = "ryu" 1014 | version = "1.0.2" 1015 | source = "registry+https://github.com/rust-lang/crates.io-index" 1016 | checksum = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8" 1017 | 1018 | [[package]] 1019 | name = "safemem" 1020 | version = "0.3.3" 1021 | source = "registry+https://github.com/rust-lang/crates.io-index" 1022 | checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072" 1023 | 1024 | [[package]] 1025 | name = "same-file" 1026 | version = "1.0.6" 1027 | source = "registry+https://github.com/rust-lang/crates.io-index" 1028 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 1029 | dependencies = [ 1030 | "winapi-util", 1031 | ] 1032 | 1033 | [[package]] 1034 | name = "scheduled-thread-pool" 1035 | version = "0.2.3" 1036 | source = "registry+https://github.com/rust-lang/crates.io-index" 1037 | checksum = "f5de7bc31f28f8e6c28df5e1bf3d10610f5fdc14cc95f272853512c70a2bd779" 1038 | dependencies = [ 1039 | "parking_lot", 1040 | ] 1041 | 1042 | [[package]] 1043 | name = "scopeguard" 1044 | version = "1.1.0" 1045 | source = "registry+https://github.com/rust-lang/crates.io-index" 1046 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 1047 | 1048 | [[package]] 1049 | name = "scrypt" 1050 | version = "0.2.0" 1051 | source = "registry+https://github.com/rust-lang/crates.io-index" 1052 | checksum = "656c79d0e90d0ab28ac86bf3c3d10bfbbac91450d3f190113b4e76d9fec3cfdd" 1053 | dependencies = [ 1054 | "base64 0.9.3", 1055 | "byte-tools", 1056 | "byteorder", 1057 | "hmac", 1058 | "pbkdf2", 1059 | "rand 0.5.6", 1060 | "sha2", 1061 | "subtle", 1062 | ] 1063 | 1064 | [[package]] 1065 | name = "serde" 1066 | version = "1.0.104" 1067 | source = "registry+https://github.com/rust-lang/crates.io-index" 1068 | checksum = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" 1069 | dependencies = [ 1070 | "serde_derive", 1071 | ] 1072 | 1073 | [[package]] 1074 | name = "serde_derive" 1075 | version = "1.0.104" 1076 | source = "registry+https://github.com/rust-lang/crates.io-index" 1077 | checksum = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" 1078 | dependencies = [ 1079 | "proc-macro2 1.0.8", 1080 | "quote 1.0.2", 1081 | "syn 1.0.14", 1082 | ] 1083 | 1084 | [[package]] 1085 | name = "serde_json" 1086 | version = "1.0.48" 1087 | source = "registry+https://github.com/rust-lang/crates.io-index" 1088 | checksum = "9371ade75d4c2d6cb154141b9752cf3781ec9c05e0e5cf35060e1e70ee7b9c25" 1089 | dependencies = [ 1090 | "itoa", 1091 | "ryu", 1092 | "serde", 1093 | ] 1094 | 1095 | [[package]] 1096 | name = "sfrs" 1097 | version = "0.1.0" 1098 | dependencies = [ 1099 | "chrono", 1100 | "diesel", 1101 | "diesel_migrations", 1102 | "dotenv", 1103 | "hex", 1104 | "itertools", 1105 | "lazy_static", 1106 | "regex 1.3.4", 1107 | "ring", 1108 | "rocket", 1109 | "rocket_contrib", 1110 | "rocket_cors", 1111 | "scrypt", 1112 | "serde", 1113 | "serde_json", 1114 | "uuid", 1115 | ] 1116 | 1117 | [[package]] 1118 | name = "sha2" 1119 | version = "0.8.1" 1120 | source = "registry+https://github.com/rust-lang/crates.io-index" 1121 | checksum = "27044adfd2e1f077f649f59deb9490d3941d674002f7d062870a60ebe9bd47a0" 1122 | dependencies = [ 1123 | "block-buffer", 1124 | "digest", 1125 | "fake-simd", 1126 | "opaque-debug", 1127 | ] 1128 | 1129 | [[package]] 1130 | name = "slab" 1131 | version = "0.4.2" 1132 | source = "registry+https://github.com/rust-lang/crates.io-index" 1133 | checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" 1134 | 1135 | [[package]] 1136 | name = "smallvec" 1137 | version = "0.6.13" 1138 | source = "registry+https://github.com/rust-lang/crates.io-index" 1139 | checksum = "f7b0758c52e15a8b5e3691eae6cc559f08eee9406e548a4477ba4e67770a82b6" 1140 | dependencies = [ 1141 | "maybe-uninit", 1142 | ] 1143 | 1144 | [[package]] 1145 | name = "smallvec" 1146 | version = "1.2.0" 1147 | source = "registry+https://github.com/rust-lang/crates.io-index" 1148 | checksum = "5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc" 1149 | 1150 | [[package]] 1151 | name = "state" 1152 | version = "0.4.1" 1153 | source = "registry+https://github.com/rust-lang/crates.io-index" 1154 | checksum = "7345c971d1ef21ffdbd103a75990a15eb03604fc8b8852ca8cb418ee1a099028" 1155 | 1156 | [[package]] 1157 | name = "subtle" 1158 | version = "1.0.0" 1159 | source = "registry+https://github.com/rust-lang/crates.io-index" 1160 | checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" 1161 | 1162 | [[package]] 1163 | name = "syn" 1164 | version = "0.15.44" 1165 | source = "registry+https://github.com/rust-lang/crates.io-index" 1166 | checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" 1167 | dependencies = [ 1168 | "proc-macro2 0.4.30", 1169 | "quote 0.6.13", 1170 | "unicode-xid 0.1.0", 1171 | ] 1172 | 1173 | [[package]] 1174 | name = "syn" 1175 | version = "1.0.14" 1176 | source = "registry+https://github.com/rust-lang/crates.io-index" 1177 | checksum = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" 1178 | dependencies = [ 1179 | "proc-macro2 1.0.8", 1180 | "quote 1.0.2", 1181 | "unicode-xid 0.2.0", 1182 | ] 1183 | 1184 | [[package]] 1185 | name = "thread_local" 1186 | version = "0.3.6" 1187 | source = "registry+https://github.com/rust-lang/crates.io-index" 1188 | checksum = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" 1189 | dependencies = [ 1190 | "lazy_static", 1191 | ] 1192 | 1193 | [[package]] 1194 | name = "thread_local" 1195 | version = "1.0.1" 1196 | source = "registry+https://github.com/rust-lang/crates.io-index" 1197 | checksum = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14" 1198 | dependencies = [ 1199 | "lazy_static", 1200 | ] 1201 | 1202 | [[package]] 1203 | name = "time" 1204 | version = "0.1.42" 1205 | source = "registry+https://github.com/rust-lang/crates.io-index" 1206 | checksum = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" 1207 | dependencies = [ 1208 | "libc", 1209 | "redox_syscall", 1210 | "winapi 0.3.8", 1211 | ] 1212 | 1213 | [[package]] 1214 | name = "toml" 1215 | version = "0.4.10" 1216 | source = "registry+https://github.com/rust-lang/crates.io-index" 1217 | checksum = "758664fc71a3a69038656bee8b6be6477d2a6c315a6b81f7081f591bffa4111f" 1218 | dependencies = [ 1219 | "serde", 1220 | ] 1221 | 1222 | [[package]] 1223 | name = "traitobject" 1224 | version = "0.1.0" 1225 | source = "registry+https://github.com/rust-lang/crates.io-index" 1226 | checksum = "efd1f82c56340fdf16f2a953d7bda4f8fdffba13d93b00844c25572110b26079" 1227 | 1228 | [[package]] 1229 | name = "typeable" 1230 | version = "0.1.2" 1231 | source = "registry+https://github.com/rust-lang/crates.io-index" 1232 | checksum = "1410f6f91f21d1612654e7cc69193b0334f909dcf2c790c4826254fbb86f8887" 1233 | 1234 | [[package]] 1235 | name = "typenum" 1236 | version = "1.11.2" 1237 | source = "registry+https://github.com/rust-lang/crates.io-index" 1238 | checksum = "6d2783fe2d6b8c1101136184eb41be8b1ad379e4657050b8aaff0c79ee7575f9" 1239 | 1240 | [[package]] 1241 | name = "ucd-util" 1242 | version = "0.1.7" 1243 | source = "registry+https://github.com/rust-lang/crates.io-index" 1244 | checksum = "5ccdc2daea7cf8bc50cd8710d170a9d816678e54943829c5082bb1594312cf8e" 1245 | 1246 | [[package]] 1247 | name = "unicase" 1248 | version = "1.4.2" 1249 | source = "registry+https://github.com/rust-lang/crates.io-index" 1250 | checksum = "7f4765f83163b74f957c797ad9253caf97f103fb064d3999aea9568d09fc8a33" 1251 | dependencies = [ 1252 | "version_check 0.1.5", 1253 | ] 1254 | 1255 | [[package]] 1256 | name = "unicase" 1257 | version = "2.6.0" 1258 | source = "registry+https://github.com/rust-lang/crates.io-index" 1259 | checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" 1260 | dependencies = [ 1261 | "version_check 0.9.1", 1262 | ] 1263 | 1264 | [[package]] 1265 | name = "unicase_serde" 1266 | version = "0.1.0" 1267 | source = "registry+https://github.com/rust-lang/crates.io-index" 1268 | checksum = "6ef53697679d874d69f3160af80bc28de12730a985d57bdf2b47456ccb8b11f1" 1269 | dependencies = [ 1270 | "serde", 1271 | "unicase 2.6.0", 1272 | ] 1273 | 1274 | [[package]] 1275 | name = "unicode-bidi" 1276 | version = "0.3.4" 1277 | source = "registry+https://github.com/rust-lang/crates.io-index" 1278 | checksum = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" 1279 | dependencies = [ 1280 | "matches", 1281 | ] 1282 | 1283 | [[package]] 1284 | name = "unicode-normalization" 1285 | version = "0.1.12" 1286 | source = "registry+https://github.com/rust-lang/crates.io-index" 1287 | checksum = "5479532badd04e128284890390c1e876ef7a993d0570b3597ae43dfa1d59afa4" 1288 | dependencies = [ 1289 | "smallvec 1.2.0", 1290 | ] 1291 | 1292 | [[package]] 1293 | name = "unicode-xid" 1294 | version = "0.1.0" 1295 | source = "registry+https://github.com/rust-lang/crates.io-index" 1296 | checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" 1297 | 1298 | [[package]] 1299 | name = "unicode-xid" 1300 | version = "0.2.0" 1301 | source = "registry+https://github.com/rust-lang/crates.io-index" 1302 | checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" 1303 | 1304 | [[package]] 1305 | name = "untrusted" 1306 | version = "0.6.2" 1307 | source = "registry+https://github.com/rust-lang/crates.io-index" 1308 | checksum = "55cd1f4b4e96b46aeb8d4855db4a7a9bd96eeeb5c6a1ab54593328761642ce2f" 1309 | 1310 | [[package]] 1311 | name = "url" 1312 | version = "1.7.2" 1313 | source = "registry+https://github.com/rust-lang/crates.io-index" 1314 | checksum = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a" 1315 | dependencies = [ 1316 | "idna", 1317 | "matches", 1318 | "percent-encoding", 1319 | ] 1320 | 1321 | [[package]] 1322 | name = "utf8-ranges" 1323 | version = "1.0.4" 1324 | source = "registry+https://github.com/rust-lang/crates.io-index" 1325 | checksum = "b4ae116fef2b7fea257ed6440d3cfcff7f190865f170cdad00bb6465bf18ecba" 1326 | 1327 | [[package]] 1328 | name = "uuid" 1329 | version = "0.8.1" 1330 | source = "registry+https://github.com/rust-lang/crates.io-index" 1331 | checksum = "9fde2f6a4bea1d6e007c4ad38c6839fa71cbb63b6dbf5b595aa38dc9b1093c11" 1332 | dependencies = [ 1333 | "rand 0.7.3", 1334 | ] 1335 | 1336 | [[package]] 1337 | name = "vcpkg" 1338 | version = "0.2.8" 1339 | source = "registry+https://github.com/rust-lang/crates.io-index" 1340 | checksum = "3fc439f2794e98976c88a2a2dafce96b930fe8010b0a256b3c2199a773933168" 1341 | 1342 | [[package]] 1343 | name = "version_check" 1344 | version = "0.1.5" 1345 | source = "registry+https://github.com/rust-lang/crates.io-index" 1346 | checksum = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" 1347 | 1348 | [[package]] 1349 | name = "version_check" 1350 | version = "0.9.1" 1351 | source = "registry+https://github.com/rust-lang/crates.io-index" 1352 | checksum = "078775d0255232fb988e6fccf26ddc9d1ac274299aaedcedce21c6f72cc533ce" 1353 | 1354 | [[package]] 1355 | name = "walkdir" 1356 | version = "2.3.1" 1357 | source = "registry+https://github.com/rust-lang/crates.io-index" 1358 | checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" 1359 | dependencies = [ 1360 | "same-file", 1361 | "winapi 0.3.8", 1362 | "winapi-util", 1363 | ] 1364 | 1365 | [[package]] 1366 | name = "wasi" 1367 | version = "0.9.0+wasi-snapshot-preview1" 1368 | source = "registry+https://github.com/rust-lang/crates.io-index" 1369 | checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" 1370 | 1371 | [[package]] 1372 | name = "winapi" 1373 | version = "0.2.8" 1374 | source = "registry+https://github.com/rust-lang/crates.io-index" 1375 | checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" 1376 | 1377 | [[package]] 1378 | name = "winapi" 1379 | version = "0.3.8" 1380 | source = "registry+https://github.com/rust-lang/crates.io-index" 1381 | checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" 1382 | dependencies = [ 1383 | "winapi-i686-pc-windows-gnu", 1384 | "winapi-x86_64-pc-windows-gnu", 1385 | ] 1386 | 1387 | [[package]] 1388 | name = "winapi-build" 1389 | version = "0.1.1" 1390 | source = "registry+https://github.com/rust-lang/crates.io-index" 1391 | checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" 1392 | 1393 | [[package]] 1394 | name = "winapi-i686-pc-windows-gnu" 1395 | version = "0.4.0" 1396 | source = "registry+https://github.com/rust-lang/crates.io-index" 1397 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 1398 | 1399 | [[package]] 1400 | name = "winapi-util" 1401 | version = "0.1.3" 1402 | source = "registry+https://github.com/rust-lang/crates.io-index" 1403 | checksum = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" 1404 | dependencies = [ 1405 | "winapi 0.3.8", 1406 | ] 1407 | 1408 | [[package]] 1409 | name = "winapi-x86_64-pc-windows-gnu" 1410 | version = "0.4.0" 1411 | source = "registry+https://github.com/rust-lang/crates.io-index" 1412 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 1413 | 1414 | [[package]] 1415 | name = "ws2_32-sys" 1416 | version = "0.2.1" 1417 | source = "registry+https://github.com/rust-lang/crates.io-index" 1418 | checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" 1419 | dependencies = [ 1420 | "winapi 0.2.8", 1421 | "winapi-build", 1422 | ] 1423 | 1424 | [[package]] 1425 | name = "yansi" 1426 | version = "0.4.0" 1427 | source = "registry+https://github.com/rust-lang/crates.io-index" 1428 | checksum = "d60c3b48c9cdec42fb06b3b84b5b087405e1fa1c644a1af3930e4dfafe93de48" 1429 | 1430 | [[package]] 1431 | name = "yansi" 1432 | version = "0.5.0" 1433 | source = "registry+https://github.com/rust-lang/crates.io-index" 1434 | checksum = "9fc79f4a1e39857fc00c3f662cbf2651c771f00e9c15fe2abc341806bd46bd71" 1435 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sfrs" 3 | version = "0.1.0" 4 | authors = ["Peter Cai "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | rocket = "0.4.2" 9 | rocket_contrib = { version = "0.4.2", features = ["diesel_sqlite_pool"] } 10 | rocket_cors = "0.5.1" 11 | diesel = { version = "1.4.3", features = ["sqlite", "chrono"] } 12 | diesel_migrations = "1.4.0" 13 | dotenv = "0.9.0" 14 | lazy_static = "1.4.0" 15 | serde = { version = "1.0.104", features = ["derive"] } 16 | scrypt = "0.2.0" 17 | uuid = { version = "0.8", features = ["v4"] } 18 | chrono = "0.4" 19 | serde_json = "1.0" 20 | regex = "1" 21 | itertools = "0.8" 22 | ring = "0.13" 23 | hex = "0.4" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SFRS 2 | --- 3 | 4 | Main repository: . __The GitHub repository is merely a mirror.__ 5 | 6 | SFRS is an implementation of the synchronization server of Standard Notes, written in Rust. It is intended for personal usage, especially for those that would like to self-host the server for maximum possible privacy, even when Standard Notes already uses purely client-side encryption by default. 7 | 8 | Standard Notes is a free and open-source note-taking application that focuses on simplicity and longevity. Please refer to [their website](https://standardnotes.org/) for further information on Standard Notes itself. 9 | 10 | Contact 11 | --- 12 | 13 | For issues and patches, please use the following contact methods 14 | 15 | - Mailing List (SourceHut): 16 | - Matrix Chat Room: #petercxy-projects:neo.angry.im 17 | 18 | Disclaimer 19 | --- 20 | 21 | This project was created for personal purposes, as a hobby, and has never gone through any security audit. It is not yet production-ready. Though I have been dog-fooding this project for some time, there is ABSOLUTELY NO GUARANTEE that this software will work as intended for any period of time. The project may or may not introduce breaking changes that could result in the need to re-initialize the database and re-import all your notes from your local backups. It is your responsibility to keep regular backups for your personal data. 22 | 23 | Installation (Non-Docker) 24 | --- 25 | 26 | There is no binary releases provided currently. You need to have Rust Nightly installed in your system to build this project. You can consult to learn how to install the nightly version of Rust in your OS. 27 | 28 | After Rust Nightly is installed, you can simply run 29 | 30 | ```bash 31 | cargo build --release 32 | ``` 33 | 34 | in the directory of this project to build the binary. The binary will be located in `target/release/sfrs`. 35 | 36 | Installation (Docker) 37 | --- 38 | 39 | I have provided a `Dockerfile` in `docker/Dockerfile`. You can run the following command 40 | 41 | ```bash 42 | docker build -f docker/Dockerfile . 43 | ``` 44 | 45 | to build a Docker container for this project. The Docker container by default uses a Docker volume located at `/data` inside the container for storing configuration and database. You will need to mount a volume at this location for your data to persist. The internal port provided by the container is `8000`. 46 | 47 | Configuration 48 | --- 49 | 50 | SFRS reads configuration from a file named `.env` in the current working directory (this is set to `/data` by default in the Docker build). The file should contain content like the following: 51 | 52 | ```bash 53 | SFRS_ENV=production 54 | DATABASE_URL= 55 | SYNC_TOKEN_SECRET= 56 | SYNC_TOKEN_SALT= 57 | ``` 58 | 59 | Replace everything in `<>` (inclusive) with the instructions inside those brackets. The database will be created at first start. 60 | 61 | By default, the program listens at `127.0.0.1:8000`, though the port can be changed by setting the variable `ROCKET_PORT` in either `.env` or in environment variables. 62 | 63 | It is necessary to place a reverse-proxy in front of SFRS. The reverse-proxy should be configured with a trusted SSL certificate. To allow the import function of the client to work properly, you need to set the max acceptable body size (in Nginx it's called `client_max_body_size`) to something bigger than the default value, e.g. `10M` or `50M`. 64 | 65 | Caveats 66 | --- 67 | 68 | * Backups through the CloudLink plugin is not supported. I may or may not introduce similar backup features in the future, but it probably won't be through the plugin, because it's outside the standard and could become incompatible at any time. I suggest you for now use the automatic local backup feature of the Desktop clients of Standard Notes to keep backups. 69 | * There are tests written, but no tests for the synchronization feature is currently implemented. However, I have taken some precautions while writing the synchronization algorithm, including a per-user mutex lock and a different `sync_token` that is not a timestamp. There are plentiful of comments in the source code of the sync interface (which I think is better than the official implementation), so please check if you are not sure. 70 | * SFRS uses SQLite as the database engine, as it was never designed for large-scale usage. Its focus is on security, simple configuration and maintanence. If you are looking for something that can support thousands of users synchronizing at the same time, SFRS is probably not for you. 71 | * SFRS is licensed under AGPLv3, which may be a bummer for some people, though I probably won't have time or money to spare to sue anybody for anything. 72 | -------------------------------------------------------------------------------- /db/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeterCxy/sfrs/10c2f0da4c30c16090b7c89c5e40cdbb0f549d6e/db/.keep -------------------------------------------------------------------------------- /diesel.toml: -------------------------------------------------------------------------------- 1 | # For documentation on how to configure this file, 2 | # see diesel.rs/guides/configuring-diesel-cli 3 | 4 | [print_schema] 5 | file = "src/schema.rs" 6 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | # Build the application 2 | FROM docker.io/debian:9-slim as builder 3 | 4 | ENV RUSTUP_HOME=/usr/local/rustup \ 5 | CARGO_HOME=/usr/local/cargo \ 6 | PATH=/usr/local/cargo/bin:$PATH 7 | 8 | RUN apt-get update && apt-get install -y sqlite3 libsqlite3-dev curl ca-certificates gcc 9 | 10 | RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs -o /rustup-init.sh 11 | 12 | RUN sh /rustup-init.sh -y --no-modify-path --default-toolchain nightly 13 | 14 | COPY . /sfrs 15 | 16 | RUN cd /sfrs && cargo build --release && cp target/release/sfrs /usr/local/bin/ 17 | 18 | # Build the main image 19 | FROM docker.io/debian:9-slim 20 | 21 | RUN apt-get update && apt-get install -y sqlite3 22 | 23 | COPY --from=builder /usr/local/bin/sfrs /usr/local/bin/sfrs 24 | 25 | VOLUME ["/data"] 26 | WORKDIR /data 27 | EXPOSE 8000/tcp 28 | ENTRYPOINT ["/usr/local/bin/sfrs"] 29 | -------------------------------------------------------------------------------- /migrations/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PeterCxy/sfrs/10c2f0da4c30c16090b7c89c5e40cdbb0f549d6e/migrations/.gitkeep -------------------------------------------------------------------------------- /migrations/2020-02-20-085623_create_user/down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE users -------------------------------------------------------------------------------- /migrations/2020-02-20-085623_create_user/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE users ( 2 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 3 | uuid VARCHAR NOT NULL, 4 | email VARCHAR NOT NULL, 5 | password VARCHAR NOT NULL, 6 | pw_cost INTEGER NOT NULL, 7 | pw_nonce VARCHAR NOT NULL, 8 | version VARCHAR NOT NULL 9 | ) -------------------------------------------------------------------------------- /migrations/2020-02-21-011449_create_items/down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE items -------------------------------------------------------------------------------- /migrations/2020-02-21-011449_create_items/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE items ( 2 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 3 | owner INTEGER NOT NULL, 4 | uuid VARCHAR NOT NULL, 5 | content VARCHAR, 6 | content_type VARCHAR NOT NULL, 7 | enc_item_key VARCHAR, 8 | deleted BOOLEAN NOT NULL, 9 | created_at VARCHAR NOT NULL, 10 | updated_at VARCHAR, 11 | FOREIGN KEY (owner) 12 | REFERENCES users (id) 13 | ) -------------------------------------------------------------------------------- /migrations/2020-02-21-102019_create_tokens/down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE tokens -------------------------------------------------------------------------------- /migrations/2020-02-21-102019_create_tokens/up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE tokens ( 2 | id VARCHAR PRIMARY KEY NOT NULL, 3 | uid INTEGER NOT NULL, 4 | timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, 5 | FOREIGN KEY (uid) 6 | REFERENCES users (id) 7 | ) -------------------------------------------------------------------------------- /migrations/2020-02-22-110735_initial_indices/down.sql: -------------------------------------------------------------------------------- 1 | DROP INDEX index_user_email_20200222110735; 2 | DROP INDEX index_item_uuid_owner_20200222110735; 3 | DROP INDEX index_token_uid_20200222110735; -------------------------------------------------------------------------------- /migrations/2020-02-22-110735_initial_indices/up.sql: -------------------------------------------------------------------------------- 1 | CREATE INDEX index_user_email_20200222110735 ON users(email); 2 | CREATE INDEX index_item_uuid_owner_20200222110735 ON items(uuid, owner); 3 | CREATE INDEX index_token_uid_20200222110735 ON tokens(uid); -------------------------------------------------------------------------------- /src/api.rs: -------------------------------------------------------------------------------- 1 | use crate::DbConn; 2 | use crate::user; 3 | use crate::item; 4 | use crate::lock::UserLock; 5 | use itertools::{Itertools, Either}; 6 | use rocket::State; 7 | use rocket::http::Status; 8 | use rocket::response::status::Custom; 9 | use rocket_contrib::json::Json; 10 | use serde::{Serialize, Deserialize}; 11 | use std::vec::Vec; 12 | 13 | lazy_static! { 14 | static ref EMAIL_RE: regex::Regex = 15 | regex::Regex::new(r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})") 16 | .unwrap(); 17 | } 18 | 19 | pub fn routes() -> impl Into> { 20 | routes![ 21 | auth, 22 | auth_change_pw, 23 | auth_sign_in, 24 | auth_params, 25 | auth_ping, 26 | items_sync 27 | ] 28 | } 29 | 30 | #[derive(Serialize)] 31 | #[serde(untagged)] 32 | enum Response { 33 | Error { 34 | errors: Vec 35 | }, 36 | Success(T) 37 | } 38 | 39 | // Some shorthands 40 | type JsonResp = Json>; 41 | 42 | fn success_resp(resp: T) -> Custom> { 43 | Custom(Status::Ok, Json(Response::Success(resp))) 44 | } 45 | 46 | fn error_resp(status: Status, errors: Vec) -> Custom> { 47 | Custom(status, Json(Response::Error { 48 | errors 49 | })) 50 | } 51 | 52 | #[derive(Serialize)] 53 | struct AuthResultUser { 54 | email: String, 55 | uuid: String 56 | } 57 | 58 | #[derive(Serialize)] 59 | struct AuthResult { 60 | user: AuthResultUser, 61 | token: String 62 | } 63 | 64 | #[post("/auth", format = "json", data = "")] 65 | fn auth(db: DbConn, new_user: Json) -> Custom> { 66 | if !EMAIL_RE.is_match(&new_user.email) { 67 | return error_resp(Status::BadRequest, vec!["Invalid email address".into()]); 68 | } 69 | 70 | match user::User::create(&db.0, &new_user) { 71 | Ok(_) => _sign_in(db, &new_user.email, &new_user.password), 72 | Err(user::UserOpError(e)) => 73 | error_resp(Status::InternalServerError, vec![e]) 74 | } 75 | } 76 | 77 | #[derive(Deserialize)] 78 | struct SignInParams { 79 | email: String, 80 | password: String 81 | } 82 | 83 | #[post("/auth/sign_in", format = "json", data = "")] 84 | fn auth_sign_in(db: DbConn, params: Json) -> Custom> { 85 | _sign_in(db, ¶ms.email, ¶ms.password) 86 | } 87 | 88 | // Shared logic for all interfaces that needs to do an automatic sign-in 89 | fn _sign_in(db: DbConn, mail: &str, passwd: &str) -> Custom> { 90 | // Try to find the user first 91 | let res = user::User::find_user_by_email(&db.0, mail) 92 | .and_then(|u| u.create_token(&db.0, passwd) 93 | .map(|x| (u.uuid, u.email, x))); 94 | match res { 95 | Ok((uuid, email, token)) => success_resp(AuthResult { 96 | user: AuthResultUser { 97 | uuid, 98 | email 99 | }, 100 | token 101 | }), 102 | Err(user::UserOpError(e)) => 103 | error_resp(Status::InternalServerError, vec![e]) 104 | } 105 | } 106 | 107 | #[derive(Serialize)] 108 | struct AuthParams { 109 | pw_cost: i32, 110 | pw_nonce: String, 111 | version: String 112 | } 113 | 114 | impl Into for user::User { 115 | fn into(self) -> AuthParams { 116 | AuthParams { 117 | pw_cost: self.pw_cost, 118 | pw_nonce: self.pw_nonce, 119 | version: self.version 120 | } 121 | } 122 | } 123 | 124 | #[get("/auth/params?")] 125 | fn auth_params(db: DbConn, email: String) -> Custom> { 126 | match user::User::find_user_by_email(&db.0, &email) { 127 | Ok(u) => success_resp(u.into()), 128 | Err(user::UserOpError(e)) => 129 | error_resp(Status::InternalServerError, vec![e]) 130 | } 131 | } 132 | 133 | #[derive(Deserialize)] 134 | struct ChangePwParams { 135 | email: String, 136 | password: String, 137 | current_password: String 138 | } 139 | 140 | #[post("/auth/change_pw", format = "json", data = "")] 141 | fn auth_change_pw(db: DbConn, params: Json) -> Custom> { 142 | let res = user::User::find_user_by_email(&db.0, ¶ms.email) 143 | .and_then(|u| 144 | u.change_pw(&db.0, ¶ms.current_password, ¶ms.password)); 145 | match res { 146 | Ok(_) => Custom(Status::NoContent, Json(Response::Success(()))), 147 | Err(user::UserOpError(e)) => 148 | error_resp(Status::InternalServerError, vec![e]) 149 | } 150 | } 151 | 152 | // For testing the User request guard 153 | #[get("/auth/ping")] 154 | fn auth_ping(_db: DbConn, u: user::User) -> Custom> { 155 | Custom(Status::Ok, Json(Response::Success(u.email))) 156 | } 157 | 158 | #[derive(Deserialize)] 159 | struct SyncParams { 160 | items: Vec, 161 | sync_token: Option, 162 | cursor_token: Option, 163 | limit: Option 164 | } 165 | 166 | #[derive(Serialize)] 167 | struct SyncConflict { 168 | #[serde(rename(serialize = "type"))] 169 | conf_type: String, 170 | server_item: Option, 171 | unsaved_item: Option 172 | } 173 | 174 | impl SyncConflict { 175 | fn uuid<'a>(&self) -> String { 176 | if let Some(ref item) = self.server_item { 177 | item.uuid.clone() 178 | } else if let Some(ref item) = self.unsaved_item { 179 | item.uuid.clone() 180 | } else { 181 | panic!("SyncConflict should have either server_item or unsaved_item"); 182 | } 183 | } 184 | } 185 | 186 | #[derive(Serialize)] 187 | struct SyncResp { 188 | retrieved_items: Vec, 189 | saved_items: Vec, 190 | conflicts: Vec, 191 | sync_token: Option, // for convenience, we will actually always return this 192 | cursor_token: Option 193 | } 194 | 195 | #[post("/items/sync", format = "json", data = "")] 196 | fn items_sync( 197 | db: DbConn, lock: State, 198 | u: user::User, params: Json 199 | ) -> Custom> { 200 | // Only allow one sync per user at the same time 201 | // Operations below are far from atomic (neither are they in Ruby or Go impl) 202 | // so allowing multiple synchronize sessions each time can cause 203 | // some confusing behavior, e.g. another sync session might insert 204 | // something new into the database after this one gets the current_max_id 205 | // but before this one returns. It can also mess things up during 206 | // insertions into the database. 207 | // In short, do not let the same user synchronize from two clients 208 | // at the same time. All code below assumes that this lock works 209 | // and at any given point in time, up to one sync process is running 210 | // for each user. 211 | let mutex = lock.get_mutex(u.id); 212 | let _lock = mutex.lock().unwrap(); 213 | 214 | // sync_token should always be set to the maximum ID currently available 215 | // (for this user, of course) 216 | // Remember that we have a mutex at the beginning of this function, 217 | // so all that can change the current_max_id for the current user 218 | // is operations later in this function. 219 | let new_sync_token = match item::SyncItem::get_current_max_id(&db.0, &u) { 220 | Ok(Some(id)) => Some(crate::sync_tokens::max_id_to_token(id)), 221 | Ok(None) => None, 222 | Err(item::ItemOpError(e)) => 223 | return error_resp(Status::InternalServerError, vec![e]) 224 | }; 225 | 226 | let mut resp = SyncResp { 227 | retrieved_items: vec![], 228 | saved_items: vec![], 229 | conflicts: vec![], 230 | sync_token: new_sync_token, 231 | cursor_token: None 232 | }; 233 | 234 | let inner_params = params.into_inner(); 235 | 236 | let from_id: Option = if let Some(cursor_token) = inner_params.cursor_token { 237 | // If the client provides cursor_token, 238 | // then, we return all records 239 | // until sync_token (the head of the last sync) 240 | match crate::sync_tokens::token_to_max_id(&cursor_token) { 241 | Err(()) => 242 | return error_resp(Status::InternalServerError, vec!["Invalid cursor_token".into()]), 243 | Ok(id) => Some(id) 244 | } 245 | } else if let Some(sync_token) = inner_params.sync_token { 246 | // If there is no cursor_token, then we are doing 247 | // a normal sync, so just return all records from sync_token 248 | match crate::sync_tokens::token_to_max_id(&sync_token) { 249 | Err(()) => 250 | return error_resp(Status::InternalServerError, vec!["Invalid sync_token".into()]), 251 | Ok(id) => Some(id) 252 | } 253 | } else { 254 | None 255 | }; 256 | 257 | // First, retrieve what the client needs 258 | let result = item::SyncItem::items_of_user(&db.0, &u, 259 | from_id, None, inner_params.limit); 260 | 261 | match result { 262 | Err(item::ItemOpError(e)) => { 263 | return error_resp(Status::InternalServerError, vec![e]) 264 | }, 265 | Ok(items) => { 266 | if !items.is_empty() { 267 | // If we fetched something, and the length is right at limit 268 | // we may have more to fetch. In this case, we need to 269 | // inform the client to continue fetching 270 | let next_from = items.last().unwrap().id; 271 | if let Some(limit) = inner_params.limit { 272 | if items.len() as i64 == limit { 273 | // We may still have something to fetch 274 | resp.cursor_token = Some(crate::sync_tokens::max_id_to_token(next_from)); 275 | } 276 | } 277 | } 278 | 279 | resp.retrieved_items = items.into_iter().map(|x| x.into()).collect(); 280 | } 281 | } 282 | 283 | // Detect conflicts between client items and server items 284 | let (items_conflicted, items_to_save): (Vec<_>, Vec<_>) = 285 | inner_params.items.into_iter().partition_map(|client_item| { 286 | let conflict: Vec<_> = resp.retrieved_items.iter() 287 | .filter(|server_item| client_item.uuid == server_item.uuid) 288 | .collect(); 289 | if !conflict.is_empty() { 290 | Either::Left((client_item, conflict[0].clone())) 291 | } else { 292 | Either::Right(client_item) 293 | } 294 | }); 295 | 296 | // Convert conflicts into the format our client wants 297 | resp.conflicts = items_conflicted.into_iter().map(|(_client_item, server_item)| { 298 | // Our implementation never produces `uuid_conflict` 299 | // because the primary key of the `items` table is an internal ID 300 | // and we retrieve content based on (user, uuid) tuple, not just uuid. 301 | // The whole point of having `uuid_conflict` in their official impl 302 | // is because they use `uuid` as the primary key, so two items 303 | // on the same server cannot share the same uuid 304 | SyncConflict { 305 | conf_type: "sync_conflict".to_string(), 306 | server_item: Some(server_item), 307 | unsaved_item: None 308 | } 309 | }).collect(); 310 | 311 | // Then, update all items sent by client 312 | let mut last_id: i64 = -1; 313 | for mut it in items_to_save.into_iter() { 314 | // Always update updated_at for all items on server 315 | it.updated_at = 316 | Some(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)); 317 | 318 | match item::SyncItem::items_insert(&db.0, &u, &it) { 319 | Err(item::ItemOpError(e)) => { 320 | return error_resp(Status::InternalServerError, vec![e]); 321 | }, 322 | Ok(id) => { 323 | last_id = id; 324 | resp.saved_items.push(it); 325 | } 326 | } 327 | } 328 | 329 | if last_id > -1 { 330 | // Since we have added more items to the database, 331 | // the sync_token we had no longer points to the latest item 332 | // Update sync_token to the latest one of our saved items 333 | // This is ALWAYS the case. `sync_token` indicates the 334 | // LATEST known state of the system by the client, 335 | // but it MAY still need to fill in a bit of history 336 | // (that's where `cursor_token` comes into play) 337 | resp.sync_token = Some(crate::sync_tokens::max_id_to_token(last_id)); 338 | } 339 | 340 | // Remove conflicted items from retrieved items 341 | let conflicts = &resp.conflicts; 342 | resp.retrieved_items = resp.retrieved_items.into_iter().filter(|x| { 343 | !conflicts.iter() 344 | .map(|y| x.uuid == y.uuid()) 345 | .fold(false, |x, y| x || y) 346 | }).collect(); 347 | 348 | success_resp(resp) 349 | } -------------------------------------------------------------------------------- /src/db.rs: -------------------------------------------------------------------------------- 1 | use diesel::connection::{SimpleConnection, Connection}; 2 | use diesel::deserialize::{Queryable, QueryableByName}; 3 | use diesel::query_builder::{AsQuery, QueryFragment, QueryId}; 4 | use diesel::result::{ConnectionResult, QueryResult}; 5 | use diesel::sqlite::{Sqlite, SqliteConnection}; 6 | use diesel::sql_types::*; 7 | use rocket_contrib::databases::{r2d2, DatabaseConfig, Poolable}; 8 | use std::sync::RwLock; 9 | 10 | // We need a global RwLock for SQLite 11 | // This is unfortunate when we still use SQLite 12 | // but should be mostly fine for our purpose 13 | // (however, due to disk sync delays, the RwLock alone 14 | // may still produce some SQLITE_BUSY errors randomly. 15 | // We implemented a wrapper later in this module to enable busy_timeout 16 | // to avoid this.) 17 | lazy_static! { 18 | pub static ref DB_LOCK: RwLock<()> = RwLock::new(()); 19 | } 20 | 21 | #[macro_export] 22 | macro_rules! lock_db_write { 23 | () => { 24 | crate::DB_LOCK.write() 25 | .map_err(|_| "Cannot lock database for writing".into()) 26 | }; 27 | } 28 | 29 | #[macro_export] 30 | macro_rules! lock_db_read { 31 | () => { 32 | crate::DB_LOCK.read() 33 | .map_err(|_| "Cannot lock database for reading".into()) 34 | }; 35 | } 36 | 37 | pub trait SqliteLike = Connection; 38 | 39 | pub struct BusyWaitSqliteConnection(SqliteConnection); 40 | 41 | impl Poolable for BusyWaitSqliteConnection { 42 | type Manager = diesel::r2d2::ConnectionManager; 43 | type Error = r2d2::Error; 44 | 45 | fn pool(config: DatabaseConfig) -> Result, Self::Error> { 46 | let manager = diesel::r2d2::ConnectionManager::new(config.url); 47 | r2d2::Pool::builder().max_size(config.pool_size).build(manager) 48 | } 49 | } 50 | 51 | // Enable busy_timeout for SQLite connections by re-implementing the Connection trait 52 | // (Note: busy_timeout is never the best solution, so the global RwLock is still needed, 53 | // and this busy_timeout is just to make sure that we won't fail due to disk sync lagging behind 54 | // when we acquire the RwLock because it may take some time for the SQLite lock state to be written to disk) 55 | // 56 | impl SimpleConnection for BusyWaitSqliteConnection { 57 | fn batch_execute(&self, query: &str) -> QueryResult<()> { 58 | self.0.batch_execute(query) 59 | } 60 | } 61 | 62 | impl Connection for BusyWaitSqliteConnection { 63 | type Backend = ::Backend; 64 | type TransactionManager = ::TransactionManager; 65 | 66 | fn establish(database_url: &str) -> ConnectionResult { 67 | let c = SqliteConnection::establish(database_url)?; 68 | c.batch_execute("PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 60000;") 69 | .unwrap(); 70 | Ok(Self(c)) 71 | } 72 | 73 | fn execute(&self, query: &str) -> QueryResult { 74 | self.0.execute(query) 75 | } 76 | 77 | fn query_by_index(&self, source: T) -> QueryResult> 78 | where 79 | T: AsQuery, 80 | T::Query: QueryFragment + QueryId, 81 | Self::Backend: HasSqlType, 82 | U: Queryable, 83 | { 84 | self.0.query_by_index(source) 85 | } 86 | 87 | fn query_by_name(&self, source: &T) -> QueryResult> 88 | where 89 | T: QueryFragment + QueryId, 90 | U: QueryableByName, 91 | { 92 | self.0.query_by_name(source) 93 | } 94 | 95 | fn execute_returning_count(&self, source: &T) -> QueryResult 96 | where 97 | T: QueryFragment + QueryId, 98 | { 99 | self.0.execute_returning_count(source) 100 | } 101 | 102 | fn transaction_manager(&self) -> &Self::TransactionManager { 103 | self.0.transaction_manager() 104 | } 105 | } -------------------------------------------------------------------------------- /src/item.rs: -------------------------------------------------------------------------------- 1 | use crate::schema::items; 2 | use crate::schema::items::dsl::*; 3 | use crate::{SqliteLike, lock_db_write, lock_db_read}; 4 | use crate::user; 5 | use diesel::dsl::max; 6 | use diesel::prelude::*; 7 | use serde::{Serialize, Deserialize}; 8 | use std::vec::Vec; 9 | 10 | #[derive(Debug)] 11 | pub struct ItemOpError(pub String); 12 | 13 | impl ItemOpError { 14 | fn new(s: impl Into) -> ItemOpError { 15 | ItemOpError(s.into()) 16 | } 17 | } 18 | 19 | impl Into for &str { 20 | fn into(self) -> ItemOpError { 21 | ItemOpError::new(self) 22 | } 23 | } 24 | 25 | #[derive(Queryable)] 26 | pub struct Item { 27 | // This "id", though primary key, is not how the client actually 28 | // identifies an item, and it is not sent to the client. 29 | // Instead, this "id" is more like a "timestamp", in the sense 30 | // that each time an item is modified, it increments. 31 | // (this incrementing is achieved by deleting and re-inserting 32 | // the item and relying on AUTOINCREMENT) 33 | // This is used in place of the role of timestamp in the Ruby 34 | // and Go implementation. 35 | pub id: i64, 36 | pub owner: i32, 37 | pub uuid: String, 38 | pub content: Option, 39 | pub content_type: String, 40 | pub enc_item_key: Option, 41 | pub deleted: bool, 42 | pub created_at: String, 43 | pub updated_at: Option 44 | } 45 | 46 | #[derive(Insertable)] 47 | #[table_name = "items"] 48 | struct InsertItem { 49 | owner: i32, 50 | uuid: String, 51 | content: Option, 52 | content_type: String, 53 | enc_item_key: Option, 54 | deleted: bool, 55 | created_at: String, 56 | updated_at: Option 57 | } 58 | 59 | #[derive(Serialize, Deserialize, Clone)] 60 | pub struct SyncItem { 61 | pub uuid: String, 62 | pub content: Option, 63 | pub content_type: String, 64 | pub enc_item_key: Option, 65 | #[serde(default)] 66 | pub deleted: bool, 67 | pub created_at: String, 68 | pub updated_at: Option 69 | } 70 | 71 | impl Into for Item { 72 | fn into(self) -> SyncItem { 73 | SyncItem { 74 | uuid: self.uuid, 75 | content: self.content, 76 | content_type: self.content_type, 77 | enc_item_key: self.enc_item_key, 78 | deleted: self.deleted, 79 | created_at: self.created_at, 80 | updated_at: self.updated_at 81 | } 82 | } 83 | } 84 | 85 | impl SyncItem { 86 | pub fn items_of_user( 87 | db: &impl SqliteLike, u: &user::User, 88 | since_id: Option, max_id: Option, 89 | limit: Option 90 | ) -> Result, ItemOpError> { 91 | lock_db_read!() 92 | .and_then(|_| { 93 | let mut stmt = items.filter(owner.eq(u.id)).into_boxed(); 94 | if let Some(limit) = limit { 95 | stmt = stmt.limit(limit); 96 | } 97 | 98 | if let Some(since_id) = since_id { 99 | stmt = stmt.filter(id.gt(since_id)); 100 | } 101 | 102 | if let Some(max_id) = max_id { 103 | stmt = stmt.filter(id.le(max_id)); 104 | } 105 | 106 | stmt.order(id.asc()) 107 | .load::(db) 108 | .map_err(|_| "Database error".into()) 109 | }) 110 | } 111 | 112 | pub fn find_item_by_uuid(db: &impl SqliteLike, u: &user::User, i: &str) -> Result { 113 | lock_db_read!() 114 | .and_then(|_| { 115 | items.filter(owner.eq(u.id).and(uuid.eq(i))) 116 | .first::(db) 117 | .map_err(|_| "Database error".into()) 118 | }) 119 | } 120 | 121 | // Get the current maximum item ID for a user. 122 | // Remember that IDs do not identify item; instead, they are incremented to the largest value 123 | // every time an item is updated (see Self::items_insert). 124 | // The ID returned by this function is more like a "timestamp" of the latest "state" 125 | pub fn get_current_max_id(db: &impl SqliteLike, u: &user::User) -> Result, ItemOpError> { 126 | lock_db_read!() 127 | .and_then(|_| { 128 | items.filter(owner.eq(u.id)) 129 | .select(max(id)) 130 | .first::>(db) 131 | .map_err(|_| "Database error".into()) 132 | }) 133 | } 134 | 135 | pub fn items_insert(db: &impl SqliteLike, u: &user::User, it: &SyncItem) -> Result { 136 | // First, try to find the original item, if any, delete it, and insert a new one with the same UUID 137 | // This way, the ID is updated each time an item is updated 138 | // This method acts both as insertion and update 139 | let orig = lock_db_read!() 140 | .and_then(|_| { 141 | items.filter(uuid.eq(&it.uuid).and(owner.eq(u.id))) 142 | .load::(db) 143 | .map_err(|_| "Database error".into()) 144 | })?; 145 | 146 | let _lock = lock_db_write!()?; 147 | if !orig.is_empty() { 148 | diesel::delete(items.filter(uuid.eq(&it.uuid).and(owner.eq(u.id)))) 149 | .execute(db) 150 | .map(|_| ()) 151 | .map_err(|_| "Database error".into())?; 152 | } 153 | 154 | diesel::insert_into(items::table) 155 | .values(InsertItem { 156 | owner: u.id, 157 | uuid: it.uuid.clone(), 158 | content: if it.deleted { None } else { it.content.clone() }, 159 | content_type: it.content_type.clone(), 160 | enc_item_key: if it.deleted { None } else { it.enc_item_key.clone() }, 161 | deleted: it.deleted, 162 | created_at: it.created_at.clone(), 163 | updated_at: it.updated_at.clone() 164 | }) 165 | .execute(db) 166 | .map_err(|_| "Database error".into())?; 167 | std::mem::drop(_lock); 168 | 169 | Self::find_item_by_uuid(db, u, &it.uuid) 170 | .map(|i| i.id) 171 | } 172 | } -------------------------------------------------------------------------------- /src/lock.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::sync::{Arc, RwLock, Mutex}; 3 | 4 | // A per-user lock used for sync requests 5 | pub struct UserLock { 6 | lock_map: RwLock>>> 7 | } 8 | 9 | impl UserLock { 10 | pub fn new() -> UserLock { 11 | UserLock { 12 | lock_map: RwLock::new(HashMap::new()) 13 | } 14 | } 15 | 16 | pub fn get_mutex(&self, uid: i32) -> Arc> { 17 | if !self.lock_map.read().unwrap().contains_key(&uid) { 18 | self.lock_map.write().unwrap().insert(uid, Arc::new(Mutex::new(()))); 19 | } 20 | 21 | self.lock_map.read().unwrap().get(&uid).unwrap().clone() 22 | } 23 | } -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #![feature(proc_macro_hygiene, decl_macro, trait_alias)] 2 | 3 | #[macro_use] 4 | extern crate rocket; 5 | #[macro_use] 6 | extern crate rocket_contrib; 7 | #[macro_use] 8 | extern crate diesel; 9 | #[macro_use] 10 | extern crate diesel_migrations; 11 | #[macro_use] 12 | extern crate serde; 13 | #[macro_use] 14 | extern crate lazy_static; 15 | 16 | mod db; 17 | mod schema; 18 | mod sync_tokens; 19 | mod api; 20 | mod tokens; 21 | mod user; 22 | mod item; 23 | mod lock; 24 | 25 | #[cfg(test)] 26 | mod tests; 27 | 28 | pub use db::*; 29 | 30 | use diesel::prelude::*; 31 | use dotenv::dotenv; 32 | use rocket::Rocket; 33 | use rocket::config::{Config, Environment, Value, Limits}; 34 | use std::collections::HashMap; 35 | use std::env; 36 | 37 | embed_migrations!(); 38 | 39 | #[database("db")] 40 | pub struct DbConn(BusyWaitSqliteConnection); 41 | 42 | #[get("/")] 43 | fn index() -> &'static str { 44 | "Hello, world!" 45 | } 46 | 47 | fn db_path() -> String { 48 | env::var("DATABASE_URL") 49 | .expect("DATABASE_URL must be set") 50 | } 51 | 52 | fn db_config() -> HashMap<&'static str, Value> { 53 | let mut database_config = HashMap::new(); 54 | let mut databases = HashMap::new(); 55 | 56 | database_config.insert("url", Value::from(db_path())); 57 | databases.insert("db", Value::from(database_config)); 58 | 59 | return databases; 60 | } 61 | 62 | fn get_environment() -> Environment { 63 | let v = env::var("SFRS_ENV").unwrap_or("development".to_string()); 64 | 65 | if v == "development" { 66 | Environment::Development 67 | } else { 68 | Environment::Production 69 | } 70 | } 71 | 72 | fn build_config() -> Config { 73 | Config::build(get_environment()) 74 | .extra("databases", db_config()) 75 | .limits(Limits::new().limit("json", 50 * 1024 * 1024)) 76 | .finalize() 77 | .unwrap() 78 | } 79 | 80 | fn run_db_migrations(rocket: Rocket) -> Rocket { 81 | let db = DbConn::get_one(&rocket).expect("Could not connect to Database"); 82 | match embedded_migrations::run(&*db) { 83 | Ok(()) => rocket, 84 | Err(e) => { 85 | // We should not do anything if database failed to migrate 86 | panic!("Failed to run database migrations: {:?}", e); 87 | } 88 | } 89 | } 90 | 91 | pub fn build_rocket() -> Rocket { 92 | // Make CORS options 93 | let cors = rocket_cors::CorsOptions { 94 | allowed_origins: rocket_cors::AllowedOrigins::All, 95 | allowed_methods: vec![rocket::http::Method::Get, rocket::http::Method::Post] 96 | .into_iter().map(From::from).collect(), 97 | allowed_headers: rocket_cors::AllowedHeaders::all(), 98 | send_wildcard: true, 99 | ..Default::default() 100 | }.to_cors().unwrap(); 101 | 102 | let r = rocket::custom(build_config()) 103 | .attach(cors) 104 | .attach(DbConn::fairing()) 105 | .manage(lock::UserLock::new()) 106 | .mount("/", api::routes()); 107 | run_db_migrations(r) 108 | } 109 | 110 | fn main() { 111 | dotenv().ok(); 112 | build_rocket().launch(); 113 | } 114 | -------------------------------------------------------------------------------- /src/schema.rs: -------------------------------------------------------------------------------- 1 | table! { 2 | items (id) { 3 | id -> BigInt, // Forced, diesel does not support intepreting Integer as i64 4 | owner -> Integer, 5 | uuid -> Text, 6 | content -> Nullable, 7 | content_type -> Text, 8 | enc_item_key -> Nullable, 9 | deleted -> Bool, 10 | created_at -> Text, 11 | updated_at -> Nullable, 12 | } 13 | } 14 | 15 | table! { 16 | tokens (id) { 17 | id -> Text, 18 | uid -> Integer, 19 | timestamp -> Nullable, 20 | } 21 | } 22 | 23 | table! { 24 | users (id) { 25 | id -> Integer, 26 | uuid -> Text, 27 | email -> Text, 28 | password -> Text, 29 | pw_cost -> Integer, 30 | pw_nonce -> Text, 31 | version -> Text, 32 | } 33 | } 34 | 35 | joinable!(items -> users (owner)); 36 | joinable!(tokens -> users (uid)); 37 | 38 | allow_tables_to_appear_in_same_query!( 39 | items, 40 | tokens, 41 | users, 42 | ); 43 | -------------------------------------------------------------------------------- /src/sync_tokens.rs: -------------------------------------------------------------------------------- 1 | use ring::aead::*; 2 | use ring::digest::*; 3 | use ring::pbkdf2::*; 4 | use ring::rand::{SecureRandom, SystemRandom}; 5 | 6 | // In the API endpoint `/items/sync`, we use `max_id` of the 7 | // current user as the sync token. However, this may be prone 8 | // to side-channel leakage since all users in database share 9 | // the same auto-incrementing ID. An attacker may be able to 10 | // call `/items/sync` with one update each time and extract 11 | // what others' are doing based on changes in ID. 12 | // Therefore, we should at least not send the ID as a token 13 | // in plain-text to the client. 14 | 15 | lazy_static! { 16 | static ref TOKEN_KEY: [u8; 32] = get_token_key(); 17 | } 18 | 19 | pub fn get_token_key() -> [u8; 32] { 20 | let pwd = std::env::var("SYNC_TOKEN_SECRET") 21 | .expect("Please set SYNC_TOKEN_SECRET").into_bytes(); 22 | let salt = std::env::var("SYNC_TOKEN_SALT") 23 | .expect("Please set SYNC_TOKEN_SALT").into_bytes(); 24 | let mut ret = [0; 32]; 25 | derive(&SHA256, 100, &salt, &pwd, &mut ret); 26 | ret 27 | } 28 | 29 | pub fn max_id_to_token(max_id: i64) -> String { 30 | let sealing_key = SealingKey::new(&CHACHA20_POLY1305, &*TOKEN_KEY).unwrap(); 31 | let mut nonce = [0u8; 12]; 32 | SystemRandom::new().fill(&mut nonce).unwrap(); 33 | let mut id_str = max_id.to_string().as_bytes().to_vec(); 34 | id_str.resize(id_str.len() + CHACHA20_POLY1305.tag_len(), 0); 35 | let out_len = seal_in_place(&sealing_key, &nonce, &[], &mut id_str, CHACHA20_POLY1305.tag_len()) 36 | .unwrap(); 37 | let mut out = id_str[0..out_len].to_vec(); 38 | out.extend_from_slice(&nonce); 39 | hex::encode(out) 40 | } 41 | 42 | pub fn token_to_max_id(token: &str) -> Result { 43 | let opening_key = OpeningKey::new(&CHACHA20_POLY1305, &*TOKEN_KEY).unwrap(); 44 | let data = hex::decode(token).map_err(|_| ())?; 45 | let len = data.len(); 46 | if len <= 12 { 47 | return Err(()); 48 | } 49 | 50 | let mut id_str = (&data[0..(len - 12)]).to_vec(); 51 | let nonce = &data[(len - 12)..len]; 52 | let decrypted = open_in_place(&opening_key, nonce, &[], 0, &mut id_str) 53 | .map_err(|_| ())?; 54 | String::from_utf8(decrypted.to_vec()) 55 | .map_err(|_| ())? 56 | .parse() 57 | .map_err(|_| ()) 58 | } -------------------------------------------------------------------------------- /src/tests.rs: -------------------------------------------------------------------------------- 1 | use crate::build_rocket; 2 | use rocket::local::Client; 3 | use rocket::http::{Header, ContentType, Status}; 4 | use lazy_static::*; 5 | 6 | fn get_test_client() -> Client { 7 | dotenv::from_filename(".env.test").unwrap(); 8 | Client::new(build_rocket()) 9 | .expect("valid rocket instance") 10 | } 11 | 12 | lazy_static! { 13 | static ref CLIENT: Client = get_test_client(); 14 | } 15 | 16 | #[test] 17 | fn sync_token_dec_1() { 18 | dotenv::from_filename(".env.test").unwrap(); 19 | // We have to test decryption of a particular encrypted ID 20 | // to ensure we break nothing during updates 21 | let id = crate::sync_tokens::token_to_max_id("a3e43acc6c407dcb155598410be6524bfe483452b0c43b8c4cc8fe37ef183e6b6fc1").unwrap(); 22 | assert_eq!(id, 114514); 23 | } 24 | 25 | #[test] 26 | fn sync_token_dec_2() { 27 | dotenv::from_filename(".env.test").unwrap(); 28 | // We have to test decryption of a particular encrypted ID 29 | // to ensure we break nothing during updates 30 | let id = crate::sync_tokens::token_to_max_id("cfb84e2eb08f8aaf959cc20a9f86225594abb0f0a40f56f692ea1475a00777f902a251").unwrap(); 31 | assert_eq!(id, 1919810); 32 | } 33 | 34 | #[test] 35 | fn sync_token_enc_dec_1() { 36 | dotenv::from_filename(".env.test").unwrap(); 37 | let token = crate::sync_tokens::max_id_to_token(114514); 38 | let id = crate::sync_tokens::token_to_max_id(&token).unwrap(); 39 | assert_eq!(id, 114514); 40 | } 41 | 42 | #[test] 43 | fn sync_token_enc_dec_2() { 44 | dotenv::from_filename(".env.test").unwrap(); 45 | let token = crate::sync_tokens::max_id_to_token(1919810); 46 | let id = crate::sync_tokens::token_to_max_id(&token).unwrap(); 47 | assert_eq!(id, 1919810); 48 | } 49 | 50 | 51 | #[test] 52 | fn should_add_user() { 53 | let mut resp = CLIENT 54 | .post("/auth") 55 | .header(ContentType::JSON) 56 | .body(r#"{ 57 | "email": "test@example.com", 58 | "password": "testpw", 59 | "pw_cost": 100, 60 | "pw_nonce": "whatever", 61 | "version": "001" 62 | }"#) 63 | .dispatch(); 64 | assert_eq!(resp.status(), Status::Ok); 65 | serde_json::from_str::(&resp.body_string().unwrap()).unwrap() 66 | .get("token").unwrap().as_str().unwrap(); 67 | } 68 | 69 | #[test] 70 | fn should_not_add_user_twice() { 71 | CLIENT.post("/auth") 72 | .header(ContentType::JSON) 73 | .body(r#"{ 74 | "email": "test1@example.com", 75 | "password": "testpw", 76 | "pw_cost": 100, 77 | "pw_nonce": "whatever", 78 | "version": "001" 79 | }"#) 80 | .dispatch() 81 | .body_string() 82 | .unwrap(); 83 | let resp = CLIENT 84 | .post("/auth") 85 | .header(ContentType::JSON) 86 | .body(r#"{ 87 | "email": "test1@example.com", 88 | "password": "does not matter", 89 | "pw_cost": 100, 90 | "pw_nonce": "whatever", 91 | "version": "001" 92 | }"#) 93 | .dispatch(); 94 | assert_eq!(resp.status(), Status::InternalServerError); 95 | } 96 | 97 | #[test] 98 | fn should_not_add_user_invalid_email() { 99 | let resp = CLIENT 100 | .post("/auth") 101 | .header(ContentType::JSON) 102 | .body(r#"{ 103 | "email": "test.example.com", 104 | "password": "testpw", 105 | "pw_cost": 100, 106 | "pw_nonce": "whatever", 107 | "version": "001" 108 | }"#) 109 | .dispatch(); 110 | assert_eq!(resp.status(), Status::BadRequest); 111 | } 112 | 113 | #[test] 114 | fn should_log_in_successfully() { 115 | CLIENT.post("/auth") 116 | .header(ContentType::JSON) 117 | .body(r#"{ 118 | "email": "test2@example.com", 119 | "password": "testpw", 120 | "pw_cost": 100, 121 | "pw_nonce": "whatever", 122 | "version": "001" 123 | }"#) 124 | .dispatch() 125 | .body_string() 126 | .unwrap(); 127 | let mut resp = CLIENT 128 | .post("/auth/sign_in") 129 | .header(ContentType::JSON) 130 | .body(r#"{ 131 | "email": "test2@example.com", 132 | "password": "testpw" 133 | }"#) 134 | .dispatch(); 135 | assert_eq!(resp.status(), Status::Ok); 136 | serde_json::from_str::(&resp.body_string().unwrap()).unwrap() 137 | .get("token").unwrap().as_str().unwrap(); 138 | } 139 | 140 | #[test] 141 | fn should_log_in_fail() { 142 | CLIENT.post("/auth") 143 | .header(ContentType::JSON) 144 | .body(r#"{ 145 | "email": "test3@example.com", 146 | "password": "testpw", 147 | "pw_cost": 100, 148 | "pw_nonce": "whatever", 149 | "version": "001" 150 | }"#) 151 | .dispatch() 152 | .body_string() 153 | .unwrap(); 154 | let resp = CLIENT 155 | .post("/auth/sign_in") 156 | .header(ContentType::JSON) 157 | .body(r#"{ 158 | "email": "test3@example.com", 159 | "password": "testpw1" 160 | }"#) 161 | .dispatch(); 162 | assert_eq!(resp.status(), Status::InternalServerError); 163 | } 164 | 165 | #[test] 166 | fn should_change_pw_successfully() { 167 | CLIENT.post("/auth") 168 | .header(ContentType::JSON) 169 | .body(r#"{ 170 | "email": "test4@example.com", 171 | "password": "testpw", 172 | "pw_cost": 100, 173 | "pw_nonce": "whatever", 174 | "version": "001" 175 | }"#) 176 | .dispatch() 177 | .body_string() 178 | .unwrap(); 179 | let resp = CLIENT 180 | .post("/auth/change_pw") 181 | .header(ContentType::JSON) 182 | .body(r#"{ 183 | "email": "test4@example.com", 184 | "password": "testpw1", 185 | "current_password": "testpw" 186 | }"#) 187 | .dispatch(); 188 | assert_eq!(resp.status(), Status::NoContent); 189 | } 190 | 191 | #[test] 192 | fn should_change_pw_fail() { 193 | CLIENT.post("/auth") 194 | .header(ContentType::JSON) 195 | .body(r#"{ 196 | "email": "test5@example.com", 197 | "password": "testpw", 198 | "pw_cost": 100, 199 | "pw_nonce": "whatever", 200 | "version": "001" 201 | }"#) 202 | .dispatch() 203 | .body_string() 204 | .unwrap(); 205 | let resp = CLIENT 206 | .post("/auth/change_pw") 207 | .header(ContentType::JSON) 208 | .body(r#"{ 209 | "email": "test5@example.com", 210 | "password": "testpw1", 211 | "current_password": "testpw2" 212 | }"#) 213 | .dispatch(); 214 | assert_eq!(resp.status(), Status::InternalServerError); 215 | } 216 | 217 | #[test] 218 | fn should_change_pw_successfully_and_log_in_successfully() { 219 | CLIENT.post("/auth") 220 | .header(ContentType::JSON) 221 | .body(r#"{ 222 | "email": "test6@example.com", 223 | "password": "testpw", 224 | "pw_cost": 100, 225 | "pw_nonce": "whatever", 226 | "version": "001" 227 | }"#) 228 | .dispatch() 229 | .body_string() 230 | .unwrap(); 231 | let resp = CLIENT 232 | .post("/auth/change_pw") 233 | .header(ContentType::JSON) 234 | .body(r#"{ 235 | "email": "test6@example.com", 236 | "password": "testpw1", 237 | "current_password": "testpw" 238 | }"#) 239 | .dispatch(); 240 | assert_eq!(resp.status(), Status::NoContent); 241 | let resp = CLIENT 242 | .post("/auth/sign_in") 243 | .header(ContentType::JSON) 244 | .body(r#"{ 245 | "email": "test6@example.com", 246 | "password": "testpw1" 247 | }"#) 248 | .dispatch(); 249 | assert_eq!(resp.status(), Status::Ok); 250 | } 251 | 252 | #[test] 253 | fn should_fail_authorize() { 254 | let resp = CLIENT.get("/auth/ping").dispatch(); 255 | assert_eq!(resp.status(), Status::Unauthorized); 256 | } 257 | 258 | #[test] 259 | fn should_fail_authorize_2() { 260 | let resp = CLIENT.get("/auth/ping") 261 | .header(Header::new("Authorization", "Bearer iwoe0nvie0bv024ibv043bv")) 262 | .dispatch(); 263 | assert_eq!(resp.status(), Status::Unauthorized); 264 | } 265 | 266 | #[test] 267 | fn should_success_authorize() { 268 | let token = CLIENT.post("/auth") 269 | .header(ContentType::JSON) 270 | .body(r#"{ 271 | "email": "test7@example.com", 272 | "password": "testpw", 273 | "pw_cost": 100, 274 | "pw_nonce": "whatever", 275 | "version": "001" 276 | }"#) 277 | .dispatch() 278 | .body_string() 279 | .unwrap(); 280 | let val = serde_json::from_str::(&token).unwrap(); 281 | let token = val.get("token").unwrap().as_str().unwrap(); 282 | let mut resp = CLIENT.get("/auth/ping") 283 | .header(Header::new("Authorization", format!("Bearer {}", token))) 284 | .dispatch(); 285 | assert_eq!(resp.status(), Status::Ok); 286 | assert_eq!(resp.body_string().unwrap(), "\"test7@example.com\""); 287 | } -------------------------------------------------------------------------------- /src/tokens.rs: -------------------------------------------------------------------------------- 1 | use crate::schema::tokens; 2 | use crate::schema::tokens::dsl::*; 3 | use crate::{SqliteLike, lock_db_write, lock_db_read}; 4 | use chrono::NaiveDateTime; 5 | use diesel::prelude::*; 6 | use std::sync::{RwLockReadGuard, RwLockWriteGuard}; 7 | use uuid::Uuid; 8 | 9 | #[derive(Queryable, Insertable)] 10 | #[table_name = "tokens"] 11 | pub struct Token { 12 | id: String, 13 | uid: i32, 14 | timestamp: Option 15 | } 16 | 17 | impl Token { 18 | // Return user id if any 19 | pub fn find_token_by_id(db: &impl SqliteLike, tid: &str) -> Option { 20 | (lock_db_read!() as Result, String>).ok() 21 | .and_then(|_| { 22 | tokens.filter(id.eq(tid)) 23 | .load::(db) 24 | .ok() 25 | .and_then(|mut v| { 26 | if !v.is_empty() { 27 | Some(v.remove(0).uid) 28 | } else { 29 | None 30 | } 31 | }) 32 | }) 33 | } 34 | 35 | // Create a new token for a user 36 | pub fn create_token(db: &impl SqliteLike, user: i32) -> Option { 37 | let tid = Uuid::new_v4().to_hyphenated().to_string(); 38 | (lock_db_write!() as Result, String>).ok() 39 | .and_then(|_| { 40 | diesel::insert_into(tokens::table) 41 | .values(Token { 42 | id: tid.clone(), 43 | uid: user, 44 | timestamp: None // There's default value from SQLite 45 | }) 46 | .execute(db) 47 | .ok() 48 | .map(|_| tid) 49 | }) 50 | } 51 | } -------------------------------------------------------------------------------- /src/user.rs: -------------------------------------------------------------------------------- 1 | use crate::schema::users; 2 | use crate::schema::users::dsl::*; 3 | use crate::{SqliteLike, lock_db_write, lock_db_read}; 4 | use ::uuid::Uuid; 5 | use diesel::prelude::*; 6 | use rocket::request; 7 | use rocket::http::Status; 8 | use serde::Deserialize; 9 | 10 | #[derive(Debug)] 11 | pub struct UserOpError(pub String); 12 | 13 | impl UserOpError { 14 | fn new(s: impl Into) -> UserOpError { 15 | UserOpError(s.into()) 16 | } 17 | } 18 | 19 | impl Into for &str { 20 | fn into(self) -> UserOpError { 21 | UserOpError::new(self) 22 | } 23 | } 24 | 25 | // Password should ALWAYS be hashed 26 | #[derive(Debug)] 27 | pub struct Password(String); 28 | 29 | impl Password { 30 | fn new(passwd: &str) -> Password { 31 | let params = scrypt::ScryptParams::new(11, 8, 1).unwrap(); 32 | Password(scrypt::scrypt_simple(passwd, ¶ms).unwrap()) 33 | } 34 | } 35 | 36 | impl PartialEq<&str> for Password { 37 | fn eq(&self, other: &&str) -> bool { 38 | scrypt::scrypt_check(*other, &self.0).is_ok() 39 | } 40 | } 41 | 42 | impl Into for String { 43 | fn into(self) -> Password { 44 | Password::new(&self) 45 | } 46 | } 47 | 48 | // Convert itself to a hash String for db operations 49 | impl Into for Password { 50 | fn into(self) -> String { 51 | self.0 52 | } 53 | } 54 | 55 | // A raw User returned from database 56 | // we need to wrap the password in the Password type 57 | #[derive(Queryable)] 58 | struct UserQuery { 59 | pub id: i32, 60 | pub uuid: String, 61 | pub email: String, 62 | pub password: String, 63 | pub pw_cost: i32, 64 | pub pw_nonce: String, 65 | pub version: String 66 | } 67 | 68 | impl Into for UserQuery { 69 | fn into(self) -> User { 70 | User { 71 | id: self.id, 72 | uuid: self.uuid, 73 | email: self.email, 74 | // We can directly construct Password here 75 | // because it's already the hashed value from db 76 | password: Password(self.password), 77 | pw_cost: self.pw_cost, 78 | pw_nonce: self.pw_nonce, 79 | version: self.version 80 | } 81 | } 82 | } 83 | 84 | #[derive(Debug)] 85 | pub struct User { 86 | pub id: i32, 87 | pub uuid: String, 88 | pub email: String, 89 | pub password: Password, 90 | pub pw_cost: i32, 91 | pub pw_nonce: String, 92 | pub version: String 93 | } 94 | 95 | #[derive(Deserialize)] 96 | pub struct NewUser { 97 | pub email: String, 98 | pub password: String, 99 | pub pw_cost: i32, 100 | pub pw_nonce: String, 101 | pub version: String 102 | } 103 | 104 | #[derive(Insertable)] 105 | #[table_name="users"] 106 | struct NewUserInsert { 107 | uuid: String, 108 | email: String, 109 | password: String, 110 | pw_cost: i32, 111 | pw_nonce: String, 112 | version: String 113 | } 114 | 115 | impl User { 116 | pub fn create(db: &impl SqliteLike, new_user: &NewUser) -> Result { 117 | let uid = Uuid::new_v4().to_hyphenated().to_string(); 118 | let user_hashed = NewUserInsert { 119 | uuid: uid.clone(), 120 | email: new_user.email.clone(), 121 | password: Password::new(&new_user.password).into(), 122 | pw_cost: new_user.pw_cost.clone(), 123 | pw_nonce: new_user.pw_nonce.clone(), 124 | version: new_user.version.clone(), 125 | }; 126 | 127 | match Self::find_user_by_email(db, &new_user.email) { 128 | Ok(_) => Err(UserOpError::new("User already registered")), 129 | Err(_) => lock_db_write!() 130 | .and_then(|_| diesel::insert_into(users::table) 131 | .values(user_hashed) 132 | .execute(db) 133 | .map(|_| uid) 134 | .map_err(|_| UserOpError::new("Database error"))) 135 | } 136 | } 137 | 138 | pub fn find_user_by_email(db: &impl SqliteLike, user_email: &str) -> Result { 139 | let mut results = lock_db_read!() 140 | .and_then(|_| users.filter(email.eq(user_email)) 141 | .limit(1) 142 | .load::(db) 143 | .map_err(|_| UserOpError::new("Database error")))?; 144 | if results.is_empty() { 145 | Result::Err(UserOpError::new("No matching user found")) 146 | } else { 147 | Result::Ok(results.remove(0).into()) // Take ownership, kill the stupid Vec 148 | } 149 | } 150 | 151 | pub fn find_user_by_id(db: &impl SqliteLike, user_id: i32) -> Result { 152 | let mut results = lock_db_read!() 153 | .and_then(|_| users.filter(id.eq(user_id)) 154 | .limit(1) 155 | .load::(db) 156 | .map_err(|_| UserOpError::new("Database error")))?; 157 | if results.is_empty() { 158 | Result::Err(UserOpError::new("No matching user found")) 159 | } else { 160 | Result::Ok(results.remove(0).into()) // Take ownership, kill the stupid Vec 161 | } 162 | } 163 | 164 | pub fn find_user_by_token(db: &impl SqliteLike, token: &str) -> Result { 165 | crate::tokens::Token::find_token_by_id(db, token) 166 | .ok_or("Invalid token".into()) 167 | .and_then(|uid| Self::find_user_by_id(db, uid)) 168 | } 169 | 170 | // Create a JWT token for the current user if password matches 171 | pub fn create_token(&self, db: &impl SqliteLike, passwd: &str) -> Result { 172 | if self.password != passwd { 173 | Err(UserOpError::new("Password mismatch")) 174 | } else { 175 | crate::tokens::Token::create_token(db, self.id) 176 | .ok_or("Failed to generate token".into()) 177 | } 178 | } 179 | 180 | // Change the password in database, if old password is provided 181 | // The current instance of User model will not be mutated 182 | pub fn change_pw(&self, db: &impl SqliteLike, passwd: &str, new_passwd: &str) -> Result<(), UserOpError> { 183 | if self.password != passwd { 184 | Err(UserOpError::new("Password mismatch")) 185 | } else { 186 | // Update database 187 | // TODO: Maybe we should revoke all JWTs somehow? 188 | // maybe we can record when the user last changed? 189 | lock_db_write!() 190 | .and_then(|_| diesel::update(users.find(self.id)) 191 | .set(password.eq::(Password::new(new_passwd).into())) 192 | .execute(db) 193 | .map(|_| ()) 194 | .map_err(|_| UserOpError::new("Database error"))) 195 | } 196 | } 197 | } 198 | 199 | // Implement request guard for User type 200 | // This is intended for protecting authorized endpoints 201 | impl<'a, 'r> request::FromRequest<'a, 'r> for User { 202 | type Error = UserOpError; 203 | 204 | fn from_request(request: &'a request::Request<'r>) -> request::Outcome { 205 | let token = request.headers().get_one("authorization"); 206 | match token { 207 | None => request::Outcome::Failure((Status::Unauthorized, "Token missing".into())), 208 | Some(token) => { 209 | if !token.starts_with("Bearer ") { 210 | return request::Outcome::Failure((Status::Unauthorized, "Malformed Token".into())); 211 | } 212 | 213 | let result = Self::find_user_by_token( 214 | &request.guard::().unwrap().0, &token[7..]); 215 | match result { 216 | Ok(u) => request::Outcome::Success(u), 217 | Err(err) => request::Outcome::Failure((Status::Unauthorized, err)) 218 | } 219 | } 220 | } 221 | } 222 | } -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm -rf db/database.test.db 4 | cargo test 5 | rm -rf db/database.test.db --------------------------------------------------------------------------------