Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
49 changes: 49 additions & 0 deletions Hummingbird.docc/Examples/OTPAuthenticationExample.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# OTP Authentication Example

Example demonstrating how to setup one time passwords, using sessions.

> The source code for this example can be found [here](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp)

This example starts with a standard username/password login. There is a link to a signup screen where you can enter your name, email and password. When you return to the login screen you can use your email and password to access the main page. On the main page is a button to add an OTP token to your account. This links to a page consisting of a QR code generated from the OTP secret and a text input for you to verify your OTP password generation is correct. Use Apple Passwords or Google Authenticator to scan the QR code. Once verified you are allowed to press the button that adds the OTP secret to your account. From this point on when you login you will also be requested for your one time password.

## Database

`PostgresNIO` and ``PostgresMigrations`` are used in this example to access and store your persistent data. The demo creates two tables and an index.
- Table `users` with columns `id`, `name`, `email`, `passwordHash`
- Table `totp` with columns `user_id` and `secret`
- Index for `email` in table `users`

You can find the migrations for these in the [Migrations folder](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Migrations). These are added to the migration list in the `buildApplication` function. We need to apply these migrations before the server starts but after the PostgresClient connection manager background process has started. This can be done by calling the ``/PostgresMigrations/DatabaseMigrations/apply(client:groups:logger:dryRun:)`` function inside a closure sent to ``/Hummingbird/Application/beforeServerStarts(perform:)``.

On top of the two tables created, the example uses the postgres driver ``/HummingbirdPostgres/PostgresPersistDriver`` for the persist framework to store session keys. You will find out more about the persist framework at <doc:PersistentData> and there is a guide to the migration support in <doc:MigrationsGuide>.

There is a docker-compose file available to run a local Postgres database.

## Walkthrough

### Controllers

The example has three controllers
- [`UserController`](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Controllers/UserController.swift): API for completing user creation/login/logout
- [`WebController`](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Controllers/WebController.swift): The app uses ``/Hummingbird/FileMiddleware`` to serve most web pages but this controller is used to create the dynamic main web page.
- [`TOTPController`](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Controllers/TOTPController.swift): API for starting, verifying and completing TOTP creation.

### Authentication

For authentication purposes the example uses ``/HummingbirdBasicAuth/BasicAuthenticator`` to provide a standard username/password login and ``/HummingbirdAuth/SessionAuthenticator`` for authenticating based off a session id. Both of these require a repository type that defines how to access a user based off either a username or session identifier. We create a protocol [`UserRepository`](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Repositories/UserRepository.swift) for the repository and conform it to the relevant protocols to be used with the basic and session authenticator middleware. And then we implement a concrete version of this protocol that uses `PostgresNIO`.

To use the `SessionAuthenticator` we need to add the ``/HummingbirdAuth/SessionMiddleware``. This extracts session id from the request and responds with `set-cookie` headers if the session needs updated. The session middleware converts the session id into an associated session type. In the case of this example the session type consists of two possible authentication states, either `authenticated` or `challenge`. The only challenge available is the TOTP. A user is only considered to be authenticated is the session state is `authenticated`.

To convert the session state from `challenge` to `authenticated` we have included a [`TOTPMiddleware`](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Middleware/TOTPMiddleware.swift). This will extract the TOTP token from the request headers and then compare it to the TOTP tokens generated by ``/HummingbirdOTP/TOTP``. If one of them is equal then we change the session state to `authenticated`.

### RequestContexts

This example uses multiple ``/Hummingbird/RequestContext``. If starts with ``/Hummingbird/BasicRequestContext`` which provides the functionality for a basic Hummingbird application, but does not support authentication or sessions. When we call any route that requires authentication or sessions we convert this context to a [`AppSessionRequestContext`](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/RequestContext.swift). This conversion is done using ``/Hummingbird/RouterMethods/group(_:context:)-w6fz`` which creates a new ``/Hummingbird/RouterGroup`` using the new `AppSessionRequestContext`.

And then in routes that require an authenticated state we have added conversion to an `AuthenticatedRequestContext` which requires an authenticated identity. This means those routes don't need to check the authenticated state they are provided with a non-optional identity.

You can find out more about `RequestContext` transformations in <doc:RequestContexts#RequestContext-transformation>.

### Dynamic HTML

The `WebController` generates dynamic content for the logged in screen. It uses ``Mustache`` to render the content. The mustache templates are stored in the [Resources](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Resources) folder in the App. The templates are loaded at initialization using `Bundle.module.resourcePath`. The `WebController` when rendering the logged in screen extracts information from the authenticated users and uses that as a context while rendering the page mustache template. The resulting output is then wrapped in an [`HTML`](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-otp/Sources/App/Extensions/html.swift) type that conforms to ``/Hummingbird/ResponseGenerator`` that outputs a `Response` witht eh correct `content-type` header.
3 changes: 2 additions & 1 deletion Hummingbird.docc/HummingbirdOTP/OneTimePasswords.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ Compare it with the password provided by the user to verify the user credentials
## See Also

- ``HummingbirdOTP/TOTP``
- ``HummingbirdOTP/HOTP``
- ``HummingbirdOTP/HOTP``
- <doc:OTPAuthenticationExample>
4 changes: 4 additions & 0 deletions Hummingbird.docc/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ Below is a list of guides and tutorials to help you get started with building yo
- <doc:MustacheSyntax>
- <doc:MustacheFeatures>

### Examples

- <doc:OTPAuthenticationExample>

### Reference Documentation

- ``/Hummingbird``
Expand Down