Hackernoon logoHow to Register Users on Your Wix Website by@stefanhorne

How to Register Users on Your Wix Website

Stefan Horne Hacker Noon profile picture

@stefanhorneStefan Horne

Software developer @ Virgin Experience Days

Signing up to a website typically involves completing a form, whereby you hand over some of your personal information in exchange for a personalised experience. This can be said for most types of registration, but signing up to a website has a unique point of frustration in that it requires a sufficiently complex yet easily memorable password.

Incidentally, the frustration stems--in part--from the fact that we've all been trained to use passwords that are difficult for us to remember, but easy for computers to guess.

We're all aware of how cumbersome it can be to devise a new password (or to opt for that one we always reuse, against our better judgment) only to find that it doesn't meet this particular website's complexity requirements, at which point we just stick an extra digit on the end (against our better judgement, again) and hope to God that we remember it the next time we have to log in. Oh, and "We've sent you an email. Please click the link to verify your email address."--ugh.

What if we could avoid all this friction and register with the click of a button?

Enter: third-party authentication

You've seen the buttons.

Often referred to as "social logins", these integrations allow website owners like yourself to leverage an already-established relationship with the user to streamline the whole process, providing a better experience for the user and increasing the likelihood that they'll sign up to your site.

With Wix's integrated development environment (IDE), Velo, it is now possible to add custom third-party authentication to your Wix website--hooray!

We'll take a look at how to do this soon enough, but let's first take a look at how third-party authentication actually works under the hood.

(In case you only care about the code, all the below examples can be found on my GitHub here)

OAuth, you say?

These third-party integrations follow a conventional flow called OAuth 2, whose Wikipedia page describes it as "an open standard for access delegation", but what does that actually mean?

OAuth isn't an API, nor is it a specific technology; it's simply a convenient, conventional way to establish trust between two parties. It's conventional just like it's conventional to shake someone's hand when meeting them (or not to, given recent events). OAuth can be implemented with 3 people, a pen, and a scrap of paper. Allow me to illustrate with the following exchange:

Slade and Cassidy were two peas in a pod. They worked together for years, and even went fishing together at the weekends.

One day Slade received word that his lockbox had finally arrived at a local shop, so he headed over during his lunch break to pick it up. When he arrived, he found the aged shopkeeper humming to herself and polishing a large copper vase.

"Hi", he said, "I'm here to pick up a lockbox that was delivered for me?"

"Afternoon sir," she replied, "tha's no problem—if we could just ge' ya ta fill in a wee form and give us a copy of yer key."

"A copy of my key? Why d'you need that?"

"Well, how else would we know the box is yers? and the form too—we'll need yer full name and date of birth, please."

"My what? What d'you need all that information for?"

"Why, our records, of course."

"I'm sorry, but isn't that a bit excessive?" he asked, "I'm just here to pick up my lockbox—look, it's got my name on it. How about if I just gave you my name?"

"Sorry sir", she returned to polishing the vase, "but if ya can't prove yer identity then there's nothin' we can do for ya.", she said with a degree of finality that told him it would be unwise to press further.

Cassidy would know what to do, he thought, as he looked down at his watch. He'd have to hurry if he wanted to make it back to the office by the end of his break.

"Be right back", he turned on his heel.

A few minutes later, he was standing in front of Cassidy's office. He let himself in, sank into the guest chair across from her desk, and proceeded to explain his predicament.

"...and that vase had been polished quite enough if you ask me", he finished.

"Ohhh, Janet? I know her—she's lovely, really. You say she needs your name?" Slade nodded as Cassidy grabbed a scrap of paper from her desk and scribbled something unintelligible before signing it.

"Go and give her this—she'll know what it means.

He looked suspiciously at the paper, then up at her. It was not unlike her to play jokes on him, but today she had the look she always got when she helped him untangle his fishing line.

"Thanks Cass, I owe you one", he took the note and dashed for the door.

With ten minutes left of his lunchbreak, he stepped into Janet's store, where he quickly found the shopkeeper and offered her the slip of paper.

She accepted it from him and eyed it dubiously before picking up the telephone.

"I really need to get myself one of those", he muttered as she dialed.

"Hello, Cassidy? It's Janet—how are ya darlin?"

"No' too bad—ya know how quiet it gets around this time of year..."

"...he's doin' fine, just the gout is acting up again...."

"...no no, that'll be next month..."

"..."

"..."

"Yes, well I've go' a young man here—he's go' a wee scrap o' paper with yer signature on it."

"Of course. It says...", Slade looked impatiently at his watch as she read aloud the code that had been scribbled on the note.

"His name is Slade, is it? Well, that settles it then..."

"...you take care darlin', bye-bye."

She turned to him, "Right lad! If yer okay with Cass then yer okay with me", and patted him on the shoulder before heading into the back of the shop, returning a few seconds later with a green lockbox bearing his name in golden letters.

He smiled as he took it and placed it on the counter. Then he pulled out a key that was hanging from a cord around his neck, stuck it into the keyhole, and turned it with a satisfying click.

Then he placed his hands on the lid and slowly opened it.

"Bologne today, my favourite!"

By delegating authorisation to Cassidy, Slade was able to get his lunch without forking over any extraneous information. And furthermore, he would be able to ask Cassidy not to share his name anymore if he changed his mind.

This entire exchange relied on pre-existing trust between Cassidy and the others. This is the essence of OAuth.

So, how can I implement this on my Wix website?

Finally, the bit you've been waiting for, how can you implement this? We'll take a look at a specific implementation that uses GitHub's OAuth API, but the flow will be similar for other providers.

1. Establish trust

First, you (the storekeeper) have to establish trust with the third party (Cassidy). The specifics will vary, but this typically involves registering yourself and then registering your application with them. Once you've done this you will receive a public and private key that you must use to identify your application with every request. After all, people can recognise each other by voice, but computers cannot.

Note: do not share your private key / secret

2. Direct your users

Next, you have to direct your user to the provider's authorisation page when they register. But unlike Slade, they won't know how to get there, so you have to make it simple for them: build them a button.

This can be done quite easily with the Velo JavaScript IDE.

import wixLocation from 'wix-location'

const client_id = "<YOUR CLIENT ID HERE>";

$w.onReady(async function () {

    $w('#button1').onClick(() => {
        // redirect the user to github
        return wixLocation.to(`https://github.com/login/oauth/authorize?client_id=${client_id}&scope=user:email`)
    })

});

So, the user clicks your button, is whisked away briefly to authorise your app, before being redirected back to your site with a code in the URL.

Admittedly, me doing this is silly because it's my own application, but let's just imagine that I'm one of your users and that My Awesome App is your awesome app.

(BTW, if you're wondering how the third party knows where to send the user with the code, it's wherever you told them to in the previous step--see Authorization callback URL)

3. Retrieve their information

Ok, now that they've stepped back into your shop with code in hand, you have to politely accept it and call the third party to confirm that they issued it. If it's the real deal they'll exchange it for a token that can henceforth, and until the user revokes access, be used to retrieve any information they have granted you (in this case we've only asked for their email address).

Just to recap, here's the flow so far:

Shut up and show me some code already!

Okay okay, here's how to get the access token and the email address using GitHub as the third party:

async function getAccessToken(code) {
    const response = await axios.post(`https://github.com/login/oauth/access_token`, {
        client_id,
        client_secret,
        code
    });

    if (!response.status === 200)
        throw new Error(`Oh no, something went wrong!`)

    const params = parseParams(response.data)

    return {
        accessToken: params.access_token
    }
}
async function getEmailAddress(accessToken) {
    const response = await axios.get(`https://api.github.com/user/emails`, {
        headers: {
            Authorization: `Bearer ${accessToken}`
        }
    })

    if (!response.status === 200)
        throw new Error('Oh no, something went wrong!')

    const primary = response.data.filter(email => email.primary)[0]

    return primary.email
}

4. Log them in

Finally, you'll log the user in with the Velo Users API, supplying their email address, which we retrieved in the previous step, and receive a session token in return (If a Wix user with the specified email address doesn't exist, a new member is created with a randomized password). Then, it's just a question of applying the session token on the frontend.

Backend:

import wixUsersBackend from 'wix-users-backend';

async function login(code) {
    const { accessToken } = await getAccessToken(code)
    const email = await getEmailAddress(accessToken)

    const sessionToken = await wixUsersBackend.generateSessionToken(email)

    return { sessionToken }
}

Page code:

import wixLocation from "wix-location";
import wixUsers from "wix-users";

import { login } from "backend/auth";

$w.onReady(async function () {
  if (!wixUsers.currentUser.loggedIn) {
    // retrieve the code from the url
    const { code } = wixLocation.query;
    const { sessionToken } = await login(code);

    // log them in
    if (sessionToken) {
      await wixUsers.applySessionToken(sessionToken);
    }

    wixLocation.to("/home");
  }
});

Reminder: the complete versions of these examples can be found on my GitHub, here. Feel free to fork!

And there you have it, folks. With user registered and logged in you can forward them to your homepage or your members' area, where you might give them the option to sign up for a weekly newsletter, allow them to comment on your blog posts, or simply offer them a personalised "Hellooo!"; where to go from here is up to you.

We covered a specific implementation using GitHub, and I hope it was useful to you, but I also hope that you walk away with a more intuitive understanding of OAuth, so that next time you see those social login buttons you'll say "Hey, this is just like that time Slade got his lunch!".

This article is part of a writing contest hosted by Hacker Noon in partnership with Wix. Learn how to enter here and take a shot at winning $1000 every month, from March 1st, 2021 to May 31st, 2021

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.