Im trying to extract IP info from IPinfo website but be able to have the query have the IP set prior to the extract data function so its easy to change the searched IP and possibly use it for searching the IP when using Signinlogs etc... see below roughly what iv got atm.
let _IP = "'[INSERT IP HERE]'"; //IP im searching for
let _link = strcat('#"https://ipinfo.io/', _IP, '/json"'); //attempt to concat the IP into the URL
let IPCheck = externaldata(ip: string, city: string, region : string, country : string, org : string )[_link] //external data function to pull json data from URL
with(format=multijson);
IPCheck
The below works. as I want it to
let IPCheck = externaldata(ip: string, city: string, region : string, country : string, org : string )[#"https://ipinfo.io/[INSERT IP HERE]/json"] //external data function to pull json data from URL
with(format=multijson);
IPCheck
But want to create the URL before hand, creating this as a string does NOT appear to work
Any ideas on how to work around this or a better way of extracting this data?
This can be done using the http_request plugin.
Having said that, I have no idea why you would like to do such a thing within ADX.
let IP = "8.8.8.8";
let URL = strcat("https://ipinfo.io/", IP, "/json");
evaluate http_request(URL)
ResponseHeaders
ResponseBody
ResponseStatusCode
ResponseReasonPhrase
{"access-control-allow-origin":"*","x-frame-options":"SAMEORIGIN","x-xss-protection":"1; mode=block","x-content-type-options":"nosniff","referrer-policy":"strict-origin-when-cross-origin","x-envoy-upstream-service-time":"1","strict-transport-security":"max-age=2592000; includeSubDomains","vary":"Accept-Encoding","Alt-Svc":"h3=":443"; ma=2592000,h3-29=":443"; ma=2592000","Transfer-Encoding":"chunked","Date":"Fri, 30 Dec 2022 11:16:14 GMT","Via":"1.1 google"}
{"ip":"8.8.8.8","hostname":"dns.google","anycast":true,"city":"Mountain View","region":"California","country":"US","loc":"37.4056,-122.0775","org":"AS15169 Google LLC","postal":"94043","timezone":"America/Los_Angeles","readme":"https://ipinfo.io/missingauth"}
200
OK
Related
I have a "createUser" function on a Go server in which I hash a new user's password and store their data from a form sent via POST.
The database of users and their stats is pulled up and converted into a string map containing structs with their info. It looks like this:
var userStruct struct {
Users map[string]struct {
Admin, Moderator, Root bool
Pass *string
}
}
The reason it is a pointer is because later on I might want to change the password.
So, when I create a new user I unmarshal the JSON from the POST request into a struct like this:
var newUser struct{
Username, Password string
IsAdmin, IsModerator bool
}
I use json.NewDecoder to decode it into the struct as follows:
err := json.NewDecoder(r.Body).Decode(&newUser)
Then, I hash it and store the results using sha, json.MarshalIndent and ioutil.WriteFile:
sha := sha1.New()
sha.Write([]byte(newUser.Password))
var hashedPass string;
hashedPass = hex.EncodeToString(sha.Sum(nil))
fmt.Println(hashedPass)
userStruct.Users[newUser.Username] = struct {
Admin, Moderator, Root bool
Pass *string
}{
Admin: newUser.IsAdmin,
Moderator: newUser.IsModerator,
Root: false,
Pass: &hashedPass,
}
fmt.Println(*userStruct.Users[newUser.Username].Pass)
file, _ := json.MarshalIndent(userStruct, "", " ")
_ = ioutil.WriteFile("userInfo.json", file, 0644)
Then, on the login side, I convert the string slice of the parsed form of the credentials to a byte slice and compare the username/password to the ones stored in the database.
here, which shows that I can use the Gob encoder:
r.ParseForm()
sha := sha1.New()
buf := &bytes.Buffer{}
gob.NewEncoder(buf).Encode(r.Form["password"])
bufBytes := buf.Bytes()
sha.Write(bufBytes)
bs := sha.Sum(nil)
fmt.Println(hex.EncodeToString(bs))
usrJSON, _ := ioutil.ReadFile("userInfo.json")
var userStruct struct {
Users map[string]struct {
Root, Admin, Moderator bool
Pass *string
}
}
json.Unmarshal(usrJSON, &userStruct)
username := strings.ToLower(strings.Join(r.Form["username"], "")
I then compare the username and the password. The password comparing is the only problem we need to focus on, though:
if *userStruct.Users[username].Pass == hex.EncodeToString(bs) {
}
Attempting to debug, I outputted the results of the hashing in both the user creation function, and the user login function.
The password I used for an example is myverysecretpassword.
The stored hash looks like this:
7816b9b6485dd785aab9f91a31a0b80997ed44b9
The password attempt looks like this:
08618c3225370a2205d698d06df48ba4b820c1d4
As I look deeper and deeper into this, I realize that it might be my usage of pointers/addresses, but I'm still confused anyways.
What is going on?
It looks like I didn't quite understand this at the bottom of the answer on the post about converting string slices to byte slices:
Gob is simple and to the point. However, the format is only readable with other Go code.
Reading it a couple of times makes sense, Go encoding isn't meant to convert a string slice directly to a byte slice.
According to the comments, Gob is an encoder, not a string slice to byte slice converter.
I can use http.Request.Form.Get("key") instead, to get the data as a string and convert it into bytes using []byte().
POST a string to an endpoint (formatted in JSON), which looks something like this:
let rawString = reportJSON.rawString(.utf8, options: .prettyPrinted)!
let newParams = ["report": rawString]
APIHelper.shared.session.request(endPoint,
method: .post,
parameters: newParams,
encoding: URLEncoding.default)
print(rawString) looks like this in the Xcode console:
...
"remarks" : "Door is broke. It’s time to fix this door’s handle.",
...
Webserver raw log shows the single quotes ' are incorrectly parsed:
...
"remarks" : "Door is broke. ItÆs time to fix this doorÆs handle.",
...
But then I did a test by I manually writing a string:
var rawString = "{\"someKeyValue\": \"It's another string with apostrophe's.\"}"
Web server correctly receives and prints:
{"someKeyValue": "It's another string with apostrophe's."}
So is something is funky with my reportJSON.rawString() object? Is it sending something up to the server that is different than what is printed in my Xcode console log? Or could it be the webserver?
I have seen quite a few posts on this question and none seem to answer my question. They are usually far more complicated than what I am asking. I have a list of one or more stocks that I would like to get the latest price for from the Internet. I found a nice API for doing that and was excited to create a simple structure and do the basics of a URLSession. I was able to pull the data into my structured format and print it in the console no problem. For example:
Quote(symbol: "C", companyName: "Citigroup Inc.", latestPrice: 68.86)
I want to update my SQLite3 database records with the current price. I cannot get the data out.
So I have my opentrades array based on a model:
class OpenTradeDur: NSObject {
#objc dynamic var trNo: Int
#objc dynamic var trPDate: String
#objc dynamic var trTicker: String
#objc dynamic var trDur: String
#objc dynamic var trCurPrice: Double
and the Quote structure is simple:
struct Quote: Decodable {
let symbol: String
let companyName: String
let latestPrice: Double
}
I have tried multiple variations of functions and actions and variables but my latest attempt that is still no closer to working is running in my viewDidLoad of my ViewController where I do some initial setup:
for _ in opentrades {
rn = rn + 1
let url = URL(string: "https://api.iextrading.com/1.0/stock/\(opentrades[rn].trTicker)/quote")
let session = URLSession.shared
let task = session.dataTask(with: url!) {(data, response, error) in
guard let data = data else { return }
do {
let quote = try JSONDecoder.decode(Quote.self,from: data)
print(quote)
self.opentrades[rn].trCurPrice = quote.latestPrice
} catch {}
}
task.resume()
}
I found a few posts that talk about completion handlers but even in those examples only give an answer that ends up printing to console. I just need a simple implementation. What I really need is a function that I can just call and say:
price = getPrice(stockTicker)
eg. price = getPrice("C")
and what that is doing behind the scenes if getting the JSON data from
https://api.iextrading.com/1.0/stock/C/quote
Can anyone point me in the right direction?
[2018-10-25]
I have managed to get this working in a fashion by creating a delegate protocol in the class I have performing the URLSession and then extending my ViewController with the delegate. And this works for a single quote at a time. I can initiate the process with a button and when the data comes back through the delegate's didLoad function I have it update the screen. But I was looking for a backend process to make multiple calls to the quote api and update multiple records. But I could not get that to synch up. But I had a thought and went back to the API documentation found a batch call where I can return all of the data for multiple stocks in one call. That is exactly what I need however I am stuck once again. The returned data is JSON data but not jsonapi.org compliant. I am going to post this as a new question and try hard to make sense in my asking of the question.
Edit: I received a great response from my new question and it has solved the problem I was experiencing here so I will provide an update.
As I tried to explain previously, my application runs through a list of open stock trades at startup and wants to update the latest price for each of them. I have an array I run through to set the price and then update my database to save those changes. Then my app opens with the new data in place.
I now have a function that takes a stock symbol as an input and returns the price immediately...
func getPrice(ticker: String) -> Double {
var price = 0.0
let urlString = "https://api.iextrading.com/1.0/stock/\(ticker)/quote"
let data = try! Data(contentsOf: URL(string: urlString)!)
do {
let response = try JSONDecoder().decode(Quote.self,from: data)
price = response.latestPrice
} catch let jsonErr { print("Error decoding JSON:",jsonErr)}
return price
}
I simply run through my array of trades and set the price...
opentrades[rn].trCurPrice = getPrice(ticker: opentrades[rn].trTicker)
I will be testing this to see how it works out without using a URLSession especially during the trading day and times of high activity and potential network latency.
I'm new to coding. I have JSON request which returns different parameters, for example "unitid" and "buldingid".
i want to store the "buldingid" by NSUserDfaults. I use code below for storing it, but every time I get nil response for "buldingid".
reading:
NSUserDefaults.standardUserDefaults().setObject(buildingid, forKey: "buildingidKey")
NSUserDefaults.standardUserDefaults().synchronize()
writing:
let buildingid: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("buildingidKey") as? [NSString]
i saved it in a label then stored in NSUserDfaults but it doesn't work (error: Attempt to insert non-property list object)
what should I do to get the correct response for "buldingid"?
Thanks!
I suppose from your code that buildingid is a String, so something like this should work:
NSUserDefaults.standardUserDefaults().setObject(String(buildingid), forKey: "buildingidKey")
NSUserDefaults.standardUserDefaults().synchronize()
Retrieving it should be done like this:
let buildingid = NSUserDefaults.standardUserDefaults().stringForKey("buildingidKey")
I'm having trouble parsing the following JSON file with SwiftyJSON. I've looked around the web and tried different suggested solutions with no luck.
Here is the JSON:
{'info-leag':{'Status':1,'Name':'Testing Name','url-lig':'test.testing.com','uid':'12345'}}
And my relevant code:
//initializes request
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let json = JSON(data: data)
//stores data as UTF8 String
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
The first part seems to work fine, I am able to get the JSON and save it as data, at the bottom I converted it to a string to make sure that I was getting the right information, I then later print it to make sure.
I tried different things like:
let name = json["info-league"]["Name"] //can't seem to get the context
I'm trying to get the Name and uid to be saved as 2 strings as well as the Status as an int.
Thanks!
Once you've made your JSON valid like this:
{"info-league":{"Status":1,"Name":"Testing Name","url-lig":"test.testing.com","uid":"12345"}}
you will be able to use your example, it works (I just tested):
let name = json["info-league"]["Name"]
but it's better to use SwiftyJSON types:
let name = json["info-league"]["Name"].string
let status = json["info-league"]["Status"].int
so your variables are of known types for later use.
If you don't do this they will be of type JSON, a type created by SwiftyJSON, and you will have to cast them later (not a problem, depends how you're organised in your code).
Try:
let name = json["info-league"]["Name"].string