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
use crate::bytes_serializable::BytesSerializable;
use crate::command::CommandPayload;
use crate::error::Error;
use crate::identifier::Identifier;
use crate::users::defaults::*;
use crate::validatable::Validatable;
use bytes::BufMut;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::str::{from_utf8, FromStr};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ChangePassword {
    #[serde(skip)]
    pub user_id: Identifier,
    pub current_password: String,
    pub new_password: String,
}

impl CommandPayload for ChangePassword {}

impl Default for ChangePassword {
    fn default() -> Self {
        ChangePassword {
            user_id: Identifier::default(),
            current_password: "secret".to_string(),
            new_password: "topsecret".to_string(),
        }
    }
}

impl Validatable<Error> for ChangePassword {
    fn validate(&self) -> Result<(), Error> {
        if self.current_password.is_empty()
            || self.current_password.len() > MAX_PASSWORD_LENGTH
            || self.current_password.len() < MIN_PASSWORD_LENGTH
        {
            return Err(Error::InvalidPassword);
        }

        if self.new_password.is_empty()
            || self.new_password.len() > MAX_PASSWORD_LENGTH
            || self.new_password.len() < MIN_PASSWORD_LENGTH
        {
            return Err(Error::InvalidPassword);
        }

        Ok(())
    }
}

impl FromStr for ChangePassword {
    type Err = Error;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let parts = input.split('|').collect::<Vec<&str>>();
        if parts.len() != 3 {
            return Err(Error::InvalidCommand);
        }

        let user_id = parts[0].parse::<Identifier>()?;
        let current_password = parts[1].to_string();
        let new_password = parts[2].to_string();

        let command = ChangePassword {
            user_id,
            current_password,
            new_password,
        };
        command.validate()?;
        Ok(command)
    }
}

impl BytesSerializable for ChangePassword {
    fn as_bytes(&self) -> Vec<u8> {
        let user_id_bytes = self.user_id.as_bytes();
        let mut bytes = Vec::new();
        bytes.extend(user_id_bytes);
        #[allow(clippy::cast_possible_truncation)]
        bytes.put_u8(self.current_password.len() as u8);
        bytes.extend(self.current_password.as_bytes());
        #[allow(clippy::cast_possible_truncation)]
        bytes.put_u8(self.new_password.len() as u8);
        bytes.extend(self.new_password.as_bytes());
        bytes
    }

    fn from_bytes(bytes: &[u8]) -> Result<ChangePassword, Error> {
        if bytes.len() < 9 {
            return Err(Error::InvalidCommand);
        }

        let user_id = Identifier::from_bytes(bytes)?;
        let mut position = user_id.get_size_bytes() as usize;
        let current_password_length = bytes[position];
        position += 1;
        let current_password =
            from_utf8(&bytes[position..position + current_password_length as usize])?.to_string();
        position += current_password_length as usize;
        let new_password_length = bytes[position];
        position += 1;
        let new_password =
            from_utf8(&bytes[position..position + new_password_length as usize])?.to_string();

        let command = ChangePassword {
            user_id,
            current_password,
            new_password,
        };
        command.validate()?;
        Ok(command)
    }
}

impl Display for ChangePassword {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}|{}|{}",
            self.user_id, self.current_password, self.new_password
        )
    }
}

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

    #[test]
    fn should_be_serialized_as_bytes() {
        let command = ChangePassword {
            user_id: Identifier::numeric(1).unwrap(),
            current_password: "user".to_string(),
            new_password: "secret".to_string(),
        };

        let bytes = command.as_bytes();
        let user_id = Identifier::from_bytes(&bytes).unwrap();
        let mut position = user_id.get_size_bytes() as usize;
        let current_password_length = bytes[position];
        position += 1;
        let current_password =
            from_utf8(&bytes[position..position + current_password_length as usize]).unwrap();
        position += current_password_length as usize;
        let new_password_length = bytes[position];
        position += 1;
        let new_password =
            from_utf8(&bytes[position..position + new_password_length as usize]).unwrap();

        assert!(!bytes.is_empty());
        assert_eq!(user_id, command.user_id);
        assert_eq!(current_password, command.current_password);
        assert_eq!(new_password, command.new_password);
    }

    #[test]
    fn should_be_deserialized_from_bytes() {
        let user_id = Identifier::numeric(1).unwrap();
        let current_password = "secret";
        let new_password = "topsecret";
        let mut bytes = Vec::new();
        bytes.extend(user_id.as_bytes());
        #[allow(clippy::cast_possible_truncation)]
        bytes.put_u8(current_password.len() as u8);
        bytes.extend(current_password.as_bytes());
        #[allow(clippy::cast_possible_truncation)]
        bytes.put_u8(new_password.len() as u8);
        bytes.extend(new_password.as_bytes());

        let command = ChangePassword::from_bytes(&bytes);
        assert!(command.is_ok());

        let command = command.unwrap();
        assert_eq!(command.user_id, user_id);
        assert_eq!(command.current_password, current_password);
        assert_eq!(command.new_password, new_password);
    }

    #[test]
    fn should_be_read_from_string() {
        let user_id = Identifier::numeric(1).unwrap();
        let current_password = "secret";
        let new_password = "topsecret";
        let input = format!("{user_id}|{current_password}|{new_password}");
        let command = ChangePassword::from_str(&input);
        assert!(command.is_ok());

        let command = command.unwrap();
        assert_eq!(command.user_id, user_id);
        assert_eq!(command.current_password, current_password);
        assert_eq!(command.new_password, new_password);
    }
}