Skip to content

(DOCSP-27598): Clean up web auth examples #2640

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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 3, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
262 changes: 97 additions & 165 deletions examples/web/src/__tests__/authentication-log-in-and-out.test.js

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
async function loginAnonymous() {
// Create an anonymous credential
const credentials = Realm.Credentials.anonymous();
try {
// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);
return user;
} catch (err) {
console.error("Failed to log in", err);
}

// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);

return user;
}
const user = await loginAnonymous();
console.log("Successfully logged in!", user.id);

Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
async function loginApiKey(apiKey) {
// Create an API Key credential
const credentials = Realm.Credentials.apiKey(apiKey);
try {
// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);
return user;
} catch (err) {
console.error("Failed to log in", err);
}

// Authenticate the user
const user = await app.logIn(credentials);

// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);

return user;
}

const user = await loginApiKey(REALM_API_KEY.key); // add previously generated API key
console.log("Successfully logged in!", user);
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
// Get the ID token from the Apple SDK
AppleID.auth
.signIn()
.then(({ id_token }) => {
// Define credentials with the ID token from the Apple SDK
const credentials = Realm.Credentials.apple(id_token);
// Log the user in to your app
return app.logIn(credentials);
})
.then((user) => {
console.log(`Logged in with id: ${user.id}`);
});
const { id_token } = await AppleID.auth.signIn();

// Define credentials with the ID token from the Apple SDK
const credentials = Realm.Credentials.apple(id_token);

// Log the user in to your app
const user = await app.logIn(credentials);
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,8 @@ const redirectUri = "https://app.example.com/handleOAuthLogin";
const credentials = Realm.Credentials.apple(redirectUri);

// Calling logIn() opens an Apple authentication screen in a new window.
app.logIn(credentials).then((user) => {
// The logIn() promise will not resolve until you call `handleAuthRedirect()`
// from the new window after the user has successfully authenticated.
console.log(`Logged in with id: ${user.id}`);
});
const user = app.logIn(credentials);

// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();
// The logIn() promise will not resolve until you call `Realm.handleAuthRedirect()`
// from the new window after the user has successfully authenticated.
console.log(`Logged in with id: ${user.id}`);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we split this into two code snippets? It's not totally clear to the skimmer that handleAuthRedirect() happens in another window / URL. Similar comment for the other OAuth providers.

Also, we have the same codeblock for Facebook but an entirely different format for Google. Should we unify these?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

i thought about doing that in the first pass but didn't b/c of fact it was pretty outside scope of original ticket + some laziness. but we already got outside the scope of the ticket so might as well go for it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

and in the spirit of scope creep, i think i'll just throw in https://jira.mongodb.org/browse/DOCSP-28363 w this ticket as well.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

90% sure https://jira.mongodb.org/browse/DOCSP-28363 doesn't require any work. waiting for final confirmation from the eng who opened that ticket. but merging this now.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,8 @@ const redirectUri = "https://app.example.com/handleOAuthLogin";
const credentials = Realm.Credentials.facebook(redirectUri);

// Calling logIn() opens a Facebook authentication screen in a new window.
app.logIn(credentials).then((user) => {
// The logIn() promise will not resolve until you call `handleAuthRedirect()`
// from the new window after the user has successfully authenticated.
console.log(`Logged in with id: ${user.id}`);
});
const user = await app.logIn(credentials);

// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();
// The app.logIn() promise will not resolve until you call `Realm.handleAuthRedirect()`
// from the new window after the user has successfully authenticated.
console.log(`Logged in with id: ${user.id}`);
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
async function loginCustomFunction(payload) {
// Create a Custom Function credential
const credentials = Realm.Credentials.function(payload);
try {
// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);
return user;
} catch (err) {
console.error("Failed to log in", err);
}

// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);

return user;
}
loginCustomFunction({ username: "ilovemongodb" }).then((user) => {
console.log("Successfully logged in!", user);
});
const user = await loginCustomFunction({ username: "ilovemongodb" });
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
async function loginCustomJwt(jwt) {
// Create a Custom JWT credential
const credentials = Realm.Credentials.jwt(jwt);
try {
// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);
return user;
} catch (err) {
console.error("Failed to log in", err);
}

// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);

return user;
}
loginCustomJwt("eyJ0eXAi...Q3NJmnU8oP3YkZ8").then((user) => {
console.log("Successfully logged in!", user);
});
const user = await loginCustomJwt("eyJ0eXAi...Q3NJmnU8oP3YkZ8");
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
async function loginEmailPassword(email, password) {
// Create an email/password credential
const credentials = Realm.Credentials.emailPassword(email, password);
try {
// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);
return user;
} catch (err) {
console.error("Failed to log in", err);
}

// Authenticate the user
const user = await app.logIn(credentials);
// `App.currentUser` updates to match the logged in user
console.assert(user.id === app.currentUser.id);

return user;
}

const user = await loginEmailPassword("[email protected]", "passw0rd");
console.log("Successfully logged in!", user);
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,4 @@ const { accessToken } = FB.getAuthResponse();
// Define credentials with the access token from the Facebook SDK
const credentials = Realm.Credentials.facebook(accessToken);
// Log the user in to your app
app.logIn(credentials).then((user) => {
console.log(`Logged in with id: ${user.id}`);
});
await app.logIn(credentials);
33 changes: 17 additions & 16 deletions source/web/authenticate.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ To log in, create an anonymous credential and pass it to ``App.logIn()``:

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.anon-auth.js
:language: javascript
:emphasize-lines: 3, 6

.. _web-login-email-password:

Expand All @@ -51,7 +50,6 @@ password and pass it to ``App.logIn()``:

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.email-password-auth.js
:language: javascript
:emphasize-lines: 3, 6

.. _web-login-api-key:

Expand All @@ -66,7 +64,6 @@ API key and pass it to ``App.logIn()``:

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.api-key-auth.js
:language: javascript
:emphasize-lines: 3, 6

.. _web-login-custom-function:

Expand All @@ -82,7 +79,6 @@ with a payload object and pass it to ``App.logIn()``:

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.custom-function-auth.js
:language: javascript
:emphasize-lines: 3, 6

.. _web-login-custom-jwt:

Expand All @@ -99,7 +95,6 @@ and pass it to ``App.logIn()``:

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.custom-jwt.js
:language: javascript
:emphasize-lines: 3, 6


.. _web-login-facebook:
Expand Down Expand Up @@ -129,16 +124,19 @@ require you to install the Facebook SDK. The built in flow follows three main st
specify a URL for your app that is also listed as a redirect URI in the
provider configuration.

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.builtin-facebook-oauth.js
:language: javascript

2. A new window opens to a Facebook authentication screen and the user
authenticates and authorizes your app in that window. Once complete, the new
window redirects to the URL specified in the credential.

3. You call ``handleAuthRedirect()`` on the redirected page, which stores the
3. You call ``Realm.handleAuthRedirect()`` on the redirected page, which stores the
user's Atlas App Services access token and closes the window. Your original app window will
automatically detect the access token and finish logging the user in.

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.builtin-facebook-oauth.js
:language: javascript
.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.builtin-facebook-oauth-redirect.js
:language: javascript

.. _web-facebook-auth-token:

Expand Down Expand Up @@ -195,7 +193,7 @@ is a Google SDK that lets users sign up to or log in to a website with one click
This example shows how to set up Google Authentication with App Services in
a very basic web app. The app only contains an ``index.html`` file.

.. code-block:: html
.. code-block:: xml
:caption: index.html

<!DOCTYPE html>
Expand Down Expand Up @@ -257,7 +255,7 @@ require you to install a Google SDK. The built-in flow follows three main steps:
authenticates and authorizes your app in that window. Once complete, the new
window redirects to the URL specified in the credential.

#. Call ``handleAuthRedirect()`` on the redirected page, which stores the
#. Call ``Realm.handleAuthRedirect()`` on the redirected page, which stores the
user's App Services access token and closes the window. Your original app window will
automatically detect the access token and finish logging the user in.

Expand All @@ -270,9 +268,9 @@ require you to install a Google SDK. The built-in flow follows three main steps:

.
├── auth.html
── index.html
── index.html

.. code-block:: html
.. code-block:: xml
:caption: index.html

<!DOCTYPE html>
Expand Down Expand Up @@ -311,7 +309,7 @@ require you to install a Google SDK. The built-in flow follows three main steps:
</script>
</html>

.. code-block:: html
.. code-block:: xml
:caption: auth.html

<!DOCTYPE html>
Expand Down Expand Up @@ -367,16 +365,19 @@ steps:
specify a URL for your app that is also listed as a redirect URI in the
provider configuration.

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.builtin-apple-oauth.js
:language: javascript

2. A new window opens to an Apple authentication screen and the user
authenticates and authorizes your app in that window. Once complete, the new
window redirects to the URL specified in the credential.

3. You call ``handleAuthRedirect()`` on the redirected page, which stores the
3. You call ``Realm.handleAuthRedirect()`` on the redirected page, which stores the
user's App Services access token and closes the window. Your original app window will
automatically detect the access token and finish logging the user in.

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.builtin-apple-oauth.js

.. literalinclude:: /examples/generated/web/authentication-log-in-and-out.test.snippet.builtin-apple-oath-handle-redirect.js
:language: javascript

.. _web-apple-auth-token:

Expand Down
9 changes: 5 additions & 4 deletions source/web/mongodb.txt
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,6 @@ Find Multiple Documents

You can find multiple documents using :js-sdk:`collection.find() <Realm.MongoDBCollection.html#find>`.

The following snippet finds all documents that describe perennial plants in the
:ref:`collection of documents that describe plants for sale in a group of stores
<web-mongodb-example-dataset>`:

The following snippet finds all documents in a
:ref:`collection of documents that describe plants for sale in a group of stores
<web-mongodb-example-dataset>` that contain a field named
Expand All @@ -195,6 +191,11 @@ Running this snippet produces output resembling the following:
.. literalinclude:: /examples/generated/web/mongodb-data-access.test.snippet.find-multiple-documents-result.js
:language: javascript

You **cannot** use the ``.skip()`` operator with the Realm SDK.
To paginate results, you can use range queries with the ``.sort()`` and ``.limit()``,
as described in :manual:`Using Range Queries </reference/method/cursor.skip/#pagination-example>`
documentation in the MongoDB Manual.

.. _web-mongodb-count:

Count Documents in the Collection
Expand Down