use std::sync::Arc;
use gpui_kit::{App, AppContext as _, Context, Entity, EventEmitter, Global};
use subspace_core::credentials::Credentials;
use subspace_github_auth::{
AuthError, Authenticator, Cancel, GitHubOAuth, OAuthClient, Prompt, Started,
};
use crate::Services;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Phase {
Idle,
Starting,
Browser,
Device {
user_code: String,
verification_uri: String,
},
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignInEvent {
SignedIn(String),
SignedOut(String),
}
enum Outcome {
SignedIn(String),
Cancelled,
Failed(String),
}
impl From<AuthError> for Outcome {
fn from(error: AuthError) -> Self {
match error {
AuthError::Cancelled => Self::Cancelled,
error => Self::Failed(error.to_string()),
}
}
}
pub struct GitHubSignIn {
authenticator: Arc<dyn Authenticator>,
phase: Phase,
cancel: Option<Cancel>,
run: u64,
}
impl EventEmitter<SignInEvent> for GitHubSignIn {}
struct Shared(Entity<GitHubSignIn>);
impl Global for Shared {}
pub fn init(client: Option<OAuthClient>, cx: &mut App) {
if let Some(client) = client {
install(Arc::new(GitHubOAuth::for_client(client)), cx);
}
}
pub fn install(authenticator: Arc<dyn Authenticator>, cx: &mut App) -> Entity<GitHubSignIn> {
let entity = cx.new(|_| GitHubSignIn::new(authenticator));
cx.set_global(Shared(entity.clone()));
entity
}
pub fn shared(cx: &App) -> Option<Entity<GitHubSignIn>> {
cx.try_global::<Shared>().map(|shared| shared.0.clone())
}
impl GitHubSignIn {
pub fn new(authenticator: Arc<dyn Authenticator>) -> Self {
Self {
authenticator,
phase: Phase::Idle,
cancel: None,
run: 0,
}
}
pub fn phase(&self) -> &Phase {
&self.phase
}
pub fn in_progress(&self) -> bool {
matches!(
self.phase,
Phase::Starting | Phase::Browser | Phase::Device { .. }
)
}
pub fn start(&mut self, cx: &mut Context<Self>) {
if self.in_progress() {
return;
}
let Some(credentials) = credentials(cx) else {
self.set_phase(Phase::Failed("Sign-in is unavailable here.".into()), cx);
return;
};
let cancel = Cancel::default();
self.run += 1;
self.cancel = Some(cancel.clone());
self.set_phase(Phase::Starting, cx);
let run = self.run;
let authenticator = self.authenticator.clone();
cx.spawn(async move |this, cx| {
let started = cx
.background_spawn(async move { authenticator.start() })
.await;
let started = match started {
Ok(started) => started,
Err(error) => {
let _ = this.update(cx, |this, cx| this.finish(run, error.into(), cx));
return;
}
};
let Started { prompt, pending } = started;
let _ = this.update(cx, |this, cx| this.prompt(run, prompt, cx));
let outcome = cx
.background_spawn(async move {
let signed_in = pending.finish(&cancel)?;
keep(&credentials, &cancel, &signed_in.login, &signed_in.token)
})
.await
.unwrap_or_else(Outcome::from);
let _ = this.update(cx, |this, cx| this.finish(run, outcome, cx));
})
.detach();
}
pub fn cancel(&mut self, cx: &mut Context<Self>) {
if let Some(cancel) = self.cancel.take() {
cancel.cancel();
}
self.run += 1;
self.set_phase(Phase::Idle, cx);
}
pub fn sign_out(&mut self, login: String, cx: &mut Context<Self>) {
let Some(credentials) = credentials(cx) else {
return;
};
let authenticator = self.authenticator.clone();
cx.spawn(async move |this, cx| {
let account = login.clone();
let removed = cx
.background_spawn(async move {
let token = credentials.sign_out(&account)?;
if let Some(token) = token {
authenticator.revoke(&token);
}
Ok::<(), subspace_core::credentials::CredentialError>(())
})
.await;
let _ = this.update(cx, |this, cx| match removed {
Ok(()) => cx.emit(SignInEvent::SignedOut(login)),
Err(error) => this.set_phase(Phase::Failed(error.0), cx),
});
})
.detach();
}
pub fn show(&mut self, phase: Phase, cx: &mut Context<Self>) {
self.set_phase(phase, cx);
}
fn set_phase(&mut self, phase: Phase, cx: &mut Context<Self>) {
self.phase = phase;
cx.notify();
}
fn prompt(&mut self, run: u64, prompt: Prompt, cx: &mut Context<Self>) {
if run != self.run {
return;
}
let phase = match prompt {
Prompt::Browser { url } => {
cx.open_url(&url);
Phase::Browser
}
Prompt::Device {
user_code,
verification_uri,
} => Phase::Device {
user_code,
verification_uri,
},
};
self.set_phase(phase, cx);
}
fn finish(&mut self, run: u64, outcome: Outcome, cx: &mut Context<Self>) {
if run != self.run {
return;
}
let from_browser = self.phase == Phase::Browser;
self.cancel = None;
match outcome {
Outcome::SignedIn(login) => {
self.set_phase(Phase::Idle, cx);
if from_browser {
cx.activate(true);
}
cx.emit(SignInEvent::SignedIn(login));
}
Outcome::Cancelled => self.set_phase(Phase::Idle, cx),
Outcome::Failed(message) => self.set_phase(Phase::Failed(message), cx),
}
}
}
fn credentials(cx: &App) -> Option<Arc<Credentials>> {
cx.try_global::<Services>()
.map(|services| services.credentials.clone())
}
fn keep(
credentials: &Credentials,
cancel: &Cancel,
login: &str,
token: &subspace_core::Secret,
) -> Result<Outcome, AuthError> {
if cancel.is_cancelled() {
return Err(AuthError::Cancelled);
}
Ok(match credentials.sign_in(login, token) {
Ok(()) => Outcome::SignedIn(login.to_owned()),
Err(error) => Outcome::Failed(error.0),
})
}
mod view;
pub use view::{sign_in_button, status};
#[cfg(test)]
mod tests;