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
use std::fmt;

/// Struct to package the user identity with name and domain
#[derive(Clone, Debug)]
pub struct KrbUser
{
	pub realm: String,
	pub name: String,
}

impl KrbUser
{
	/// # Examples
	///
	/// ```
	/// let user = KrbUser::new("Username".to_string(), "DOMAIN.COM".to_string());
	/// ```
	pub fn new(name: String, realm: String) -> Self
	{
		Self { name, realm }
	}
}

impl fmt::Display for KrbUser
{
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
	{
		write!(f, "{}/{}", self.realm, self.name)
	}
}

impl TryFrom<&str> for KrbUser
{
	type Error = String;

	fn try_from(value: &str) -> Result<Self, Self::Error>
	{
		let parts: Vec<&str> = value.split(|c| ['/', '\\'].contains(&c)).collect();

		if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty()
		{
			return Err(format!("Invalid user '{}', it must be <domain>/<username>", value));
		}

		Ok(KrbUser::new(parts[1].to_string(), parts[0].to_string()))
	}
}

impl TryFrom<&String> for KrbUser
{
	type Error = String;

	fn try_from(value: &String) -> Result<Self, Self::Error>
	{
		Self::try_from(value.as_str())
	}
}

impl TryFrom<String> for KrbUser
{
	type Error = String;

	fn try_from(value: String) -> Result<Self, Self::Error>
	{
		Self::try_from(&value)
	}
}