added env vars

This commit is contained in:
Denys Konovalov 2021-12-17 11:10:01 +01:00
parent e82ea910ab
commit a797126f41
4 changed files with 44 additions and 10 deletions

@ -1,6 +1,6 @@
[package] [package]
name = "api" name = "api"
version = "0.9.0-dev" version = "0.9.5-dev"
edition = "2018" edition = "2018"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Denys Konovalov <denys.konovalov@protonmail.com>"] authors = ["Denys Konovalov <denys.konovalov@protonmail.com>"]

@ -5,6 +5,7 @@ use diesel::{Insertable, Queryable};
use quickxml_to_serde::{xml_string_to_json, Config}; use quickxml_to_serde::{xml_string_to_json, Config};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use serde_json::{json, Map}; use serde_json::{json, Map};
use std::env;
#[derive(Queryable, Serialize, Insertable, Deserialize, Clone)] #[derive(Queryable, Serialize, Insertable, Deserialize, Clone)]
#[table_name = "timetable"] #[table_name = "timetable"]
@ -32,8 +33,18 @@ pub struct Lesson {
async fn get_timetable_xml(url: &str) -> serde_json::value::Value { async fn get_timetable_xml(url: &str) -> serde_json::value::Value {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let resp = client let resp = client
.get(format!("{}/{}", config::TIMETABLE_URL, url)) .get(format!(
.basic_auth(config::TIMETABLE_USER, config::TIMETABLE_PASSWORD) "{}/{}",
env::var("IW_TIMETABLE_URL").unwrap_or(config::IW_TIMETABLE_URL.to_string()),
url
))
.basic_auth(
env::var("IW_TIMETABLE_USER").unwrap_or(config::IW_TIMETABLE_USER.to_string()),
Some(
env::var("IW_TIMETABLE_PASSWORD")
.unwrap_or(config::IW_TIMETABLE_PASSWORD.to_string()),
),
)
.send() .send()
.await .await
.unwrap() .unwrap()

@ -7,6 +7,7 @@ use jsonwebtoken::{encode, EncodingKey, Header};
use rocket::{response::status, serde::json::Json}; use rocket::{response::status, serde::json::Json};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use std::env;
use std::error::Error; use std::error::Error;
use std::fmt::Display; use std::fmt::Display;
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{Duration, SystemTime, UNIX_EPOCH};
@ -102,11 +103,17 @@ pub async fn get_keycloak_token(
("username", user), ("username", user),
("password", password), ("password", password),
("totp", otp), ("totp", otp),
("client_id", config::KC_CLIENT_ID.to_string()), (
"client_id",
env::var("KC_CLIENT_ID").unwrap_or(config::KC_CLIENT_ID.to_string()),
),
("grant_type", String::from("password")), ("grant_type", String::from("password")),
]; ];
let resp = client let resp = client
.post(config::KC_OPENID_TOKEN_ENDPOINT) .post(
env::var("KC_OPENID_TOKEN_ENDPOINT")
.unwrap_or(config::KC_OPENID_TOKEN_ENDPOINT.to_string()),
)
.form(&params) .form(&params)
.send() .send()
.await?; .await?;
@ -116,7 +123,10 @@ pub async fn get_keycloak_token(
pub async fn get_keycloak_userinfo(token: String) -> Result<KeycloakUser, Box<dyn Error>> { pub async fn get_keycloak_userinfo(token: String) -> Result<KeycloakUser, Box<dyn Error>> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let resp = client let resp = client
.get(config::KC_OPENID_USERINFO_ENDPOINT) .get(
env::var("KC_OPENID_USERINFO_ENDPOINT")
.unwrap_or(config::KC_OPENID_USERINFO_ENDPOINT.to_string()),
)
.header("Authorization", format!("Bearer {}", token)) .header("Authorization", format!("Bearer {}", token))
.send() .send()
.await? .await?
@ -220,7 +230,7 @@ pub async fn login(
let system_time = OffsetDateTime::now_utc(); let system_time = OffsetDateTime::now_utc();
let datetime = system_time.format("%d/%m/%Y %T"); let datetime = system_time.format("%d/%m/%Y %T");
let my_claims = Claims { let my_claims = Claims {
iss: String::from(config::JWT_ISSUER), iss: env::var("JWT_ISSUER").unwrap_or(config::JWT_ISSUER.to_string()),
user: userinfo.preferred_username, user: userinfo.preferred_username,
roles: userinfo.roles, roles: userinfo.roles,
groups: userinfo.groups, groups: userinfo.groups,
@ -237,7 +247,11 @@ pub async fn login(
let jwt = encode( let jwt = encode(
&Header::default(), &Header::default(),
&my_claims, &my_claims,
&EncodingKey::from_secret(config::JWT_SECRET.as_ref()), &EncodingKey::from_secret(
env::var("JWT_SECRET")
.unwrap_or(config::JWT_SECRET.to_string())
.as_ref(),
),
); );
Ok(Json(Token { Ok(Json(Token {
outcome: (TokenStatus::Success, String::new()), outcome: (TokenStatus::Success, String::new()),

@ -25,6 +25,7 @@ use rocket::{
}; };
use rocket_sync_db_pools::{database, diesel::PgConnection}; use rocket_sync_db_pools::{database, diesel::PgConnection};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use std::env;
#[database("timetable")] #[database("timetable")]
pub struct DbConn(PgConnection); pub struct DbConn(PgConnection);
@ -90,7 +91,11 @@ impl<'r> FromRequest<'r> for ApiKey<'r> {
}; };
let token = decode::<Claims>( let token = decode::<Claims>(
key, key,
&DecodingKey::from_secret(config::JWT_SECRET.as_ref()), &DecodingKey::from_secret(
env::var("JWT_SECRET")
.unwrap_or(config::JWT_SECRET.to_string())
.as_ref(),
),
&validation, &validation,
); );
token.is_ok() token.is_ok()
@ -110,7 +115,11 @@ impl<'r> FromRequest<'r> for ApiKey<'r> {
let teacher_permissions: Vec<String> = vec![]; let teacher_permissions: Vec<String> = vec![];
let token = decode::<Claims>( let token = decode::<Claims>(
key, key,
&DecodingKey::from_secret(config::JWT_SECRET.as_ref()), &DecodingKey::from_secret(
env::var("JWT_SECRET")
.unwrap_or(config::JWT_SECRET.to_string())
.as_ref(),
),
&validation, &validation,
); );
let token = token.unwrap(); let token = token.unwrap();