Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃獰聽馃帀 Enable OAuth login #15414

Merged
merged 20 commits into from
Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ export const useAnalytics = (): AnalyticsServiceProviderValue => {
return analyticsContext;
};

export const useAnalyticsIdentifyUser = (userId?: string): void => {
export const useAnalyticsIdentifyUser = (userId?: string, traits?: Record<string, unknown>): void => {
const analyticsService = useAnalyticsService();

useEffect(() => {
if (userId) {
analyticsService.identify(userId);
analyticsService.identify(userId, traits);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId]);
Expand Down
2 changes: 2 additions & 0 deletions airbyte-webapp/src/hooks/services/Experiment/experiments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ export interface Experiments {
"connector.orderOverwrite": Record<string, number>;
"authPage.rightSideUrl": string | undefined;
"authPage.hideSelfHostedCTA": boolean;
"authPage.oauth.google": boolean;
"authPage.oauth.github": boolean;
}
4 changes: 2 additions & 2 deletions airbyte-webapp/src/packages/cloud/cloudRoutes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ const MainViewRoutes = () => {
};

export const Routing: React.FC = () => {
const { user, inited } = useAuthService();
const { user, inited, providers } = useAuthService();
const config = useConfig();
useFullStory(config.fullstory, config.fullstory.enabled, user);

Expand All @@ -156,7 +156,7 @@ export const Routing: React.FC = () => {
[user]
);
useAnalyticsRegisterValues(analyticsContext);
useAnalyticsIdentifyUser(user?.userId);
useAnalyticsIdentifyUser(user?.userId, { providers });
useTrackPageAnalytics();

if (!inited) {
Expand Down
2 changes: 2 additions & 0 deletions airbyte-webapp/src/packages/cloud/lib/auth/AuthProviders.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export enum AuthProviders {
GoogleIdentityPlatform = "google_identity_platform",
}

export type OAuthProviders = "github" | "google";
33 changes: 10 additions & 23 deletions airbyte-webapp/src/packages/cloud/lib/auth/GoogleAuthService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { OAuthProviders } from "./AuthProviders";

import {
Auth,
User,
Expand All @@ -15,35 +17,16 @@ import {
updatePassword,
updateEmail,
AuthErrorCodes,
signInWithPopup,
GoogleAuthProvider,
GithubAuthProvider,
} from "firebase/auth";

import { Provider } from "config";
import { FieldError } from "packages/cloud/lib/errors/FieldError";
import { EmailLinkErrorCodes, ErrorCodes } from "packages/cloud/services/auth/types";

interface AuthService {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

鈩癸笍 We never exported this type, and implementing the interface in TypeScript does not even help not needing to respecify the types in the GoogleAuthService anyway. Thus this interface is not really fulfilling any purpose (besides needing to arbitrarily type the method signature twice) and I removed it.

login(email: string, password: string): Promise<UserCredential>;

signOut(): Promise<void>;

signUp(email: string, password: string): Promise<UserCredential>;

reauthenticate(email: string, passwordPassword: string): Promise<UserCredential>;

updatePassword(newPassword: string): Promise<void>;

resetPassword(email: string): Promise<void>;

finishResetPassword(code: string, newPassword: string): Promise<void>;

sendEmailVerifiedLink(): Promise<void>;

updateEmail(email: string, password: string): Promise<void>;

signInWithEmailLink(email: string): Promise<UserCredential>;
}

export class GoogleAuthService implements AuthService {
export class GoogleAuthService {
constructor(private firebaseAuthProvider: Provider<Auth>) {}

get auth(): Auth {
Expand All @@ -54,6 +37,10 @@ export class GoogleAuthService implements AuthService {
return this.auth.currentUser;
}

async loginWithOAuth(provider: OAuthProviders) {
await signInWithPopup(this.auth, provider === "github" ? new GithubAuthProvider() : new GoogleAuthProvider());
}

async login(email: string, password: string): Promise<UserCredential> {
return signInWithEmailAndPassword(this.auth, email, password).catch((err) => {
switch (err.code) {
Expand Down
7 changes: 6 additions & 1 deletion airbyte-webapp/src/packages/cloud/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,19 @@
"login.companyName": "Company name*",
"login.companyName.placeholder": "Acme Inc.",
"login.subscribe": "Receive community and feature updates. You can unsubscribe any time. ",
"login.security": "By using the service, you agree to to our <terms>Terms of Service</terms> and <privacy>Privacy\u00a0Policy</privacy>.",
"login.disclaimer": "By signing up and continuing, you agree to our <terms>Terms of Service</terms> and <privacy>Privacy Policy</privacy>.",
"login.inviteTitle": "Invite access",
"login.inviteLinkExpired": "This invite link expired. A new invite link was sent to your email.",
"login.inviteLinkInvalid": "This invite link is no longer valid.",
"login.rightSideFrameTitle": "More about Airbyte",
"login.quoteText": "Airbyte has cut <b>months of employee hours off</b> of our ELT pipeline development and delivered usable data to us in hours instead of weeks. We are excited for the future of Airbyte, enthusiastic about their approach, and optimistic about our future together.",
"login.quoteAuthor": "Micah Mangione",
"login.quoteAuthorJobTitle": "Director of Technology",
"login.oauth.or": "or",
"login.oauth.google": "Continue with Google",
"login.oauth.github": "Continue with GitHub",
"login.oauth.differentCredentialsError": "Use your email and password to sign in.",
"login.oauth.unknownError": "An unknown error happened during sign in: {error}",

"confirmResetPassword.newPassword": "Enter a new password",
"confirmResetPassword.success": "Your password has been reset. Please log in with the new password.",
Expand Down
117 changes: 92 additions & 25 deletions airbyte-webapp/src/packages/cloud/services/auth/AuthService.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { User as FbUser } from "firebase/auth";
import { User as FirebaseUser } from "firebase/auth";
import React, { useCallback, useContext, useMemo, useRef } from "react";
import { useQueryClient } from "react-query";
import { useEffectOnce } from "react-use";
import { Observable, Subject } from "rxjs";

import { Action, Namespace } from "core/analytics";
import { isCommonRequestError } from "core/request/CommonRequestError";
import { useAnalyticsService } from "hooks/services/Analytics";
import useTypesafeReducer from "hooks/useTypesafeReducer";
import { AuthProviders } from "packages/cloud/lib/auth/AuthProviders";
import { AuthProviders, OAuthProviders } from "packages/cloud/lib/auth/AuthProviders";
import { GoogleAuthService } from "packages/cloud/lib/auth/GoogleAuthService";
import { User } from "packages/cloud/lib/domain/users";
import { useGetUserService } from "packages/cloud/services/users/UserService";
Expand Down Expand Up @@ -39,13 +41,18 @@ export type AuthSendEmailVerification = () => Promise<void>;
export type AuthVerifyEmail = (code: string) => Promise<void>;
export type AuthLogout = () => Promise<void>;

type OAuthLoginState = "waiting" | "loading" | "done";

interface AuthContextApi {
user: User | null;
inited: boolean;
emailVerified: boolean;
isLoading: boolean;
loggedOut: boolean;
providers: string[] | null;
hasPasswordLogin: () => boolean;
login: AuthLogin;
loginWithOAuth: (provider: OAuthProviders) => Observable<OAuthLoginState>;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

鈩癸笍 This method returns an Obersvable, since we need to know in the UI, when the middle of the method starts (the user selected an account, and we start loading the user), to show the loading spinner. Thus we can't express that with a Promise.

signUpWithEmailLink: (form: { name: string; email: string; password: string; news: boolean }) => Promise<void>;
signUp: AuthSignUp;
updatePassword: AuthUpdatePassword;
Expand All @@ -70,10 +77,61 @@ export const AuthenticationProvider: React.FC = ({ children }) => {
const analytics = useAnalyticsService();
const authService = useInitService(() => new GoogleAuthService(() => auth), [auth]);

/**
* Create a user object in the Airbyte database from an existing Firebase user.
* This will make sure that the user account is tracked in our database as well
* as create a workspace for that user. This method also takes care of sending
* the relevant user creation analytics events.
*/
const createAirbyteUser = async (
firebaseUser: FirebaseUser,
userData: { name?: string; companyName?: string; news?: boolean } = {}
): Promise<User> => {
// Create the Airbyte user on our server
const user = await userService.create({
authProvider: AuthProviders.GoogleIdentityPlatform,
authUserId: firebaseUser.uid,
email: firebaseUser.email ?? "",
name: userData.name ?? firebaseUser.displayName ?? "",
companyName: userData.companyName ?? "",
news: userData.news ?? false,
});

analytics.track(Namespace.USER, Action.CREATE, {
actionDescription: "New user registered",
user_id: firebaseUser.uid,
name: user.name,
email: user.email,
// Which login provider was used, e.g. "password", "google.com", "github.com"
provider: firebaseUser.providerData[0]?.providerId,
...getUtmFromStorage(),
});

return user;
};

const onAfterAuth = useCallback(
async (currentUser: FbUser, user?: User) => {
user ??= await userService.getByAuthId(currentUser.uid, AuthProviders.GoogleIdentityPlatform);
loggedIn({ user, emailVerified: currentUser.emailVerified });
async (currentUser: FirebaseUser, user?: User) => {
try {
user ??= await userService.getByAuthId(currentUser.uid, AuthProviders.GoogleIdentityPlatform);
loggedIn({
user,
emailVerified: currentUser.emailVerified,
providers: currentUser.providerData.map(({ providerId }) => providerId),
});
} catch (e) {
if (isCommonRequestError(e) && e.status === 404) {
// If there is a firebase user but not database user we'll create a db user in this step
// and retry the onAfterAuth step. This will always happen when a user logins via OAuth
// the first time and we don't have a database user yet for them. In rare cases this can
// also happen for email/password users if they closed their browser or got some network
// errors in between creating the firebase user and the database user originally.
const user = await createAirbyteUser(currentUser);
await onAfterAuth(currentUser, user);
} else {
throw e;
}
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[userService]
Expand Down Expand Up @@ -103,13 +161,37 @@ export const AuthenticationProvider: React.FC = ({ children }) => {
isLoading: state.loading,
emailVerified: state.emailVerified,
loggedOut: state.loggedOut,
providers: state.providers,
hasPasswordLogin(): boolean {
return !!state.providers?.includes("password");
},
async login(values: { email: string; password: string }): Promise<void> {
await authService.login(values.email, values.password);

if (auth.currentUser) {
await onAfterAuth(auth.currentUser);
}
},
loginWithOAuth(provider): Observable<OAuthLoginState> {
const state = new Subject<OAuthLoginState>();
try {
state.next("waiting");
authService
.loginWithOAuth(provider)
.then(async () => {
state.next("loading");
if (auth.currentUser) {
await onAfterAuth(auth.currentUser);
state.next("done");
state.complete();
}
})
.catch((e) => state.error(e));
} catch (e) {
state.error(e);
}
return state.asObservable();
},
async logout(): Promise<void> {
await userService.revokeUserSession();
await authService.signOut();
Expand Down Expand Up @@ -148,7 +230,7 @@ export const AuthenticationProvider: React.FC = ({ children }) => {
await authService.finishResetPassword(code, newPassword);
},
async signUpWithEmailLink({ name, email, password, news }): Promise<void> {
let firebaseUser: FbUser;
let firebaseUser: FirebaseUser;

try {
({ user: firebaseUser } = await authService.signInWithEmailLink(email));
Expand All @@ -175,29 +257,14 @@ export const AuthenticationProvider: React.FC = ({ children }) => {
news: boolean;
}): Promise<void> {
// Create a user account in firebase
const { user: fbUser } = await authService.signUp(form.email, form.password);

// Create the Airbyte user on our server
const user = await userService.create({
authProvider: AuthProviders.GoogleIdentityPlatform,
authUserId: fbUser.uid,
email: form.email,
name: form.name,
companyName: form.companyName,
news: form.news,
});
const { user: firebaseUser } = await authService.signUp(form.email, form.password);

// Create a user in our database for that firebase user
await createAirbyteUser(firebaseUser, { name: form.name, companyName: form.companyName, news: form.news });

// Send verification mail via firebase
await authService.sendEmailVerifiedLink();

analytics.track(Namespace.USER, Action.CREATE, {
actionDescription: "New user registered",
user_id: fbUser.uid,
name: user.name,
email: user.email,
...getUtmFromStorage(),
});

if (auth.currentUser) {
await onAfterAuth(auth.currentUser);
}
Expand Down
6 changes: 5 additions & 1 deletion airbyte-webapp/src/packages/cloud/services/auth/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { User } from "packages/cloud/lib/domain/users";

export const actions = {
authInited: createAction("AUTH_INITED")<void>(),
loggedIn: createAction("LOGGED_IN")<{ user: User; emailVerified: boolean }>(),
loggedIn: createAction("LOGGED_IN")<{ user: User; emailVerified: boolean; providers: string[] }>(),
emailVerified: createAction("EMAIL_VERIFIED")<boolean>(),
loggedOut: createAction("LOGGED_OUT")<void>(),
updateUserName: createAction("UPDATE_USER_NAME")<{ value: string }>(),
Expand All @@ -18,6 +18,7 @@ export interface AuthServiceState {
emailVerified: boolean;
loading: boolean;
loggedOut: boolean;
providers: string[] | null;
}

export const initialState: AuthServiceState = {
Expand All @@ -26,6 +27,7 @@ export const initialState: AuthServiceState = {
emailVerified: false,
loading: false,
loggedOut: false,
providers: null,
};

export const authStateReducer = createReducer<AuthServiceState, Actions>(initialState)
Expand All @@ -40,6 +42,7 @@ export const authStateReducer = createReducer<AuthServiceState, Actions>(initial
...state,
currentUser: action.payload.user,
emailVerified: action.payload.emailVerified,
providers: action.payload.providers,
inited: true,
loading: false,
loggedOut: false,
Expand All @@ -57,6 +60,7 @@ export const authStateReducer = createReducer<AuthServiceState, Actions>(initial
currentUser: null,
emailVerified: false,
loggedOut: true,
providers: null,
};
})
.handleAction(actions.updateUserName, (state, action): AuthServiceState => {
Expand Down
Loading