I have an issue with Firebase error code 401 - json

So recently I'm trying to make a GlobalBan script for my admin module in ROBLOX, but I came across an error when I tried to do GlobalBan.
Below is the error and script:
local defaultDatabase = "Private";
local authenticationToken = "Private"
local HttpService = game:GetService("HttpService");
local DataStoreService = game:GetService("DataStoreService");
local FirebaseService = {};
local UseFirebase = true;
--== Script;
function FirebaseService:SetUseFirebase(value)
UseFirebase = value and true or false;
end
function FirebaseService:GetFirebase(name, database)
database = database or defaultDatabase;
local datastore = DataStoreService:GetDataStore(name);
local databaseName = database..HttpService:UrlEncode(name);
local authentication = ".json?auth="..authenticationToken;
local Firebase = {};
function Firebase.GetDatastore()
return datastore;
end
function Firebase:GetAsync(directory)
local data = nil;
--== Firebase Get;
local getTick = tick();
local tries = 0; repeat until pcall(function() tries = tries +1;
data = HttpService:GetAsync(databaseName..HttpService:UrlEncode(directory and "/"..directory or "")..authentication, true);
end) or tries > 2;
if type(data) == "string" then
if data:sub(1,1) == '"' then
return data:sub(2, data:len()-1);
elseif data:len() <= 0 then
return nil;
end
end
return tonumber(data) or data ~= "null" and data or nil;
end
function Firebase:SetAsync(directory, value, header)
if not UseFirebase then return end
if value == "[]" then self:RemoveAsync(directory); return end;
--== Firebase Set;
header = header or {["X-HTTP-Method-Override"]="PUT"};
local replyJson = "";
if type(value) == "string" and value:len() >= 1 and value:sub(1,1) ~= "{" and value:sub(1,1) ~= "[" then
value = '"'..value..'"';
end
local success, errorMessage = pcall(function()
replyJson = HttpService:PostAsync(databaseName..HttpService:UrlEncode(directory and "/"..directory or "")..authentication, value,
Enum.HttpContentType.ApplicationUrlEncoded, false, header);
end);
if not success then
warn("FirebaseService>> [ERROR] "..errorMessage);
pcall(function()
replyJson = HttpService:JSONDecode(replyJson or "[]");
end)
end
end
function Firebase:RemoveAsync(directory)
if not UseFirebase then return end
self:SetAsync(directory, "", {["X-HTTP-Method-Override"]="DELETE"});
end
function Firebase:IncrementAsync(directory, delta)
delta = delta or 1;
if type(delta) ~= "number" then warn("FirebaseService>> increment delta is not a number for key ("..directory.."), delta(",delta,")"); return end;
local data = self:GetAsync(directory) or 0;
if data and type(data) == "number" then
data = data+delta;
self:SetAsync(directory, data);
else
warn("FirebaseService>> Invalid data type to increment for key ("..directory..")");
end
return data;
end
function Firebase:UpdateAsync(directory, callback)
local data = self:GetAsync(directory);
local callbackData = callback(data);
if callbackData then
self:SetAsync(directory, callbackData);
end
end
return Firebase;
end
return FirebaseService;
Error Code:
23:50:36.033 TestService: Data table for bans is currently nil. - Studio
23:50:36.255 FirebaseService>> [ERROR] HTTP 401 (Unauthorized) - Studio
I have tried to create new database + renewing my auth token, still getting Error code 401.
I feel like its my auth token issue but at the same time I don't think it is either, hope you guys can help me figure out the error. Feel free to ask if you need more info regarding this issue.

It turns out my auth token was the wrong one, everything's good now

Related

API call with invalid database connection pointer & misuse error when updating values in table - objective c application

I am working on a messaging iOS application and below is the code to update a table when a new message is received for a chat:
- (BOOL) updateInfoForChat:(Chat*)chat {
BOOL success;
int code = 0;
if (!dbOpen && dbConnection != NULL) {
if (sqlite3_open_v2([[DatabaseManager databasePath] UTF8String], &dbConnection, SQLITE_OPEN_READWRITE|SQLITE_OPEN_FULLMUTEX, NULL) == SQLITE_OK) {
dbOpen = YES;
const char* key = [[self getDBKey] UTF8String];
sqlite3_key(dbConnection, key, (int)strlen(key));
chat.lastMessage = [chat.lastMessage stringByReplacingOccurrencesOfString:#"\"" withString:#"%27"];
char *errMsg;
NSString *insertSQL = [NSString stringWithFormat:#"UPDATE Chats SET "
"lastMessageTime = %f, lastMessageText = \"%#\", canReply = \"%#\", isArchived = \"%#\" WHERE chatRoomId = \"%#\" AND lastMessageTime <= (SELECT messageTime FROM Messages WHERE chatRoomId = \"%#\" ORDER BY messageTime DESC LIMIT 1)",
chat.lastMsgTime, chat.lastMessage , chat.canReply ? #"True" : #"False" , chat.isArchived ? #"True" : #"False", chat.chatRoomID, chat.chatRoomID];
const char *sql_stmt = [insertSQL UTF8String];
code = (sqlite3_exec(dbConnection, sql_stmt, NULL, NULL, &errMsg));
if (code == SQLITE_OK) {
//commenting this out as this makes the logs very noisy
}
else {
NSLog(#"This method did not get executed with error: %s",sqlite3_errmsg(dbConnection));
}
sqlite3_close_v2(dbConnection);
dbOpen = NO;
}
else {
NSLog(#"This method did not get executed with error: %s",sqlite3_errmsg(dbConnection));
}
}
return success = (code == SQLITE_OK);
}
Having received messages in a couple of chats, I get the errors below when application hits this code:
API call with invalid database connection pointer
misuse at line 133563 of [d24547a13b]
This method did not get executed with error: bad parameter or other API misuse
Can someone suggest where the issue could be coming from?

Vector-Lua:How to transform table to json ?

ERROR transform{component_kind="transform" component_id=cut_field component_type=lua component_name=cut_field}: vector::internal_events::lua: Error in lua script; discarding event. error=RuntimeErrorHooksProcess { source: RuntimeError("[string "src/transforms/lua/v2/mod.rs:158:17"]:23: attempt to index a nil value (global 'json')\nstack traceback:\n\t[string "src/transforms/lua/v2/mod.rs:158:17"]:23: in function 'hook_process'") } internal_log_rate_secs=30
This is my config:
`[transforms.cut_field]
type = "lua"
inputs = ["log_source"]
version = "2"
search_dirs = [ "/usr/lib64/lua" ]
source = """
function hook_process(event, emit)
if next(event) == nil then
print("event empty")
end
if event == nil then
print("event is nil")
end
local str = json.encode(event)
print(str)
emit(event)
end
"""
hooks.process = "hook_process"`
My vector version is: vector 0.17.0 (x86_64-unknown-linux-gnu 3d34cde 2021-10-08)

Downloading dwg to Forge

I'm in the process of learning the Forge platform. I'm currently using an example (Jigsawify) written by Kean Walmsley because it most accurately describes my goals. I'm running into an issue of getting my file to download from an Azure Storage Account to Forge. The error I receive is "The value for one of the HTTP headers is not in the correct format." My question is how does someone go about troubleshooting HTTP protocol when writing, in this case, a workitem in code? I can put in a breakpoint to view the workitem, but I'm not versed enough to understand where the flaw is in the HTTP header, or even where to find it. Is there a specific property of the workitem I should be looking at? If I could find the HTTP statement, I could test it, but I don't where I should find it.
Or am I just completely off base?
Anyway here's the code. It's a modified version of what Kean wrote:
static void SubmitWorkItem(Activity activity)
{
Console.WriteLine("Submitting workitem...");
CloudStorageAccount storageAccount =
CloudStorageAccount.Parse(Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));
StorageCredentials crd = storageAccount.Credentials;
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare ShareRef = fileClient.GetShareReference("000scrub");
CloudFileDirectory rootDir = ShareRef.GetRootDirectoryReference();
CloudFile Fileshare = rootDir.GetFileReference("3359fort.dwg");
// Create a workitem
var wi = new WorkItem()
{
Id = "", // Must be set to empty
Arguments = new Arguments(),
ActivityId = activity.Id
};
if (Fileshare.Exists())
{
wi.Arguments.InputArguments.Add(new Argument()
{
Name = "HostDwg", // Must match the input parameter in activity
Resource = Fileshare.Uri.ToString(),
StorageProvider = StorageProvider.Generic // Generic HTTP download (vs A360)
});
}
wi.Arguments.OutputArguments.Add(new Argument()
{
Name = "Results", // Must match the output parameter in activity
StorageProvider = StorageProvider.Generic, // Generic HTTP upload (vs A360)
HttpVerb = HttpVerbType.POST, // Use HTTP POST when delivering result
Resource = null, // Use storage provided by AutoCAD.IO
ResourceKind = ResourceKind.ZipPackage // Upload as zip to output dir
});
container.AddToWorkItems(wi);
container.SaveChanges();
// Polling loop
do
{
Console.WriteLine("Sleeping for 2 sec...");
System.Threading.Thread.Sleep(2000);
container.LoadProperty(wi, "Status"); // HTTP request is made here
Console.WriteLine("WorkItem status: {0}", wi.Status);
}
while (
wi.Status == ExecutionStatus.Pending ||
wi.Status == ExecutionStatus.InProgress
);
// Re-query the service so that we can look at the details provided
// by the service
container.MergeOption =
Microsoft.OData.Client.MergeOption.OverwriteChanges;
wi = container.WorkItems.ByKey(wi.Id).GetValue();
// Resource property of the output argument "Results" will have
// the output url
var url =
wi.Arguments.OutputArguments.First(
a => a.Name == "Results"
).Resource;
if (url != null)
DownloadToDocs(url, "SGA.zip");
// Download the status report
url = wi.StatusDetails.Report;
if (url != null)
DownloadToDocs(url, "SGA-Report.txt");
}
Any help is appreciated,
Chuck
Azure requires that you specify the x-ms-blob-type header when you upload to a presigned URL. See https://github.com/Autodesk-Forge/design.automation-.net-input.output.sample/blob/master/Program.cs#L167
So, I was able to figure out how to download my file from Azure to Forge using Albert's suggestion of moving to a blob service. Here's the code:
static void SubmitWorkItem(Activity activity)
{
Console.WriteLine("Submitting workitem...");
CloudStorageAccount storageAccount =
CloudStorageAccount.Parse(Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient BlobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = BlobClient.GetContainerReference("000scrub");
CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference("3359fort.dwg");
// Create a workitem
var wi = new WorkItem()
{
Id = "", // Must be set to empty
Arguments = new Arguments(),
ActivityId = activity.Id
};
if (blockBlob.Exists())
{
wi.Arguments.InputArguments.Add(new Argument()
{
Name = "HostDwg", // Must match the input parameter in activity
Resource = blockBlob.Uri.ToString(),
StorageProvider = StorageProvider.Generic, // Generic HTTP download (vs A360)
Headers = new System.Collections.ObjectModel.ObservableCollection<Header>()
{
new Header() { Name = "x-ms-blob-type", Value = "BlockBlob" } // This is required for Azure.
}
});
}
wi.Arguments.OutputArguments.Add(new Argument()
{
Name = "Results", // Must match the output parameter in activity
StorageProvider = StorageProvider.Generic, // Generic HTTP upload (vs A360)
HttpVerb = HttpVerbType.POST, // Use HTTP POST when delivering result
Resource = null, // Use storage provided by AutoCAD.IO
ResourceKind = ResourceKind.ZipPackage, // Upload as zip to output dir
});
container.AddToWorkItems(wi);
container.SaveChanges();
// Polling loop
do
{
Console.WriteLine("Sleeping for 2 sec...");
System.Threading.Thread.Sleep(2000);
container.LoadProperty(wi, "Status"); // HTTP request is made here
Console.WriteLine("WorkItem status: {0}", wi.Status);
}
while (
wi.Status == ExecutionStatus.Pending ||
wi.Status == ExecutionStatus.InProgress
);
// Re-query the service so that we can look at the details provided
// by the service
container.MergeOption =
Microsoft.OData.Client.MergeOption.OverwriteChanges;
wi = container.WorkItems.ByKey(wi.Id).GetValue();
// Resource property of the output argument "Results" will have
// the output url
var url =
wi.Arguments.OutputArguments.First(
a => a.Name == "Results"
).Resource;
if (url != null)
DownloadToDocs(url, "SGA.zip");
// Download the status report
url = wi.StatusDetails.Report;
if (url != null)
DownloadToDocs(url, "SGA-Report.txt");
}
What isn't complete is the result section. The ZIP has nothing in it, but hey, baby steps right?
Thanks Albert.
-Chuck

GCE how to add external IP to existing instance at boot

I'm using Gcloud-java to manage some VM instances. The code to create a new instance is clear and is the following:
Address externalIp = compute.getAddress(addressId);
InstanceId instanceId = InstanceId.of("us-central1-a", "test-instance");
NetworkId networkId = NetworkId.of("default");
PersistentDiskConfiguration attachConfiguration =
PersistentDiskConfiguration.builder(diskId).boot(true).build();
AttachedDisk attachedDisk = AttachedDisk.of("dev0", attachConfiguration);
NetworkInterface networkInterface = NetworkInterface.builder(networkId)
.accessConfigurations(AccessConfig.of(externalIp.address()))
.build();
MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
InstanceInfo instance =
InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface);
Operation operation = compute.create(instance);
// Wait for operation to complete
operation = operation.waitFor();
if (operation.errors() == null) {
System.out.println("Instance " + instanceId + " was successfully created");
} else {
// inspect operation.errors()
throw new RuntimeException("Instance creation failed");
}
But what should I do if I have en existing instance that I want to start and I want to attach an external IP?
I've tried in this way: first I create a RegionAddressId and get an Address with which I create the networkInterface.
RegionAddressId addressId = RegionAddressId.of("europe-west1", "test-address");
Operation operationAdd = compute.create(AddressInfo.of(addressId));
operationAdd = operationAdd.waitFor();
Address externalIp = compute.getAddress(addressId);
NetworkId networkId = NetworkId.of("default");
NetworkInterface networkInterface = NetworkInterface.builder(networkId)
.accessConfigurations(NetworkInterface.AccessConfig.of(externalIp.address()))
.build();
The I get my instance and add the accessConfig
InstanceId instanceId = InstanceId.of("my-server", "europe-west1-b","my-instance");
Instance instance = compute.getInstance(instanceId);
instance.addAccessConfig("default", NetworkInterface.AccessConfig.of(externalIp.address()));
Operation operation = instance.start();
The result is that my instance is booted with another external IP that I don't know how to obtain.
What is the correct procedure?
Thanks
I've found by myself the solution.
Compute compute = ComputeOptions.defaultInstance().service();
InstanceId instanceId = InstanceId.of("my-server", "europe-west1-b","my-instance");
Operation operation = compute.start(instanceId);
Operation completedOperation = operation.waitFor();
if (completedOperation == null) {
// operation no longer exists
} else if (completedOperation.errors() != null) {
// operation failed, handle error
}
Instance instance = compute.getInstance(instanceId);
String publicIp =
instance.networkInterfaces().get(0).accessConfigurations().get(0).natIp();
I start the instance using the start method of Compute and then (after the operation is completed) I get the instance

TypeError: string indices must be integers

Hi i have a problem with my code that i get a error in a loop that works for a few times but then throws me a typeerro: string indices must be integers.
I want to call an api to get a json back and get some parts of the json response. heres the code:
class API(object):
def __init__(self, api_key):
self.api_key = api_key
def _request(self, api_url, params={}):
args = {'api_key': self.api_key}
for key, value in params.items():
if key not in args:
args[key] = value
response = requests.get(
Consts.URL['base'].format(
url=api_url
),
params=args
)
if response.status_code == requests.codes.ok:
return response.json()
else:
return "not possible"
print(response.url)
def get_list(self):
excel = EXCEL('s6.xlsx')
api_url = Consts.URL['list'].format(
version = Consts.API_VERSIONS['matchversion'],
start = excel.get_gamenr()
)
return self._request(api_url)
def get_match(self, matchid):
idlist = matchid
api_url = Consts.URL['match'].format(
version = Consts.API_VERSIONS['matchversion'],
matchId = idlist
)
return self._request(api_url)
def match_ids(self):
api = API('c6ea2f68-7ed6-40fa-9b99-fd591c55c05f')
x = api.get_list()
y = x['matches']
count = len(y)
ids = []
while count > 0:
count = count - 1
temp = y[0]
ids.append(temp['matchId'])
del y[0]
return ids
def match_info(self):
matchids = self.match_ids()
print(matchids)
matchinfolist = {}
counter = 1
for gameids in matchids:
info = self.get_match(gameids)
myid = self.find_partid(info['participantIdentities'])
prepdstats = info['participants'][myid-1]
print(prepdstats)
matchinfolist['stats' + str(counter)] = prepdstats
return matchinfolist
def find_partid(self, partlist):
partid = 0
idlist = partlist
while partid < 10:
partid = partid + 1
tempplayer = idlist[0]['player']
if tempplayer['summonerId'] == 19204660:
playernr = partid
partid = 500
del idlist[0]
return playernr
when i run the match_info() function i get this error
Traceback (most recent call last):
File "C:\Users\Niklas\Desktop\python riot\main.py", line 17, in <module>
main()
File "C:\Users\Niklas\Desktop\python riot\main.py", line 10, in main
print(api.match_info())
File "C:\Users\Niklas\Desktop\python riot\api.py", line 78, in match_info
myid = self.find_partid(info['participantIdentities'])
TypeError: string indices must be integers
but only after the loop in the function has run for a few times. I have no idea what im doing wrong. Any help would be nice.
Here is a link to the json: https://euw.api.pvp.net/api/lol/euw/v2.2/match/2492271473?api_key=c6ea2f68-7ed6-40fa-9b99-fd591c55c05f
The error shows up on
myid = self.find_partid(info['participantIdentities'])
For this line to execute, info must be a mapping with string keys, not a string itself. info is
info = self.get_match(gameids)
get_match ends with
return self._request(api_url)
_request ends with
if response.status_code == requests.codes.ok:
return response.json()
else:
return "not possible"
For the loop to ever run, response.json() must be a dict with key 'participantIdentities'. Your bug is expecting that to always be true.
One fix might be to make the expectation always ture. If there is a satisfactory default value, return {'participantIdentities': <default value>}. Otherwise, return None and change the loop to
info = self.get_match(gameids)
if info is not None:
# as before
else:
# whatever default action you want