1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::net::SocketAddr;
use std::collections::HashMap;
use std::sync::RwLock;
use std::clone::Clone;

use lazy_static::*;
use handlebars::Handlebars;
use serde_derive::{Serialize, Deserialize};
use serde_json::value::{Map, Value as Json};

mod filters;
mod handlers;
pub mod log;
mod db;
mod messages;
mod registration;
mod errors;
mod utils;
mod user_record;
mod login;


#[derive(Debug, Deserialize)]
struct Config {
    ip_address: Option<String>,
    resource_folder: Option<String>,
    cert_path: Option<String>,
    key_path: Option<String>,
    dictionary_file: Option<String>,
    messages_file: Option<String>,
    errors_file: Option<String>,
    default_language_code: Option<String>,
    default_language_name: Option<String>,
    start_separator: Option<String>,
    end_separator: Option<String>,

    db_folder: Option<String>,
    db_filename: Option<String>,
    log_folder: Option<String>,
    log_filename_prefix: Option<String>,
    log_level_on_terminal: Option<String>,
    log_level_on_write: Option<String>,

    min_password_length: Option<String>,  // due to concatenation String is preferred rather than usize or u32
    permitted_special_characters_in_password: Option<String>,

    token_length: Option<usize>,
    token_chars: Option<String>,
    token_validity_time: Option<u32>,
    token_validity_unit: Option<String>,

    id_length: Option<usize>,
    id_chars: Option<String>,
    id_validity: Option<u32>,

    email_enabled: Option<bool>,
    email_from: Option<String>,
    app_messages: Option<String>,
    app_errors: Option<String>,

    pair_separator: Option<String>,
    value_separator: Option<String>,
    
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Lang {
    pub code: String,
    pub name: String,
}

impl Lang {
    // Example: "English(en)" is answered as Lang { code: en, name: English}
    pub fn new(val: String) -> Lang { 
        let parts: Vec<&str> = val.split( '(' ).collect();
        let subparts: Vec<&str> = parts[1].split( ')' ).collect();
        Lang {
            code: subparts[0].to_string(),
            name: parts[0].to_string(),
        }
    }
}

type Dictionaries = HashMap<String, HashMap<String,String>>;

// Initialize App Settings
lazy_static!{
    static ref TEMPLATES: Handlebars<'static> = load_templates();
    static ref CONFIG: Config = load_config();
    static ref DICTIONARIES: Dictionaries = load_dictionaries();
    static ref MESSAGES: Dictionaries = load_messages();
    static ref ERRORS: Dictionaries = load_errors();
    static ref LANGUAGES: RwLock<Vec<Lang>> = RwLock::new( Vec::new() ); // initialize with empty collection
    static ref LANGUAGE_CODE: RwLock<String> = RwLock::new( default_language_code() );
    static ref SESSIONS: RwLock<HashMap<String, String>> = RwLock::new( HashMap::new() ); 
}

fn load_templates() -> Handlebars<'static> {
    let mut hb = Handlebars::new();
    let folder = CONFIG.resource_folder.as_ref().unwrap().to_owned();
    
    let mut file_path = folder.clone() + "/first_page.hbs";
    hb.register_template_file("first_page", &file_path).unwrap();
    
    file_path = folder.clone() + "/language_partial.hbs";
    hb.register_template_file("language_partial", &file_path).unwrap();
    

    file_path = folder.clone() + "/registration_page.hbs";
    hb.register_template_file("registration_page", &file_path).unwrap();

    file_path = folder.clone() + "/confirm_registration_page.hbs";
    hb.register_template_file("confirm_registration_page", &file_path).unwrap();

    file_path = folder.clone() + "/error_page.hbs";
    hb.register_template_file("error_page", &file_path).unwrap();

    file_path = folder.clone() + "/login_page.hbs";
    hb.register_template_file("login_page", &file_path).unwrap();

    file_path = folder.clone() + "/login_success_page.hbs";
    hb.register_template_file("login_success_page", &file_path).unwrap();

    file_path = folder.clone() + "/forgot_password_page.hbs";
    hb.register_template_file("forgot_password_page", &file_path).unwrap();

    file_path = folder.clone() + "/reset_password_page.hbs";
    hb.register_template_file("reset_password_page", &file_path).unwrap();

    file_path = folder.clone() + "/status_page.hbs";
    hb.register_template_file("status_page", &file_path).unwrap();
    
    hb
}

pub fn render(template_name: &str, data: &Map<String, Json>) -> String {
    TEMPLATES.render(template_name, data)
        .unwrap_or_else( |err| err.to_string() )
}

fn load_config() -> Config {
    let path = Path::new("Settings.toml");
    let display = path.display();
    let mut file = match File::open(&path) {
        Err(why) => panic!("Couldn't open {}: {}", display, why),
        Ok(file) => file,
    };
    let mut content = String::new();
    match file.read_to_string(&mut content) {
        Err(why) => panic!("Couldn't read {}: {}", display, why),
        Ok(_) => (),
    }
    let decoded: Config = toml::from_str(&content).unwrap();
    decoded 
}

fn load_dictionaries() -> Dictionaries {
    let folder = CONFIG.resource_folder.as_ref().unwrap().to_owned();
    let file_name = CONFIG.dictionary_file.as_ref().unwrap().to_owned();
    let file_path = folder + "/" + &file_name;
    load_content(&file_path)
}
fn load_messages() -> Dictionaries {
    let folder = CONFIG.resource_folder.as_ref().unwrap().to_owned();
    let file_name = CONFIG.messages_file.as_ref().unwrap().to_owned();
    let file_path = folder + "/" + &file_name;
    load_content(&file_path)
}
fn load_errors() -> Dictionaries {
    let folder = CONFIG.resource_folder.as_ref().unwrap().to_owned();
    let file_name = CONFIG.errors_file.as_ref().unwrap().to_owned();
    let file_path = folder + "/" + &file_name;
    load_content(&file_path)
}
fn load_content(file_path: &str) -> Dictionaries {
    let path = Path::new(file_path);
    if !path.exists() {
        panic!("{:?} NOT FOUND ................", &path);
    }
    let display = path.display();
    let mut file = match File::open(&path) {
        Err(why) => panic!("Couldn't open {}: {}", display, why),
        Ok(file) => file,
    };
    let mut content = String::new();
    match file.read_to_string(&mut content) {
        Err(why) => panic!("Couldn't read {}: {}...........",display, why),
        Ok(_) => (),
    }
    process(content)
}

fn process(content: String) -> Dictionaries {
    let lines = content.lines().collect::<Vec<&str>>();
    let lang_row = lines.first().unwrap().split(",").collect::<Vec<&str>>();
    let mut lang_map: Dictionaries = HashMap::new();
    let mut languages = Vec::new();
    for i in 1..lang_row.len() {
        let new_dictionary = HashMap::new();
        let lang = Lang::new( lang_row[i].to_string() );
        languages.push(lang.clone());
        lang_map.insert( lang.code, new_dictionary );
    }
    let lang_codes: Vec<String> = languages.iter().map(|each| each.code.clone()).collect();
    
    set_languages(languages);

    for row in 1..lines.len() {
        let fields: Vec<&str> = lines[row].split(",").collect();
        for i in 1..fields.len() {
            let dictionary = lang_map.get_mut( &lang_codes[i-1] ).unwrap();
            let key = fields[0].to_string();
            let value = fields[i].to_string();
            dictionary.insert( key, value);
        }
    }
    lang_map    
}

fn default_language_code() -> String {
    CONFIG.default_language_code.as_ref().unwrap().to_string()
}
pub fn language_code() -> String {
    LANGUAGE_CODE.read().unwrap().to_string()
}
pub fn set_language_code(new_lang_code: String) {
    let mut lang_code = LANGUAGE_CODE.write().unwrap();
    *lang_code = new_lang_code;
}
pub fn get_language_dictionary() -> &'static HashMap<String, String> {
    let lang_code = language_code();
    get_dictionary(&lang_code)
}

pub fn get_dictionary(lang: &str) -> &'static HashMap<String, String> {
    DICTIONARIES.get(lang).unwrap()
}

pub fn get_messages_map() -> &'static HashMap<String, String> {
    let lang_code = language_code();
    MESSAGES.get(&lang_code).unwrap()
}
pub fn get_default_messages_map() -> &'static HashMap<String, String> {
    let lang_code = default_language_code();
    MESSAGES.get(&lang_code).unwrap()
}
pub fn get_errors_map() -> &'static HashMap<String, String> {
    let lang_code = language_code();
    ERRORS.get(&lang_code).unwrap()
}


pub fn get_languages() -> Vec<Lang> {
    let langs = LANGUAGES.read().unwrap().to_vec();
    langs
}
pub fn set_languages(new_list: Vec<Lang>) {
    let mut list = LANGUAGES.write().unwrap();
    *list = new_list;    
}



#[tokio::main]
pub async fn start() {
    let conn = db::conn();
    let routes = filters::app_pages(conn);
    let ip_addr = CONFIG.ip_address.as_ref().unwrap();
    let cert_path = CONFIG.cert_path.as_ref().unwrap();
    let key_path = CONFIG.key_path.as_ref().unwrap();
    let socket_addr: SocketAddr = ip_addr.as_str().parse().unwrap();
    println!("Login App runs at: {:?}", CONFIG.ip_address);
    warp::serve(routes)
        .tls()
        .cert_path(cert_path)
        .key_path(key_path)
        .run(socket_addr)
        .await;
}