1 module konnexengine.crypto.utilities; 2 3 import std.conv : to; 4 import std.json; 5 import std.digest: toHexString; 6 import vibe.http.client : requestHTTP, HTTPMethod; 7 import vibe.data.json : Json, parseJsonString; 8 import vibe.stream.operations : readAllUTF8; 9 import vibe.core.log : logInfo, logWarn, logCritical; 10 11 import dauth: makeHash, toPassword, randomSalt, isSameHash, parseHash, Salt; 12 import dotenv : Env; 13 14 string hashPassword(string plaintext) 15 { 16 char[] input = cast(char[]) plaintext; 17 auto pass = toPassword(input); 18 auto hash = makeHash(pass).toString(); 19 return hash; 20 } 21 22 bool checkPassword(string hashString, string password) 23 { 24 char[] input = cast(char[]) password; 25 auto p = toPassword(input); 26 return isSameHash(p, parseHash(hashString)); 27 } 28 29 string generateToken(string ns, string id, string name, string created) 30 { 31 struct TokenRequest 32 { 33 34 this(string ns, string id, string name, string created) 35 { 36 this.namespace = ns; 37 this.user_id = id; 38 this.username = name; 39 this.created_at = created; 40 } 41 42 string namespace; 43 string user_id; 44 string username; 45 string created_at; 46 } 47 48 string token = ""; 49 // logInfo(ns); 50 auto request = TokenRequest(ns, id, name, created); 51 // logInfo(request.namespace); 52 Env.load(".env", false); 53 // string authUrl = Env["AUTH_SERVICE_URL"]; 54 string authUrl = "http://0.0.0.0:8099/login"; 55 56 logInfo("\nTrying URL: " ~ authUrl); 57 58 requestHTTP(authUrl, (scope req) { 59 60 req.method = HTTPMethod.POST; 61 req.contentType = "application/json"; 62 63 req.writeJsonBody([ 64 "namespace": JSONValue(request.namespace.to!string), 65 "user_id": JSONValue(request.user_id.to!string), 66 "username": JSONValue(request.username.to!string), 67 "created_at": JSONValue(request.created_at.to!string) 68 ]); 69 70 }, (scope res) { 71 72 token = res.bodyReader.readAllUTF8(); 73 // logWarn("\nAuthService --- Response: %s\n", parseJsonString(token).toPrettyString()); 74 75 }); 76 return token; 77 } 78 79 Json decodeToken(T)(T t) 80 { 81 import fastjwt.jwt : decodeJWTToken, JWTAlgorithm; 82 import stringbuffer : StringBuffer; 83 84 string secret = "SuperStrongPassword"; 85 JWTAlgorithm algo = JWTAlgorithm.HS512; 86 StringBuffer header; 87 StringBuffer payload; 88 89 const ulong rslt = decodeJWTToken(t["token"].get!string, secret, algo, header, payload); 90 91 if (rslt > 0) 92 { 93 return Json(["message": Json("Your token was not OK")]); 94 } 95 96 return parseJsonString(payload.getData()); 97 }