Add the ability to click on the verification link and verify your email
authorNick Downing <nick@ndcode.org>
Sat, 15 Jan 2022 03:45:36 +0000 (14:45 +1100)
committerNick Downing <nick@ndcode.org>
Sat, 15 Jan 2022 03:45:36 +0000 (14:45 +1100)
api/errors.json
api/sign_up/send_verification_email.json.jst
api/sign_up/verify_email.json.jst [new file with mode: 0644]
my_account/sign_up/index.html.jst
my_account/verify_email/index.html.jst [new file with mode: 0644]

index 3860cfa..4ac84de 100644 (file)
@@ -20,6 +20,9 @@
   "419": "Verification code mismatch",
   "420": "Account already exists",
   "421": "Account does not exist",
+  "422": "Email already verified",
+  "423": "Link code missing",
+  "424": "Link code mismatch",
   "500": "Internal server error",
   "501": "Not implemented",
   "502": "Bad gateway",
index 47da582..7ef9d16 100644 (file)
@@ -44,12 +44,12 @@ return async env => {
             421
           )
 
-        let key = crypto.randomBytes(16).toString('hex')
+        let link_code = crypto.randomBytes(16).toString('hex')
         let expires = new XDate()
         expires.addDays(1)
         account.set(
           'verify_email',
-          transaction.json_to_logjson({key, expires: expires.getTime()})
+          transaction.json_to_logjson({link_code, expires: expires.getTime()})
         )
 
         let given_names = await logjson.logjson_to_json(
@@ -71,7 +71,7 @@ return async env => {
 We have received a request to sign up using your email address.
 
 If this request is valid, please verify your email address by visiting the below link:
-${globals.site_url}/my_account/verify_email/index.html?email=${encodeURIComponent(email)}&key=${key}
+${globals.site_url}/my_account/verify_email/index.html?email=${encodeURIComponent(email)}&link_code=${encodeURIComponent(link_code)}
 
 The link is valid for 24 hours.
 
diff --git a/api/sign_up/verify_email.json.jst b/api/sign_up/verify_email.json.jst
new file mode 100644 (file)
index 0000000..b82e328
--- /dev/null
@@ -0,0 +1,89 @@
+let crypto = require('crypto')
+let logjson = (await import('@ndcode/logjson')).default
+let XDate = require('xdate')
+
+return async env => {
+  let post_request = await _require('/_lib/post_request.jst')
+  let session_cookie = await _require('/_lib/session_cookie.jst')
+  let Problem = await _require('/_lib/Problem.jst')
+
+  post_request(
+    // env
+    env,
+    // endpoint
+    '/api/sign_up/verify_email',
+    // func
+    async (email, link_code) => {
+      // coerce and/or validate
+      email = email.slice(0, 256).toLowerCase()
+      link_code = link_code.slice(0, 256).toLowerCase()
+      if (email.length === 0 || link_code.length < 32)
+        throw new Problem(
+          'Bad request',
+          'Minimum length check failed',
+          400
+        )
+
+      let transaction = await env.site.database.Transaction()
+      try {
+        // initialize env.session_key, set cookie in env.response
+        await session_cookie(env, transaction)
+
+        let account = await (
+          await (
+            await transaction.get({})
+          ).get('accounts', {})
+        ).get(email)
+        if (account === undefined)
+          throw new Problem(
+            'Account does not exist',
+            `Please create the account for "${email}" before attempting to verify the email link.`
+            421
+          )
+
+        if (
+          await logjson.logjson_to_json(
+            await account.get('email_verified')
+          )
+        )
+          throw new Problem(
+            'Email already verified',
+            `Your email "${email}" is already verified. You can now sign in.`
+            422
+          )
+
+        let verify_email = await account.get('verify_email')
+        if (
+          verify_email === undefined ||
+            XDate.now() >= await logjson.logjson_to_json(
+              await verify_email.get('expires')
+            )
+        )
+          throw new Problem(
+            'Link code missing',
+            `Link code for email "${email}" does not exist or has expired.`,
+            423
+          )
+        if (
+          link_code !== await logjson.logjson_to_json(
+            await verify_email.get('link_code')
+          )
+        )
+          throw new Problem(
+            'Link code mismatch',
+            `Provided link code "${link_code}" does not match expected value.`,
+            423
+          )
+
+        await account.delete('verify_email')
+        await account.set('email_verified', true)
+
+        await transaction.commit()
+      }
+      catch (error) {
+        transaction.rollback()
+        throw error
+      }
+    }
+  )
+}
index 8a3963a..894787c 100644 (file)
@@ -107,7 +107,7 @@ return async env => {
                   img#verification-image(src="/api/verification_image.png?seq=0" width=300 height=150) {}
                 }
                 div.'col-md-2'.my-auto.text-center {
-                  input.btn.btn-outline-secondary#'new-code'(type="button" value="New code") {}
+                  input.btn.btn-outline-secondary#'step-1-new-code'(type="button" value="New code") {}
                 }
               }
 
@@ -141,8 +141,8 @@ return async env => {
             div.card-body {
               p#step-2-message {'Please enter your details first.'}
 
-              input.btn.btn-outline-secondary.mr-3#step-2-back(type="button" value="Back") {}
-              input.btn.btn-outline-secondary#step-2-continue(type="button" value="Continue") {}
+              input.btn.btn-outline-secondary#step-2-back(type="button" value="Back") {}
+              input.btn.btn-outline-secondary.ml-3#step-2-continue(type="button" value="Continue") {}
             }
           }
         }
@@ -169,8 +169,8 @@ return async env => {
             div.card-body {
               p#step-3-message {'Please create your account first.'}
 
-              input.btn.btn-outline-secondary.mr-3#step-3-back(type="button" value="Back") {}
-              input.btn.btn-outline-secondary#step-3-resend-email(type="button" value="Resend email") {}
+              input.btn.btn-outline-secondary#step-3-back(type="button" value="Back") {}
+              input.btn.btn-outline-secondary.ml-3#step-3-resend-email(type="button" value="Resend email") {}
             }
           }
         }
@@ -240,20 +240,19 @@ return async env => {
           return true
         }
 
-        let step_3_email = ''
+        let step_2_details = ''
         let step_2 = async () => {
           $('#step-2-tick').hide()
           $('#step-2-cross').hide()
           $('#step-2-spinner').show()
           try {
-            let details = coerce_details()
+            step_2_details = coerce_details()
             await sign_up_create_account(
               // verification_code
               document.getElementById('verification-code').value.slice(0, 6).toLowerCase(),
               // details
-              details
+              step_2_details
             )
-            step_3_email = details.email
           }
           catch (e) {
             $('#step-2-tick').hide()
@@ -268,7 +267,7 @@ return async env => {
           $('#step-2-cross').hide()
           $('#step-2-spinner').hide()
 
-          document.getElementById('step-2-message').textContent = `Your account with email "${document.getElementById('email').value}" has been created.`
+          document.getElementById('step-2-message').textContent = `Your account with email "${step_2_details.email}" has been created.`
           return true
         }
 
@@ -277,7 +276,7 @@ return async env => {
           $('#step-3-cross').hide()
           $('#step-3-spinner').show()
           try {
-            await sign_up_send_verification_email(step_3_email)
+            await sign_up_send_verification_email(step_2_details.email)
           }
           catch (e) {
             $('#step-3-tick').hide()
@@ -292,12 +291,12 @@ return async env => {
           $('#step-3-cross').hide()
           $('#step-3-spinner').hide()
 
-          document.getElementById('step-3-message').textContent = 'Verification email has been sent. Please check your email for next steps.'
+          document.getElementById('step-3-message').textContent = `Verification email has been sent to "${step_2_details.email}". Please check your email for next steps.`
           return true
         }
+
         document.addEventListener(
-          'DOMContentLoaded', 
+          'DOMContentLoaded',
           () => {
             document.getElementById('given-names').addEventListener(
               'change',
@@ -320,6 +319,15 @@ return async env => {
               draft_change_handler
             )
 
+            let image_seq = 1
+            document.getElementById('step-1-new-code').addEventListener(
+              'click',
+              () => {
+                document.getElementById('verification-image').src = `/api/verification_image.png?seq=${image_seq}`
+                image_seq += 1
+              }
+            )
+
             document.getElementById('step-1-continue').addEventListener(
               'click',
               async () => {
@@ -339,7 +347,7 @@ return async env => {
                 if (await step_3())
                   $('#step-3-collapse').collapse('show')
               }
-           )
+            )
 
             document.getElementById('step-3-back').addEventListener(
               'click',
@@ -353,14 +361,6 @@ return async env => {
                   $('#step-3-collapse').collapse('show')
               }
             )
-
-            let image_seq = 1
-            $('#new-code').click(
-              () => {
-                document.getElementById('verification-image').src = `/api/verification_image.png?seq=${image_seq}`
-                image_seq += 1
-              }
-            ) 
           }
         )
       }
diff --git a/my_account/verify_email/index.html.jst b/my_account/verify_email/index.html.jst
new file mode 100644 (file)
index 0000000..dee5ab3
--- /dev/null
@@ -0,0 +1,183 @@
+let logjson = (await import('@ndcode/logjson')).default
+
+return async env => {
+  let breadcrumbs = await _require('/_lib/breadcrumbs.jst')
+  let icon_cross = await env.site.get_min_svg('/_svg/icon_cross.svg')
+  let icon_tick = await env.site.get_min_svg('/_svg/icon_tick.svg')
+  let navbar = await _require('/_lib/navbar.jst')
+  let session_cookie = await _require('/_lib/session_cookie.jst')
+
+  // preload draft details if any
+  let details = {}
+  if (Object.prototype.hasOwnProperty.call(env.parsed_url.query, 'email'))
+    details.email = decodeURIComponent(env.parsed_url.query.email)
+  if (
+     Object.prototype.hasOwnProperty.call(
+      env.parsed_url.query,
+      'link_code'
+     )
+   )
+    details.link_code =
+      decodeURIComponent(env.parsed_url.query.link_code)
+  console.log('details', JSON.stringify(details))
+
+  await navbar(
+    env,
+    // head
+    async _out => {},
+    // body
+    async _out => {
+      await breadcrumbs(env, _out)
+
+      p {'You will need to verify your email address via an email link before you can sign in to your account.'}
+
+      div.accordion#accordion.mb-5(role="tablist" aria-multiselectable="true") {
+        div.card {
+          div.card-header#step-1-heading(role="tab") {
+            span#step-1-tick(style="display: none;") {
+              span.icon-color.pr-3 {_out.push(icon_tick)}
+            }
+            span#step-1-cross(style="display: none;") {
+              span.icon-color.pr-3 {_out.push(icon_cross)}
+            }
+            //span#step-1-spinner(style="display: none;") {
+            //  span.icon-color.pr-3 {
+            //    div.spinner-border(role="status") {
+            //      span.sr-only {'Loading...'}
+            //    }
+            //  }
+            //}
+            a.h5(data-toggle="collapse" data-parent="#accordion" href="#step-1-collapse" aria-expanded="true" aria-controls="step-1-collapse") {
+              'Link details'
+            }
+          }
+          div#step-1-collapse.collapse.show(role="tabpanel" aria-labelledby="step-1-heading" data-parent="#accordion") {
+            div.card-body {
+              div.row {
+                div.col-md-6 {
+                  div.form-group {
+                   label.form-label(for="email") {'Email *'}
+                    input.form-control#email(type="email" value=details.email || '' placeholder="Account email address" required="required" maxlength=256) {}
+                  }
+                }
+                div.col-md-6 {
+                  div.form-group {
+                    label.form-label(for="link-code") {'Link code *'}
+                    input.form-control#link-code(type="text" value=details.link_code || '' placeholder="Type the code from the email link" required="required" minlength=32 maxlength=32) {}
+                  }
+                }
+              }
+
+              input.btn.btn-success#step-1-continue(type="button" value="Continue") {}
+              p.'mt-3'.mb-0 {'* These fields are required.'}
+            }
+          }
+        }
+        div.card {
+          div.card-header#step-2-heading(role="tab") {
+            span#step-2-tick(style="display: none;") {
+              span.icon-color.pr-3 {_out.push(icon_tick)}
+            }
+            span#step-2-cross(style="display: none;") {
+              span.icon-color.pr-3 {_out.push(icon_cross)}
+            }
+            span#step-2-spinner(style="display: none;") {
+              span.icon-color.pr-3 {
+                div.spinner-border(role="status") {
+                  span.sr-only {'Loading...'}
+                }
+              }
+            }
+            a.h5.collapsed(data-toggle="collapse" data-parent="#accordion" href="#step-2-collapse" aria-expanded="false" aria-controls="step-2-collapse") {
+              'Verify email'
+            }
+          }
+          div#step-2-collapse.collapse(role="tabpanel" aria-labelledby="step-2-heading" data-parent="#accordion") {
+            div.card-body {
+              p#step-2-message {'Please enter email link details first.'}
+
+              input.btn.btn-outline-secondary#step-2-back(type="button" value="Back") {}
+              input.btn.btn-outline-secondary.ml-2#step-2-sign-in(type="button" value="Sign in") {}
+            }
+          }
+        }
+      }
+    },
+    // scripts
+    async _out => {
+      script(src="/js/api_call.js") {}
+
+      script {
+        let sign_up_verify_email = async (...arguments) => api_call(
+          '/api/sign_up/verify_email.json',
+          ...arguments
+        )
+
+        let step_1 = async () => {
+          if (
+            !document.getElementById('email').reportValidity() ||
+              !document.getElementById('link-code').reportValidity()
+          ) {
+            $('#step-1-tick').hide()
+            $('#step-1-cross').show()
+            //$('#step-1-spinner').hide()
+            return false
+          }
+          $('#step-1-tick').show()
+          $('#step-1-cross').hide()
+          //$('#step-1-spinner').hide()
+          return true
+        }
+
+        let step_2 = async () => {
+          $('#step-2-tick').hide()
+          $('#step-2-cross').hide()
+          $('#step-2-spinner').show()
+          let email
+          try {
+            email = document.getElementById('email').value.slice(0, 256).toLowerCase()
+            await sign_up_verify_email(
+              // email
+              email,
+              // link_code
+              document.getElementById('link-code').value.slice(0, 32).toLowerCase()
+            )
+          }
+          catch (e) {
+            $('#step-2-tick').hide()
+            $('#step-2-cross').show()
+            $('#step-2-spinner').hide()
+
+            document.getElementById('step-2-message').textContent = e.message
+            $('#step-2-collapse').collapse('show')
+            return false
+          }
+          $('#step-2-tick').show()
+          $('#step-2-cross').hide()
+          $('#step-2-spinner').hide()
+
+          document.getElementById('step-2-message').textContent = `Your email "${email}" has been verified. You can now sign in.`
+          return true
+        }
+
+        document.addEventListener(
+          'DOMContentLoaded',
+          () => {
+            document.getElementById('step-1-continue').addEventListener(
+              'click',
+              async () => {
+                if (await step_1() && await step_2())
+                  $('#step-2-collapse').collapse('show')
+              }
+            )
+
+            document.getElementById('step-2-back').addEventListener(
+              'click',
+              () => {$('#step-1-collapse').collapse('show')}
+            )
+          }
+        )
+      }
+    }
+  )
+}