Files
crosslangextras/Tesses.CrossLang.Shell/src/login.tcross
2026-05-08 01:40:51 -05:00

128 lines
3.8 KiB
Plaintext

func Tesses.CrossLang.Shell.Login(dd)
{
var accounts = [];
if(FS.Local.FileExists(Env.CrossLangConfig / "auth.json"))
{
accounts = Json.Decode(FS.ReadAllText(FS.Local,Env.CrossLangConfig / "auth.json"));
if(TypeOf(accounts) != "List") accounts = [];
}
//crosslang login local https://cpkg.tesseslanguage.com/
//crosslang login [NAME] [HOST] [TOKEN]
if(dd.Arguments.Length < 3)
{
//not valid
Console.WriteLine("USAGE: crosslang login [name] [host]");
Console.WriteLine("USAGE: crosslang login [name] [host] [token]");
Console.WriteLine();
Console.WriteLine("ARGUMENTS:");
Console.WriteLine("name: the session name");
Console.WriteLine("host: the host of the package server such as https://cpkg.tesseslanguage.com/");
Console.WriteLIne("token: allows you to login from an existing session token, if it is not included this will ask for email and password");
}
else if(dd.Arguments.Length == 3)
{
//name server-url
var name = dd.Arguments[1];
var host = dd.Arguments[2];
Console.Write("Name (empty for CrossLang Shell): ");
var name = Console.ReadLine() ?? "";
if(name == "") name = "CrossLang Shell";
Console.Write("Email: ");
var email = Console.ReadLine();
Console.Write("Password: ");
var echo = Console.Echo;
Console.Echo = false;
var password = Console.ReadLine();
Console.Echo = echo;
Console.WriteLine();
var accountRequest = {
name,
email,
password
};
var req = {
Method="POST",
Body = Net.Http.TextHttpRequestBody(accountRequest.ToString(),"application/json")
};
var http = Net.Http.MakeRequest($"{host.TrimEnd('/')}/api/v1/login",req);
if(http.StatusCode == 401 && http.ResponseHeaders.TryGetFirst("Content-Type") == "application/json")
{
var json = Json.Decode(http.ReadAsString());
Console.WriteLined($"Failed to login, reason={json.reason}");
return 1;
}
else if(http.ResponseHeaders.TryGetFirst("Content-Type") == "application/json")
{
var json = Json.Decode(http.ReadAsString());
var hasSet=false;
each(var ents : accounts)
{
if(ents.name == name)
{
ents.host = host;
ents.token = json.token;
hasSet=true;
}
}
if(!hasSet)
{
accounts.Add({
name,
host,
token = json.token
});
}
FS.WriteAllText(FS.Local,Env.CrossLangConfig / "auth.json",Json.Encode(accounts));
Console.WriteLine("Logged in successfully");
}
}
else if(dd.Arguments.Length == 4)
{
var name = dd.Arguments[1];
var host = dd.Arguments[2];
var token = dd.Arguments[3];
var hasSet=false;
each(var ents : accounts)
{
if(ents.name == name)
{
ents.host = host;
ents.token = token;
hasSet=true;
}
}
if(!hasSet)
{
accounts.Add({
name,
host,
token
});
}
FS.WriteAllText(FS.Local,Env.CrossLangConfig / "auth.json",Json.Encode(accounts));
Console.WriteLine("Added session successfully");
}
}