use serde::Deserialize;
use crate::native::{
apple_credential_state_native_async, apple_sign_in_native_async, apple_sign_in_native_support,
};
use crate::{AuthError, Support, crypto};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AppleScope {
FullName,
Email,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use]
pub struct SignInWithApple {
scopes: Vec<AppleScope>,
nonce: Option<String>,
state: Option<String>,
}
impl SignInWithApple {
pub fn new() -> Self {
SignInWithApple {
scopes: vec![AppleScope::FullName, AppleScope::Email],
nonce: None,
state: None,
}
}
pub fn scopes(mut self, scopes: impl IntoIterator<Item = AppleScope>) -> Self {
self.scopes = scopes.into_iter().collect();
self
}
pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
self.nonce = Some(nonce.into());
self
}
pub fn state(mut self, state: impl Into<String>) -> Self {
self.state = Some(state.into());
self
}
}
impl Default for SignInWithApple {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RealUserStatus {
Unsupported,
Unknown,
LikelyReal,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AppleCredential {
pub user: String,
pub identity_token: String,
pub authorization_code: String,
pub email: Option<String>,
pub given_name: Option<String>,
pub family_name: Option<String>,
pub real_user_status: RealUserStatus,
pub nonce: String,
pub hashed_nonce: String,
pub state: Option<String>,
}
#[derive(Deserialize)]
struct Answer {
user: String,
#[serde(rename = "identityToken")]
identity_token: String,
#[serde(rename = "authorizationCode")]
authorization_code: String,
#[serde(default)]
email: Option<String>,
#[serde(default, rename = "givenName")]
given_name: Option<String>,
#[serde(default, rename = "familyName")]
family_name: Option<String>,
#[serde(default, rename = "realUserStatus")]
real_user_status: i32,
#[serde(default)]
state: Option<String>,
}
pub fn support() -> Support {
if cfg!(any(target_os = "ios", target_os = "macos")) {
apple_sign_in_native_support()
} else {
Support::Unsupported
}
}
pub fn sign_in(
request: SignInWithApple,
) -> impl std::future::Future<Output = Result<AppleCredential, AuthError>> + Send {
let (tx, rx) = day_async::oneshot();
start(request, Box::new(move |answer| tx.send(answer)));
async move { rx.await.unwrap_or(Err(AuthError::Cancelled)) }
}
fn start(
request: SignInWithApple,
on_done: Box<dyn FnOnce(Result<AppleCredential, AuthError>) + Send>,
) {
if support() == Support::Unsupported {
on_done(Err(AuthError::Unsupported));
return;
}
let nonce = match request.nonce {
Some(n) => n,
None => match crypto::random_token(32) {
Ok(n) => n,
Err(e) => {
on_done(Err(e));
return;
}
},
};
let hashed_nonce = crypto::base64url(&crypto::sha256(nonce.as_bytes()));
let request_nonce = crypto::hex(&crypto::sha256(nonce.as_bytes()));
let scopes: Vec<&str> = request
.scopes
.iter()
.map(|s| match s {
AppleScope::FullName => "fullName",
AppleScope::Email => "email",
})
.collect();
let state = request.state.clone();
let state_arg = state.clone().unwrap_or_default();
let scopes = scopes.join(",");
let _ = apple_sign_in_native_async(&scopes, &request_nonce, &state_arg, move |answer| {
on_done(match answer {
Ok(text) if text == "cancelled" => Err(AuthError::Cancelled),
Ok(text) if text == "unsupported" => Err(AuthError::Unsupported),
Ok(text) if text.starts_with("error:") => {
Err(AuthError::Platform(text[6..].to_string()))
}
Ok(json) => match serde_json::from_str::<Answer>(&json) {
Ok(a) => Ok(AppleCredential {
user: a.user,
identity_token: a.identity_token,
authorization_code: a.authorization_code,
email: a.email.filter(|e| !e.is_empty()),
given_name: a.given_name.filter(|e| !e.is_empty()),
family_name: a.family_name.filter(|e| !e.is_empty()),
real_user_status: match a.real_user_status {
1 => RealUserStatus::Unknown,
2 => RealUserStatus::LikelyReal,
_ => RealUserStatus::Unsupported,
},
nonce: nonce.clone(),
hashed_nonce: hashed_nonce.clone(),
state: a.state.filter(|s| !s.is_empty()).or(state.clone()),
}),
Err(e) => Err(AuthError::Platform(format!("credential JSON: {e}"))),
},
Err(e) => Err(AuthError::from(e)),
});
});
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CredentialState {
Authorized,
Revoked,
NotFound,
}
pub fn credential_state(
user: &str,
) -> impl std::future::Future<Output = Result<CredentialState, AuthError>> + Send {
let (tx, rx) = day_async::oneshot();
if support() == Support::Unsupported {
tx.send(Err(AuthError::Unsupported));
} else {
let _ = apple_credential_state_native_async(user, move |answer| {
tx.send(match answer {
Ok(1) => Ok(CredentialState::Authorized),
Ok(2) => Ok(CredentialState::Revoked),
Ok(_) => Ok(CredentialState::NotFound),
Err(e) => Err(AuthError::from(e)),
});
});
}
async move { rx.await.unwrap_or(Err(AuthError::Cancelled)) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn request_builder_keeps_what_it_is_given() {
let r = SignInWithApple::new()
.scopes([AppleScope::Email])
.nonce("n")
.state("s");
assert_eq!(r.scopes, vec![AppleScope::Email]);
assert_eq!(r.nonce.as_deref(), Some("n"));
assert_eq!(r.state.as_deref(), Some("s"));
assert_eq!(SignInWithApple::default().scopes.len(), 2);
}
#[test]
fn unsupported_hosts_answer_through_the_callback() {
if support() != Support::Unsupported {
return;
}
let (tx, rx) = std::sync::mpsc::channel();
start(
SignInWithApple::new(),
Box::new(move |a| {
let _ = tx.send(a);
}),
);
assert_eq!(rx.recv().ok(), Some(Err(AuthError::Unsupported)));
}
}