soundcloud api resolve issue after oAuth - javascript

I am having what I hope is an easy to solve problem with the Soundcloud API using JavaScript:
unauthorized, the following code works fine:
var group = 'https://soundcloud.com/groups/chilled';
SC.initialize({
client_id: 'MY_CLIENT_ID',
redirect_uri: 'http://localhost:49957/tn/callback.html'
});
// Resolve works fine and gives number ID of group
SC.resolve(group + '?client_id=' + client_id).then(function (g) {
console.log('Group 1: ' + g.id);
});
after I authorise a user:
SC.connect().then(function () {
return SC.get('/me');
}).then(function (me) {
authUser = me.id
});
// Resolve no longer works and i get 401 unauthorised
SC.resolve(group + '?client_id=' + client_id).then(function (g) {
console.log('Group 1: ' + g.id);
});
can anyone help me to understand what I am doing wrong - I can't seem to find an example to follow anywhere. Driving me potty!
Many thanks in advance,
James

For anyone else out there facing the same issues, I have answered my own question:
Firstly, I was not properly logged in due to an error on Soundcloud's sample code in their callback.html used to return to the site after oAuth client side login flow. In Soundcloud's sample callback.html, the code:
<body onload="window.opener.setTimeout(window.opener.SC.connectCallback, 1)">
must be altered to:
<body onload="window.setTimeout(window.opener.SC.connectCallback, 1)">
This allows the popup to close properly and completes the login flow if the application settings are correctly configured to the same domain (localhost or production, but not a mix of the two).
Further to this callback, i have added the following code:
var params = getSearchParameters();
window.opener.oAuthToken = params.code;
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray(prmstr) {
var params = {};
var prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
In my subsequent pages, I can get any data as a sub-resource of the '/me/...' endpoint now, but anything I used to be able to interrogate via public access is still in accessible. Since I can now iterate through the logged in users groups, I no longer have to resolve the name of a group via the public resource '/resolve/', so my issue is not solved, but avoided in my current development.

Related

Firebase get user profile picture with uid

I know I can get the current logged in user's profile picture, but how do I get someone else's based on their uid?
Here's what I tried:
database.ref("classes/" + currentClassId + "/chat/main").on('value', (snapshot) => {
var p = 0
console.log(snapshot.val())
if(snapshot.val() != null){p = snapshot.val().data.msgCount}
var min = p - 100
if(min <= 0){min = 0}
var max = p
$("#log").empty()
if(snapshot.val() != null){
for(i=min; i<=max - 1; i++){
console.log(i)
database.ref("classes/" + currentClassId + "/chat/main/log/" + i).once('value').then(s => {
$("#log").append([
$("<div/>").append([
$("<img/>").attr("src", firebase.auth().getUser(s.val().sender.uid).then(function(profile){
return profile.PhotoUrl // <<<<<< !!!!!! This part doesnt work !!!!!! <<<<<<
})),
$("<p/>").text(s.val().message).addClass("message")
]).css("display: inline;")
])
})
}
}
})
Here's what I got:
Uncaught (in promise) TypeError: firebase.auth(...).getUser is not a function
at <anonymous>:178:65
Is there another way to get the profile picture url of another registered user in firebase auth? (I'm only using Javascript, no NodeJS, so I don't think I can use firebase admin?)
What you're trying to do isn't possible from client app code. For security reasons, users can not directly access other users' profile information at all. There is simply no API for it, and no permission at a low level.
If you want users to be able to see information about others, you will need to write that data to a database, then query the database to get a hold of it later.

http client for OAuth endpoint

I'm trying to get an OAuth access token from the GitLab CE endpoint for OAuth. I've got the code parameter fine in JS, but when I make an Ajax request to the access token page, it throws an error about the server not being CORS enabled, and the origin null not being allowed. Why is my origin null? I also looked at the gitlab documentation, it says you have to use a http client, and then it shows an example of RestClient. What is this? I've tried using it but it doesn't work. Please see below for my code:
if (getQueryVariable('code') === false) {
if (local !== false) {
window.location.replace('https://gitlab.com/oauth/authorize?client_id=####&redirect_uri=http://localhost:4000&response_type=code');
} else { //live
window.location.replace('https://gitlab.com/oauth/authorize?client_id=####&redirect_uri=http://roconnor.gitlab.io/repoViewer&response_type=code');
}
} else {
var oauthcode;
if (local !== false) {
oauthcode = $.getJSON('http://gitlab.com/oauth/token?client_id=####&client_secret=####&code=' + getQueryVariable('code') + '&grant_type=AUTHORIZATION_CODE&redirect_uri=http://localhost:4000');
var parameters = 'client_id=####&client_secret=####&code=' + getQueryVariable('code') + '&grant_type=AUTHORIZATION_CODE&redirect_uri=http://localhost:4000'
RestClient.post 'http://gitlab.com/oauth/token', parameters //this is the code given by the docs
} else {
oauthcode = $.getJSON('http://gitlab.com/oauth/token?client_id=####&client_secret=####&code=' + getQueryVariable('code') + '&grant_type=AUTHORIZATION_CODE&redirect_uri=http://roconnor.gitlab.io/repoViewer');
}
console.log(oauthcode); //the error gets thrown here

Signature generation in Amazon S3 using Javascript

I am trying to send a PUT request to an Amazon compatible storage, and I keep getting the following error:
"<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your Secret Access Key and signing method. For more information, see REST Authentication and SOAP Authentication for details.</Message><RequestId>0af9f985:155f11613d1:1732:13</RequestId></Error>"
Can someone please tell me how to generate the correct signature using the Secret Access Key and other parameters, in Javascript. I know that I am using the correct credentials, because all other operations supported by Amazon S3 are working, using the Amazon S3 SDK. I went through this link:
http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html, but I couldn't find what the method is expecting for each parameters.
Adding the code, that I have written. This is pretty much the same as you see in the Javascript SDK, only the method canonicalizedResource, is more simpler:
private stringToSign(request: any) {
var parts = [];
parts.push(request.headers['method']);
parts.push(request.headers['Content-MD5'] || '');
parts.push(request.headers['Content-Type'] || '');
parts.push(request.headers['presigned-expires'] || '');
var headers = this.canonicalizedAmzHeaders(request);
if (headers) parts.push(headers);
parts.push(this.canonicalizedResource(request));
return parts.join('\n');;
}
private canonicalizedAmzHeaders(request: any) {
var amzHeaders = [];
AWS.util.each(request.headers, function(name) {
if (name.match(/^x-amz-/i))
amzHeaders.push(name);
});
amzHeaders.sort(function(a, b) {
return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
});
var parts = [];
AWS.util.each(amzHeaders, function(name) {
parts.push(amzHeaders[name].toLowerCase() + ':' + request.headers[amzHeaders[name]]);
});
return parts.join('\n');
}
private canonicalizedResource(request) {
return request.path || '/';
}
I call the method like:
var signature = this.sign(AWS.config.credentials.secretAccessKey, this.stringToSign(request));
Can you make sure your system time is up to date? I have had issues when my system time is out of sync. AWS rejects those API calls.

Concerns in using everyauth

I am having serious trouble in using everyauth. All I need is facebook login. For that I am trying to use the example of everyauth. Once I do facebook authentication, how can I check in every page if the user is logged in or not/ get his facebook information. What I have done is
var exp = require('express');
var app = exp.createServer();
var conf = require('/Users/lakeshkansakar/clicker/node_modules/everyauth/example/conf')
var everyauth = require('everyauth');
everyauth.debug = true;
var usersById = {};
var nextUserId = 0;
function addUser (source, sourceUser) {
var user;
user = usersById[++nextUserId] = {id: nextUserId};
user[source] = sourceUser;
return user;
}
var usersByFbId = {};
var usersByTwitId = {};
everyauth.everymodule
.findUserById( function (id, callback) {
callback(null, usersById[id]);
});
everyauth
.facebook
.appId(conf.fb.appId)
.appSecret(conf.fb.appSecret)
.findOrCreateUser( function (session, accessToken, accessTokenExtra, fbUserMetadata) {
return usersByFbId[fbUserMetadata.id] || (usersByFbId[fbUserMetadata.id] = addUser('facebook', fbUserMetadata));;
})
.redirectPath('/');
everyauth
.twitter
.consumerKey(conf.twit.consumerKey)
.consumerSecret(conf.twit.consumerSecret)
.findOrCreateUser( function (sess, accessToken, accessSecret, twitUser) {
return usersByTwitId[twitUser.id] || (usersByTwitId[twitUser.id] = addUser('twitter', twitUser));;
})
.redirectPath('/');
In every get request, I then tried to check if everyauth.loggedIn is true or not. However, everyauth.loggedIn is shown to be undefined. Why is it so? How to check if the user has logged in using facebook?
Not sure that this will help or not, but I researched both EveryAuth and Passport, and was able to implement Passport for Facebook and Google very quickly. It looks like a much cleaner implementation of authentication.
http://passportjs.org/
Once you are logged In, you will be redirected to "/" as mentioned in .redirectPath('/');.
In the routes for "/", you can check for everyauth.loggedIn.
You can see more details here.. How can I check if a user is already logged in? (everyauth, node.js)
Hope this helps!

Problem to catch REQUIRES_AUTH and xhr.status from HttpContext.Response

Trying to find solution for redirection to the login page after Ajax-call if a user is not authenticated longer.
I used a method described here
How to manage a redirect request after a jQuery Ajax call
private static void RedirectionToLogin(ActionExecutingContext filterContext)
{
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
filterContext.HttpContext.Response.AddHeader("REQUIRES_AUTH", "1");
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
JavaScript is
$(window).ajaxComplete(function (event, request, settings) {
alert(request.getResponseHeader('REQUIRES_AUTH'));
alert(request.status);
if (request.getResponseHeader('REQUIRES_AUTH') === 1) {
window.location = App.basePath + "Login/LogOn";
{
});
If user was logged out request.getResponseHeader('REQUIRES_AUTH')) is always NULL
Why request.getResponseHeader('REQUIRES_AUTH')) is NULL???
I think the reason you are getting a null value for "REQUIRES_AUTH" is that your log in page
~/Login/Logon
does not require authentication. Which is correct, otherwise you would not be able to log in! Also your javascript has a curly bracket the wrong way around. (typo) should be:
$(window).ajaxComplete(function (event, request, settings) {
alert(request.getResponseHeader('REQUIRES_AUTH'));
alert(request.status);
if (request.getResponseHeader('REQUIRES_AUTH') === 1) {
window.location = App.basePath + "Login/LogOn";
}
});
I am also looking for a nice solution for this problem, but am still a bit stuck. Have you managed to solve this problem? if so, how did you manage it?

Categories