Skip to content

TokenAuthable

Josh Wright edited this page Jan 14, 2021 · 4 revisions

TokenAuthable

A protocol for automatically authenticating incoming requests based on their Authentication:​ Bearer ... header. When the request is intercepted by a related TokenAuthMiddleware<T>, it will query the table of T in Services.db for a row that has a matching token value. If the exists, the correlating User type will be queried and set on the request.

public protocol TokenAuthable: Model
// Start with a Rune `Model`.
struct MyToken: TokenAuthable {
    // `KeyPath` to the relation of the `User`.
    static var userKey: KeyPath<UserToken, BelongsTo<User>> = \.$user

    var id: Int?
    let value: String

    @BelongsTo
    var user: User
}

// Add the TokenAuthMiddleware in front of any endpoints that need
// auth.
app
    // Will apply this auth middleware to all following requests.
    .on(MyToken.tokenAuthMiddleware())
    .on(.GET, "/todos") { req in
        // Middleware will have authed and set a user on the
        // request, or returned an unauthorized response.
        let authedUser = try req.get(User.self)

        ...
    }

Inheritance

Model

Requirements

valueKeyString

The name of the row that stores the token's value. Defaults to "value".

var valueKeyString: String

userKey

A keypath to the parent User model. Note that this a KeyPath to the relationship type, so it will begin with a "$", such as \.$user as opposed to \.user.

var userKey: KeyPath<Self, Self.BelongsTo<User>>
Alchemy
Types
Protocols
Global Typealiases
Global Variables
Global Functions
Fusion
Types
Protocols
Papyrus
Types
Protocols
Clone this wiki locally