Skip to main content

fastauth_oauth/
social.rs

1//! The `Social` plugin value and its configuration.
2
3use std::fmt;
4use std::sync::Arc;
5
6use fastauth_core::AuthError;
7use fastauth_core::adapter::Adapter;
8use fastauth_core::error::ErrorCodes;
9use fastauth_core::plugin::{Plugin, PluginBuilder};
10use fastauth_core::value::Value;
11use http::StatusCode;
12
13use crate::http::{DynHttpClient, Http, HttpClient};
14use crate::provider::{DynProvider, OAuthProfile, OAuthProvider};
15use crate::routes::{LinkSocial, ListAccounts, SignInSocial, SocialCallback, UnlinkAccount};
16
17/// Whether a social sign-in may attach to an existing user with the same email.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum AccountLinking {
20    /// Link when the provider reports the email as verified (default).
21    #[default]
22    ByVerifiedEmail,
23    /// Never link by email; the sign-in fails with `account_not_linked`. Signed-in users can
24    /// still link through `/link-social`.
25    Off,
26}
27
28/// Extra `user` columns for a user created by a social sign-in, from the provider's profile
29/// and the provider id. See [`Social::map_profile`].
30pub type MapProfile =
31    dyn Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError> + Send + Sync;
32
33/// A provider with its own sign-up options, from [`OAuthProviderExt`]:
34/// `Github::new(..).map_profile(..)` or `Github::new(..).disable_sign_up(true)`.
35pub struct ConfiguredProvider {
36    pub(crate) provider: Arc<dyn DynProvider>,
37    pub(crate) map_profile: Option<Arc<MapProfile>>,
38    pub(crate) disable_sign_up: bool,
39}
40
41impl fmt::Debug for ConfiguredProvider {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("ConfiguredProvider")
44            .field("id", &self.provider.id())
45            .field("map_profile", &self.map_profile.is_some())
46            .field("disable_sign_up", &self.disable_sign_up)
47            .finish()
48    }
49}
50
51impl<P: OAuthProvider> From<P> for ConfiguredProvider {
52    fn from(provider: P) -> Self {
53        Self {
54            provider: Arc::new(provider),
55            map_profile: None,
56            disable_sign_up: false,
57        }
58    }
59}
60
61impl ConfiguredProvider {
62    /// Maps the profile to extra `user` columns for users created through this provider. It
63    /// replaces [`Social::map_profile`] for this provider; the two are not merged.
64    pub fn map_profile<F>(mut self, map: F) -> Self
65    where
66        F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
67            + Send
68            + Sync
69            + 'static,
70    {
71        self.map_profile = Some(Arc::new(map));
72        self
73    }
74
75    /// Refuses to create users through this provider (`?error=signup_disabled`). Existing
76    /// users still sign in with it, including ones linked by verified email.
77    pub fn disable_sign_up(mut self, disable: bool) -> Self {
78        self.disable_sign_up = disable;
79        self
80    }
81}
82
83/// Per-provider sign-up options on every [`OAuthProvider`], built-in or your own.
84pub trait OAuthProviderExt: OAuthProvider + Sized {
85    /// See [`ConfiguredProvider::map_profile`].
86    fn map_profile<F>(self, map: F) -> ConfiguredProvider
87    where
88        F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
89            + Send
90            + Sync
91            + 'static,
92    {
93        ConfiguredProvider::from(self).map_profile(map)
94    }
95
96    /// See [`ConfiguredProvider::disable_sign_up`].
97    fn disable_sign_up(self, disable: bool) -> ConfiguredProvider {
98        ConfiguredProvider::from(self).disable_sign_up(disable)
99    }
100}
101
102impl<P: OAuthProvider> OAuthProviderExt for P {}
103
104/// Social sign-in as a plugin: `.plugin(Social::new().provider(Github::from_env()?))`.
105pub struct Social {
106    pub(crate) providers: Vec<ConfiguredProvider>,
107    pub(crate) http: Arc<dyn DynHttpClient>,
108    pub(crate) account_linking: AccountLinking,
109    pub(crate) map_profile: Option<Arc<MapProfile>>,
110}
111
112impl fmt::Debug for Social {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.debug_struct("Social")
115            .field("providers", &self.providers)
116            .field("account_linking", &self.account_linking)
117            .field("map_profile", &self.map_profile.is_some())
118            .finish_non_exhaustive()
119    }
120}
121
122#[cfg(feature = "reqwest")]
123impl Default for Social {
124    fn default() -> Self {
125        Self::new()
126    }
127}
128
129impl Social {
130    /// No providers yet, and the reqwest client.
131    #[cfg(feature = "reqwest")]
132    pub fn new() -> Self {
133        Self::with_http_client(crate::http::ReqwestClient::new())
134    }
135
136    /// No providers yet, and your own HTTP client.
137    pub fn with_http_client(client: impl HttpClient) -> Self {
138        Self {
139            providers: Vec::new(),
140            http: Arc::new(client),
141            account_linking: AccountLinking::default(),
142            map_profile: None,
143        }
144    }
145
146    /// Adds a provider, plain or with its own options from [`OAuthProviderExt`]. A provider
147    /// with the same id replaces the earlier one.
148    pub fn provider(mut self, provider: impl Into<ConfiguredProvider>) -> Self {
149        let provider = provider.into();
150        self.providers
151            .retain(|p| p.provider.id() != provider.provider.id());
152        self.providers.push(provider);
153        self
154    }
155
156    /// Maps the provider's profile to extra `user` columns when a social sign-in creates a
157    /// user, so app and plugin columns without a default get a value. It runs only for new
158    /// users. A provider's own mapping ([`OAuthProviderExt::map_profile`]) wins over this one.
159    ///
160    /// The columns are checked against `user`: each must be an app or plugin column, set once,
161    /// with the column's type. Server-only columns are allowed. A mistake is a 500 with the
162    /// reason logged. An error you return is passed on: a 4xx redirects to the error callback
163    /// URL with `?error=` set to its code, so a mapping can also refuse a sign-up.
164    pub fn map_profile<F>(mut self, map: F) -> Self
165    where
166        F: Fn(&OAuthProfile, &str) -> Result<Vec<(&'static str, Value)>, AuthError>
167            + Send
168            + Sync
169            + 'static,
170    {
171        self.map_profile = Some(Arc::new(map));
172        self
173    }
174
175    pub fn account_linking(mut self, linking: AccountLinking) -> Self {
176        self.account_linking = linking;
177        self
178    }
179
180    pub(crate) fn find(&self, id: &str) -> Option<&ConfiguredProvider> {
181        self.providers.iter().find(|p| p.provider.id() == id)
182    }
183
184    pub(crate) fn http(&self) -> Http<'_> {
185        Http::from_dyn(&*self.http)
186    }
187}
188
189impl Plugin for Social {
190    const ID: &'static str = "social";
191    type Requires = ();
192    type UserFields = ();
193    type SessionFields = ();
194
195    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
196        app.endpoint(SignInSocial(self.clone()))
197            .endpoint(SocialCallback(self.clone()))
198            .endpoint(LinkSocial(self.clone()))
199            .endpoint(ListAccounts)
200            .endpoint(UnlinkAccount)
201            .errors::<SocialError>();
202    }
203}
204
205/// Errors the social endpoints answer with as JSON. Callback failures redirect instead,
206/// with `?error=` set to one of Better Auth's callback error strings.
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub enum SocialError {
209    /// 404 `PROVIDER_NOT_FOUND`.
210    ProviderNotFound,
211    /// 400 `ACCOUNT_NOT_FOUND`.
212    AccountNotFound,
213    /// 400 `FAILED_TO_UNLINK_LAST_ACCOUNT`: it is the user's only way to sign in.
214    LastAccount,
215}
216
217impl From<SocialError> for AuthError {
218    fn from(err: SocialError) -> Self {
219        match err {
220            SocialError::ProviderNotFound => AuthError::new(
221                StatusCode::NOT_FOUND,
222                "PROVIDER_NOT_FOUND",
223                "provider not found",
224            ),
225            SocialError::AccountNotFound => AuthError::new(
226                StatusCode::BAD_REQUEST,
227                "ACCOUNT_NOT_FOUND",
228                "account not found",
229            ),
230            SocialError::LastAccount => AuthError::new(
231                StatusCode::BAD_REQUEST,
232                "FAILED_TO_UNLINK_LAST_ACCOUNT",
233                "you can't unlink your last account",
234            ),
235        }
236    }
237}
238
239impl ErrorCodes for SocialError {
240    const CODES: &'static [&'static str] = &[
241        "PROVIDER_NOT_FOUND",
242        "ACCOUNT_NOT_FOUND",
243        "FAILED_TO_UNLINK_LAST_ACCOUNT",
244    ];
245}