11use serde:: Deserialize ;
22use std:: hash:: Hasher ;
33use json:: { object, JsonValue } ;
4+ use argon2:: { self , Config } ;
45
56#[ derive( Debug , Clone , Deserialize ) ]
67pub struct User {
78 pub name : String ,
8- pub password : String ,
9+ password_hash : String ,
910}
1011
12+ const SALT : & [ u8 ] = "fguU2N7af73!5^rD!!cZE9Z!5CK&f67yFPYRBvHM4%8UbbBNXVW-d+t7*QQwzn4c" . as_bytes ( ) ;
13+
1114impl User {
15+ pub fn new ( name : & str , password : & str ) -> Self {
16+ let config = Config :: default ( ) ;
17+ let hash = argon2:: hash_encoded ( password. as_bytes ( ) , SALT , & config) . unwrap ( ) ;
18+
19+ Self {
20+ name : String :: from ( name) ,
21+ password_hash : hash,
22+ }
23+ }
24+
1225 pub fn from_json ( json : & JsonValue ) -> Self {
1326 Self {
1427 name : String :: from ( json[ "name" ] . as_str ( ) . unwrap ( ) ) ,
15- password : String :: from ( json[ "password " ] . as_str ( ) . unwrap ( ) ) ,
28+ password_hash : String :: from ( json[ "password_hash " ] . as_str ( ) . unwrap ( ) ) ,
1629 }
1730 }
1831
1932 pub fn to_json ( self : & Self ) -> JsonValue {
2033 object ! {
2134 name: self . name. clone( ) ,
22- password : self . password . clone( ) ,
35+ password_hash : self . password_hash . clone( ) ,
2336 }
2437 }
2538
2639 pub fn verify_password ( self : & Self , password : & str ) -> bool {
27- self . password == password
40+ argon2 :: verify_encoded ( & self . password_hash , password. as_bytes ( ) ) . is_ok ( )
2841 }
2942}
3043
3144impl std:: cmp:: PartialEq for User {
3245 fn eq ( & self , other : & Self ) -> bool {
33- self . name == other. name && self . password == other. password
46+ self . name == other. name && self . password_hash == other. password_hash
3447 }
3548}
3649
@@ -39,6 +52,6 @@ impl std::cmp::Eq for User {}
3952impl std:: hash:: Hash for User {
4053 fn hash < H : Hasher > ( & self , state : & mut H ) {
4154 self . name . hash ( state) ;
42- self . password . hash ( state) ;
55+ self . password_hash . hash ( state) ;
4356 }
4457}
0 commit comments