Alamofire V3 how to invalidate credential - alamofire

I'm using Alamofire V3 with iOS 9 and I'm doing a simple request as in the README
Alamofire.request(.GET, WS_URL)
.authenticate(user: user, password: password)
.validate(statusCode: 200..<300)
.responseJSON { response in
...
}
After a first valid request, I changed the credential with invalid ones and the request succeed, but it should fail.
How can I invalidate previous credentials?
UPDATE
I've found a possible solution but I'm not sure that it 's the best one.
let plainString = "\(user):\(password)
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let headers = ["Authorization": "Basic " + base64String!]
Alamofire.request(.GET, urlRequest, headers: headers)
.authenticate(usingCredential: self.credential)
.responseJSON{ responseJson in
...
}
Thanks

As written in the documentation
Depending upon your server implementation, an Authorization header may also be appropriate

Assuming your endpoint is ok and they you are getting success responses...
let defines a constant which cannot be modified once set.
var defines a variable which can.
Try using a variable instead, if you've assign it compile then re-compile. Otherwise using a different name for your variable.
print them to see their values.

In these cases, the "reset" command is your best friend:
$ git reset --soft HEAD~1
Reset will rewind your current HEAD branch to the specified revision.
Note the --soft flag: this makes sure that the changes in undone revisions are preserved. After running the command, you'll find the changes as uncommitted local modifications in your working copy.
If you don't want to keep these changes, simply use the --hard flag. Be sure to only do this when you're sure you don't need these changes anymore.
$ git reset --hard HEAD~1

Related

intermittent error from rally 'Not authorized to perform action: Invalid key' for POST request in chrome extension

I developed a chrome extension using Rally's WSAPI v2.0, and it basically does the following things:
get user and project, and store them
get current iteration everytime
send a post request to create a workitem
For the THIRD step, I sometimes get error ["Not authorized to perform action: Invalid key"] since end of last month.
[updated]Error can be reproduced everytime if I log in Rally website via SSO before using the extension to send requests via apikey.
What's the best practice to send subsequent requests via apikey in my extension since I can't control end users' habits?
I did see some similar posts but none of them is helpful... and in case it helps:
I'm adding ZSESSIONID:apikey in my request header, instead of user /
password to authenticate, so I believe no security token is needed
(https://comm.support.ca.com/kb/api-key-and-oauth-client-faq/kb000011568)
url starts with https://rally1.rallydev.com/slm/webservice/v2.0/
issue is fixed after clearing cookies for
https://rally1.rallydev.com/, but somehow it appears again some time
later
I checked the cookie when the issue was reproduced, and found one with name of ZSESSIONID and its value became something else rather than the apikey. Not sure if that matters though...
code for request:
function initXHR(method, url, apikey, cbFunc) {
let httpRequest = new XMLHttpRequest();
...
httpRequest.open(method, url);
httpRequest.setRequestHeader('Content-Type', ' application\/json');
httpRequest.setRequestHeader('Accept', ' application\/json');
httpRequest.setRequestHeader('ZSESSIONID', apikey);
httpRequest.onreadystatechange = function() {
...
};
return httpRequest;
}
...
usReq = initXHR ('POST', baseURL+'hierarchicalrequirement/create', apikey, function(){...});
Anyone has any idea / suggestion? Thanks a million!
I've seen this error when the API key had both read-only and full-access grants configured. I would start by making sure your key only has the full-access grant.

Set GitHub default branch through API call

I need to create a branch dev which is other than master branch. Also need to set dev as default branch using GITHUB API.
Please share details if anyone know which API to call or a way to do it, programmatically. I know that it can be done through the Web UI, however I am looking for a solution that does not involve manual intervention.
I don't have enough reputation to reply to the Adam's comment above but the problem is name is a required field. The JSON should actually be:
PATCH /repos/:owner/:repo
{
"name":":repo"
"default_branch": "dev"
}
Following the guide here: https://developer.github.com/v3/repos/#edit , default_branch input should make what you want
default_branch (string): Updates the default branch for this repository.
So, you should submit a PATCH request like:
PATCH /repos/:owner/:repo
{"default_branch": "dev"}
You can use requests library:
import requests
access_token = "your_access_token"
headers = {'Authorization': f'token {access_token}',
'Content-Type':'application/json'}
data={"name":"knowledge-engine", "default_branch": "development"}
owner = "username"
repo_name = "repo_name"
url = f"https://api.github.com/repos/{owner}/{repo_name}"
requests.patch(url, data=json.dumps(data), headers=headers)
<Response [200]>
Docs:
https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line
http://docs.python-requests.org/en/master/
https://developer.github.com/v3/repos/#edit
Easiest way to update the default branch if you have the github cli:
gh api repos/{owner}/{repo} --method PATCH --field 'default_branch=dev'
Note the CLI will replace the {owner} and {repo} for you if you are in the locally checked out repository.

CSRF failure in custom mongoose pre-hook (Keystone.js)

using keystone LocalFile type to handle image uploads. similar to the Cloudinary autoCleanup option, I want to be able to delete the uploaded file itself, in addition to the corresponding mongo entry when deleting entries through the admin ui.
in this case, I want to delete an "Album", and it's corresponding album cover.
Album.schema.pre('remove', function(next){
var path = this._original.album_cover.path + "/" + this._original.album_cover.filename
fs.unlink(path, function () {
console.log('deleted');
})
I get "CSRF failure" when using the fs module. I thought all CSRF protection was handled internally with Keystone.
Anyone know of a better solution to this?
Took a 10 minute break and came back and it seems to be working now. I also found this, which seems to be the explanation.
"Moreover double check your session timeout. In my dev settings the session duration is set to 3 minutes. So, if I end up editing something for more than that time, Keystone will return a CSRF error on save because the new session (generate in the meantime) invalidates the old token."
https://github.com/keystonejs/keystone/issues/1330

ASP.NET Web API - Reading querystring/formdata before each request

For reasons outlined here I need to review a set values from they querystring or formdata before each request (so I can perform some authentication). The keys are the same each time and should be present in each request, however they will be located in the querystring for GET requests, and in the formdata for POST and others
As this is for authentication purposes, this needs to run before the request; At the moment I am using a MessageHandler.
I can work out whether I should be reading the querystring or formdata based on the method, and when it's a GET I can read the querystring OK using Request.GetQueryNameValuePairs(); however the problem is reading the formdata when it's a POST.
I can get the formdata using Request.Content.ReadAsFormDataAsync(), however formdata can only be read once, and when I read it here it is no longer available for the request (i.e. my controller actions get null models)
What is the most appropriate way to consistently and non-intrusively read querystring and/or formdata from a request before it gets to the request logic?
Regarding your question of which place would be better, in this case i believe the AuthorizationFilters to be better than a message handler, but either way i see that the problem is related to reading the body multiple times.
After doing "Request.Content.ReadAsFormDataAsync()" in your message handler, Can you try doing the following?
Stream requestBufferedStream = Request.Content.ReadAsStreamAsync().Result;
requestBufferedStream.Position = 0; //resetting to 0 as ReadAsFormDataAsync might have read the entire stream and position would be at the end of the stream causing no bytes to be read during parameter binding and you are seeing null values.
note: The ability of a request's content to be read single time only or multiple times depends on the host's buffer policy. By default, the host's buffer policy is set as always Buffered. In this case, you will be able to reset the position back to 0. However, if you explicitly make the policy to be Streamed, then you cannot reset back to 0.
What about using ActionFilterAtrributes?
this code worked well for me
public HttpResponseMessage AddEditCheck(Check check)
{
var request= ((System.Web.HttpContextWrapper)Request.Properties.ToList<KeyValuePair<string, object>>().First().Value).Request;
var i = request.Form["txtCheckDate"];
return Request.CreateResponse(HttpStatusCode.Ok);
}

speedy_c2dm: NoMethodError (undefined method `gsub' for nil:NilClass)

I set up speedy_c2dm to send "push" messages to android devices.
The gem was working fine, but now I get this NoMethodError message when I call
SpeedyC2DM::API.send_notification(options)
the options parameter is good, I have verified this.
From the ruby-doc I got the following code from the gem:
def get_auth_token(email, password)
data = "accountType=HOSTED_OR_GOOGLE&Email=#{email}&Passwd=#{password}&service=ac2dm"
headers = { "Content-type" => "application/x-www-form-urlencoded",
"Content-length" => "#{data.length}"}
uri = URI.parse(AUTH_URL)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response, body = http.post(uri.path, data, headers)
return body.split("\n")[2].gsub("Auth=", "")
end
You can see that the last line uses gsub, so I believe the problem is in the authentication method.
I have changed the password of the account since I created this, I updated the file with the password, initializers/speedy_c2dm.rb:
C2DM_API_EMAIL = "myemail#gmail.com"
C2DM_API_PASSWORD = "mynewpassword"
SpeedyC2DM::API.set_account(C2DM_API_EMAIL, C2DM_API_PASSWORD)
Can this be causing the error? That I changed the password even though I updated this file?
(Google doesn't let me to go back to the old password, I have to create a new one different from the old ones if I change it again)
Its the only thing I can think of since I didn't modify the gem's code.
How can I fix it? C2DM is deprecated now, but its supposed to keep working for old users. I don't want to migrate to GCM if I don't need to, everything is set up to work with C2DM
Any other ideas to fix it are welcome.
The problem was fixed after I removed the "two step verification" for logging in to my email.
This change can be made in the account configuration of gmail.