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
use super::auth::{validate_email, Auth};
use super::rand_string;
use std::borrow::Borrow;
use crate::error;
use crate::prelude::*;
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome, Request};
impl User {
/// This method allows to reset the password of a user.
/// In order for the new password to be saved, it must be passed to a [`Users`] instance.
/// This function is meant for cases where the user lost their password.
/// In case the user is authenticated,
/// you can change it more easily with [`change_password`](`super::auth::Auth::change_password`).
/// This function will fail in case the password is not secure enough.
///
/// ```rust
/// use rocket::{State, post};
/// use rocket_auth2::{Error, Users, User};
/// #[post("/reset-password/<new_password>")]
/// async fn reset_password(mut user: User, users: &State<Users>, new_password: String) -> Result<(), Error> {
/// user.set_password(&new_password);
/// users.modify(&user).await?;
/// Ok(())
/// }
/// ```
pub fn set_password(&mut self, new: &str) -> Result<(), Box<dyn std::error::Error>> {
crate::forms::is_password_secure(new)?;
let password = new.as_bytes();
let salt = rand_string(10);
let config = argon2::Config::default();
let hash = argon2::hash_encoded(password, salt.as_bytes(), &config)?;
self.password = hash;
Ok(())
}
/// Compares the password of the currently authenticated user with a another password.
/// Useful for checking password before resetting email/password.
/// To avoid bruteforcing this function should not be directly accessible from a route.
/// Additionally, it is good to implement rate limiting on routes using this function.
pub fn compare_password(&self, password: &str) -> Result<bool, argon2::Error> {
verify_encoded(&self.password, password.as_bytes())
}
/// This is an accessor function for the private `id` field.
/// This field is private, so that it is not modified by accident when updating a user.
/// ```rust
/// use rocket::{State, get};
/// use rocket_auth2::{Error, User};
/// #[get("/show-my-id")]
/// fn show_my_id(user: User) -> String {
/// format!("Your user_id is: {}", user.id())
/// }
/// ```
pub fn id(&self) -> i32 {
self.id
}
/// This is an accessor field for the private `email` field.
/// This field is private so an email cannot be updated without checking whether it is valid.
/// ```rust
/// use rocket::{State, get};
/// use rocket_auth2::{Error, User};
/// #[get("/show-my-email")]
/// fn show_my_email(user: User) -> String {
/// format!("Your user_id is: {}", user.email())
/// }
/// ```
pub fn email(&self) -> &str {
&self.email
}
/// This functions allows to easily modify the email of a user.
/// In case the input is not a valid email, it will return an error.
/// In case the user corresponds to the authenticated client, it's easier to use [`Auth::change_email`].
/// ```rust
/// # use rocket::{State, get};
/// # use rocket_auth2::{Error, Auth};
/// #[get("/set-email/<email>")]
/// async fn set_email(email: String, auth: Auth<'_>) -> Result<String, Error> {
/// let mut user = auth.get_user().await.unwrap();
/// user.set_email(email)?;
/// auth.users.modify(&user).await?;
/// Ok("Your user email was changed".into())
/// }
/// ```
pub fn set_email(&mut self, email: String) -> Result<()> {
if validate_email(&email) {
self.email = email.to_lowercase();
Ok(())
} else {
Err(Error::InvalidEmailAddressError)
}
}
pub fn is<Q>(&self, role: &Q) -> bool
where
Role: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.roles.contains(role)
}
}
use std::fmt::{self, Debug};
use std::hash::Hash;
impl Debug for User {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"User {{ id: {:?}, email: {:?}, roles: {:?}, password: \"*****\" }}",
self.id, self.email, self.roles
)
}
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for User {
type Error = Error;
async fn from_request(request: &'r Request<'_>) -> Outcome<User, Error> {
use rocket::outcome::Outcome::*;
let guard = request.guard().await;
let auth: Auth = match guard {
Success(auth) => auth,
Error(x) => return Error(x),
Forward(x) => return Forward(x),
};
if let Some(user) = auth.get_user().await {
Outcome::Success(user)
} else {
Outcome::Error((Status::Unauthorized, error::Error::UserNotFoundError))
}
}
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for AdminUser {
type Error = Error;
async fn from_request(request: &'r Request<'_>) -> Outcome<AdminUser, Error> {
use rocket::outcome::Outcome::*;
let guard = request.guard().await;
let auth: Auth = match guard {
Success(auth) => auth,
Error(x) => return Error(x),
Forward(x) => return Forward(x),
};
if let Some(user) = auth.get_user().await {
if user.is(ADMIN_ROLE) {
return Outcome::Success(AdminUser(user));
}
}
Outcome::Error((Status::Unauthorized, error::Error::UnauthorizedError))
}
}
use crate::user::roles::{Role, ADMIN_ROLE};
use argon2::verify_encoded;
use std::ops::*;
impl Deref for AdminUser {
type Target = User;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for AdminUser {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl std::convert::TryFrom<User> for AdminUser {
type Error = Error;
fn try_from(value: User) -> Result<Self> {
if value.is(ADMIN_ROLE) {
Ok(AdminUser(value))
} else {
Err(Error::UnauthorizedError)
}
}
}