diff options
| author | physcik <mynameisgennadiy@vk.com> | 2026-04-17 23:11:33 +0500 |
|---|---|---|
| committer | physcik <mynameisgennadiy@vk.com> | 2026-04-17 23:11:33 +0500 |
| commit | e293a40d6bb62e4fa8cc212fcc8bb4b3501da287 (patch) | |
| tree | f0da17a7292dbfd8aa5722f9cbd774f9ad2f9e23 /backend/src/Authentication/Tokens.zig | |
| parent | c03658c1b5a8dad87f4b11d1b48f2c057ac3a439 (diff) | |
Sesstion token generation + storage
Diffstat (limited to 'backend/src/Authentication/Tokens.zig')
| -rw-r--r-- | backend/src/Authentication/Tokens.zig | 42 |
1 files changed, 42 insertions, 0 deletions
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; +} |
