1use actix_session::{Session, SessionExt};
2use actix_web::{
3 body::EitherBody,
4 dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
5 get, post, web, Error, HttpResponse,
6};
7use arc_auth_core::{Identity, IdentityStore};
8use arc_web::{ArcAppBuilder, ArcPlugin};
9use futures_util::future::LocalBoxFuture;
10use serde::Deserialize;
11use std::{
12 future::{ready, Ready},
13 sync::{Arc, LazyLock},
14};
15use tera::{Context, Tera};
16
17static TEMPLATES: LazyLock<Tera> = LazyLock::new(|| {
18 let mut tera = Tera::default();
19 tera.add_raw_templates([
20 ("layout.html", include_str!("../templates/layout.html")),
21 ("signin.html", include_str!("../templates/signin.html")),
22 ("profile.html", include_str!("../templates/profile.html")),
23 ("users.html", include_str!("../templates/users.html")),
24 ])
25 .expect("arc-auth-session templates must be valid");
26 tera
27});
28
29fn render(name: &str, context: &Context, status: actix_web::http::StatusCode) -> HttpResponse {
30 match TEMPLATES.render(name, context) {
31 Ok(body) => HttpResponse::build(status)
32 .content_type("text/html; charset=utf-8")
33 .body(body),
34 Err(error) => HttpResponse::InternalServerError().body(error.to_string()),
35 }
36}
37
38fn signin_response(
39 session: &Session,
40 email: &str,
41 error: Option<&str>,
42 status: actix_web::http::StatusCode,
43) -> HttpResponse {
44 let mut context = Context::new();
45 context.insert(
46 "csrf_token",
47 &arc_web::helpers::csrf::get_csrf_token(session),
48 );
49 context.insert("email", email);
50 context.insert("error", &error);
51 render("signin.html", &context, status)
52}
53
54pub const IDENTITY_SESSION_KEY: &str = "arc_auth_identity";
55pub fn identity(session: &Session) -> Option<Identity> {
56 session.get(IDENTITY_SESSION_KEY).ok().flatten()
57}
58
59#[derive(Deserialize)]
60struct SignIn {
61 email: String,
62 password: String,
63 csrf_token: String,
64}
65#[post("/signin")]
66async fn signin(
67 form: web::Form<SignIn>,
68 session: Session,
69 store: web::Data<dyn IdentityStore>,
70) -> HttpResponse {
71 if !arc_web::helpers::csrf::validate_and_regenerate_csrf_token(&session, &form.csrf_token) {
72 return HttpResponse::Forbidden().finish();
73 }
74 match store.authenticate(&form.email, &form.password).await {
75 Ok(user) => {
76 cache_identity(&session, &user);
77 HttpResponse::SeeOther()
78 .insert_header(("Location", "/admin"))
79 .finish()
80 }
81 Err(_) => signin_response(
82 &session,
83 &form.email,
84 Some("Email or password was not recognized."),
85 actix_web::http::StatusCode::UNAUTHORIZED,
86 ),
87 }
88}
89async fn signin_page(session: Session) -> HttpResponse {
90 signin_response(&session, "", None, actix_web::http::StatusCode::OK)
91}
92#[derive(Deserialize)]
93struct SignOut {
94 csrf_token: String,
95}
96#[post("/signout")]
97async fn signout(form: web::Form<SignOut>, session: Session) -> HttpResponse {
98 if !arc_web::helpers::csrf::validate_and_regenerate_csrf_token(&session, &form.csrf_token) {
99 return HttpResponse::Forbidden().finish();
100 }
101 session.remove(IDENTITY_SESSION_KEY);
102 arc_web::helpers::session::clear_session_user(&session);
103 HttpResponse::SeeOther()
104 .insert_header(("Location", "/"))
105 .finish()
106}
107
108fn csrf_ok(session: &Session, token: &str) -> bool {
109 arc_web::helpers::csrf::validate_and_regenerate_csrf_token(session, token)
110}
111
112fn cache_identity(session: &Session, identity: &Identity) {
113 let _ = session.insert(IDENTITY_SESSION_KEY, identity);
114 arc_web::helpers::session::set_session_user(
115 session,
116 &arc_web::helpers::session::SessionUser {
117 id: identity.id.clone(),
118 name: identity.name.clone(),
119 email: identity.email.clone(),
120 },
121 );
122}
123#[get("/profile")]
124async fn profile(session: Session) -> HttpResponse {
125 let Some(user) = identity(&session) else {
126 return HttpResponse::Found()
127 .insert_header(("Location", "/signin"))
128 .finish();
129 };
130 profile_response(&session, &user, None, actix_web::http::StatusCode::OK)
131}
132
133fn profile_response(
134 session: &Session,
135 user: &Identity,
136 error: Option<&str>,
137 status: actix_web::http::StatusCode,
138) -> HttpResponse {
139 let mut context = Context::new();
140 context.insert(
141 "csrf_token",
142 &arc_web::helpers::csrf::get_csrf_token(session),
143 );
144 context.insert("user", user);
145 context.insert("error", &error);
146 render("profile.html", &context, status)
147}
148#[derive(Deserialize)]
149struct ProfileForm {
150 name: String,
151 email: String,
152 csrf_token: String,
153}
154#[post("/profile")]
155async fn profile_save(
156 form: web::Form<ProfileForm>,
157 session: Session,
158 store: web::Data<dyn IdentityStore>,
159) -> HttpResponse {
160 if !csrf_ok(&session, &form.csrf_token) {
161 return HttpResponse::Forbidden().finish();
162 }
163 let Some(user) = identity(&session) else {
164 return HttpResponse::Unauthorized().finish();
165 };
166 match store
167 .update_profile(&user.id, &form.name, &form.email)
168 .await
169 {
170 Ok(updated) => {
171 cache_identity(&session, &updated);
172 HttpResponse::SeeOther()
173 .insert_header(("Location", "/profile"))
174 .finish()
175 }
176 Err(e) => HttpResponse::BadRequest().body(e.to_string()),
177 }
178}
179#[derive(Deserialize)]
180struct PasswordForm {
181 current_password: String,
182 new_password: String,
183 csrf_token: String,
184}
185#[post("/profile/password")]
186async fn password_save(
187 form: web::Form<PasswordForm>,
188 session: Session,
189 store: web::Data<dyn IdentityStore>,
190) -> HttpResponse {
191 if !csrf_ok(&session, &form.csrf_token) {
192 return HttpResponse::Forbidden().finish();
193 }
194 let Some(user) = identity(&session) else {
195 return HttpResponse::Unauthorized().finish();
196 };
197 if store
198 .authenticate(&user.email, &form.current_password)
199 .await
200 .is_err()
201 {
202 return HttpResponse::Unauthorized().body("current password is incorrect");
203 }
204 match store.change_password(&user.id, &form.new_password).await {
205 Ok(()) => HttpResponse::SeeOther()
206 .insert_header(("Location", "/profile"))
207 .finish(),
208 Err(e) => HttpResponse::BadRequest().body(e.to_string()),
209 }
210}
211
212#[get("/admin/users")]
213async fn users(session: Session, store: web::Data<dyn IdentityStore>) -> HttpResponse {
214 let Some(actor) = identity(&session) else {
215 return HttpResponse::Found()
216 .insert_header(("Location", "/signin"))
217 .finish();
218 };
219 if !actor.has_role("admin") {
220 return HttpResponse::Forbidden().finish();
221 }
222 match store.list().await {
223 Ok(identities) => {
224 users_response(&session, &identities, None, actix_web::http::StatusCode::OK)
225 }
226 Err(e) => HttpResponse::InternalServerError().body(e.to_string()),
227 }
228}
229
230fn users_response(
231 session: &Session,
232 identities: &[Identity],
233 error: Option<&str>,
234 status: actix_web::http::StatusCode,
235) -> HttpResponse {
236 let mut context = Context::new();
237 context.insert("users", identities);
238 context.insert(
239 "csrf_token",
240 &arc_web::helpers::csrf::get_csrf_token(session),
241 );
242 context.insert("error", &error);
243 render("users.html", &context, status)
244}
245
246#[derive(Deserialize)]
247struct CreateUserForm {
248 name: String,
249 email: String,
250 password: String,
251 roles: String,
252 csrf_token: String,
253}
254
255#[post("/admin/users")]
256async fn user_create(
257 form: web::Form<CreateUserForm>,
258 session: Session,
259 store: web::Data<dyn IdentityStore>,
260) -> HttpResponse {
261 if !csrf_ok(&session, &form.csrf_token) {
262 return HttpResponse::Forbidden().finish();
263 }
264 let Some(actor) = identity(&session) else {
265 return HttpResponse::Unauthorized().finish();
266 };
267 if !actor.has_role("admin") {
268 return HttpResponse::Forbidden().finish();
269 }
270 let roles = form
271 .roles
272 .split(',')
273 .map(str::trim)
274 .filter(|v| !v.is_empty())
275 .map(str::to_owned)
276 .collect::<Vec<_>>();
277 match store
278 .create_user(&form.name, &form.email, &form.password, &roles)
279 .await
280 {
281 Ok(_) => HttpResponse::SeeOther()
282 .insert_header(("Location", "/admin/users"))
283 .finish(),
284 Err(error) => match store.list().await {
285 Ok(identities) => {
286 let message = error.to_string();
287 users_response(
288 &session,
289 &identities,
290 Some(&message),
291 actix_web::http::StatusCode::UNPROCESSABLE_ENTITY,
292 )
293 }
294 Err(_) => HttpResponse::InternalServerError().finish(),
295 },
296 }
297}
298#[derive(Deserialize)]
299struct RolesForm {
300 roles: String,
301 csrf_token: String,
302}
303#[post("/admin/users/{id}/roles")]
304async fn roles_save(
305 id: web::Path<String>,
306 form: web::Form<RolesForm>,
307 session: Session,
308 store: web::Data<dyn IdentityStore>,
309) -> HttpResponse {
310 if !csrf_ok(&session, &form.csrf_token) {
311 return HttpResponse::Forbidden().finish();
312 }
313 let Some(actor) = identity(&session) else {
314 return HttpResponse::Unauthorized().finish();
315 };
316 if !actor.has_role("admin") {
317 return HttpResponse::Forbidden().finish();
318 }
319 let roles = form
320 .roles
321 .split(',')
322 .map(str::trim)
323 .filter(|v| !v.is_empty())
324 .map(str::to_owned)
325 .collect::<Vec<_>>();
326 match store.set_roles(&id, &roles).await {
327 Ok(_) => HttpResponse::SeeOther()
328 .insert_header(("Location", "/admin/users"))
329 .finish(),
330 Err(e) => HttpResponse::BadRequest().body(e.to_string()),
331 }
332}
333
334pub fn routes(cfg: &mut web::ServiceConfig) {
335 cfg.route("/signin", web::get().to(signin_page))
336 .service(signin)
337 .service(signout)
338 .service(profile)
339 .service(profile_save)
340 .service(password_save)
341 .service(users)
342 .service(user_create)
343 .service(roles_save);
344}
345
346pub struct SessionAuthPlugin;
347#[async_trait::async_trait]
348impl ArcPlugin for SessionAuthPlugin {
349 fn name(&self) -> &'static str {
350 "auth-session"
351 }
352 fn register(&self, builder: ArcAppBuilder) -> ArcAppBuilder {
353 builder.register_routes(routes)
354 }
355}
356
357pub struct RequireSession;
359impl<S, B> Transform<S, ServiceRequest> for RequireSession
360where
361 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
362 S::Future: 'static,
363 B: 'static,
364{
365 type Response = ServiceResponse<EitherBody<B>>;
366 type Error = Error;
367 type InitError = ();
368 type Transform = SessionCheck<S>;
369 type Future = Ready<Result<Self::Transform, ()>>;
370 fn new_transform(&self, service: S) -> Self::Future {
371 ready(Ok(SessionCheck {
372 service: Arc::new(service),
373 }))
374 }
375}
376pub struct SessionCheck<S> {
377 service: Arc<S>,
378}
379impl<S, B> Service<ServiceRequest> for SessionCheck<S>
380where
381 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
382 S::Future: 'static,
383 B: 'static,
384{
385 type Response = ServiceResponse<EitherBody<B>>;
386 type Error = Error;
387 type Future = LocalBoxFuture<'static, Result<Self::Response, Error>>;
388 forward_ready!(service);
389 fn call(&self, req: ServiceRequest) -> Self::Future {
390 if req
391 .get_session()
392 .get::<Identity>(IDENTITY_SESSION_KEY)
393 .ok()
394 .flatten()
395 .is_none()
396 {
397 return Box::pin(async move {
398 Ok(req.into_response(
399 HttpResponse::Found()
400 .insert_header(("Location", "/signin"))
401 .finish()
402 .map_into_right_body(),
403 ))
404 });
405 }
406 let fut = self.service.call(req);
407 Box::pin(async move { fut.await.map(ServiceResponse::map_into_left_body) })
408 }
409}
410
411#[cfg(test)]
412mod tests {
413 use super::*;
414 #[test]
415 fn signin_uses_accessible_scaffold_fields_and_escapes_values() {
416 let mut context = Context::new();
417 context.insert("csrf_token", "csrf");
418 context.insert("email", "<script>alert(1)</script>");
419 context.insert("error", &Option::<String>::None);
420 let html = TEMPLATES.render("signin.html", &context).unwrap();
421 assert!(html.contains("/public/styles.css"));
422 assert!(html.contains("focused-shell"));
423 assert!(html.contains("class=\"field\""));
424 assert!(html.contains("for=\"signin-email\""));
425 assert!(!html.contains("<script>"));
426 assert!(html.contains("<script>"));
427 }
428}