about summary refs log tree commit diff
path: root/splorm/src/handler/api/auth.rs
blob: a256ffd8f04ee7c120e82fdc3618a8f345d86f35 (plain)
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
//! `/api/auth`
//!
//! Routes dealing in authentication. Routes here integrate with `knowing`,
//! which provides our authentication.

use std::time::Duration;

use axum::{Extension, body::Body, extract::State, http::StatusCode, response::Response};
use gny::web::cookie::{self, SetCookie};
use sessionhash::RequestContext;
use somethings::auth::Session;

use crate::{Query, RuntimeError, config::Settings, extractor::Wrap, state::SplormState};

/// POST /auth/register
pub async fn register(
	State(state): State<SplormState>,
	Extension(settings): Extension<Settings>,
	ctx: RequestContext,
	body: String,
) -> Result<Response, RuntimeError> {
	tracing::trace!("{ctx} GET /api/register");

	if !settings.registration_enabled() {
		return Err(RuntimeError::Generic403);
	}

	macro_rules! get {
		($query:ident $field:literal) => {
			$query
				.get_first_value($field)
				.ok_or(RuntimeError::incomplete_form($field))
		};
	}

	let query: Query = body.parse()?;
	let name = get!(query "name")?;
	let plaintext_password = get!(query "password")?.to_owned();

	let result = knowing::user_register(state.database(), name, plaintext_password).await;
	let _user = match result {
		Ok(user) => user,
		Err(knowing::Error::DatabaseError(dbe)) => return Err(dbe.into()),
		_ => unreachable!(),
	};

	tracing::info!("registered user {name}");

	Response::builder()
		.status(302)
		.header("Location", "/")
		.body(Body::from(format!("registered user {name}")))
		.map_err(|_| RuntimeError::Unknown)
}

/// POST /auth/login
pub async fn login(
	State(state): State<SplormState>,
	ctx: RequestContext,
	body: String,
) -> Result<Response, RuntimeError> {
	tracing::trace!("{ctx} GET /api/login");

	macro_rules! get {
		($query:ident $field:literal) => {
			$query
				.get_first_value($field)
				.ok_or(RuntimeError::incomplete_form($field))
		};
	}

	let query: Query = body.parse()?;
	let name = get!(query "name")?;
	let plaintext_password = get!(query "password")?.to_owned();

	let result = knowing::user_login(state.database(), name, plaintext_password).await;
	let session = match result {
		Ok(user) => user,
		Err(knowing::Error::DatabaseError(dbe)) => return Err(dbe.into()),
		Err(knowing::Error::AuthenticationFailed) => {
			return Err(RuntimeError::authentication_failed(name.to_owned()));
		}
		_ => unreachable!(),
	};

	let session_cookie = SetCookie::new("sid", session.sessionid().as_str())
		.max_age(Some(cookie::WEEK))
		.secure(true)
		.httponly(true)
		.path(Some("/"));

	tracing::info!("user {name} logged in");

	Response::builder()
		.status(302)
		.header("Location", "/")
		.header("Set-Cookie", session_cookie.as_string())
		.body(Body::from(format!("registered user {name}")))
		.map_err(|_| RuntimeError::Unknown)
}

/// POST /auth/logout
pub async fn logout(
	State(state): State<SplormState>,
	Wrap(session): Wrap<Session>,
	ctx: RequestContext,
) -> Result<Response, RuntimeError> {
	tracing::trace!("{ctx} GET /api/logout");

	let result = knowing::remove_session(state.database(), session.sessionid().as_str()).await;
	match result {
		Ok(_) => (),
		Err(knowing::Error::DatabaseError(dbe)) => return Err(dbe.into()),
		_ => unreachable!(),
	}

	let session_cookie = SetCookie::new("sid", "")
		.max_age(Some(Duration::from_secs(0)))
		.secure(true)
		.httponly(true)
		.path(Some("/"));

	tracing::info!("user {} logged out", session.user().name());

	Response::builder()
		.status(StatusCode::SEE_OTHER)
		.header("Location", "/")
		.header("Set-Cookie", session_cookie.as_string())
		.body(Body::from(format!("goodbye {}", session.user().name())))
		.map_err(|_| RuntimeError::Unknown)
}