token::save() resultified, doc updated

This commit is contained in:
B. Petersen
2021-06-25 14:16:50 +02:00
committed by bjoern
parent 70e776e407
commit 15c38ba395
2 changed files with 28 additions and 21 deletions

View File

@@ -334,16 +334,16 @@ pub async fn set_config_from_qr(context: &Context, qr: &str) -> Result<(), Error
context, context,
token::Namespace::InviteNumber, token::Namespace::InviteNumber,
chat_id, chat_id,
lot.invitenumber.unwrap_or_default(), &lot.invitenumber.unwrap_or_default(),
) )
.await; .await?;
token::save( token::save(
context, context,
token::Namespace::Auth, token::Namespace::Auth,
chat_id, chat_id,
lot.auth.unwrap_or_default(), &lot.auth.unwrap_or_default(),
) )
.await; .await?;
Ok(()) Ok(())
} }
_ => bail!("qr code does not contain config: {}", qr), _ => bail!("qr code does not contain config: {}", qr),

View File

@@ -28,15 +28,13 @@ impl Default for Namespace {
} }
} }
/// Creates a new token and saves it into the database. /// Saves a token to the database.
///
/// Returns created token.
pub async fn save( pub async fn save(
context: &Context, context: &Context,
namespace: Namespace, namespace: Namespace,
foreign_id: Option<ChatId>, foreign_id: Option<ChatId>,
token: String, token: &str,
) -> String { ) -> Result<()> {
match foreign_id { match foreign_id {
Some(foreign_id) => context Some(foreign_id) => context
.sql .sql
@@ -44,21 +42,29 @@ pub async fn save(
"INSERT INTO tokens (namespc, foreign_id, token, timestamp) VALUES (?, ?, ?, ?);", "INSERT INTO tokens (namespc, foreign_id, token, timestamp) VALUES (?, ?, ?, ?);",
paramsv![namespace, foreign_id, token, time()], paramsv![namespace, foreign_id, token, time()],
) )
.await .await?,
.ok(), None => {
None => context context
.sql .sql
.execute( .execute(
"INSERT INTO tokens (namespc, token, timestamp) VALUES (?, ?, ?);", "INSERT INTO tokens (namespc, token, timestamp) VALUES (?, ?, ?);",
paramsv![namespace, token, time()], paramsv![namespace, token, time()],
) )
.await .await?
.ok(), }
}; };
token Ok(())
} }
/// Lookup most recently created token for a namespace/chat combination.
///
/// As there may be more than one valid token for a chat-id,
/// (eg. when a qr code token is withdrawn, recreated and revived later),
/// use lookup() for qr-code creation only;
/// do not use lookup() to check for token validity.
///
/// To check if a given token is valid, use exists().
pub async fn lookup( pub async fn lookup(
context: &Context, context: &Context,
namespace: Namespace, namespace: Namespace,
@@ -98,7 +104,8 @@ pub async fn lookup_or_new(
} }
let token = dc_create_id(); let token = dc_create_id();
save(context, namespace, foreign_id, token).await save(context, namespace, foreign_id, &token).await.ok();
token
} }
pub async fn exists(context: &Context, namespace: Namespace, token: &str) -> bool { pub async fn exists(context: &Context, namespace: Namespace, token: &str) -> bool {