Skip to content

BasicAuthable

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

BasicAuthable

A protocol for automatically authenticating incoming requests based on their Authentication:​ Basic ... header. When the request is intercepted by the BasicAuthMiddleware<T>, it will query the table of T in Services.db for a row that has a matching username & validate the password. If the row exists & the password matches, the type T will be set on the request.

public protocol BasicAuthable: Model
// Start with a Rune `Model`.
struct MyUser: BasicAuthable {
    // Note that this defaults to "username" but you can override
    // with a custom value.
    static var usernameKeyString = "email"

    var id: Int?
    let email: String
    let passwordHash: String
}

// Add the BasicAuthMiddleware in front of any endpoints that need
// auth.
app
    // Will apply this auth middleware to all following requests.
    .use(MyUser.basicAuthMiddleware())
    .get("/login") { 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

usernameKeyString

The name of the username row in the model. Defaults to "username", but can be overridden for custom rows. This row should be unique.

var usernameKeyString: String

passwordHashKeyString

The name of the hashed password row in the model. Defaults to "password_hash", but can be overridden for custom rows.

var passwordHashKeyString: String

verify(password:​passwordHash:​)

Verifies a model's password hash given the password string from the Authentication header. Defaults to comparing passwordHash to a Bcrypt hash of the password. Can be overridden for custom password verification.

static func verify(password: String, passwordHash: String) throws -> Bool

Parameters

  • password: The password from an Authentication header, to be compared with the passwordHash of an existing model.
  • passwordHash: The password value of the existing model. Technically doesn't need to be a hashed value if passwordHashKeyString points to an unhashed value, but that wouldn't be very secure, would it?

Throws

Any error that might occur during the verification process, by default a CryptoError if hashing fails.

Returns

a Bool indicating if password matched passwordHash.

Alchemy
Types
Protocols
Global Typealiases
Global Variables
Global Functions
Fusion
Types
Protocols
Papyrus
Types
Protocols
Clone this wiki locally