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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use hex;
use lazy_static::lazy_static;
use rand::prelude::*;
use regex::Regex;
use std::fmt;

lazy_static! {
	#[doc(hidden)]
	pub static ref RANDOMID_PATTERN: regex::Regex = 
		Regex::new(r"^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$")
		.unwrap();
	
	#[doc(hidden)]
	pub static ref USERID_PATTERN: regex::Regex = 
		Regex::new(r"^([\p{L}\p{M}\p{N}\-_]|\.[^.])+$")
		.unwrap();

	#[doc(hidden)]
	pub static ref CONTROL_CHARS_PATTERN: regex::Regex = 
		Regex::new(r#"\p{C}"#)
		.unwrap();
	
	#[doc(hidden)]
	pub static ref DOMAIN_PATTERN: regex::Regex = 
		Regex::new(r"^([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9\-]+$")
		.unwrap();
}

/// IDType identifies the type of RandomID used
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy)]
pub enum IDType {
	WorkspaceID,
	UserID
}

/// The RandomID class is similar to v4 UUIDs. To obtain the maximum amount of entropy, all bits
/// are random and no version information is stored in them. The only null value for the RandomID
/// is all zeroes. Lastly, the only permissible format for the string version of the RandomID
/// has all letters in lowercase and dashes are placed in the same places as for UUIDs. 
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct RandomID {
	data: String
}

impl RandomID {

	/// Creates a new populated RandomID
	pub fn generate() -> RandomID {
		
		let mut rdata: [u8; 16] = [0; 16];
		rand::thread_rng().fill_bytes(&mut rdata[..]);
		let out = RandomID {
			data: format!("{}-{}-{}-{}-{}", hex::encode(&rdata[0..4]), hex::encode(&rdata[4..6]),
						hex::encode(&rdata[6..8]), hex::encode(&rdata[8..10]),
						hex::encode(&rdata[10..])) };

		out
	}

	/// Creates a RandomID from an existing string and ensures that formatting is correct.
	pub fn from(data: &str) -> Option<RandomID> {
		if !RANDOMID_PATTERN.is_match(data) {
			return None
		}

		let mut out = RandomID{ data: String::from("00000000-0000-0000-0000-000000000000")};
		out.data = data.to_lowercase();

		Some(out)
	}

	/// Returns the RandomID as a string
	pub fn as_string(&self) -> &str {
		&self.data
	}
}

impl fmt::Display for RandomID {

	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
	write!(f, "{}", self.data)
	}
}

/// A basic data type for housing Mensago user IDs. User IDs on the Mensago platform must be no
/// more than 64 ASCII characters. These characters may be from the following: lowercase a-z,
/// numbers, a dash, or an underscore. Periods may also be used so long as they are not consecutive.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct UserID {
	data: String,
	idtype: IDType
}

impl UserID {

	/// Creates a UserID from an existing string. If it contains illegal characters, it will
	/// return None. All capital letters will have their case squashed for compliance.
	pub fn from(data: &str) -> Option<UserID> {

		if data.len() > 64 || data.len() == 0 {
			return None
		}

		if !USERID_PATTERN.is_match(data) {
			return None
		}

		let mut out = UserID { data: String::from(data), idtype: IDType::UserID };
		out.data = data.to_lowercase();

		out.idtype = if RANDOMID_PATTERN.is_match(&out.data) {
			IDType::WorkspaceID
		} else {
			IDType::UserID
		};

		Some(out)
	}

	/// Creates a UserID from a workspace ID
	pub fn from_wid(wid: &RandomID) -> UserID {
		UserID {
			data: String::from(wid.as_string()),
			idtype: IDType::WorkspaceID,
		}
	}

	/// Returns the UserID as a string
	pub fn as_string(&self) -> &str {
		&self.data
	}

	/// Returns true if the UserID is also a workspace ID.
	pub fn get_type(&self) -> IDType {
		self.idtype
	}
}

impl fmt::Display for UserID {

	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
	write!(f, "{}", self.data)
	}
}


/// A basic data type for housing Internet domains.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct Domain {
	data: String
}

impl Domain {

	/// Creates a Domain from an existing string. If it contains illegal characters, it will
	/// return None. All capital letters will have their case squashed. This type exists to ensure
	/// that valid domains are used across the library
	pub fn from(data: &str) -> Option<Domain> {
		if !DOMAIN_PATTERN.is_match(data) {
			return None
		}

		let mut out = Domain { data: String::from(data) };
		out.data = data.to_lowercase();

		Some(out)
	}

	/// Returns the Domain as a string
	pub fn as_string(&self) -> &str {
		&self.data
	}
}

impl fmt::Display for Domain {

	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
	write!(f, "{}", self.data)
	}
}

/// A basic data type representing a full Mensago address. It is used to ensure passing around
/// valid data within the library.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct MAddress {
	pub uid: UserID,
	pub domain: Domain,
	address: String,
}

impl MAddress {

	/// Creates a new MAddress from a string. If the string does not contain a valid Mensago
	/// address, None will be returned.
	pub fn from(data: &str) -> Option<MAddress> {

		let parts = data.split("/").collect::<Vec<&str>>();

		if parts.len() != 2 {
			return None
		}
		
		let out = MAddress {
			uid: UserID::from(parts[0])?,
			domain: Domain::from(parts[1])?,
			address: String::from(format!("{}/{}", parts[0], parts[1])),
		};

		Some(out)
	}

	/// Creates an MAddress from its components
	pub fn from_parts(uid: &UserID, domain: &Domain) -> MAddress {
		MAddress {
			uid: uid.clone(),
			domain: domain.clone(),
			address: String::from(format!("{}/{}", uid, domain)),
		}
	}

	/// Returns the MAddress as a string
	pub fn as_string(&self) -> String {
		String::from(format!("{}/{}", self.uid, self.domain))
	}

	/// Returns the UserID portion of the address
	pub fn get_uid(&self) -> &UserID {
		&self.uid
	}

	/// Returns the Domain portion of the address
	pub fn get_domain(&self) -> &Domain {
		&self.domain
	}
}

impl fmt::Display for MAddress {

	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}/{}", self.uid, self.domain)
	}
}

/// A basic data type representing a full Mensago address. It is used to ensure passing around
/// valid data within the library.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct WAddress {
	wid: RandomID,
	domain: Domain,

	// We keep this extra copy around because converting the item to a full string is a very
	// common operation
	address: String,
}

impl WAddress {

	/// Creates a new WAddress from a string. If the string does not contain a valid workspace
	/// address, None will be returned.
	pub fn from(data: &str) -> Option<WAddress> {

		let parts = data.split("/").collect::<Vec<&str>>();

		if parts.len() != 2 {
			return None
		}
		
		let out = WAddress { 
			wid: RandomID::from(parts[0])?,
			domain: Domain::from(parts[1])?,
			address: String::from(format!("{}/{}", parts[0], parts[1])),
		};

		Some(out)
	}

	/// Creates a WAddress from its components
	pub fn from_parts(wid: &RandomID, domain: &Domain) -> WAddress {
		WAddress {
			wid: wid.clone(),
			domain: domain.clone(),
			address: String::from(format!("{}/{}", wid, domain)),
		}
	}

	/// Returns the WAddress as a string
	pub fn as_string(&self) -> String {
		String::from(format!("{}/{}", self.wid, self.domain))
	}

	/// Returns the RandomID portion of the address
	pub fn get_wid(&self) -> &RandomID {
		&self.wid
	}

	/// Returns the Domain portion of the address
	pub fn get_domain(&self) -> &Domain {
		&self.domain
	}
}

impl fmt::Display for WAddress {

	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}/{}", self.wid, self.domain)
	}
}

/// A basic data type representing an Argon2id password hash. It is used to ensure passing around
/// valid data within the library. This might someday be genericized, but for now it's fine.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct ArgonHash {
	hash: String,
	hashtype: String
}

impl ArgonHash {

	/// Creates a new ArgonHash from the provided password
	pub fn from(password: &str) -> ArgonHash {
		ArgonHash {
			hash: eznacl::hash_password(password, &eznacl::HashStrength::Basic),
			hashtype: String::from("argon2id"),
		}
	}

	/// Creates an ArgonHash object from a verified string
	pub fn from_hashstr(passhash: &str) -> ArgonHash {
		ArgonHash {
			hash: String::from(passhash),
			hashtype: String::from("argon2id"),
		}
	}

	/// Returns the object's hash string
	pub fn get_hash(&self) -> &str {
		&self.hash
	}

	/// Returns the object's hash type
	pub fn get_hashtype(&self) -> &str {
		&self.hashtype
	}
}

impl fmt::Display for ArgonHash {

	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.hash)
	}
}


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

	#[test]
	fn test_randomid() {

		let testid = RandomID::generate();
		
		let strid = RandomID::from(testid.as_string());
		assert_ne!(strid, None);
	}
	
	#[test]
	fn test_userid() {

		assert_ne!(UserID::from("valid_e-mail.123"), None);
		
		match UserID::from("11111111-1111-1111-1111-111111111111") {
			Some(v) => {
				assert!(v.get_type() == IDType::WorkspaceID)
			},
			None => {
				panic!("test_userid failed workspace ID assignment")
			}
		}

		match UserID::from("Valid.but.needs_case-squashed") {
			Some(v) => {
				assert_eq!(v.as_string(), "valid.but.needs_case-squashed")
			},
			None => {
				panic!("test_userid failed case-squashing check")
			}
		}
		
		assert_eq!(UserID::from("invalid..number1"), None);
		assert_eq!(UserID::from("invalid#2"), None);
	}

	#[test]
	fn test_domain() {

		assert_ne!(Domain::from("foo-bar.baz.com"), None);

		match Domain::from("FOO.bar.com") {
			Some(v) => {
				assert_eq!(v.as_string(), "foo.bar.com")
			},
			None => {
				panic!("test_domain failed case-squashing check")
			}
		}
		
		assert_eq!(Domain::from("a bad-id.com"), None);
		assert_eq!(Domain::from("also_bad.org"), None);
	}

	#[test]
	fn test_maddress() {
		
		assert_ne!(MAddress::from("cats4life/example.com"), None);
		assert_ne!(MAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3/example.com"), None);

		assert_eq!(MAddress::from("has spaces/example.com"), None);
		assert_eq!(MAddress::from(r#"has_a_"/example.com"#), None);
		assert_eq!(MAddress::from("\\not_allowed/example.com"), None);
		assert_eq!(MAddress::from("/example.com"), None);
		assert_eq!(MAddress::from(
			"5a56260b-aa5c-4013-9217-a78f094432c3/example.com/example.com"), None);
		assert_eq!(MAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3"), None);
	}

	#[test]
	fn test_waddress() {
		
		assert_ne!(WAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3/example.com"), None);
		assert_eq!(WAddress::from("cats4life/example.com"), None);
	}
}