yggdrasil/src/util/structs/Token.rs

65 lines
1.9 KiB
Rust

/*
* Yggdrasil: Minecraft authentication server
* Copyright (C) 2023 0xf8.dev@proton.me
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use serde::{Deserialize, Serialize};
use structs::Account::Account;
use crate::*;
#[derive(Deserialize, Serialize, Debug)]
pub struct Token {
id: i64,
access: String,
client: String,
account: Account,
issued: i64,
expires: i64,
}
impl Token {
pub async fn from_id(db: &Database, id: i64) -> Option<Self> {
let record = sqlx::query_as!(RawToken, "SELECT * FROM tokens WHERE id = $1", id)
.fetch_one(&db.pool)
.await;
match record {
Ok(t) => Some(t.complete(db).await),
Err(_) => None,
}
}
pub fn random_token() -> String {
random_string::generate(128, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.")
}
}
pub struct RawToken {
id: i64,
access: String,
client: String,
account: i64,
issued: i64,
expires: i64
}
impl RawToken {
pub async fn complete(self, db: &Database) -> Token {
Token {
id: self.id,
access: self.access,
client: self.client,
account: Account::from_id(db, self.account).await.expect("Couldn't resolve token owner"),
issued: self.issued,
expires: self.expires,
}
}
}