//! "Sign in with NEIAM": the app's half of neiam-auth.
//!
//! Ported from neiam-htmx-neiam-auth's `src/auth/oidc.rs` (the neiam-htmx
//! template's link policy, shared by the Rust siblings). The crate verifies
//! the user at the provider; this adapter decides which local account that is
//! and starts the normal `user_sessions` session, so everything downstream
//! (`UserContext`, the middleware) is unchanged.
//!
//! Policy, in order:
//! 1. `(iss, sub)` already linked: refresh the link and sign that user in
//! (refused if the account is deactivated).
//! 2. `link=1` with a valid session: attach to the signed-in user.
//! 3. The provider has `TRUST_EMAIL`, the email is verified, and exactly one
//! active user has it (case-insensitive): attach.
//! 4. A valid invite (`invite=<token>`, email-pinned invites must match the
//! verified email), or the provider provisions this login (`PROVISION=auto`
//! or a `PROVISION_GROUPS` match): create the user with no password. A
//! taken username or email is never auto-linked or suffixed.
//! 5. Otherwise: denied.
//!
//! recourse addition: when the provider has `TRUST_EMAIL` and says the email
//! is verified, and it is the account's address, the account's email counts as
//! verified (`users.email_verified_at`). New accounts are never staff.
use std::sync::Arc;
use axum::http::{header::SET_COOKIE, request::Parts, HeaderMap, HeaderValue};
use chrono::Utc;
use neiam_auth::axum::{LinkDenied, Linker, LoginCtx};
use neiam_auth::sea_orm as links;
use neiam_auth::OidcIdentity;
use neiam_auth::Provision;
use sea_orm::sea_query::{Expr, Func};
use sea_orm::*;
use tracing::{error, info};
use crate::auth::{password, tokens, users::new_user_model};
use crate::entities::users;
use crate::Config;
/// Why the policy refused a login. The message is shown to the user.
#[derive(Debug, PartialEq, Eq)]
pub enum Refusal {
Denied(String),
Internal(String),
}
impl From<DbErr> for Refusal {
fn from(e: DbErr) -> Self {
Refusal::Internal(e.to_string())
}
}
impl From<anyhow::Error> for Refusal {
fn from(e: anyhow::Error) -> Self {
Refusal::Internal(e.to_string())
}
}
fn denied(msg: impl Into<String>) -> Refusal {
Refusal::Denied(msg.into())
}
/// "Sign in with NEIAM" -> "NEIAM", for "Link NEIAM account" and messages.
pub fn short_label(label: &str) -> String {
label.strip_prefix("Sign in with ").unwrap_or(label).to_string()
}
/// How the login resolved (logged).
#[derive(Debug, PartialEq, Eq)]
pub enum Resolved {
Existing,
LinkedToSession,
LinkedByEmail,
Created,
}
/// The provider vouches for this address: `TRUST_EMAIL` and `email_verified`.
fn trusted_email<'a>(id: &'a OidcIdentity, ctx: &LoginCtx) -> Option<&'a str> {
id.email.as_deref().filter(|_| ctx.provider.trust_email && id.email_verified)
}
/// Apply the link policy. `current` is the user of the request's existing
/// session, if any.
pub async fn resolve<C: ConnectionTrait>(
db: &C,
id: &OidcIdentity,
ctx: &LoginCtx,
current: Option<&users::Model>,
) -> Result<(users::Model, Resolved), Refusal> {
let label = short_label(&ctx.provider.label);
let label = &label;
// 1. Already linked.
if let Some(row) = links::find(db, &id.issuer, &id.sub).await? {
if ctx.link_current_session {
if let Some(cur) = current {
if cur.id != row.user_id {
return Err(denied(format!("This {label} account is already linked to another user here.")));
}
}
}
let user = users::Entity::find_by_id(row.user_id)
.one(db)
.await?
.ok_or_else(|| Refusal::Internal("linked user is missing".into()))?;
if !user.is_active {
return Err(denied("This account has been deactivated."));
}
if let Some(s) = crate::policy::suspension(&user) {
return Err(denied(crate::policy::suspension_message(&s)));
}
links::refresh(db, id).await?;
return Ok((user, Resolved::Existing));
}
// 2. Explicit link from /profile.
if ctx.link_current_session {
let Some(cur) = current else {
return Err(denied(format!(
"Sign in first, then use \"Link {label} account\" on your profile."
)));
};
if links::identity_for_user_at(db, cur.id, &id.issuer).await?.is_some() {
return Err(denied(format!("Your account is already linked to a different {label} account.")));
}
links::link(db, cur.id, id).await?;
return Ok((cur.clone(), Resolved::LinkedToSession));
}
// 3. Verified email from a trusted provider, exactly one active match.
if let Some(email) = trusted_email(id, ctx) {
let matches = users::Entity::find()
.filter(Expr::expr(Func::lower(Expr::col(users::Column::Email))).eq(email))
.filter(users::Column::IsActive.eq(true))
.limit(2)
.all(db)
.await?;
if let [user] = matches.as_slice() {
if links::identity_for_user_at(db, user.id, &id.issuer).await?.is_some() {
return Err(denied(format!(
"The account with this email is already linked to a different {label} account."
)));
}
links::link(db, user.id, id).await?;
return Ok((user.clone(), Resolved::LinkedByEmail));
}
}
// 4. Create: through an invite, or when the provider provisions this login.
let invite = match (&ctx.invite, ctx.provider.provision) {
(_, Provision::Auto) => None,
(Some(token), Provision::InviteOnly) => {
let email = id.email.as_deref().filter(|_| id.email_verified).unwrap_or("");
let t = tokens::validate_registration_token(db, token, email).await?;
Some(t.ok_or_else(|| denied("This invite is invalid, expired or for a different email address."))?)
}
(None, Provision::InviteOnly) => {
return Err(denied(format!(
"No account here is linked to this {label} account. Ask for an invite, or sign in \
with your password and use \"Link {label} account\" on your profile."
)));
}
};
let user = create_user(db, id, ctx, label).await?;
links::link(db, user.id, id).await?;
if let Some(t) = invite {
tokens::mark_registration_token_used(db, t.id, user.id).await?;
}
Ok((user, Resolved::Created))
}
async fn create_user<C: ConnectionTrait>(
db: &C,
id: &OidcIdentity,
ctx: &LoginCtx,
label: &str,
) -> Result<users::Model, Refusal> {
let Some(username) = id.username.clone() else {
return Err(denied(format!("{label} did not send a username, so no account can be created.")));
};
let Some(email) = id.email.clone() else {
return Err(denied(format!("{label} did not send an email address, so no account can be created.")));
};
let taken = users::Entity::find()
.filter(
Condition::any()
.add(users::Column::Username.eq(&username))
.add(Expr::expr(Func::lower(Expr::col(users::Column::Email))).eq(email.as_str())),
)
.one(db)
.await?;
if let Some(other) = taken {
let what = if other.username == username {
format!("named {username}")
} else {
"with this email".into()
};
return Err(denied(format!(
"An account {what} already exists. Sign in with its password and use \"Link {label} account\" on your profile."
)));
}
let verified = trusted_email(id, ctx).is_some();
let mut am = new_user_model(username, email, password::NO_PASSWORD.to_string(), false);
if verified {
am.email_verified_at = Set(Some(Utc::now().into()));
}
Ok(am.insert(db).await?)
}
/// A trusted provider's verified email that matches the account's address
/// marks that address verified.
async fn verify_by_trusted_email<C: ConnectionTrait>(
db: &C,
user: users::Model,
id: &OidcIdentity,
ctx: &LoginCtx,
) -> users::Model {
match trusted_email(id, ctx) {
Some(email) if user.email_verified_at.is_none() && user.email.eq_ignore_ascii_case(email) => {
let mut am: users::ActiveModel = user.clone().into();
am.email_verified_at = Set(Some(Utc::now().into()));
am.update(db).await.unwrap_or(user)
}
_ => user,
}
}
/// The `Linker` merged into the router in `main.rs`.
#[derive(Clone)]
pub struct AppLinker {
pub db: Arc<DatabaseConnection>,
pub config: Arc<Config>,
}
impl Linker for AppLinker {
async fn complete(&self, id: OidcIdentity, ctx: LoginCtx, parts: &Parts) -> Result<HeaderMap, LinkDenied> {
let db = self.db.as_ref();
let current = match crate::middleware::session_token_from_headers(&parts.headers) {
Some(token) if ctx.link_current_session => {
tokens::validate_session(db, &token).await.ok().flatten().map(|(u, _)| u)
}
_ => None,
};
let (user, how) = match resolve(db, &id, &ctx, current.as_ref()).await {
Ok(v) => v,
Err(Refusal::Denied(msg)) => {
info!(provider = %id.provider, sub = %id.sub, reason = %msg, "oidc login denied");
return Err(LinkDenied::forbidden(msg));
}
Err(Refusal::Internal(e)) => {
error!(provider = %id.provider, error = %e, "oidc login failed");
return Err(LinkDenied::internal("Sign-in failed. Please try again."));
}
};
info!(provider = %id.provider, user = %user.username, ?how, "oidc login");
let user = verify_by_trusted_email(db, user, &id, &ctx).await;
let mut update: users::ActiveModel = user.clone().into();
update.last_login_at = Set(Some(Utc::now().into()));
let _ = update.update(db).await;
let hours = self.config.session_duration_hours;
let session = tokens::create_session(db, user.id, hours).await.map_err(|e| {
error!(error = %e, "create session after oidc login failed");
LinkDenied::internal("Sign-in failed. Please try again.")
})?;
let cookie = crate::handlers::auth::session_cookie_value(&session.session_token, hours, self.config.secure_cookies());
let mut headers = HeaderMap::new();
headers.insert(
SET_COOKIE,
HeaderValue::from_str(&cookie).map_err(|_| LinkDenied::internal("bad cookie"))?,
);
Ok(headers)
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions running · Badges · Packages
⭐
Log in to mark this repository.
10.5 KiB · text
History
3d71adc