-
Notifications
You must be signed in to change notification settings - Fork 16
Documentation for OTP example #104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.