use std::future::Future;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use crate::api::seg;
use crate::auth::{EndUser, EndUserOAuthRequest, EndUserSignIn};
use crate::client::Client;
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EndUserProvider {
pub name: String,
pub kind: String,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct EndUserConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub providers: Vec<EndUserProvider>,
}
#[derive(Clone)]
pub struct EndUsers {
pub(crate) client: Client,
pub space_id: String,
pub app_id: String,
}
impl EndUsers {
fn path(&self, rest: &str) -> String {
format!("/v1/eu/{}/{rest}", seg(&self.space_id))
}
async fn grant(&self, path: &'static str, fields: Map<String, Value>) -> Result<EndUserSignIn> {
let (auth, space, app) = (self.client.ctx().auth.clone(), self.space_id.clone(), self.app_id.clone());
let fut =
Box::pin(async move { Ok(serde_json::to_value(auth.end_user_grant(&space, &app, path, fields).await?)?) });
let before = self.client.identity();
self.signed_in(before, self.client.run_json(fut, true).await?).await
}
async fn signed_in(&self, before: Option<String>, v: Value) -> Result<EndUserSignIn> {
let r: EndUserSignIn = serde_json::from_value(v)?;
self.client.identity_changed(before.as_deref(), Some(&format!("eu:{}", r.user.id))).await;
Ok(r)
}
async fn eu(&self, method: &'static str, path: String, body: Option<Value>) -> Result<Value> {
let auth = self.client.ctx().auth.clone();
let fut = Box::pin(async move { auth.eu_json(method, &path, body.as_ref(), vec![]).await });
self.client.run_json(fut, false).await
}
pub async fn config(&self) -> Result<EndUserConfig> {
let query = form_urlencoded::Serializer::new(String::new()).append_pair("app_id", &self.app_id).finish();
let v = self.eu("GET", self.path(&format!("config?{query}")), None).await?;
Ok(serde_json::from_value(v).unwrap_or_default())
}
pub async fn send_magic_code(&self, email: &str) -> Result<u64> {
let body = json!({ "app_id": self.app_id, "email": email });
let v = self.eu("POST", self.path("codes"), Some(body)).await?;
Ok(v.get("expires_in").and_then(Value::as_u64).unwrap_or(600))
}
pub async fn sign_in_with_magic_code(&self, email: &str, code: &str) -> Result<EndUserSignIn> {
let f = json!({ "grant_type": "magic_code", "email": email, "code": code });
self.grant("token", f.as_object().cloned().unwrap_or_default()).await
}
pub async fn sign_in_as_guest(&self) -> Result<EndUserSignIn> {
self.grant("guest", Map::new()).await
}
pub async fn sign_in_with_id_token(&self, provider: &str, id_token: &str) -> Result<EndUserSignIn> {
let f = json!({ "grant_type": "id_token", "provider": provider, "id_token": id_token });
self.grant("token", f.as_object().cloned().unwrap_or_default()).await
}
pub async fn sign_in_with_sign_in_code(&self, code: &str) -> Result<EndUserSignIn> {
let f = json!({ "grant_type": "sign_in_code", "code": code });
self.grant("token", f.as_object().cloned().unwrap_or_default()).await
}
pub fn oauth_begin(&self, provider: &str, redirect_uri: &str) -> Result<EndUserOAuthRequest> {
self.client.ctx().auth.end_user_oauth_begin(&self.space_id, &self.app_id, provider, redirect_uri)
}
pub async fn oauth_finish(&self, callback_url: &str, request: &EndUserOAuthRequest) -> Result<EndUserSignIn> {
let (auth, space, app) = (self.client.ctx().auth.clone(), self.space_id.clone(), self.app_id.clone());
let (cb, req) = (callback_url.to_string(), request.clone());
let fut =
Box::pin(
async move { Ok(serde_json::to_value(auth.end_user_oauth_finish(&space, &app, &cb, &req).await?)?) },
);
let before = self.client.identity();
self.signed_in(before, self.client.run_json(fut, true).await?).await
}
pub async fn sign_in_with_oauth<F, Fut>(
&self,
provider: &str,
redirect_uri: &str,
authorize: F,
) -> Result<EndUserSignIn>
where
F: FnOnce(String) -> Fut,
Fut: Future<Output = Result<String>>,
{
let req = self.oauth_begin(provider, redirect_uri)?;
let callback = authorize(req.url.clone()).await?;
self.oauth_finish(&callback, &req).await
}
pub fn user(&self) -> Option<EndUser> {
let s = self.client.session()?;
let eu = s.end_user?;
(eu.space_id == self.space_id).then_some(eu.user)
}
pub async fn me(&self) -> Result<EndUser> {
if self.user().is_none() {
return Err(Error::new("unauthenticated", "no end user of this space is signed in")
.with_hint("Sign in first: sign_in_as_guest(), sign_in_with_magic_code(), sign_in_with_oauth() or sign_in_with_id_token()."));
}
let (api, path) = (self.client.ctx().api.waiting(false), self.path("me"));
let v = self.client.run_json(Box::pin(async move { api.json("GET", &path, None).await }), false).await?;
let user: EndUser = serde_json::from_value(v.get("user").cloned().unwrap_or(Value::Null))?;
self.client.ctx().auth.set_end_user(user.clone())?;
Ok(user)
}
pub async fn sign_out(&self) -> Result<()> {
self.client.sign_out().await
}
}
impl std::fmt::Debug for EndUsers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EndUsers").field("space_id", &self.space_id).field("app_id", &self.app_id).finish()
}
}