forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

person.rs231 lines, 8.0 KiBHistoryRawDownload
1//! The person tables against the **control** database: the global account,
2//! its school memberships, and its login sessions keyed by cookie token. A
3//! person row exists once no matter how many school databases hold an
4//! `app_user` copy; the credential newtypes are [`crate::domain::user`]'s and
5//! the register-side workflow is [`crate::service::person`].
6
7use crate::constant::SESSION_DURATION_DAYS;
8use crate::database::Database;
9use crate::domain::person::{Membership, Person, PersonId, PersonSession};
10use crate::domain::session::{SessionId, SessionToken};
11use crate::domain::timestamp::Timestamp;
12use crate::domain::user::{PasswordHash, Username};
13use crate::error::AppError;
14use crate::tenant::{SchoolId, SchoolStatus};
15
16/// The raw account insert behind [`crate::service::person::create_or_load`].
17/// The unique index on `username` is the whole availability check; the loser
18/// of a race gets the same `Conflict` a sequential duplicate would.
19pub async fn create(db: &Database, person: Person) -> Result<(), AppError> {
20 match sqlx::query!(
21 "INSERT INTO person (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)",
22 person.id.uuid(),
23 person.username.as_str(),
24 person.password_hash.as_str(),
25 Timestamp::now().as_millis(),
26 )
27 .execute(db)
28 .await
29 {
30 Ok(_) => Ok(()),
31 Err(err) if crate::database::unique_violation(&err) == Some("person_username") => {
32 Err(AppError::Conflict("username already taken"))
33 }
34 Err(err) => Err(err.into()),
35 }
36}
37
38pub async fn read(db: &Database, id: &PersonId) -> Result<Option<Person>, AppError> {
39 let person = sqlx::query_as!(
40 Person,
41 r#"SELECT id AS "id: PersonId",
42 username AS "username: Username",
43 password_hash AS "password_hash: PasswordHash"
44 FROM person WHERE id = $1"#,
45 id.uuid()
46 )
47 .fetch_optional(db)
48 .await?;
49 Ok(person)
50}
51
52/// The login lookup. Usernames are stored trimmed; callers trim the same way
53/// so a padded attempt matches the canonical name.
54pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Person>, AppError> {
55 let person = sqlx::query_as!(
56 Person,
57 r#"SELECT id AS "id: PersonId",
58 username AS "username: Username",
59 password_hash AS "password_hash: PasswordHash"
60 FROM person WHERE username = $1"#,
61 username.trim()
62 )
63 .fetch_optional(db)
64 .await?;
65 Ok(person)
66}
67
68/// Every school the person belongs to, name order, with the registry's name
69/// and status joined in. Suspended schools are part of the answer — the
70/// caller decides what to offer.
71pub async fn memberships(db: &Database, person: &PersonId) -> Result<Vec<Membership>, AppError> {
72 let rows = sqlx::query_as!(
73 Membership,
74 r#"SELECT s.id AS "id: SchoolId",
75 s.name,
76 s.status AS "status: SchoolStatus"
77 FROM person_school ps
78 JOIN school s ON s.id = ps.school
79 WHERE ps.person = $1
80 ORDER BY s.name"#,
81 person.uuid()
82 )
83 .fetch_all(db)
84 .await?;
85 Ok(rows)
86}
87
88/// The person's membership in exactly one school — the `POST /auth/school`
89/// gate. An id the person does not hold is the same `None` a non-uuid is:
90/// no existence signal either way.
91pub async fn membership_of(
92 db: &Database,
93 person: &PersonId,
94 id: &SchoolId,
95) -> Result<Option<Membership>, AppError> {
96 let row = sqlx::query_as!(
97 Membership,
98 r#"SELECT s.id AS "id: SchoolId",
99 s.name,
100 s.status AS "status: SchoolStatus"
101 FROM person_school ps
102 JOIN school s ON s.id = ps.school
103 WHERE ps.person = $1 AND s.id = $2"#,
104 person.uuid(),
105 id.uuid()
106 )
107 .fetch_optional(db)
108 .await?;
109 Ok(row)
110}
111
112/// Attach a person to a school. Idempotent by the primary key: a racing or
113/// repeated join is a no-op, not an error. A school deleted mid-flight joins
114/// nothing instead of erroring, which is the honest outcome.
115pub async fn add_membership(db: &Database, person: &PersonId, id: &SchoolId) -> Result<(), AppError> {
116 sqlx::query!(
117 "INSERT INTO person_school (person, school, created_at)
118 SELECT $1, s.id, $3 FROM school s WHERE s.id = $2
119 ON CONFLICT DO NOTHING",
120 person.uuid(),
121 id.uuid(),
122 Timestamp::now().as_millis()
123 )
124 .execute(db)
125 .await?;
126 Ok(())
127}
128
129/// Active schools a registration picker may offer: id and display name,
130/// name order. Empty when none are active.
131pub async fn list_active_schools(db: &Database) -> Result<Vec<(uuid::Uuid, String)>, AppError> {
132 let rows = sqlx::query!(
133 "SELECT id, name FROM school WHERE status = 'active' ORDER BY name"
134 )
135 .fetch_all(db)
136 .await?;
137 Ok(rows.into_iter().map(|row| (row.id, row.name)).collect())
138}
139
140/// Drop every membership pointing at a school — the control-plane half of
141/// [`crate::tenant::Tenants::drop`], inside the transaction that also drops the
142/// entitlements and the registry row, so `ON DELETE NO ACTION` never refuses
143/// the registry delete and a failure leaves none of the three behind. Persons
144/// themselves survive: a person is a global account, not the school's.
145pub async fn delete_memberships_by_school(
146 exe: impl sqlx::PgExecutor<'_>,
147 school: &SchoolId,
148) -> Result<(), AppError> {
149 sqlx::query!("DELETE FROM person_school WHERE school = $1", school.uuid())
150 .execute(exe)
151 .await?;
152 Ok(())
153}
154
155/// Mint and store one person login session (the `person.` cookie).
156pub async fn create_session(db: &Database, person: &PersonId) -> Result<PersonSession, AppError> {
157 let id = SessionId::generate();
158 let token = SessionToken::generate()?;
159 let expires_at = Timestamp::in_days(SESSION_DURATION_DAYS);
160 let session = sqlx::query_as!(
161 PersonSession,
162 r#"INSERT INTO person_session (id, person, token, created_at, expires_at)
163 VALUES ($1, $2, $3, $4, $5)
164 RETURNING person AS "person: PersonId",
165 token AS "token: SessionToken",
166 expires_at AS "expires_at: Timestamp""#,
167 id.uuid(),
168 person.uuid(),
169 token.as_str(),
170 Timestamp::now().as_millis(),
171 expires_at.as_millis(),
172 )
173 .fetch_one(db)
174 .await?;
175 Ok(session)
176}
177
178pub async fn find_session_by_token(
179 db: &Database,
180 token: &str,
181) -> Result<Option<PersonSession>, AppError> {
182 let session = sqlx::query_as!(
183 PersonSession,
184 r#"SELECT person AS "person: PersonId",
185 token AS "token: SessionToken",
186 expires_at AS "expires_at: Timestamp"
187 FROM person_session WHERE token = $1"#,
188 token
189 )
190 .fetch_optional(db)
191 .await?;
192 Ok(session)
193}
194
195pub async fn delete_session_by_token(db: &Database, token: &str) -> Result<(), AppError> {
196 sqlx::query!("DELETE FROM person_session WHERE token = $1", token)
197 .execute(db)
198 .await?;
199 Ok(())
200}
201
202/// Revoke every person-login session for this account — the other half of a
203/// password reset. School sessions are deleted separately against the school
204/// database; leaving these alive would let a `person.<token>` cookie mint a
205/// new school session with the old credential.
206pub async fn delete_sessions_by_person(db: &Database, person: &PersonId) -> Result<(), AppError> {
207 sqlx::query!(
208 "DELETE FROM person_session WHERE person = $1",
209 person.uuid()
210 )
211 .execute(db)
212 .await?;
213 Ok(())
214}
215
216/// Move the person credential — the one login reads. The school-side row
217/// carries no password at all, so this is the whole credential move.
218pub async fn set_password_hash(
219 db: &Database,
220 username: &Username,
221 password_hash: &PasswordHash,
222) -> Result<(), AppError> {
223 sqlx::query!(
224 "UPDATE person SET password_hash = $2 WHERE username = $1",
225 username.as_str(),
226 password_hash.as_str()
227 )
228 .execute(db)
229 .await?;
230 Ok(())
231}