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

ambee/giterated

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

Fixes

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨74f247e

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