1
0
Fork 0
mirror of https://github.com/zigzap/zap.git synced 2025-10-20 15:14:08 +00:00

BasicAuth/Token68 works + tested

This commit is contained in:
Rene Schallner 2023-04-16 20:32:17 +02:00
parent 56121ced9a
commit 6fb7dc8176
2 changed files with 54 additions and 6 deletions

View file

@ -61,7 +61,7 @@ const BasicAuthStrategy = enum {
/// WWW-Authenticate: Basic realm="this"
///
/// T : any kind of map that implements get([]const u8) -> []const u8
pub fn BasicAuth(Lookup: type, kind: BasicAuthStrategy) type {
pub fn BasicAuth(comptime Lookup: type, comptime kind: BasicAuthStrategy) type {
return struct {
// kind: BasicAuthStrategy,
allocator: std.mem.Allocator,
@ -100,10 +100,8 @@ pub fn BasicAuth(Lookup: type, kind: BasicAuthStrategy) type {
/// Use this to just look up if the base64-encoded auth_header exists in lookup
pub fn authenticateToken68(self: *Self, auth_header: []const u8) bool {
_ = auth_header;
_ = self;
// TODO
return false;
const token = auth_header[AuthScheme.Basic.str().len..];
return self.lookup.*.contains(token);
}
// dispatch based on kind
@ -115,7 +113,7 @@ pub fn BasicAuth(Lookup: type, kind: BasicAuthStrategy) type {
}
}
pub fn authenticateRequest(self: *Self, r: *const zap.SimpleRequest) bool {
if (extractAuthHeader(.Bearer, r)) |auth_header| {
if (extractAuthHeader(.Basic, r)) |auth_header| {
return self.authenticate(auth_header);
}
return false;

View file

@ -187,3 +187,53 @@ test "BearerAuthSingle authenticateRequest" {
try std.testing.expectEqualStrings(HTTP_RESPONSE, received_response);
}
test "BasicAuth authenticateRequest" {
const a = std.testing.allocator;
const token = "QWxhZGRpbjpvcGVuIHNlc2FtZQ==";
// setup listener
var listener = zap.SimpleEndpointListener.init(
a,
.{
.port = 3000,
.on_request = null,
.log = false,
.max_clients = 10,
.max_body_size = 1 * 1024,
},
);
defer listener.deinit();
// create mini endpoint
var ep = Endpoints.SimpleEndpoint.init(.{ .path = "/test", .get = endpoint_http_get });
// create a set of Token68 entries
const Set = std.StringHashMap(void);
var set = Set.init(a); // set
defer set.deinit();
try set.put(token, {});
// create authenticator
const Authenticator = Authenticators.BasicAuth(Set, .Token68);
var authenticator = try Authenticator.init(a, &set, null);
defer authenticator.deinit();
// create authenticating endpoint
const BearerAuthEndpoint = Endpoints.AuthenticatingEndpoint(Authenticator);
var auth_ep = BearerAuthEndpoint.init(&ep, &authenticator);
try listener.addEndpoint(auth_ep.getEndpoint());
listener.listen() catch {};
std.debug.print("Listening on 0.0.0.0:3000\n", .{});
std.debug.print("Please run the following:\n", .{});
std.debug.print("./zig-out/bin/http_client http://127.0.0.1:3000/test Basic " ++ token, .{});
// start worker threads
zap.start(.{
.threads = 1,
.workers = 0,
});
try std.testing.expectEqualStrings(HTTP_RESPONSE, received_response);
}