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

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,
paper_key,
is_archived as "is_archived: bool",
timezone
timezone,
totp_secret,
totp_backup
from users
order by created_at desc

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -9,7 +9,9 @@ select u.id,
u.password_recover,
u.paper_key,
u.is_archived as "is_archived: bool",
u.timezone
u.timezone,
u.totp_secret,
u.totp_backup
from users u
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 ?"
},
"35de1a35e6cf6c683a1b2ca3605791aea9cbb852ac1d3df151cc21c341046361": {
"37000307a757b4912ca300c346b5bd8ee5d50331d94abeee076ae4db46215a56": {
"describe": {
"columns": [
{
@ -182,6 +182,16 @@
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
"nullable": [
@ -196,13 +206,15 @@
true,
true,
false,
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\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": {
"describe": {
@ -294,7 +306,7 @@
},
"query": "update users\n\nset username = ?\n\nwhere id is ?"
},
"56a88e7e68cfa94a055008510e3bc4389d7a7f64b43479d5fc8e4495ade0f84a": {
"5567f75b47f739e85da3469bec0202be315c42dfc820d3c37bba498b1b783811": {
"describe": {
"columns": [
{
@ -356,6 +368,16 @@
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
"nullable": [
@ -370,13 +392,15 @@
true,
true,
false,
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\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": {
"describe": {
@ -540,7 +564,7 @@
},
"query": "update users\n\nset paper_key = ?\n\nwhere id is ?"
},
"6a4a17c69175a677961779db048bff43d01e8773e7c4a6b25b9ee9b3c6fbacd5": {
"71c74369dc5d374d8ec5aa347b5f599728b74e545df3e986e3e7e66882f73ba0": {
"describe": {
"columns": [
{
@ -602,89 +626,15 @@
"name": "timezone",
"ordinal": 11,
"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>",
"ordinal": 1,
"type_info": "Text"
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"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,
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
@ -700,13 +650,15 @@
true,
true,
false,
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\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": {
"describe": {
@ -768,17 +720,7 @@
},
"query": "update users\n\nset password = ?\n\nwhere id is ?"
},
"9f1885c4786f73335b4d614f562bb7cad49c91bfe7f084d8c25c6c571673ab90": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 0
}
},
"query": "update refresh_tokens\n\nset revoked_at = CURRENT_TIMESTAMP\n\nwhere revoked_at is null"
},
"a2afd616a7d9742e5d416f308c30838ee11520d38a5812432af549a8a25b1393": {
"979c7ba41dac5ea5593fc169ea95b68d2311c5ae05c1e18db43424c8ed2f2e4e": {
"describe": {
"columns": [
{
@ -840,6 +782,16 @@
"name": "timezone",
"ordinal": 11,
"type_info": "Text"
},
{
"name": "totp_secret",
"ordinal": 12,
"type_info": "Blob"
},
{
"name": "totp_backup",
"ordinal": 13,
"type_info": "Text"
}
],
"nullable": [
@ -854,13 +806,121 @@
true,
true,
false,
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\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": {
"describe": {
@ -882,6 +942,16 @@
},
"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": {
"describe": {
"columns": [],
@ -892,6 +962,16 @@
},
"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": {
"describe": {
"columns": [],
@ -922,6 +1002,198 @@
},
"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": {
"describe": {
"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"
},
"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": {
"describe": {
"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"
},
"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": {
"describe": {
"columns": [
@ -1356,174 +1640,6 @@
},
"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": {
"describe": {
"columns": [],

View file

@ -17,6 +17,8 @@ pub struct Users {
pub paper_key: Option<String>,
pub is_archived: bool,
pub timezone: String,
pub totp_secret: Option<Vec<u8>>,
pub totp_backup: Option<String>,
}
impl Users {
@ -213,4 +215,32 @@ impl Users {
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" }
authorization_codes = { path = "../authorization_codes" }
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)
}
}
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),
ForgotPassword,
ResetPassword(ResetPassword),
UserSecurityTotp(UserSecurityTotp),
}
impl Page {
@ -50,6 +51,7 @@ impl Page {
Page::AdminUsersList(_) => "pages/admin/users/list",
Page::ForgotPassword => "pages/forgot-password",
Page::ResetPassword(_) => "pages/reset-password",
Page::UserSecurityTotp(_) => "pages/settings/totp",
}
}
@ -73,6 +75,7 @@ impl Page {
Page::AdminUsersList(_) => "Users",
Page::ForgotPassword => "Forgot password",
Page::ResetPassword(_) => "Reset password",
Page::UserSecurityTotp(_) => "Enable One-time password",
}
}
@ -98,6 +101,7 @@ impl Page {
Page::AdminUsersList(_) => Some(AdminMenu::Users.into()),
Page::ForgotPassword => None,
Page::ResetPassword(_) => None,
Page::UserSecurityTotp(_) => Some(UserMenu::Settings.into()),
}
}
@ -121,6 +125,7 @@ impl Page {
Page::AdminUsersList(list) => Box::new(list),
Page::ForgotPassword => Box::new(()),
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_paper_key,
user_settings_security_password,
user_settings_security_totp,
user_settings_security_totp_form,
user_settings_visual,
]
}
@ -49,6 +51,7 @@ pub mod content {
pub struct UserSecuritySettings {
pub user: JwtClaims,
pub logout_time_effective: i64,
pub totp_enabled: bool,
}
#[derive(Serialize)]
@ -57,4 +60,13 @@ pub mod content {
pub struct UserVisualSettings {
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 settings::Settings;
use std::net::IpAddr;
use url::Url;
use users::User;
#[get("/settings/security")]
pub async fn user_settings_security(
mut db: Connection<Database>,
jwt_user: JwtUser,
flash: Option<FlashMessage<'_>>,
) -> 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 {
user: jwt_user.0,
logout_time_effective: JWT_DURATION_MINUTES,
totp_enabled: user.is_totp_enabled(),
});
Ok(flash
@ -216,3 +228,173 @@ pub async fn user_settings_security_password(
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>
<!-- 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 -->
<div class="mb-4">
<h3 class="card-title">Paper key</h3>
@ -207,4 +227,50 @@
</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 %}

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,
is_archived: db.is_archived,
timezone: db.timezone,
totp_secret: db.totp_secret,
totp_backup: db.totp_backup,
}
}
}
@ -225,4 +227,24 @@ impl User {
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>,
is_archived: bool,
timezone: String,
totp_secret: Option<Vec<u8>>,
totp_backup: Option<String>,
}
impl User {
@ -55,4 +57,7 @@ impl User {
pub fn paper_key_hashed(&self) -> Option<&str> {
self.paper_key.as_deref()
}
pub fn is_totp_enabled(&self) -> bool {
self.totp_secret.is_some()
}
}