totp: new crate, sql migration + queries, enable totp page, save secret in database

This commit is contained in:
Philippe Loctaux 2023-04-25 23:37:24 +02:00
parent cb46556717
commit 233e26520c
26 changed files with 1116 additions and 364 deletions

151
Cargo.lock generated
View file

@ -12,6 +12,12 @@ dependencies = [
"regex", "regex",
] ]
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]] [[package]]
name = "ahash" name = "ahash"
version = "0.7.6" version = "0.7.6"
@ -145,6 +151,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce"
[[package]]
name = "base32"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa"
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.13.1" version = "0.13.1"
@ -215,6 +227,12 @@ version = "3.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
[[package]]
name = "bytemuck"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea"
[[package]] [[package]]
name = "byteorder" name = "byteorder"
version = "1.4.3" version = "1.4.3"
@ -309,12 +327,24 @@ dependencies = [
"unicode-width", "unicode-width",
] ]
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]] [[package]]
name = "const-oid" name = "const-oid"
version = "0.9.2" version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "520fbf3c07483f94e3e3ca9d0cfd913d7718ef2483d2cfd91c0d9e91474ab913" checksum = "520fbf3c07483f94e3e3ca9d0cfd913d7718ef2483d2cfd91c0d9e91474ab913"
[[package]]
name = "constant_time_eq"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13418e745008f7349ec7e449155f419a61b92b58a99cc3616942b926825ec76b"
[[package]] [[package]]
name = "cookie" name = "cookie"
version = "0.17.0" version = "0.17.0"
@ -356,6 +386,15 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484" checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484"
[[package]]
name = "crc32fast"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "crossbeam-channel" name = "crossbeam-channel"
version = "0.5.7" version = "0.5.7"
@ -749,6 +788,7 @@ dependencies = [
"rocket_db_pools", "rocket_db_pools",
"rocket_dyn_templates", "rocket_dyn_templates",
"settings", "settings",
"totp",
"url", "url",
"users", "users",
] ]
@ -798,6 +838,16 @@ dependencies = [
"windows-sys 0.45.0", "windows-sys 0.45.0",
] ]
[[package]]
name = "flate2"
version = "1.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]] [[package]]
name = "flume" name = "flume"
version = "0.10.14" version = "0.10.14"
@ -1268,6 +1318,20 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "image"
version = "0.24.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527909aa81e20ac3a44803521443a765550f09b5130c2c2fa1ea59c2f8f50a3a"
dependencies = [
"bytemuck",
"byteorder",
"color_quant",
"num-rational",
"num-traits",
"png",
]
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.9.2" version = "1.9.2"
@ -1566,6 +1630,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa"
dependencies = [
"adler",
]
[[package]] [[package]]
name = "mio" name = "mio"
version = "0.8.6" version = "0.8.6"
@ -1786,6 +1859,17 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "num-rational"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.15" version = "0.2.15"
@ -2204,6 +2288,18 @@ version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
[[package]]
name = "png"
version = "0.17.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d708eaf860a19b19ce538740d2b4bdeeb8337fa53f7738455e706623ad5c638"
dependencies = [
"bitflags 1.3.2",
"crc32fast",
"flate2",
"miniz_oxide",
]
[[package]] [[package]]
name = "ppv-lite86" name = "ppv-lite86"
version = "0.2.17" version = "0.2.17"
@ -2232,6 +2328,12 @@ dependencies = [
"yansi", "yansi",
] ]
[[package]]
name = "qrcodegen"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4339fc7a1021c9c1621d87f5e3505f2805c8c105420ba2f2a4df86814590c142"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.26" version = "1.0.26"
@ -2771,6 +2873,17 @@ dependencies = [
"url", "url",
] ]
[[package]]
name = "sha1"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.10.6" version = "0.10.6"
@ -3273,6 +3386,34 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "totp"
version = "0.0.0"
dependencies = [
"thiserror",
"totp-rs",
]
[[package]]
name = "totp-rs"
version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "332e333b188e843cb4cc477b2911160a533bcfc6e9e488d7bef25011f9e2ba1b"
dependencies = [
"base32",
"base64 0.21.0",
"constant_time_eq",
"hmac",
"image",
"qrcodegen",
"rand",
"sha1",
"sha2",
"url",
"urlencoding",
"zeroize",
]
[[package]] [[package]]
name = "tower-service" name = "tower-service"
version = "0.3.2" version = "0.3.2"
@ -3510,6 +3651,12 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "urlencoding"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"
[[package]] [[package]]
name = "users" name = "users"
version = "0.0.0" version = "0.0.0"
@ -3810,9 +3957,9 @@ checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
[[package]] [[package]]
name = "zeroize" name = "zeroize"
version = "1.5.7" version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f" checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9"
dependencies = [ dependencies = [
"zeroize_derive", "zeroize_derive",
] ]

View file

@ -0,0 +1,4 @@
alter table users
drop column totp_secret;
alter table users
drop column totp_backup;

View file

@ -0,0 +1,4 @@
alter table users
add column totp_secret BLOB;
alter table users
add column totp_backup TEXT;

View file

@ -9,7 +9,9 @@ select id,
password_recover, password_recover,
paper_key, paper_key,
is_archived as "is_archived: bool", is_archived as "is_archived: bool",
timezone timezone,
totp_secret,
totp_backup
from users from users
order by created_at desc order by created_at desc

View file

@ -9,7 +9,9 @@ select u.id,
u.password_recover, u.password_recover,
u.paper_key, u.paper_key,
u.is_archived as "is_archived: bool", u.is_archived as "is_archived: bool",
u.timezone u.timezone,
u.totp_secret,
u.totp_backup
from users u from users u
inner join settings s on u.id = s.first_admin inner join settings s on u.id = s.first_admin

View file

@ -9,7 +9,9 @@ select id,
password_recover, password_recover,
paper_key, paper_key,
is_archived as "is_archived: bool", is_archived as "is_archived: bool",
timezone timezone,
totp_secret,
totp_backup
from users from users
where email is (?) where email is (?)

View file

@ -9,7 +9,9 @@ select id,
password_recover, password_recover,
paper_key, paper_key,
is_archived as "is_archived: bool", is_archived as "is_archived: bool",
timezone timezone,
totp_secret,
totp_backup
from users from users
where id is (?) where id is (?)

View file

@ -9,7 +9,9 @@ select id,
password_recover, password_recover,
paper_key, paper_key,
is_archived as "is_archived: bool", is_archived as "is_archived: bool",
timezone timezone,
totp_secret,
totp_backup
from users from users
where username is (?) where username is (?)

View file

@ -9,7 +9,9 @@ select u.id,
u.password_recover, u.password_recover,
u.paper_key, u.paper_key,
u.is_archived as "is_archived: bool", u.is_archived as "is_archived: bool",
u.timezone u.timezone,
u.totp_secret,
u.totp_backup
from users u from users u
inner join authorization_codes ac on u.id = ac.user inner join authorization_codes ac on u.id = ac.user

View file

@ -9,7 +9,9 @@ select id,
password_recover, password_recover,
paper_key, paper_key,
is_archived as "is_archived: bool", is_archived as "is_archived: bool",
timezone timezone,
totp_secret,
totp_backup
from users from users
where password_recover is (?) where password_recover is (?)

View file

@ -9,7 +9,9 @@ select u.id,
u.password_recover, u.password_recover,
u.paper_key, u.paper_key,
u.is_archived as "is_archived: bool", u.is_archived as "is_archived: bool",
u.timezone u.timezone,
u.totp_secret,
u.totp_backup
from users u from users u
inner join refresh_tokens rt on u.id = rt.user inner join refresh_tokens rt on u.id = rt.user

View file

@ -0,0 +1,5 @@
update users
set totp_backup = ?
where id is ?

View file

@ -0,0 +1,5 @@
update users
set totp_secret = ?
where id is ?

View file

@ -120,7 +120,7 @@
}, },
"query": "update users\n\nset password_recover = ?\n\nwhere id is ?" "query": "update users\n\nset password_recover = ?\n\nwhere id is ?"
}, },
"35de1a35e6cf6c683a1b2ca3605791aea9cbb852ac1d3df151cc21c341046361": { "37000307a757b4912ca300c346b5bd8ee5d50331d94abeee076ae4db46215a56": {
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -182,6 +182,16 @@
"name": "timezone", "name": "timezone",
"ordinal": 11, "ordinal": 11,
"type_info": "Text" "type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
} }
], ],
"nullable": [ "nullable": [
@ -196,13 +206,15 @@
true, true,
true, true,
false, false,
false false,
true,
true
], ],
"parameters": { "parameters": {
"Right": 1 "Right": 1
} }
}, },
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone\nfrom users\n\nwhere id is (?)\n" "query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone,\n totp_secret,\n totp_backup\nfrom users\n\nwhere email is (?)\n"
}, },
"37681902a5f5d87492812a525a6488e75d20c1c436a3ba2c5aa3f54da62fe861": { "37681902a5f5d87492812a525a6488e75d20c1c436a3ba2c5aa3f54da62fe861": {
"describe": { "describe": {
@ -294,7 +306,7 @@
}, },
"query": "update users\n\nset username = ?\n\nwhere id is ?" "query": "update users\n\nset username = ?\n\nwhere id is ?"
}, },
"56a88e7e68cfa94a055008510e3bc4389d7a7f64b43479d5fc8e4495ade0f84a": { "5567f75b47f739e85da3469bec0202be315c42dfc820d3c37bba498b1b783811": {
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -356,6 +368,16 @@
"name": "timezone", "name": "timezone",
"ordinal": 11, "ordinal": 11,
"type_info": "Text" "type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
} }
], ],
"nullable": [ "nullable": [
@ -370,13 +392,15 @@
true, true,
true, true,
false, false,
false false,
true,
true
], ],
"parameters": { "parameters": {
"Right": 1 "Right": 1
} }
}, },
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone\nfrom users\n\nwhere password_recover is (?)\n" "query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone,\n totp_secret,\n totp_backup\nfrom users\n\nwhere username is (?)\n"
}, },
"56a9c0dff010858189a95087d014c7d0ce930da5d841b9d788a9c0e84b580bc6": { "56a9c0dff010858189a95087d014c7d0ce930da5d841b9d788a9c0e84b580bc6": {
"describe": { "describe": {
@ -540,7 +564,7 @@
}, },
"query": "update users\n\nset paper_key = ?\n\nwhere id is ?" "query": "update users\n\nset paper_key = ?\n\nwhere id is ?"
}, },
"6a4a17c69175a677961779db048bff43d01e8773e7c4a6b25b9ee9b3c6fbacd5": { "71c74369dc5d374d8ec5aa347b5f599728b74e545df3e986e3e7e66882f73ba0": {
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -602,89 +626,15 @@
"name": "timezone", "name": "timezone",
"ordinal": 11, "ordinal": 11,
"type_info": "Text" "type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false
],
"parameters": {
"Right": 0
}
},
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone\nfrom users\n\norder by created_at desc\n"
},
"73f0d480c8dbef497a458070a32e65f0140f9a6e098ea082870a9c904629a97b": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
}, },
{ {
"name": "created_at: DateTime<Utc>", "name": "totp_secret",
"ordinal": 1, "ordinal": 12,
"type_info": "Text" "type_info": "Blob"
}, },
{ {
"name": "updated_at: DateTime<Utc>", "name": "totp_backup",
"ordinal": 2, "ordinal": 13,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text" "type_info": "Text"
} }
], ],
@ -700,13 +650,15 @@
true, true,
true, true,
false, false,
false false,
true,
true
], ],
"parameters": { "parameters": {
"Right": 1 "Right": 1
} }
}, },
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone\nfrom users\n\nwhere username is (?)\n" "query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone,\n totp_secret,\n totp_backup\nfrom users\n\nwhere id is (?)\n"
}, },
"7b7f2430b2a719b3d5ce504c0a9302731b3ff82da99ba7771c2728d88aee642a": { "7b7f2430b2a719b3d5ce504c0a9302731b3ff82da99ba7771c2728d88aee642a": {
"describe": { "describe": {
@ -768,17 +720,7 @@
}, },
"query": "update users\n\nset password = ?\n\nwhere id is ?" "query": "update users\n\nset password = ?\n\nwhere id is ?"
}, },
"9f1885c4786f73335b4d614f562bb7cad49c91bfe7f084d8c25c6c571673ab90": { "979c7ba41dac5ea5593fc169ea95b68d2311c5ae05c1e18db43424c8ed2f2e4e": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 0
}
},
"query": "update refresh_tokens\n\nset revoked_at = CURRENT_TIMESTAMP\n\nwhere revoked_at is null"
},
"a2afd616a7d9742e5d416f308c30838ee11520d38a5812432af549a8a25b1393": {
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -840,6 +782,16 @@
"name": "timezone", "name": "timezone",
"ordinal": 11, "ordinal": 11,
"type_info": "Text" "type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
} }
], ],
"nullable": [ "nullable": [
@ -854,13 +806,121 @@
true, true,
true, true,
false, false,
false false,
true,
true
], ],
"parameters": { "parameters": {
"Right": 0 "Right": 0
} }
}, },
"query": "select u.id,\n u.created_at as \"created_at: DateTime<Utc>\",\n u.updated_at as \"updated_at: DateTime<Utc>\",\n u.is_admin as \"is_admin: bool\",\n u.username,\n u.name,\n u.email,\n u.password,\n u.password_recover,\n u.paper_key,\n u.is_archived as \"is_archived: bool\",\n u.timezone\nfrom users u\n\n inner join settings s on u.id = s.first_admin\n\nwhere u.is_admin is 1\n and u.is_archived is 0\n and u.id is s.first_admin\n\nlimit 1" "query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone,\n totp_secret,\n totp_backup\nfrom users\n\norder by created_at desc\n"
},
"9dc379b0f3a3c944a33ef01dc40489b29b2a61b9f73f6ca4b5df7e9fb9bccf90": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "created_at: DateTime<Utc>",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "updated_at: DateTime<Utc>",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false,
true,
true
],
"parameters": {
"Right": 0
}
},
"query": "select u.id,\n u.created_at as \"created_at: DateTime<Utc>\",\n u.updated_at as \"updated_at: DateTime<Utc>\",\n u.is_admin as \"is_admin: bool\",\n u.username,\n u.name,\n u.email,\n u.password,\n u.password_recover,\n u.paper_key,\n u.is_archived as \"is_archived: bool\",\n u.timezone,\n u.totp_secret,\n u.totp_backup\nfrom users u\n\n inner join settings s on u.id = s.first_admin\n\nwhere u.is_admin is 1\n and u.is_archived is 0\n and u.id is s.first_admin\n\nlimit 1"
},
"9f1885c4786f73335b4d614f562bb7cad49c91bfe7f084d8c25c6c571673ab90": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 0
}
},
"query": "update refresh_tokens\n\nset revoked_at = CURRENT_TIMESTAMP\n\nwhere revoked_at is null"
}, },
"a55b17a3a70e6445517f19536220f0dafc78a0e8b69221dee4715f84841839da": { "a55b17a3a70e6445517f19536220f0dafc78a0e8b69221dee4715f84841839da": {
"describe": { "describe": {
@ -882,6 +942,16 @@
}, },
"query": "update settings\n\nset first_admin = ?\n\nwhere id is 0\n" "query": "update settings\n\nset first_admin = ?\n\nwhere id is 0\n"
}, },
"afc08ba1fd47656c7d987e3817941004f988e683d28df2f533ff6272bc71b356": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 2
}
},
"query": "update users\n\nset totp_secret = ?\n\nwhere id is ?"
},
"b3936ae237f02cc048ca084372f7975921c79aef8fcd6d15a4d63c10f2377d24": { "b3936ae237f02cc048ca084372f7975921c79aef8fcd6d15a4d63c10f2377d24": {
"describe": { "describe": {
"columns": [], "columns": [],
@ -892,6 +962,16 @@
}, },
"query": "insert into refresh_tokens (token, ip_address, user, app, expires_at)\nvalues (?, ?, ?, ?, datetime(?, 'unixepoch'))\n" "query": "insert into refresh_tokens (token, ip_address, user, app, expires_at)\nvalues (?, ?, ?, ?, datetime(?, 'unixepoch'))\n"
}, },
"baaae9952348da17e2f4d099c6903c50bc90daed80ee2df1fd0dc1d9d2c67b26": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 2
}
},
"query": "update users\n\nset totp_backup = ?\n\nwhere id is ?"
},
"c00e5fce25caebdeeb24db20880e6c2210f583cddb0d478075f78124258712dd": { "c00e5fce25caebdeeb24db20880e6c2210f583cddb0d478075f78124258712dd": {
"describe": { "describe": {
"columns": [], "columns": [],
@ -922,6 +1002,198 @@
}, },
"query": "update refresh_tokens\n\nset revoked_at = CURRENT_TIMESTAMP\n\nwhere token is ?" "query": "update refresh_tokens\n\nset revoked_at = CURRENT_TIMESTAMP\n\nwhere token is ?"
}, },
"ca7d100a9440fb7854a27f9aafd91ce94d1df9fa1ccd65b549be92d16741f9d2": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "created_at: DateTime<Utc>",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "updated_at: DateTime<Utc>",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false,
true,
true
],
"parameters": {
"Right": 1
}
},
"query": "select u.id,\n u.created_at as \"created_at: DateTime<Utc>\",\n u.updated_at as \"updated_at: DateTime<Utc>\",\n u.is_admin as \"is_admin: bool\",\n u.username,\n u.name,\n u.email,\n u.password,\n u.password_recover,\n u.paper_key,\n u.is_archived as \"is_archived: bool\",\n u.timezone,\n u.totp_secret,\n u.totp_backup\nfrom users u\n\n inner join refresh_tokens rt on u.id = rt.user\n\nwhere rt.token is ?\n"
},
"cf12bd3112b2047f263118649ba89800509d94f3a858be99fb7ce8c8bc05d8b7": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "created_at: DateTime<Utc>",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "updated_at: DateTime<Utc>",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false,
true,
true
],
"parameters": {
"Right": 1
}
},
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone,\n totp_secret,\n totp_backup\nfrom users\n\nwhere password_recover is (?)\n"
},
"cf624c4e122477228e3bab09f7cd0dedf4776f73e7a86f19e06772a0adf83406": { "cf624c4e122477228e3bab09f7cd0dedf4776f73e7a86f19e06772a0adf83406": {
"describe": { "describe": {
"columns": [ "columns": [
@ -1012,6 +1284,102 @@
}, },
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n revoked_at as \"revoked_at: DateTime<Utc>\",\n private_der,\n public_der\n\nfrom keys\nwhere revoked_at is null\norder by created_at desc\n" "query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n revoked_at as \"revoked_at: DateTime<Utc>\",\n private_der,\n public_der\n\nfrom keys\nwhere revoked_at is null\norder by created_at desc\n"
}, },
"d6d3a401f5563ce339099ccbdedec1ac248865810cafafd5d78d6cc3f74d5237": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "created_at: DateTime<Utc>",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "updated_at: DateTime<Utc>",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false,
true,
true
],
"parameters": {
"Right": 1
}
},
"query": "select u.id,\n u.created_at as \"created_at: DateTime<Utc>\",\n u.updated_at as \"updated_at: DateTime<Utc>\",\n u.is_admin as \"is_admin: bool\",\n u.username,\n u.name,\n u.email,\n u.password,\n u.password_recover,\n u.paper_key,\n u.is_archived as \"is_archived: bool\",\n u.timezone,\n u.totp_secret,\n u.totp_backup\nfrom users u\n\n inner join authorization_codes ac on u.id = ac.user\n\nwhere ac.code is ?"
},
"d8517e5faa5292da25d21a85fcb2f676dce0f67275466566d5bbedf0f4b7f4f5": { "d8517e5faa5292da25d21a85fcb2f676dce0f67275466566d5bbedf0f4b7f4f5": {
"describe": { "describe": {
"columns": [ "columns": [
@ -1132,90 +1500,6 @@
}, },
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n label,\n redirect_uri,\n secret,\n is_confidential as \"is_confidential: bool\",\n is_archived as \"is_archived: bool\"\nfrom apps\n\nwhere id is (?)\n" "query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n label,\n redirect_uri,\n secret,\n is_confidential as \"is_confidential: bool\",\n is_archived as \"is_archived: bool\"\nfrom apps\n\nwhere id is (?)\n"
}, },
"e6d72e5ef795c6daa506d27560d6daeb36ffede94228636e2b0fa47a0855c1b2": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "created_at: DateTime<Utc>",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "updated_at: DateTime<Utc>",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false
],
"parameters": {
"Right": 1
}
},
"query": "select u.id,\n u.created_at as \"created_at: DateTime<Utc>\",\n u.updated_at as \"updated_at: DateTime<Utc>\",\n u.is_admin as \"is_admin: bool\",\n u.username,\n u.name,\n u.email,\n u.password,\n u.password_recover,\n u.paper_key,\n u.is_archived as \"is_archived: bool\",\n u.timezone\nfrom users u\n\n inner join authorization_codes ac on u.id = ac.user\n\nwhere ac.code is ?"
},
"eaf0744f65a1de803fa8cc21b67bad4bdf22760d431265cf97b911e6456b2fd8": { "eaf0744f65a1de803fa8cc21b67bad4bdf22760d431265cf97b911e6456b2fd8": {
"describe": { "describe": {
"columns": [ "columns": [
@ -1356,174 +1640,6 @@
}, },
"query": "insert into apps (id, label, redirect_uri, secret, is_confidential)\nvalues (?, ?, ?, ?, ?)\n" "query": "insert into apps (id, label, redirect_uri, secret, is_confidential)\nvalues (?, ?, ?, ?, ?)\n"
}, },
"f472d850bc00dc01a95c837f22879535d8234aa3085a0087edc79231387b4f3d": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "created_at: DateTime<Utc>",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "updated_at: DateTime<Utc>",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false
],
"parameters": {
"Right": 1
}
},
"query": "select id,\n created_at as \"created_at: DateTime<Utc>\",\n updated_at as \"updated_at: DateTime<Utc>\",\n is_admin as \"is_admin: bool\",\n username,\n name,\n email,\n password,\n password_recover,\n paper_key,\n is_archived as \"is_archived: bool\",\n timezone\nfrom users\n\nwhere email is (?)\n"
},
"f50157586b672a848294aca06fbb1b5a2d3c91ff83f7e81b42f32339bed0f35f": {
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "created_at: DateTime<Utc>",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "updated_at: DateTime<Utc>",
"ordinal": 2,
"type_info": "Text"
},
{
"name": "is_admin: bool",
"ordinal": 3,
"type_info": "Int64"
},
{
"name": "username",
"ordinal": 4,
"type_info": "Text"
},
{
"name": "name",
"ordinal": 5,
"type_info": "Text"
},
{
"name": "email",
"ordinal": 6,
"type_info": "Text"
},
{
"name": "password",
"ordinal": 7,
"type_info": "Text"
},
{
"name": "password_recover",
"ordinal": 8,
"type_info": "Text"
},
{
"name": "paper_key",
"ordinal": 9,
"type_info": "Text"
},
{
"name": "is_archived: bool",
"ordinal": 10,
"type_info": "Int64"
},
{
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
}
],
"nullable": [
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
false,
false
],
"parameters": {
"Right": 1
}
},
"query": "select u.id,\n u.created_at as \"created_at: DateTime<Utc>\",\n u.updated_at as \"updated_at: DateTime<Utc>\",\n u.is_admin as \"is_admin: bool\",\n u.username,\n u.name,\n u.email,\n u.password,\n u.password_recover,\n u.paper_key,\n u.is_archived as \"is_archived: bool\",\n u.timezone\nfrom users u\n\n inner join refresh_tokens rt on u.id = rt.user\n\nwhere rt.token is ?\n"
},
"f705411720bd037562f7e3622832262ac4c0a8fc0921fbd934d2b98146d3f413": { "f705411720bd037562f7e3622832262ac4c0a8fc0921fbd934d2b98146d3f413": {
"describe": { "describe": {
"columns": [], "columns": [],

View file

@ -17,6 +17,8 @@ pub struct Users {
pub paper_key: Option<String>, pub paper_key: Option<String>,
pub is_archived: bool, pub is_archived: bool,
pub timezone: String, pub timezone: String,
pub totp_secret: Option<Vec<u8>>,
pub totp_backup: Option<String>,
} }
impl Users { impl Users {
@ -213,4 +215,32 @@ impl Users {
Ok((query.rows_affected() == 1).then_some(())) Ok((query.rows_affected() == 1).then_some(()))
} }
pub async fn set_totp_secret(
conn: impl SqliteExecutor<'_>,
id: &str,
secret: Option<&[u8]>,
) -> Result<Option<()>, Error> {
let query: SqliteQueryResult =
sqlx::query_file!("queries/users/set_totp_secret.sql", secret, id)
.execute(conn)
.await
.map_err(handle_error)?;
Ok((query.rows_affected() == 1).then_some(()))
}
pub async fn set_totp_backup(
conn: impl SqliteExecutor<'_>,
id: &str,
backup: Option<&str>,
) -> Result<Option<()>, Error> {
let query: SqliteQueryResult =
sqlx::query_file!("queries/users/set_totp_backup.sql", backup, id)
.execute(conn)
.await
.map_err(handle_error)?;
Ok((query.rows_affected() == 1).then_some(()))
}
} }

View file

@ -27,4 +27,5 @@ jwt = { path = "../jwt" }
apps = { path = "../apps" } apps = { path = "../apps" }
authorization_codes = { path = "../authorization_codes" } authorization_codes = { path = "../authorization_codes" }
refresh_tokens = { path = "../refresh_tokens" } refresh_tokens = { path = "../refresh_tokens" }
email = { path = "../email" } email = { path = "../email" }
totp = { path = "../totp" }

View file

@ -86,3 +86,23 @@ impl From<refresh_tokens::Error> for Error {
Error::internal_server_error(e) Error::internal_server_error(e)
} }
} }
impl From<totp::Error> for Error {
fn from(e: totp::Error) -> Self {
Error::internal_server_error(e)
}
}
// std Types
impl From<String> for Error {
fn from(e: String) -> Self {
Error::internal_server_error(e)
}
}
impl From<std::time::SystemTimeError> for Error {
fn from(e: std::time::SystemTimeError) -> Self {
Error::internal_server_error(e)
}
}

View file

@ -27,6 +27,7 @@ pub enum Page {
AdminUsersList(AdminUsersList), AdminUsersList(AdminUsersList),
ForgotPassword, ForgotPassword,
ResetPassword(ResetPassword), ResetPassword(ResetPassword),
UserSecurityTotp(UserSecurityTotp),
} }
impl Page { impl Page {
@ -50,6 +51,7 @@ impl Page {
Page::AdminUsersList(_) => "pages/admin/users/list", Page::AdminUsersList(_) => "pages/admin/users/list",
Page::ForgotPassword => "pages/forgot-password", Page::ForgotPassword => "pages/forgot-password",
Page::ResetPassword(_) => "pages/reset-password", Page::ResetPassword(_) => "pages/reset-password",
Page::UserSecurityTotp(_) => "pages/settings/totp",
} }
} }
@ -73,6 +75,7 @@ impl Page {
Page::AdminUsersList(_) => "Users", Page::AdminUsersList(_) => "Users",
Page::ForgotPassword => "Forgot password", Page::ForgotPassword => "Forgot password",
Page::ResetPassword(_) => "Reset password", Page::ResetPassword(_) => "Reset password",
Page::UserSecurityTotp(_) => "Enable One-time password",
} }
} }
@ -98,6 +101,7 @@ impl Page {
Page::AdminUsersList(_) => Some(AdminMenu::Users.into()), Page::AdminUsersList(_) => Some(AdminMenu::Users.into()),
Page::ForgotPassword => None, Page::ForgotPassword => None,
Page::ResetPassword(_) => None, Page::ResetPassword(_) => None,
Page::UserSecurityTotp(_) => Some(UserMenu::Settings.into()),
} }
} }
@ -121,6 +125,7 @@ impl Page {
Page::AdminUsersList(list) => Box::new(list), Page::AdminUsersList(list) => Box::new(list),
Page::ForgotPassword => Box::new(()), Page::ForgotPassword => Box::new(()),
Page::ResetPassword(reset) => Box::new(reset), Page::ResetPassword(reset) => Box::new(reset),
Page::UserSecurityTotp(totp) => Box::new(totp),
} }
} }
} }

View file

@ -17,6 +17,8 @@ pub fn routes() -> Vec<Route> {
user_settings_security_logout_everywhere, user_settings_security_logout_everywhere,
user_settings_security_paper_key, user_settings_security_paper_key,
user_settings_security_password, user_settings_security_password,
user_settings_security_totp,
user_settings_security_totp_form,
user_settings_visual, user_settings_visual,
] ]
} }
@ -49,6 +51,7 @@ pub mod content {
pub struct UserSecuritySettings { pub struct UserSecuritySettings {
pub user: JwtClaims, pub user: JwtClaims,
pub logout_time_effective: i64, pub logout_time_effective: i64,
pub totp_enabled: bool,
} }
#[derive(Serialize)] #[derive(Serialize)]
@ -57,4 +60,13 @@ pub mod content {
pub struct UserVisualSettings { pub struct UserVisualSettings {
pub user: JwtClaims, pub user: JwtClaims,
} }
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
#[derive(Clone)]
pub struct UserSecurityTotp {
pub user: JwtClaims,
pub qr: String,
pub url: String,
}
} }

View file

@ -13,16 +13,28 @@ use rocket::time::Duration;
use rocket::{get, post}; use rocket::{get, post};
use settings::Settings; use settings::Settings;
use std::net::IpAddr; use std::net::IpAddr;
use url::Url;
use users::User; use users::User;
#[get("/settings/security")] #[get("/settings/security")]
pub async fn user_settings_security( pub async fn user_settings_security(
mut db: Connection<Database>,
jwt_user: JwtUser, jwt_user: JwtUser,
flash: Option<FlashMessage<'_>>, flash: Option<FlashMessage<'_>>,
) -> Result<Template> { ) -> Result<Template> {
let mut transaction = db.begin().await?;
// Get user info
let user = User::get_by_login(&mut transaction, &jwt_user.0.subject)
.await?
.ok_or_else(|| Error::not_found("Could not find user"))?;
transaction.commit().await?;
let page = Page::UserSecuritySettings(super::content::UserSecuritySettings { let page = Page::UserSecuritySettings(super::content::UserSecuritySettings {
user: jwt_user.0, user: jwt_user.0,
logout_time_effective: JWT_DURATION_MINUTES, logout_time_effective: JWT_DURATION_MINUTES,
totp_enabled: user.is_totp_enabled(),
}); });
Ok(flash Ok(flash
@ -216,3 +228,173 @@ pub async fn user_settings_security_password(
flash_message, flash_message,
)) ))
} }
const TOTP_COOKIE_NAME: &str = "totp";
#[get("/settings/security/totp")]
pub async fn user_settings_security_totp(
jwt_user: JwtUser,
mut db: Connection<Database>,
flash: Option<FlashMessage<'_>>,
cookie_jar: &CookieJar<'_>,
) -> Result<Template> {
let mut transaction = db.begin().await?;
// Get settings
let settings = Settings::get(&mut transaction).await?;
// Get issuer
let issuer = settings
.url()
.map(Url::parse)
.transpose()?
.and_then(|url| url.host_str().map(|res| res.to_string()))
.ok_or_else(|| Error::internal_server_error("Failed to get issuer for totp"))?;
transaction.commit().await?;
// Get secret from cookie
let secret = cookie_jar
.get(TOTP_COOKIE_NAME)
.map(|cookie| totp::Secret::Encoded(cookie.value().into()))
.ok_or_else(|| Error::internal_server_error("Failed to get totp secret"))?;
let totp = totp::new(
totp::secret_to_bytes(&secret)?,
issuer,
jwt_user.0.username.to_string(),
)?;
let totp_for_qr = totp.clone();
let page = Page::UserSecurityTotp(super::content::UserSecurityTotp {
user: jwt_user.0,
qr: task::spawn_blocking(move || totp_for_qr.get_qr()).await??,
url: totp.get_url(),
});
Ok(flash
.map(|flash| Page::with_flash(page.clone(), flash))
.unwrap_or_else(|| page.into()))
}
#[derive(Debug, FromForm)]
pub struct TotpForm<'r> {
pub enable: Option<&'r str>,
pub disable: Option<&'r str>,
pub token: Option<&'r str>,
}
#[post("/settings/security/totp", data = "<form>")]
pub async fn user_settings_security_totp_form(
mut db: Connection<Database>,
jwt_user: JwtUser,
form: Form<TotpForm<'_>>,
cookie_jar: &CookieJar<'_>,
) -> Result<Flash<Redirect>> {
let enable = matches!(form.enable, Some("true"));
let disable = matches!(form.disable, Some("true"));
let mut transaction = db.begin().await?;
// Get user info
let user = User::get_by_login(&mut transaction, &jwt_user.0.subject)
.await?
.ok_or_else(|| Error::not_found("Could not find user"))?;
// Get settings
let settings = Settings::get(&mut transaction).await?;
// Get issuer
let issuer = settings
.url()
.map(Url::parse)
.transpose()?
.and_then(|url| url.host_str().map(|res| res.to_string()))
.ok_or_else(|| Error::not_found("Failed to get issuer for totp"))?;
transaction.commit().await?;
if disable {
return match user.is_totp_enabled() {
true => {
// Delete secret and backup
let mut transaction = db.begin().await?;
user.set_totp_secret(&mut transaction, None).await?;
user.set_totp_backup(&mut transaction, None).await?;
transaction.commit().await?;
Ok(Flash::new(
Redirect::to(uri!(user_settings_security)),
FlashKind::Success,
"One-time password has been disabled.",
))
}
false => Ok(Flash::new(
Redirect::to(uri!(user_settings_security)),
FlashKind::Warning,
"One-time password is not enabled.",
)),
};
}
if enable && user.is_totp_enabled() {
return Ok(Flash::new(
Redirect::to(uri!(user_settings_security)),
FlashKind::Warning,
"One-time password is already enabled.",
));
}
let secret = match cookie_jar.get(TOTP_COOKIE_NAME) {
Some(cookie) => totp::Secret::Encoded(cookie.value().into()),
None => task::spawn_blocking(totp::Secret::generate_secret).await?,
};
let totp_secret = totp::secret_to_bytes(&secret)?;
let totp = totp::new(totp_secret.clone(), issuer, user.username().to_string())?;
if let Some(token) = form.token {
return if totp.check_current(token)? {
let mut transaction = db.begin().await?;
user.set_totp_secret(&mut transaction, Some(&totp_secret))
.await?;
user.set_totp_backup(&mut transaction, None).await?;
transaction.commit().await?;
// Remove cookie
cookie_jar.remove(Cookie::named(TOTP_COOKIE_NAME));
Ok(Flash::new(
Redirect::to(uri!(user_settings_security)),
FlashKind::Success,
"One-time password has been saved.",
))
} else {
Ok(Flash::new(
Redirect::to(uri!(user_settings_security_totp)),
FlashKind::Danger,
"Wrong code. Please try again.",
))
};
}
// Store secret in cookie, used when refreshing page, or on invalid verification
let mut cookie = Cookie::new(TOTP_COOKIE_NAME, totp.get_secret_base32());
cookie.set_secure(true);
cookie.set_http_only(true);
cookie.set_same_site(SameSite::Strict);
cookie.set_max_age(Duration::minutes(15));
cookie_jar.add(cookie);
Ok(Flash::new(
Redirect::to(uri!(user_settings_security_totp)),
FlashKind::Success,
"One-time password has been generated.",
))
}

View file

@ -51,6 +51,26 @@
</div> </div>
</div> </div>
<!-- One-time password -->
<div class="mb-4">
<h3 class="card-title">One-time password (2FA)</h3>
<p class="card-subtitle">
Protect your account by requiring an additional code when you log in.</p>
<div>
{% if totp_enabled %}
<a class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#modal-disable-totp">
Disable OTP
</a>
{% else %}
<form action="./security/totp" method="post">
<button type="submit" name="enable" value="true" class="btn">
Enable OTP
</button>
</form>
{% endif %}
</div>
</div>
<!-- Paper key --> <!-- Paper key -->
<div class="mb-4"> <div class="mb-4">
<h3 class="card-title">Paper key</h3> <h3 class="card-title">Paper key</h3>
@ -207,4 +227,50 @@
</div> </div>
</div> </div>
</div> </div>
<!-- Disable totp modal -->
<div class="modal modal-blur" tabindex="-1" id="modal-disable-totp">
<div class="modal-dialog modal-sm modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-status bg-danger"></div>
<div class="modal-body text-center py-4">
<div class="text-danger mb-2">
{% include "icons/alert-triangle-large" %}
</div>
<h3>Do you want to disable One-time password?</h3>
<div class="mt-2">This will also delete your backup code.</div>
<div class="mt-2">
You will not need to enter a code when you log in, but this makes your account less secure.
</div>
</div>
<div class="modal-footer">
<div class="w-100">
<div class="row">
<div class="col">
<a href="#" class="btn w-100" data-bs-dismiss="modal">Cancel</a>
</div>
<div class="col">
<form action="./security/totp" method="post">
<button type="submit" name="disable" value="true" class="btn btn-danger w-100">
Disable OTP
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %} {% endblock content %}

View file

@ -0,0 +1,70 @@
{% extends "shell" %}
{% block content %}
<!-- Page header -->
<div class="page-header d-print-none">
<div class="container-xl">
<div class="row g-2 align-items-center">
<div class="col">
<h2 class="page-title">
Enable One-time password
</h2>
</div>
</div>
</div>
</div>
<!-- Page body -->
<div class="page-body">
<div class="container-xl">
{% if flash %}
<div class="alert alert-{{flash.0}}" role="alert">
<h4 class="alert-title">{{ flash.1 | safe }}</h4>
</div>
{% endif %}
<div class="card">
<div class="card-body">
<h2 class="mb-4">Confirm One-time password</h2>
<div>
On your device, add your one-time password by adding the following url
or by scanning the qr code bellow:
</div>
<div class="mt-2"><strong>{{ url }}</strong></div>
{% set base_64_qr = "data:image/png;base64," ~ qr %}
<img class="my-4" src="{{ base_64_qr }}" alt="qr code to add one-time password">
<div class="mt-2">
Please keep the url or the qr code safely, it will be only shown once!
</div>
<div class="mt-2">
If you lose it <strong>you will not be able to access your account</strong>!
</div>
<form action="" method="post" class="mt-4">
<label class="form-label required" for="token">Enter the code displayed on your device</label>
<input
class="form-control"
type="text"
name="token"
id="token"
inputmode="numeric"
pattern="[0-9]*"
autocomplete="one-time-code"
required
>
<button type="submit" name="enable" value="true" class="mt-2 btn btn-primary">
Enable OTP
</button>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}

8
crates/totp/Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "totp"
version = "0.0.0"
edition = "2021"
[dependencies]
totp-rs = { version = "5.0.1", features = ["qr", "gen_secret", "otpauth", "zeroize"] }
thiserror = { workspace = true }

34
crates/totp/src/lib.rs Normal file
View file

@ -0,0 +1,34 @@
use totp_rs::{Algorithm, TotpUrlError, TOTP};
pub use totp_rs::Secret;
// error
#[derive(thiserror::Error)]
// the rest
#[derive(Debug)]
pub enum Error {
#[error("Totp url error: {0}")]
Url(#[from] TotpUrlError),
#[error("Totp secret error: {0}")]
Secret(String),
}
pub fn new(secret: Vec<u8>, issuer: String, account_name: String) -> Result<TOTP, Error> {
TOTP::new(
Algorithm::SHA1,
6,
1,
30,
secret,
Some(issuer),
account_name,
)
.map_err(Error::Url)
}
pub fn secret_to_bytes(secret: &Secret) -> Result<Vec<u8>, Error> {
secret
.to_bytes()
.map_err(|e| Error::Secret(format!("{:?}", e)))
}

View file

@ -24,6 +24,8 @@ impl From<DatabaseUsers> for User {
paper_key: db.paper_key, paper_key: db.paper_key,
is_archived: db.is_archived, is_archived: db.is_archived,
timezone: db.timezone, timezone: db.timezone,
totp_secret: db.totp_secret,
totp_backup: db.totp_backup,
} }
} }
} }
@ -225,4 +227,24 @@ impl User {
Ok(()) Ok(())
} }
pub async fn set_totp_secret(
&self,
conn: impl SqliteExecutor<'_>,
secret: Option<&[u8]>,
) -> Result<(), Error> {
DatabaseUsers::set_totp_secret(conn, self.id.as_ref(), secret).await?;
Ok(())
}
pub async fn set_totp_backup(
&self,
conn: impl SqliteExecutor<'_>,
backup: Option<&str>,
) -> Result<(), Error> {
DatabaseUsers::set_totp_backup(conn, self.id.as_ref(), backup).await?;
Ok(())
}
} }

View file

@ -22,6 +22,8 @@ pub struct User {
paper_key: Option<String>, paper_key: Option<String>,
is_archived: bool, is_archived: bool,
timezone: String, timezone: String,
totp_secret: Option<Vec<u8>>,
totp_backup: Option<String>,
} }
impl User { impl User {
@ -55,4 +57,7 @@ impl User {
pub fn paper_key_hashed(&self) -> Option<&str> { pub fn paper_key_hashed(&self) -> Option<&str> {
self.paper_key.as_deref() self.paper_key.as_deref()
} }
pub fn is_totp_enabled(&self) -> bool {
self.totp_secret.is_some()
}
} }