From e293a40d6bb62e4fa8cc212fcc8bb4b3501da287 Mon Sep 17 00:00:00 2001 From: physcik Date: Fri, 17 Apr 2026 23:11:33 +0500 Subject: Sesstion token generation + storage --- backend/src/Authentication/Tokens.zig | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 backend/src/Authentication/Tokens.zig (limited to 'backend/src/Authentication/Tokens.zig') diff --git a/backend/src/Authentication/Tokens.zig b/backend/src/Authentication/Tokens.zig new file mode 100644 index 0000000..6548ce7 --- /dev/null +++ b/backend/src/Authentication/Tokens.zig @@ -0,0 +1,42 @@ +const std = @import("std"); +const redis = @import("../Redis/Connection.zig"); +const userModel = @import("../Models/User.zig"); + +const topicName = "cp2020_auth"; +const token_ttl: u16 = 43_200; // 12 hours + +var prng: std.Random.DefaultPrng= undefined; +var rnd: std.Random = undefined; + +pub fn Init() !void { + // Random enough + var seed: u64 = undefined; + try std.posix.getrandom(std.mem.asBytes(&seed)); + prng = std.Random.DefaultPrng.init(seed); + rnd = prng.random(); +} + +/// Generates a new token in the heap. Expects [64]u8 as an input +fn generateSessionToken(buf: []u8) []u8 { + for (0..64) |i| { + buf[i] = std.Random.intRangeAtMost(rnd, u8, 'A', 'z'); + } + return buf; +} + +pub fn GenerateNewSession(allocator: std.mem.Allocator, user: userModel.User) ![]u8 { + const token: []u8 = try allocator.alloc(u8, 64); + const newToken = generateSessionToken(token); + + // Redis cache + var string: std.io.Writer.Allocating = .init(allocator); + defer string.deinit(); + try string.writer.print("{f}", .{std.json.fmt(user, .{})}); + try redis.WriteToTopic(topicName, redis.Message { + .Key = token, + .Value = string.written(), + .SecondsToLive = token_ttl, + }); + + return newToken; +} -- cgit v1.3