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
#![warn(missing_docs)]
use crate::symbolgen;
/// This is the string used to check if a glyph is lowercase
const LOWERCASES: &str = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
/// This is the string used to check if a glyph is uppercase
const UPPERCASES: &str = "A B C D E F G H U J K L M N O P Q R S T U V W X Y Z";
/// This is the string used to check if a glyph qualifies as a symbol
const SYMBOLS: &str = "! \" ; # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~";
/// This is the string used to check if a glyph qualifies as a number
const NUMBERS: &str = "1 2 3 4 5 6 7 8 9 0";
/// This is the string used to check if a glyph is one which could be mistaken as another
const SIMILAR_CHARS: &str = "i l o I O 1 0 | ' ` \"";


/// A customizable password generator.
/// Options:
/// - Symbols
/// - Numbers
/// - Uppercase letters
/// - Lowercase letters
/// - Begin with a letter
/// - No similar characters (see [`no_similar_chars()`](struct.PasswordGenerator.html#method.no_similar_chars))
pub struct PasswordGenerator {
    symbols: bool,
    numbers: bool,
    uppercase: bool,
    lowercase: bool,
    begin_with_letter: bool,
    no_similar_chars: bool,
    length: usize,
}

impl PasswordGenerator {
    /// Creates a new password generator with the given length
    ///
    /// # Returns
    /// A new PasswordGenerator with all options disabled and a given length
    pub fn new(length: usize) -> PasswordGenerator {
        PasswordGenerator {
            symbols: false,
            numbers: false,
            uppercase: false,
            lowercase: false,
            begin_with_letter: false,
            no_similar_chars: false,
            length: length,
        }
    }
    /// Configure whether to have symbols inside the password
    ///
    ///
    /// The symbols list is: `!\";#$%&'()*+,-./:;<=>?@[]^_\`{|}~`
    /// # Returns
    ///
    /// This function returns a [`PasswordGenerator`](struct.PasswordGenerator.html) after modifying it
    ///
    pub fn symbols(mut self, symbols: bool) -> Self {
        self.symbols = symbols;
        self
    }

    pub fn numbers(mut self, numbers: bool) -> Self {
        self.numbers = numbers;
        self
    }

    pub fn uppercase(mut self, uppercase: bool) -> Self {
        self.uppercase = uppercase;
        self
    }

    pub fn lowercase(mut self, lowercase: bool) -> Self {
        self.lowercase = lowercase;
        self
    }

    pub fn begin_with_letter(mut self, begin_with_letter: bool) -> Self {
        self.begin_with_letter = begin_with_letter;
        self
    }

    pub fn no_similar_chars(mut self, no_similar_chars: bool) -> Self {
        self.no_similar_chars = no_similar_chars;
        self
    }

    /// Sets the length of the password to generate
    ///
    /// # Returns
    ///
    /// This function returns a [`PasswordGenerator`](struct.PasswordGenerator.html) after modifying it
    ///
    pub fn length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

    /// Generate a password based on the current configuration.
    ///
    /// # Returns
    /// `None` if the current configuration is invalid.
    pub fn generate(&self) -> Option<String> {
        if self.length == 0 {
            return None;
        }
        let mut pass_string = String::new();
        //We need to check if we want the first character to be a letter
        if self.begin_with_letter {
            if !self.uppercase && !self.lowercase {
                return None;
            }
            //We construct a limiting PasswordGenerator for our first character
            let tmp_opts = PasswordGenerator::new(0)
                .uppercase(self.uppercase)
                .lowercase(self.lowercase)
                .no_similar_chars(self.no_similar_chars);
            pass_string.push_str(symbolgen::gen_symbol(&tmp_opts.gen_dict()).as_str());
        }
        //And now we can unconditionally start adding characters
        for _ in {
            if self.begin_with_letter {
                1
            } else {
                0
            }
        }..self.length
        {
            pass_string.push_str(symbolgen::gen_symbol(&self.gen_dict()).as_str());
        }

        Some(pass_string)
    }

    fn gen_dict(&self) -> String {
        let mut valid_string = String::new();
        macro_rules! add_to_string {
            ($opt:expr, $string:ident) => {
                if $opt {
                    valid_string.push(' ');
                    valid_string.push_str($string);
                }
            };
        }
        add_to_string!(self.lowercase, LOWERCASES);
        add_to_string!(self.uppercase, UPPERCASES);
        add_to_string!(self.symbols, SYMBOLS);
        add_to_string!(self.numbers, NUMBERS);
        //And now we pull out any similar characters from it
        if self.no_similar_chars {
            valid_string = {
                let mut result = String::new();
                for c in valid_string.chars() {
                    if !SIMILAR_CHARS.contains(c) {
                        result.push(c);
                        result.push(' ');
                    }
                }
                result
            }
        }
        valid_string
    }
}

impl Default for PasswordGenerator {
    /// Default implementation of the PasswordGenerator
    ///
    /// # Returns
    /// A PasswordGenerator with all options enabled and a length of 16
    fn default() -> PasswordGenerator {
        PasswordGenerator {
            symbols: true,
            numbers: true,
            uppercase: true,
            lowercase: true,
            begin_with_letter: true,
            no_similar_chars: true,
            length: 16,
        }
    }
}

// Generate a full password.
// pub fn gen_password(opts: WordOpts) -> String {
// let mut pass_string = String::new();
// //We need to check if we want the first character to be a letter
// if opts.begin_with_letter {
//     //We construct a limiting struct for our first character
//     let tmp_opts = WordOpts {
//         length: 0,
//         symbols: false,
//         numbers: false,
//         letters: Letters {
//             lowercase: opts.letters.lowercase,
//             uppercase: opts.letters.uppercase,
//         },
//         begin_with_letter: false,
//         no_similar_chars: opts.no_similar_chars,
//     };
//     let glyph = gen_glyph(&tmp_opts);
//     pass_string.push(glyph);
// }
// //And now we can unconditionally start adding characters
// for _ in 0..opts.length {
//     pass_string.push(gen_glyph(&opts));
// }
//
// pass_string
// }

// /// Generate a random symbol given the constraints
// fn gen_glyph(opts: &WordOpts) -> char {
//We create a valid string to generate from
// let mut valid_string = String::new();
// macro_rules! add_to_string {
//     ($opt:expr, $string:ident) => {
//         if $opt {
//             valid_string.push_str($string);
//         }
//     };
// }
// add_to_string!(opts.letters.lowercase, LOWERCASES);
// add_to_string!(opts.letters.uppercase, UPPERCASES);
// add_to_string!(opts.symbols, SYMBOLS);
// add_to_string!(opts.numbers, NUMBERS);
// //And now we pull out any similar characters from it
// if opts.no_similar_chars {
//     valid_string = {
//         let mut result = String::new();
//         for c in valid_string.chars() {
//             if !SIMILAR_CHARS.contains(c) {
//                 result.push(c);
//             }
//         }
//         result
//     }
// }
// //And now we pick a random character from this string
// let rand_glyph_index = thread_rng().gen_range(0, valid_string.len());
// //And we pull that character out of the string, and return it
// valid_string.chars().nth(rand_glyph_index).unwrap()
// }