casdoor_rust_sdk/entity/
config.rs

1// Copyright 2022 The Casdoor Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use serde_derive::Deserialize;
16use std::{fs::File, io::Read};
17
18/// CasdoorConfig is the core configuration.
19#[derive(Debug, Clone, Deserialize)]
20pub struct CasdoorConfig {
21    pub(crate) endpoint: String,
22    pub(crate) client_id: String,
23    pub(crate) client_secret: String,
24    pub(crate) certificate: String,
25    pub(crate) org_name: String,
26    pub(crate) app_name: Option<String>,
27}
28
29impl CasdoorConfig {
30    /// Create a new CasdoorConfig.
31    #[allow(dead_code)]
32    pub fn new(
33        endpoint: String,
34        client_id: String,
35        client_secret: String,
36        certificate: String,
37        org_name: String,
38        app_name: Option<String>,
39    ) -> Self {
40        CasdoorConfig {
41            endpoint,
42            client_id,
43            client_secret,
44            certificate: Self::replace_cert_to_pub_key(certificate),
45            org_name,
46            app_name,
47        }
48    }
49
50    /// Create a new CasdoorConfig from a Toml file.
51    #[allow(dead_code)]
52    pub fn from_toml(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
53        // read path file content
54        let mut file = File::open(path)?;
55        let mut content = String::new();
56        file.read_to_string(&mut content)?;
57
58        let mut conf: CasdoorConfig = toml::from_str(&content)?;
59
60        // need to convert the certificate to pem format
61        conf.certificate = Self::replace_cert_to_pub_key(conf.certificate);
62
63        Ok(conf)
64    }
65
66    fn replace_cert_to_pub_key(certificate: String) -> String {
67        certificate.replace("CERTIFICATE", "PUBLIC KEY")
68    }
69}