Getting Started with Server Side Swift: 1.1

Jonathan Guthrie
Server Side Swift and More
7 min readMar 13, 2017

--

The Turnstile SQLite Demo

Welcome to the second installment in my “Getting Started with Server Side Swift” series. Throughout this series I’m going to explain how to do the basics of getting up and running with various different aspects of Server Side Siwft usng the Perfect toolkit.

This article demonstrates running the Turnstile SQLite Demo and exploring it’s web routes & API, as well as get our hands dirty with looking into a SQLite database and finding out about what makes a session tick.

Turnstile is an authentication process built by Stormpath, modelled on Apache Shiro. Perfect has adopted it as one of the authentication options for the project, with drivers for SQLite, MySQL, CouchDB, PostgreSQL and MongoDB.

SQLite is a great teaching database tool as it’s file based and requires virtually no setup and all Macs and most Linux systems come with SQLite as a standard. However I don’t recommend using it in larger scale production systems.

First up, if you haven’t already got the Perfect Assistant application, visit https://www.perfect.org/en/assistant/ to download the Perfect Assistant.

On the “Welcome” screen, click on the “Create New Project” button.

This will slide down a sheet which as two types of projects. Under the “Examples” select the “Perfect: Turnstile with SQLite”.

Use the “Browse button” to choose a location for your app — and create a new folder for it if you wish. Note that back in the Perfect Assistant the “Project Name” is the name of the folder you chose.

Uncheck the “Integrate Linux builds with the Xcode Project” as we’re not deploying to Linux in this walkthrough.

Once you press “Save” the Perfect Assistant will go ahead and create the project, downloading all the dependencies and creating your Xcode project file.

Once complete, your project will also be listed in the “Projects” list on the left. It shows you the dependencies already in the project — don’t worry if you don’t see things that you think should be there, the sub-dependencies are automatically included too.

From here you can also open the project directory in the finder or a terminal window, and open the Xcode project.

In Xcode, open the Sources directory and you will see a number of other dependencies that have automatically been added to our project. These have been added because they are sub-dependencies.

Inside our project source directory is a main.swift file.

This contains the code for running the demo. A few things to point out.

On line 38, this is where we define the location of the SQLite database file — the SQLiteConnector.db property is set to “./authdb”.

SQLiteConnector.db = “./authdb”

Because SQLite is a file-based database, we can put the file anywhere we want, but in this case we are telling the application to put it in the run-time working directory.

You will also note in the Project Navigator, that we have a directory called “webroot”. This is where we are keeping the static assets like CSS, JavaScript and images — as well as mustache templates, which we’ll look at in another instalment in this series.

Because there are files like the SQLite database and webroot directory, we need to tell Xcode where to consider the “Working Directory” to be.

In the “scheme” dropdown, make sure you select the “Terminal-looking” black icon and make sure the target is “My Mac”. Now, lets select “Edit Scheme”.

In the “Run -> Options” tab, make sure the “Working directory” option is checked, then click the “folder” icon in the text entry area and navigate to the project’s directory. In here you’ll see the “Sources” directory and the “webroot”.

The project can now be run — either press the triangle “Run” button, or on the keyboard press CMD-R.

Once it’s built Xcode executes the application, and in the lower-right side console view the message will appear that it’s started the HTTP server on port 8181.

[INFO] Running setup: users
[INFO] Running setup: tokens
[INFO] Starting HTTP server on 0.0.0.0:8181

In a browser on localhost port 8181 we see a welcome screen, asking us to log in, as well as a few other informative links.

Click the Login link… but we haven’t created an account yet so we need to click “Register”

Enter a user name and a password. On submit you’ll see that it has returned showing that you have an “ID”, and that top right it now says “log out”.

So it looks like we have created an account and are now logged in.

Open up the developer tools for your browser. In Safari this can be done by pressing cmd-option-i. Click on “Storage”, and “Cookies”. You’ll see that we have a “TurnstileSession” cookie, and with a value like what is shown in this next screenshot:

Lets go look at the database. Switch to Perfect Assistant, and click the “Open: Project Directory” button. In the finder window that’s opened you’ll see a file called “authdb” — this corresponds to the file that we referenced in the project’s main.swift.

Back in Perfect Assistant, click the “Open: Project Terminal” button. This will launch the Terminal with the working directory as our project.

Open the SQLite database:

sqlite3 authdb

Once we see the sqlite prompt, we can see the SQL schema with:

.schema

It will show us two tables, one that holds the users, the other that holds the “tokens”. These tokens associate a browser session with a user.

sqlite> .schema
CREATE TABLE users (uniqueID TEXT PRIMARY KEY NOT NULL, username TEXT, password TEXT, facebookID TEXT, googleID TEXT, firstname TEXT, lastname TEXT, email TEXT);
CREATE TABLE tokens (token TEXT PRIMARY KEY NOT NULL, userid TEXT, created INTEGER, updated INTEGER, idle INTEGER);

To see all the users:

sqlite> SELECT * FROM users;e-IsVfqBuiLLbOV4nVjVTQ|jono| $2a$10$a8k9zRbg.vwZ1s/g48XwW.2KpEy1d3ucav6Twm5SNlP7y/IslvyVG|||||

You will see a very condensed-looking row returned. It’s not very human readable at first glance, however you’ll notice that the first chunk of text is the user id that was shown in the browser after you registered. Then there’s a pipe character (vertical line), and then your user name. In my case, I just entered “jono”. The next column is a mess of strange characters — this is actually our password we entered, but it’s been encrypted. We must never store passwords or other sensitive information in plain text in a database!

OK, so now lets have a look at whats stored in the “tokens” table.

sqlite> SELECT * FROM tokens;5_5-PL962Y7OciEOMnSA0g|e-IsVfqBuiLLbOV4nVjVTQ| 511061531|511061531|86400

This contains a value at the start that you hopefully notice is the same as the value of the cookie I showed you earlier. The next value is the associated user id from the user table. Next are the values that correspond to the date & time created, last updated (or “touched”), and the session idle time. A session is deemed to be “expired”, or “invalid”, if the difference between now and the last updated plus the idle time is greater than zero.

So now we have seen the session cookie in the browser, and the that there is an association between that same value and your userid, it might occur to you that this is indeed how authentication happens.

A session is simply a link between all your interactions and the server. Each time the browser or JSON API talks to the server, it sends this session id — often in the form of a cookie. The server can then know that it should link the interactions together — and if there is a user id in the session then it can deliver user specific information or privileges.

Next steps

For live help from our awesome community, join our Slack channel via www.perfect.ly and say hi!

For examples visit GitHub.com/perfectexamples — there is an ever growing library of examples and demos there.

If you prefer to watch the video of this, heres the link: Getting Started with Perfect — Turnstile SQLite Demo

--

--

Jonathan Guthrie
Server Side Swift and More

Developer Evangelist, Musician, and Active Activist... Newmarket ON, Canada