Skip to main content

iggy_cli/commands/binary_system/
session.rs

1/* Licensed to the Apache Software Foundation (ASF) under one
2 * or more contributor license agreements.  See the NOTICE file
3 * distributed with this work for additional information
4 * regarding copyright ownership.  The ASF licenses this file
5 * to you under the Apache License, Version 2.0 (the
6 * "License"); you may not use this file except in compliance
7 * with the License.  You may obtain a copy of the License at
8 *
9 *   http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing,
12 * software distributed under the License is distributed on an
13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 * KIND, either express or implied.  See the License for the
15 * specific language governing permissions and limitations
16 * under the License.
17 */
18
19use keyring::{Entry, Result};
20
21const SESSION_TOKEN_NAME: &str = "iggy-cli-session";
22const SESSION_KEYRING_SERVICE_NAME: &str = "iggy-cli-session";
23
24pub struct ServerSession {
25    server_address: String,
26}
27
28impl ServerSession {
29    pub fn new(server_address: String) -> Self {
30        Self { server_address }
31    }
32
33    pub fn get_server_address(&self) -> &str {
34        &self.server_address
35    }
36
37    fn get_service_name(&self) -> String {
38        format!("{SESSION_KEYRING_SERVICE_NAME}:{}", self.server_address)
39    }
40
41    pub fn get_token_name(&self) -> String {
42        String::from(SESSION_TOKEN_NAME)
43    }
44
45    pub fn is_active(&self) -> bool {
46        if let Ok(entry) = Entry::new(&self.get_service_name(), &self.get_token_name()) {
47            return entry.get_password().is_ok();
48        }
49
50        false
51    }
52
53    pub fn store(&self, token: &str) -> Result<()> {
54        let entry = Entry::new(&self.get_service_name(), &self.get_token_name())?;
55        entry.set_password(token)?;
56        Ok(())
57    }
58
59    pub fn get_token(&self) -> Option<String> {
60        if let Ok(entry) = Entry::new(&self.get_service_name(), &self.get_token_name())
61            && let Ok(token) = entry.get_password()
62        {
63            return Some(token);
64        }
65
66        None
67    }
68
69    pub fn delete(&self) -> Result<()> {
70        let entry = Entry::new(&self.get_service_name(), &self.get_token_name())?;
71        entry.delete_credential()
72    }
73}