From 0789f23c4e226c61fb2638e0ff0205207b427f04 Mon Sep 17 00:00:00 2001 From: Daniel Vassallo Date: Fri, 1 Nov 2019 12:27:02 -0700 Subject: [PATCH] Update the tutorial based on recent changes --- src/pages/docs.html | 337 ++++++++++++++++++++------------------------ 1 file changed, 150 insertions(+), 187 deletions(-) diff --git a/src/pages/docs.html b/src/pages/docs.html index f451b82..52b5f2c 100644 --- a/src/pages/docs.html +++ b/src/pages/docs.html @@ -85,52 +85,22 @@

Tutorial

- In this tutorial we will build a simple to-do web app. Even if the web app you're - building has nothing to do with to-dos, the techniques we'll cover can be - applied to make many other kinds of web apps. + In this tutorial we will build a simple to-do web app. Even if what you're building has nothing to do with to-dos, the techniques we'll cover here can be applied to many other kinds of web apps.

- With just 199 lines code inside a single static HTML file we will create an - end-to-end encrypted web application with: + You can think of this tutorial as a demonstration of the core functionality of Userbase in the simplest way possible. We are going to focus solely on building a fully functional web app. Making things pretty is left as an exercise to the reader.

- -

You can see a live demo of what we'll building here.

Prerequisites

-

You'll need to be familiar with HTML and JavaScript. Beyond the basics of JavaScript, you will need to be familiar with DOM manipulation, events, and Promises.

- - -

What's in a name?

- -

- The reason we are calling our application "Ugly To-Do" is because we aren't - going to apply any styling but solely focus on core functionality. You can think - of this tutorial as a sort of "hello world" for Userbase, a demonstration of the - core functionality in the simplest way possible. -

- -

- In a real project you'll likely want a more sophisticated approach: for instance, you may use React to control the DOM or a module bundler to package your application from multiple files, and at the very - least you'll want to display better error messages and add some styling. -

- -

- We are working on a collection of tutorials and sample applications that will - show you how to do all these things with Userbase and more. You can subscribe to our mailing list to get updates on these and more. -

+

You just need to be familiar with HTML and JavaScript basics.

Setting up

-

Let's get setup to build our application. Open up a new file in your favorite editor:

+

Let's get going. Open up a new file in your favorite code editor:

     
@@ -161,66 +131,54 @@
   
 
   

- Now open up this file in a web browser of your choosing. At this point all - you'll see is a blank page. As we add functionality throughout the tutorial, you - can reload the app by refreshing this page to see changes. + Now open up this file in a web browser of your choosing. At this point all you'll see is a blank page. As we add functionality throughout the tutorial, you can refresh this page to see the changes.

Creating a developer account

-

To complete this tutorial, you'll need to create a Userbase developer account, and then create an app from within your account. Take not of the Application ID of your app.

+

To complete this tutorial, you'll need to create a Userbase developer account, and then create an app from within your account. Take note of the Application ID of your app.

- We are now ready to start building the application. We'll start by implementing - functionality to sign up and sign in users and then implement to-do - functionality. + We're now ready to start building our web app. We'll start by implementing the sign up and login features, and then in the second part we'll implement the to-do functionality.

Installing the SDK

- To use the Userbase SDK in our app, we'll load it from a CDN with a <script> tag in the head of + We're going to load the Userbase SDK from a CDN with a <script> tag in the head of our page: -
-
-      
-    
-
+
+    
+  
- The Userbase SDK will now be accessible via the global userbase variable. +

The Userbase SDK will now be accessible via the userbase variable. This will be our only dependency.

Configuring the SDK

- Before doing anything with the Userbase SDK, we need to configure it with our - Application ID (make sure to replace 'YOUR_APP_ID' with the Application ID of the Userbase App you created earlier): + Before doing anything with the Userbase SDK, we need to let it know our Application ID. + Simply replace 'YOUR_APP_ID' with the Application ID of the app you created earlier:

-
-
-      
+  
+    
+    <body>
+      <!-- application code -->
+      <script type="text/javascript">
+        userbase.configure({ appId: 'YOUR_APP_ID' })
+      </script>
+    </body>
+    </html>
+    
   
-

Now anything we do with the client (e.g. sign in a user, persist data) will @@ -230,8 +188,7 @@

Letting new users create an account

- Any actions that our users take will need to take place within an authenticated session. - We'll start off by adding a way to for new users to create an account with our app. + Any actions that our users take needs to happen within an authenticated session. We'll start by adding a way to for new users to create an account with our app.

First, we'll add a sign up form:

@@ -244,11 +201,11 @@ <div id="auth-view"> <h1>Create an account</h1> <form id="signup-form"> - <input id="create-account-username" type="email" required placeholder="Email"> - <input id="create-account-password" type="password" required placeholder="Password"> + <input id="signup-username" type="text" required placeholder="Username"> + <input id="signup-password" type="password" required placeholder="Password"> <input type="submit" value="Create an account"> </form> - <div id="create-account-error"></div> + <div id="signup-error"></div> </div> <!-- application code --> @@ -258,22 +215,24 @@
-

Then, we'll add code to handle the form submissions:

+

Then, we'll add the code to handle the form submission:

-
+    
       
       <!-- application code -->
       <script type="text/javascript">
+        userbase.configure({ appId: 'YOUR_APP_ID' })
+
         function handleSignUp(e) {
           e.preventDefault()
   
-          const username = document.getElementById('create-account-username').value
-          const password = document.getElementById('create-account-password').value
+          const username = document.getElementById('signup-username').value
+          const password = document.getElementById('signup-password').value
   
           userbase.signUp(username, password)
-            .then((session) => alert('You signed up!'))
-            .catch((e) => document.getElementById('create-account-error').innerHTML = e)
+            .then((user) => alert('You signed up!'))
+            .catch((e) => document.getElementById('signup-error').innerHTML = e)
         }
   
         document.getElementById('signup-form').addEventListener('submit', handleSignUp)
@@ -283,46 +242,36 @@
   

- Whenever a submit event is triggered on our sign up form, handleSignUp will be called. + Whenever someone submits the form, the handleSignUp function will be called.

The first thing we do in handleSignUp is call preventDefault() on the - submit event. This will prevent the page from submitting to the server. + submit event. This will prevent the page from submitting to the server. We want to handle this form completely on the client-side.

Next we get the values of the username and password inputs and call - userbase.signUp(username, password) which will request a new account to be created with the Userbase service. A Promise is returned that either resolves - with a new session object, in which case we fire an alert (for now), or rejects - with an error, in which case we display the error message. + userbase.signUp(username, password). This will request a new account to be created with the Userbase service, and returns a Promise that resolves with a user object.

- Go ahead and reload the web app in your browser. Enter a username and password - in the form under "Sign Up" and submit. You'll get an alert saying "You signed - up!". + Go ahead and reload the web app in your browser. Enter a username and password in the form under "Sign Up" and submit. You'll get an alert saying that you signed up. And if go to your Userbase developer account, you should see the new user under your app.

- Now try signing up for another account using the same username and you'll see an - error message displayed under the form (since an account already exists with - this username). + Now try signing up for another account using the same username and you'll see an error message displayed under the form.

- We'll come back in a bit and change this function to do something more - interesting than just sending an alert when an user successfully signs up. + We'll come back to this in a bit to change this function to do something more interesting.

Letting users log in

Now that users can create accounts, let's give them the ability to sign in.

-

- First, we'll add a "Login" form to the page above our "Create Account" - form: -

+

First, we'll add a "Login" form to the page above our "Create Account" form:

     
@@ -331,7 +280,7 @@
       <div id="auth-view">
         <h1>Login</h1>
         <form id="login-form"> 
-          <input id="login-username" type="email" required placeholder="Email">
+          <input id="login-username" type="text" required placeholder="Username">
           <input id="login-password" type="password" required placeholder="Password">
           <input type="submit" value="Sign in">
         </form>
@@ -344,10 +293,12 @@
 
   

Then, we'll add code to handle the form submission:

-
+  
     
     <!-- application code -->
     <script type="text/javascript">
+      userbase.configure({ appId: 'YOUR_APP_ID' })
+
       function handleLogin(e) {
         e.preventDefault()
 
@@ -355,7 +306,7 @@
         const password = document.getElementById('login-password').value
 
         userbase.signIn(username, password)
-          .then((session) => alert('You signed in!'))
+          .then((user) => alert('You signed in!'))
           .catch((e) => document.getElementById('login-error').innerHTML = e)
       }
 
@@ -369,7 +320,7 @@
     
   
-

And finally, bind the login form within our login handler:

+

And finally, let's bind our login form within our login handler:

     
@@ -378,7 +329,7 @@
 
     ...
 
-        .catch((e) => document.getElementById('create-account-error').innerHTML = e)
+        .catch((e) => document.getElementById('signup-error').innerHTML = e)
       }
 
       document.getElementById('login-form').addEventListener('submit', handleLogin)
@@ -388,19 +339,14 @@
     
   
-

You'll notice this looks very similar to the sign up code above.

-

- We define a function, handleLogin, to handle form submissions. The function - prevents the default form behavior, extracts the input values from the DOM, and - calls userbase.signIn(username, password). This will attempt to sign in the user with the Userbase service, handling a success with an alert and a failure - by displaying the error. + You'll notice this looks very similar to the sign up code above. The handleLogin function prevents the default form behavior, extracts the input values from the DOM, and calls userbase.signIn(username, password). This will attempt to sign in the user with the Userbase service, handling a success with an alert and a failure by displaying the error.

- Reload the app and you'll now see a "Sign In" form. Enter the username and - password you used to create an account in the step above and submit the form. - You'll get an alert saying "You signed in!" + Reload the app and you should see our new login form. Enter the username and + password you used to create an account in the step above, and submit the form. + You should get an alert saying that you signed in.

@@ -411,13 +357,13 @@

Showing the to-do view

- After a r is signed in, we'll want to hide the authentication forms, indicate + After a user signs in, we'll want to hide the authentication forms, indicate to the user they are logged in, and display their to-do list.

-

First, we'll add a new container to the body:

+

First, we'll add a new container under the authentication forms:

-
+  
     
     </div>
 
@@ -426,11 +372,12 @@
       <div id="username"></div>
 
       <h1>To-Do List</h1>
+      <div id="todos"></div>
     </div>
 
     <!-- application code -->
     <script type="text/javascript">
-      function handleLogin(e) {
+      userbase.configure({ appId: 'YOUR_APP_ID' })
 
     ...
 
@@ -438,7 +385,7 @@
     
   
-

Then, we'll add function to display this view and initially make it hidden:

+

Then, we'll add a function to display this view and initially make it hidden:

@@ -459,7 +406,7 @@
 
   

Now that we have a function to show a view for signed in users, let's change - handleLogin to call this function when it succeed: + handleLogin to call this function when it succeeds:

@@ -470,7 +417,7 @@
       const password = document.getElementById('login-password').value
 
       userbase.signIn(username, password)
-        .then((session) => showTodos(session.username))
+        .then((user) => showTodos(user.username))
         .catch((e) => document.getElementById('login-error').innerHTML = e)
     }
     
@@ -483,18 +430,18 @@
     function handleSignUp(e) {
       e.preventDefault()
 
-      const password = document.getElementById('create-account-password').value
+      const password = document.getElementById('signup-password').value
 
       userbase.signUp(username, password)
-        .then((session) => showTodos(session.username))
-        .catch((e) => document.getElementById('create-account-error').innerHTML = e)
+        .then((user) => showTodos(user.username))
+        .catch((e) => document.getElementById('signup-error').innerHTML = e)
     }
     
   

- Reload the app and sign in using your username and password. You'll see the - authentication view disappear and your username show up along with "To-Do List". + Reload the app and sign in again using your username and password. You should see the + authentication view disappear and your username show up along with the to-do list heading.

Using to the database

@@ -505,11 +452,11 @@

- First, let's add a couple elements for showing a loading indicator and error + First, let's add a couple of elements for showing a loading indicator and error messages:

-
+  
     
@@ -775,7 +722,7 @@
     
-

Then, add code to handle click events and log out the user:

+

Then, add code to handle click event and log out the user:

     
@@ -784,7 +731,7 @@
     
     ...
 
-        .catch((e) => document.getElementById('create-account-error').innerHTML = e)
+        .catch((e) => document.getElementById('signup-error').innerHTML = e)
       }
 
       function handleLogout() {
@@ -805,9 +752,9 @@
         document.getElementById('login-username').value = ''
         document.getElementById('login-password').value = ''
         document.getElementById('login-error').innerText = ''
-        document.getElementById('create-account-username').value = ''
-        document.getElementById('create-account-password').value = ''
-        document.getElementById('create-account-error').innerText = ''
+        document.getElementById('signup-username').value = ''
+        document.getElementById('signup-password').value = ''
+        document.getElementById('signup-error').innerText = ''
       }
 
       function handleDatabaseChange(items) {
@@ -824,23 +771,23 @@
     
   
-

The logout function calls userbase.signOut which sends a request to end the user's session to the Userbase service. A Promise is returned that either resolves if the user was signed out successfully, in which case we hide the to-do view and show the account view using showAuth, or rejects with an error, in which case we display the error message.

+

The handleLogout function calls userbase.signOut which sends a request to end the user's session to the Userbase service. A Promise is returned that resolves when the user was signed out, in which case we hide the to-do view and show the authentication view.

Automatically resuming a session

-

Whenever a new session is created, either by signing up or signing in a user, the Userbase client will store information about the session in browser storage to allow for the session to be resumed when the user returns after having navigating away, whether by closing the page or otherwise.

+

Whenever a user logs in, the Userbase SDK will store information about the session in browser to allow the session to be resumed when the user returns after having navigating away.

Let's modify our app to automatically sign in a user when the page loads. We'll add a view that indicates we are signing in the user:

-

Add add a view to show when initializing:

+

Add a view to show when the app is figuring out whether it can resume a previous session:

     
     </head>
  
     <body>
-      <!-- Init View -->
-      <div id="init-view">Signing you in...</div>
+      <!-- Loading View -->
+      <div id="loading-view">Loading...</div>
 
       <!-- Auth View -->
       <div id="auth-view">
@@ -850,7 +797,7 @@
 
   

In order to automatically resume a session if one is available, we add the following to our application code:

-
+  
     
     <!-- application code -->
     <script type="text/javascript">
@@ -866,17 +813,22 @@
       document.getElementById('auth-view').style.display = 'none'
 
       userbase.signInWithSession()
-        .then((session) => showTodos(session.username))
+        .then((session) => {
+          if (session.user) {
+            showTodos(session.user.username)
+          } else {
+            showAuth()
+            document.getElementById('loading-view').style.display = 'none')
+          }
+        })
         .catch(() => showAuth())
-        .then(() => document.getElementById('init-view').style.display = 'none')
 
     </script>
     
   

- We hide the auth view initially, as we'll now only show it if an existing - session can't be resumed. + We hide the authentication view initially, as we'll now only show it if an existing session can't be resumed.

@@ -885,16 +837,27 @@

- This function looks for a previous session in browser storage and if one is - found tries to sign in the user automatically with the Userbase service. It - returns a Promise that will resolve with a new session if the user was able to - be signed in or otherwise reject with ann error message? indicating the reason - for failure. + The userbase.signInWithSession function returns a Promise that resolves when the SDK has determined if it can reuse the previous session. If so, the user gets automatically logged in, and the session.user object gets set. If there was no previous session, or the session cannot be resumed, the session.user object will not be set.

- A failure could be due to either no previous session, the user had - signed out, or their session expired. In our simple app we'll just send the user + If userbase.signInWithSession fails, we'll just send the user to the sign in page regardless of the reason.

-
\ No newline at end of file + +

What's next?

+ +

+ In a real project you'll likely want a more sophisticated approach: for instance, you may use React to control the DOM or a module bundler to package your application from multiple files, and at the very + least you'll want to display better error messages and add some styling. +

+ +

+ We are working on a collection of tutorials and sample applications that will + show you how to do all these things with Userbase and more. You can subscribe to our mailing list to get updates on these and more. +

+ +

If you have any questions, or there's anything we can do to help you with your web app, please get in touch via email or Twitter. Thank you!

+ + +
\ No newline at end of file