JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Changes

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨0b2a26d

⁨src/authentication.rs⁩ - ⁨2091⁩ bytes
Raw
1 use std::{error::Error, time::SystemTime};
2
3 use chrono::Duration;
4 use jsonwebtoken::{encode, Algorithm, EncodingKey};
5 use serde::{Deserialize, Serialize};
6 use tokio::{fs::File, io::AsyncReadExt};
7 use toml::Table;
8
9 use crate::{
10 messages::authentication::{AuthenticationTokenRequest, AuthenticationTokenResponse},
11 model::{instance::Instance, user::User},
12 };
13
14 #[derive(Debug, Serialize, Deserialize)]
15 struct UserTokenMetadata {
16 user: User,
17 generated_for: Instance,
18 exp: u64,
19 }
20
21 pub struct AuthenticationTokenGranter {
22 pub config: Table,
23 }
24
25 impl AuthenticationTokenGranter {
26 pub async fn token_request(
27 &mut self,
28 request: AuthenticationTokenRequest,
29 ) -> Result<AuthenticationTokenResponse, Box<dyn Error + Send>> {
30 let secret_key = self.config["authentication"]["secret_key"]
31 .as_str()
32 .unwrap();
33 let private_key = {
34 let mut file = File::open(self.config["keys"]["private"].as_str().unwrap())
35 .await
36 .unwrap();
37
38 let mut key = vec![];
39 file.read_to_end(&mut key).await.unwrap();
40
41 key
42 };
43
44 if request.secret_key != secret_key {
45 error!("Incorrect secret key!");
46
47 panic!()
48 }
49
50 let encoding_key = EncodingKey::from_rsa_pem(&private_key).unwrap();
51
52 let claims = UserTokenMetadata {
53 user: User {
54 username: String::from("ambee"),
55 instance: Instance {
56 url: String::from("giterated.dev"),
57 },
58 },
59 generated_for: Instance {
60 url: String::from("giterated.dev"),
61 },
62 exp: (SystemTime::UNIX_EPOCH.elapsed().unwrap()
63 + std::time::Duration::from_secs(24 * 60 * 60))
64 .as_secs(),
65 };
66
67 let token = encode(
68 &jsonwebtoken::Header::new(Algorithm::RS256),
69 &claims,
70 &encoding_key,
71 )
72 .unwrap();
73
74 Ok(AuthenticationTokenResponse { token })
75 }
76 }
77