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
283
284
285
286
287
288
289
290
// utils.rs
// utility functions implemented here;
use rand::{thread_rng, Rng};
use bcrypt::{DEFAULT_COST, hash as bhash};
use ::log::*; // external crate for macros such as debug!, info!, so on
use std::collections::HashMap;
use std::process::Command;
use std::thread;
use regex::Regex;

use crate::messages::Msg;

pub fn generate_token() -> String {
    let token_length: usize = super::app_config("token_length").parse().unwrap();
    let characters = super::app_config("token_chars");
    let chars_len: usize = characters.as_bytes().len();
    let charset: &[u8] = characters.as_bytes();
    let mut rng = thread_rng();
    let result: String = (0..token_length).map(|_| {
        let index = rng.gen_range(0, chars_len);
        charset[index] as char
    }).collect();
    result
}   

pub fn generate_id() -> String { // for session id in web pages
    let len: usize = super::app_config("id_length").parse().unwrap();
    let chars = super::app_config("id_chars");
    let chars_len: usize = chars.as_bytes().len();
    let charset: &[u8] = chars.as_bytes();
    let mut rng = thread_rng();
    let result: String = (0..len).map(|_| {
        let index = rng.gen_range(0, chars_len);
        charset[index] as char
    }).collect();
    result
}    
pub fn hash(an_item: &str) -> String {
    bhash(an_item, DEFAULT_COST).unwrap()
}

// For example: String such as "email=test1&password=test2&repeat-password=test3" will be split
// into a hashmap; here pair separator is &, value separator is =
pub fn str_to_map(data: &str, pair_separator: char, value_separator: char) -> HashMap<String, String> {
    let pairs: Vec<&str> = data.split(|c| c == pair_separator).collect();
    debug!("Pairs are: {:?}", &pairs);
    let mut map = HashMap::new();
    for pair in pairs {
        let result: Vec<&str> = pair.split(|c| c == value_separator).collect();
        map.insert(result[0].to_string(), result[1].to_string());
    }
    debug!("Hashmap is: {:?}", &map);
    map
}


#[derive(Debug)]
pub struct Email {
    from: String,
    to: String,
    subject: String,
    body: String,
}

impl Email {
    // constructor
    pub fn new(from: &str, to: &str, subject: &str, body: &str) -> Email {
        Email { 
            from: from.to_string(), 
            to: to.to_string(), 
            subject: subject.to_string(),
            body: body.to_string()
        }
    }

    pub fn send(&self) { // email is sent, using msmtp, an SMTP Client, installed in linux machine
        let from = self.from.clone();
        let to = self.to.clone();
        let subject = self.subject.clone();
        let body = self.body.clone();
        thread::spawn(move || {
            // email message is echoed into msmtp app
            let mail_cmd = format!("echo -e 'From: {}\nSubject: {}\n\n{}' | msmtp {}", from, subject, body, to);
            let output = Command::new("sh")
                            .arg("-c")
                            .arg(mail_cmd)
                            .output()
                            .expect("failed to execute sh command echo hello!!!");
            debug!("msmtp output: {:?}", output);
        });        
    }
}

#[derive(Debug)]
pub struct Validator {}

impl Validator {
    // constructor
    pub fn validate_password(key: String) -> Vec<Msg> {
        let password = Password { key };
        password.validate_pattern()
    }
    pub fn validate_email_id_pattern(id: String) -> bool {
        let email_id = EmailID { id };
        email_id.validate_pattern()
    }
}

#[derive(Debug)]
struct EmailID {
    id: String
}

impl EmailID {
    fn validate_pattern(&self) -> bool {
        let re = Regex::new(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$");
        match re {
            Ok(re) => re.is_match(&self.id), 
            Err(error) => {
                error!("{:?} occurred in utils::EmailID::validate_pattern()", error);
                false
            }
        }
    }
}

#[derive(Debug)]
struct Password {
    key: String,
}

impl Password {

    fn validate_pattern(&self) -> Vec<Msg> { // covers password related validations
        
        let mut errors = vec![];

        if !self.has_lowercase() {
            errors.push(Msg::PasswordHasNoLowercase)  
        }
        if !self.has_uppercase() {
            errors.push(Msg::PasswordHasNoUppercase)
        }
        if !self.has_number() {
            errors.push(Msg::PasswordHasNoNumber)
        }
        if !self.has_spl_chars() {
            errors.push(Msg::PasswordHasNoSplChar)
        }
        if !self.length_ok() {
            errors.push(Msg::PasswordLengthNotOk)
        }

        errors
    }

    fn has_lowercase(&self) -> bool { // checks whether password contains at least one lowercase or not
        match Regex::new(r"^.*[a-z]+.*$") {
            Ok(re) => re.is_match(&self.key), 
            Err(error) => {
                error!("{:?} occurred in utils::Password::has_lowercase()", error);
                false
            }
        }
    }

    fn has_uppercase(&self) -> bool { // checks whether password contains at least one uppercase or not
        match Regex::new(r"^.*[A-Z]+.*$") {
            Ok(re) => re.is_match(&self.key), 
            Err(error) => {
                error!("{:?} occurred in utils::Password::has_uppercase()", error);
                false
            }
        }
    }

    fn has_number(&self) -> bool { // checks whether password contains at least one number or not
        match Regex::new(r"^.*[0-9]+.*$") {
            Ok(re) => re.is_match(&self.key), 
            Err(error) => {
                error!("{:?} occurred in utils::Password::has_number()", error);
                false
            }
        }
    }

    fn has_spl_chars(&self) -> bool { // checks whether password contains at least one special character or not
        let spl_chars = super::app_config("permitted_special_characters_in_password"); // retrieve special characters from file named settings.toml
        let re_str = r"^.*[".to_owned() + &spl_chars + "]+.*$";
        match Regex::new(&re_str) {
            Ok(re) => re.is_match(&self.key),
            Err(error) => {
                error!("{:?} occurred in utils::Password::has_spl_chars()", error);
                false
            }
        }
    }

    fn length_ok(&self) -> bool {
        let passwd_len = super::app_config("min_password_length");
        let re_str = r"^[\s\S]{".to_owned() + &passwd_len + ",}$";
        match Regex::new(&re_str) {
            Ok(re) => re.is_match(&self.key),
            Err(error) => {
                error!("{:?} occurred in utils::Password::length_ok", error);
                false
            }
        }
    }
}  // end of impl Password


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn utest_valid_email_pattern() {
        let email_id = EmailID{ id: "sample1_email@integration.test".to_string() };
        assert_eq!(email_id.validate_pattern(), true)
    }

    #[test]
    fn utest_invalid_email_pattern() {
        let email_id = EmailID{ id: "aaaa".to_string() };
        assert_eq!(email_id.validate_pattern(), false)
    }

    #[test]
    fn utest_password_contains_no_lowercase() {
        let result = Password{ key: "PASS123".to_string() }.has_lowercase();
        assert_eq!(result, false)
    }

    #[test]
    fn utest_password_contains_lowercase() {
        let result = Password{ key: "pASS123".to_string() }.has_lowercase();
        assert_eq!(result, true)
    }

    #[test]
    fn utest_password_contains_no_uppercase() {
        let result = Password{ key: "pass123".to_string() }.has_uppercase();
        assert_eq!(result, false)
    }

    #[test]
    fn utest_password_contains_uppercase() {
        let result = Password{ key: "PASS123".to_string() }.has_uppercase();
        assert_eq!(result, true)
    }

    #[test]
    fn utest_password_contains_no_number() {
        let result = Password{ key: "pass".to_string() }.has_number();
        assert_eq!(result, false)        
    }

    #[test]
    fn utest_password_contains_number() {
        let result = Password{ key: "pass2".to_string() }.has_number();
        assert_eq!(result, true)        
    }

    #[test]
    fn utest_password_length_ok() {
        let result = Password{ key: "pass1234".to_string() }.length_ok();
        assert_eq!(result, true)
    }

    #[test]
    fn utest_password_length_not_ok() {
        let result = Password{ key: "pass34".to_string() }.length_ok();
        assert_eq!(result, false)        
    }

    #[test]
    fn utest_password_contains_no_special_character() {
        let result = Password{ key: "PASS123".to_string() }.has_spl_chars();
        assert_eq!(result, false)
    }

    #[test]
    fn utest_password_contains_special_character() {
        let result = Password{ key: "pASS12*".to_string() }.has_spl_chars();
        assert_eq!(result, true)
    }

}
 // End of mod tests