Bukdu.jl icon indicating copy to clipboard operation
Bukdu.jl copied to clipboard

Example basic authentication

Open rbontekoe opened this issue 4 years ago • 1 comments

A basic authentication example would be great. I saw the example auth.jl but like to know how I can return a 401 Unauthorized response to force the user to login.

rbontekoe avatar Feb 03 '21 11:02 rbontekoe

Here's example like AuthHandler from HTTP.jl docs: https://juliaweb.github.io/HTTP.jl/stable/public_interface/#HTTP.Handlers

using Bukdu
using HTTP

struct ExampleController <: ApplicationController
    conn::Conn
end

const ANIMALS = Dict("uuid" => "ok")

function authenticate(c::ExampleController)
    req = c.conn.request
    if HTTP.hasheader(req, "Animal-UUID")
        uuid = HTTP.header(req, "Animal-UUID")
        if haskey(ANIMALS, uuid)
            return render(Text, "ok")
        end
    end
    req.response.status = 401 # 401 Unauthorized
    return render(Text, "Authentication failed")
end

routes() do
    post("/auth", ExampleController, authenticate)
end

Bukdu.start(8190, host="127.0.0.1")

test requests:

using HTTP
HTTP.post("http://127.0.0.1:8190/auth", ["Animal-UUID"=>"uuid"])
HTTP.post("http://127.0.0.1:8190/auth", ["Animal-UUID"=>"wrong"])
HTTP.post("http://127.0.0.1:8190/auth")

wookay avatar Feb 03 '21 15:02 wookay