1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
mod user;
use std::{error::Error, fmt};

use crate::FirebaseError;
pub use user::*;
use wasm_bindgen::{prelude::*, JsCast};

#[derive(Clone, Debug, derive_more::Deref)]
pub struct AuthError {
    pub kind: AuthErrorKind,
    #[deref]
    pub source: FirebaseError,
}

impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.source.fmt(f)
    }
}

impl Error for AuthError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.source)
    }
}

impl From<FirebaseError> for AuthError {
    fn from(err: FirebaseError) -> Self {
        Self {
            kind: err.code().parse().unwrap(),
            source: err,
        }
    }
}

#[derive(Clone, Debug, strum_macros::EnumString)]
#[non_exhaustive]
pub enum AuthErrorKind {
    #[strum(serialize = "auth/app-deleted")]
    AppDeleted,
    #[strum(serialize = "auth/app-not-authorized")]
    AppNotAuthorized,
    #[strum(serialize = "auth/argument-error")]
    ArgumentError,
    #[strum(serialize = "auth/invalid-api-key")]
    InvalidApiKey,
    #[strum(serialize = "auth/invalid-user-token")]
    InvalidUserToken,
    #[strum(serialize = "auth/invalid-tenant-id")]
    InvalidTenantId,
    #[strum(serialize = "auth/network-request-failed")]
    NetworkRequestFailed,
    #[strum(serialize = "auth/operation-not-allowed")]
    OperationNotAllowed,
    #[strum(serialize = "auth/requires-recent-login")]
    RequiresRecentLogin,
    #[strum(serialize = "auth/too-many-requests")]
    TooManyRequests,
    #[strum(serialize = "auth/unauthorized-domain")]
    UnauthorizedDomain,
    #[strum(serialize = "auth/user-disabled")]
    UserDisabled,
    #[strum(serialize = "auth/user-token-expired")]
    UserTokenExpired,
    #[strum(serialize = "auth/web-storage-unsupported")]
    WebStorageUnsupported,
    #[strum(serialize = "auth/invalid-email")]
    InvalidEmail,
    #[strum(serialize = "auth/user-not-found")]
    UserNotFound,
    #[strum(serialize = "auth/wrong-password")]
    WrongPassword,
    #[strum(serialize = "auth/email-already-in-use")]
    EmailAlreadyInUse,
    #[strum(serialize = "auth/weak-password")]
    WeakPassword,
    #[strum(serialize = "auth/missing-android-pkg-name")]
    MissingAndroidPackageName,
    #[strum(serialize = "auth/missing-continue-uri")]
    MissingContinueUri,
    #[strum(serialize = "auth/missing-ios-bundle-id")]
    MissingIOSBundleId,
    #[strum(serialize = "auth/invalid-continue-uri")]
    InvalidContinueUri,
    #[strum(serialize = "auth/unauthorized-continue-uri")]
    UnauthorizedContinueUri,
    #[strum(serialize = "auth/expired-action-code")]
    ExpiredActionCode,
    #[strum(default)]
    Other(String),
}

#[derive(Debug, Clone, TypedBuilder, serde::Serialize)]
#[builder(field_defaults(default))]
pub struct ActionCodeSettings {
    pub android: Option<AndroidActionCodeSettings>,
    #[builder(setter(strip_option))]
    pub handle_code_in_app: Option<bool>,
    pub ios: Option<IOSActionCodeSettings>,
    #[builder(!default)]
    pub url: String,
    pub dynamic_link_domain: Option<String>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Eq, TypedBuilder, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AndroidActionCodeSettings {
    #[builder(default, setter(strip_option))]
    pub install_app: Option<bool>,
    #[builder(default)]
    pub minimum_version: Option<String>,
    pub package_name: String,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Eq, TypedBuilder, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IOSActionCodeSettings {
    pub bundle_id: String,
}

pub async fn create_user_with_email_and_password(
    auth: &Auth,
    email: &str,
    password: &str,
) -> Result<UserCredential, AuthError> {
    create_user_with_email_and_password_js(auth, email, password)
        .await
        .map(|cred| cred.unchecked_into::<UserCredential>())
        .map_err(|err| err.unchecked_into::<FirebaseError>().into())
}

pub async fn sign_in_with_email_and_password(
    auth: &Auth,
    email: &str,
    password: &str,
) -> Result<UserCredential, AuthError> {
    sign_in_with_email_and_password_js(auth, email, password)
        .await
        .map(|cred| cred.unchecked_into::<UserCredential>())
        .map_err(|err| err.unchecked_into::<FirebaseError>().into())
}

pub async fn send_sign_in_link_to_email(
    auth: &Auth,
    email: &str,
    action_code_settings: &ActionCodeSettings,
) -> Result<(), AuthError> {
    let action_code_settings = serde_wasm_bindgen::to_value(action_code_settings).unwrap();

    send_sign_in_link_to_email_js(auth, email, action_code_settings)
        .await
        .map_err(|err| err.unchecked_into::<FirebaseError>().into())
}

pub async fn sign_in_with_email_link(
    auth: &Auth,
    email: &str,
    email_link: &str,
) -> Result<UserCredential, AuthError> {
    sign_in_with_email_link_js(auth, email, email_link)
        .await
        .map(|u| u.unchecked_into::<UserCredential>())
        .map_err(|err| err.unchecked_into::<FirebaseError>().into())
}

pub async fn send_password_reset_email(
    auth: &Auth,
    email: &str,
    action_code_settings: Option<&ActionCodeSettings>,
) -> Result<(), AuthError> {
    let action_code_settings = serde_wasm_bindgen::to_value(&action_code_settings).unwrap();

    send_password_reset_email_js(auth, email, action_code_settings)
        .await
        .map_err(|err| err.unchecked_into::<FirebaseError>().into())
}

pub async fn verify_password_reset_code(auth: &Auth, code: &str) -> Result<String, AuthError> {
    verify_password_reset_code_js(auth, code)
        .await
        .map(|res| res.unchecked_into::<js_sys::JsString>())
        .map(|s| ToString::to_string(&s))
        .map_err(|err| err.unchecked_into::<FirebaseError>().into())
}

pub async fn confirm_password_reset(
    auth: &Auth,
    code: &str,
    new_password: &str,
) -> Result<(), JsValue> {
    confirm_password_reset_js(auth, code, new_password)
        .await
        .map_err(|err| err.unchecked_into::<FirebaseError>().into())
}

#[wasm_bindgen(module = "firebase/auth")]
extern "C" {
    #[derive(Clone, Debug)]
    pub type Auth;
    #[derive(Clone, Debug)]
    pub type UserCredential;

    #[wasm_bindgen(js_name = getAuth)]
    pub fn get_auth() -> Auth;

    #[wasm_bindgen(js_name = onAuthStateChanged)]
    pub fn on_auth_state_changed(auth: &Auth, callback: &Closure<dyn FnMut(Option<User>)>);

    #[wasm_bindgen(js_name = createUserWithEmailAndPassword, catch)]
    async fn create_user_with_email_and_password_js(
        auth: &Auth,
        email: &str,
        password: &str,
    ) -> Result<JsValue, JsValue>;

    #[wasm_bindgen(js_name = signInWithEmailAndPassword, catch)]
    async fn sign_in_with_email_and_password_js(
        auth: &Auth,
        email: &str,
        password: &str,
    ) -> Result<JsValue, JsValue>;

    #[wasm_bindgen(js_name = signInWithEmailLink, catch)]
    async fn sign_in_with_email_link_js(
        auth: &Auth,
        email: &str,
        email_link: &str,
    ) -> Result<JsValue, JsValue>;

    #[wasm_bindgen(js_name = isSignInWithEmailLink, )]
    pub fn is_sign_in_with_email_link(auth: &Auth, email_link: &str) -> bool;

    #[wasm_bindgen(js_name = sendSignInLinkToEmail, catch)]
    async fn send_sign_in_link_to_email_js(
        auth: &Auth,
        email: &str,
        action_code_settings: JsValue,
    ) -> Result<(), JsValue>;

    #[wasm_bindgen(js_name = signOut)]
    pub async fn sign_out(auth: &Auth);

    #[wasm_bindgen(js_name = sendPasswordResetEmail, catch)]
    async fn send_password_reset_email_js(
        auth: &Auth,
        email: &str,
        action_code_settings: JsValue,
    ) -> Result<(), JsValue>;

    #[wasm_bindgen(js_name = verifyPasswordResetCode, catch)]
    async fn verify_password_reset_code_js(auth: &Auth, code: &str) -> Result<JsValue, JsValue>;

    #[wasm_bindgen(js_name = confirmPasswordReset, catch)]
    async fn confirm_password_reset_js(
        auth: &Auth,
        code: &str,
        new_password: &str,
    ) -> Result<(), JsValue>;

    // =======================================================
    //                  UserCredential
    // =======================================================

    #[wasm_bindgen(method, getter)]
    pub fn user(this: &UserCredential) -> user::User;

    #[wasm_bindgen(method, getter, js_name = providerId)]
    pub fn provider_id(this: &UserCredential) -> String;

    #[wasm_bindgen(method, getter, js_name = operationType)]
    pub fn operation_type(this: &UserCredential) -> String;
}