Skip to main content

grp_core/common/users/
logged.rs

1use serde_json::Value;
2
3use crate::error::structs::Error;
4use crate::common::structs::{Context, RequestType};
5use crate::common::users::structs::User;
6use crate::config::Config;
7use crate::platform::Platform;
8
9impl Platform {
10    /// # Return
11    /// a the logged user as `grp_core::structs::User`
12    /// 
13    /// # Error
14    /// a `grp_core::Error` containing the detail of the error. 
15    pub async fn get_logged_user(&self, conf: &Config) -> Result<User, Error> {
16        let context = Context {
17            request_type: RequestType::UserList,
18            owner: Some(conf.user.clone()),
19            repo: None,
20            additional: None,
21        };
22        
23        let url = match &self {
24            Platform::Github |
25            Platform::Gitlab |
26            Platform::Codeberg |
27            Platform::Forgejo |
28            Platform::Gitea => { 
29               format!("{}/user", self.get_base_url(&conf.endpoint))
30            },
31        };
32        
33        let result = self.get(url, true, conf).await?;
34        
35        let text = self.unwrap(
36            result, "Failed during fetch of logged user",
37            conf, context
38        ).await?;
39
40        let json: Value = serde_json::from_str(&text).map_err(Error::from_serde(&text))?;
41
42        let user = match &self {
43            Platform::Github =>  {
44                let name = json["login"].as_str().unwrap().to_string();
45                User { id: name.clone(), name: name.clone(), path: None }
46            },
47            Platform::Gitea |
48            Platform::Forgejo |
49            Platform::Codeberg => {
50                let name = json["login"].as_str().unwrap().to_string();
51                User { id: name.clone(), name: name.clone(), path: None }
52            },
53            Platform::Gitlab => {
54                let id = json["id"].as_u64().unwrap().to_string();
55                let name = json["username"].as_str().unwrap().to_string();
56                User { id: id.clone(), name: name.clone(), path: None }
57            },
58        };
59        
60        return Ok(user);
61    }
62}