Check if twitter username exists - authentication

Is there a way to check if a twitter username exists?
Without being authenticated with OAuth or the twitter basic authentication?

UPDATE 2021: This API is not available.
As of right now, you're better off using the API the signup form uses to check username availability in realtime. Requests are of the format:
https://twitter.com/users/username_available?username=whatever
And give you a JSON response with a valid key giving you a true if the username can be registered:
{"valid":false,"reason":"taken","msg":"Username has already been taken","desc":"That username has been taken. Please choose another."}
{"valid":true,"reason":"available","msg":"Available!","desc":"Available!"}
{"valid":false,"reason":"is_banned_word","msg":"Username is unavailable","desc":"The username \"root\" is unavailable. Sorry!"}
The reason this is better than checking for 404 responses is that sometimes words are reserved (like 'root' above), or a username is actually taken but for some reason the account is gone from the Twitter front end.

UPDATE
The Twitter REST API v1 is no longer active.
So use
https://api.twitter.com/1.1/users/show.json?screen_name=username
You can also use the API with username :
http://api.twitter.com/1/users/show.xml?screen_name=tarnfeld
Will give you :
<?xml version="1.0" encoding="UTF-8"?>
<user>
...................
<screen_name>tarnfeld</screen_name>
<location>Portsmouth, UK</location>
.................
</status>
</user>
Or if not exist :
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<request>/1/users/show.xml?screen_name=tarnfeldezf</request>
<error>Not found</error>
</hash>

As API v1 is no longer available, here is another way to check if a twitter account exists. The page headers of a non existing account contain 404 (page not found).
function twitterAccountExists($username){
$headers = get_headers("https://twitter.com/".$username);
if(strpos($headers[0], '404') !== false ) {
return false;
} else {
return true;
}
}

Here is how it works on PHP :
$user_infos = 'http://api.twitter.com/1/users/show.xml?screen_name='.$username;
if (!#fopen($user_infos, 'r'))
{
return false;
}
return true;

This worked for me, close to what sferik has posted.
def twitter_user_exists?(user)
Twitter.user(user)
true
rescue Twitter::Error::NotFound
false
end

You can try to grab the http://twitter.com/username page and read the response to see if you get the "Sorry, that page doesn’t exist!" page.
Edit:
As #Pablo Fernandez mentioned in a comment, it will be better (faster, more reliable) to check the response header, which will be "404 not-found" if the user doesn't exist.

Using Ruby, you could install the twitter gem and then define the following method:
require 'twitter'
def user_exists?(user)
Twitter.user(user)
true
rescue Twitter::NotFound
false
end
Then, simply pass in a Twitter user name or id to your method, like so:
user_exists?("sferik") #=> true
user_exists?(7505382) #=> true

You can try:
<?php
$user = "toneid";
$contents = #file_get_contents('http://www.twitter.com/'.$user);
if (!$contents) {
// Report error
echo "Not a valid user";
} else {
// If is a valid url
echo "OK!";
}
?>

UPDATE: This API is not available since 2012.
According to the api docs you can pass an email address to the user/
show method, I would assume that if a user didn't exist you'd get back
a 404, which should allow you to determine whether or not the user
exists.
eg: http://twitter.com/users/show.xml?email=t...#example.com
result if not exist :
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<request>/users/show.xml?email=tur...#example.com</request>
<error>Not found</error>
</hash

Related

How to find access_token expired or not in Onedrive?

In Onedrive I am able to use their Live SDK API and get the Access_token and the filepicker for my users is also working properly.
But, every time a user tries to attach a file I am calling the API to get the Access_token.
Is this a problem, when more number of users try to call this API every time they try to attach the files( did Microsoft has a limit for number of API call).
Also, If i try to use Refresh_token for Access_token using WL.offline_access scope how would my app know the Access_token is expired?
You'll need to add logic to your code to see if the user is already has a session occurring. You can do this this by adding WL.Event.subscribe and checking for "auth.statusChange". If the users status has changed at any point, it will call the function to check the users current status (i.e. connect, notConnected, and unknown) by calling WL.getLoginStatus. WL.getLoginStatus will also return the users session object (access_token, expires_in, etc) if you want to use any values there.
Your code will look something like this.
< script type = "text/javascript" >
WL.Event.subscribe("auth.statusChange", chkStatus);
function chkStatus() {
WL.getLoginStatus(
function(response) {
if (response.status == "connected") {
document.getElementById("info").innerText = "You're signed in";
} else {
WL.login({
"scope": "wl.skydrive_update"
});
}
More info on WL.getLoginStatus can be found at https://msdn.microsoft.com/EN-US/library/hh550842.aspx. I hope that helps.

Perform authentication to Polarion webservice with Savon

I am attempting to follow the discussion here using Ruby and Savon. I am able to retrieve a session ID, but whenever I perform a request from the clients that require authentication (tracker), I receive an Authorization Failed error.
require 'Savon'
tracker_url = 'http://myserver/polarion/ws/services/TrackerWebService?wsdl'
session_url = 'http://myserver/polarion/ws/services/SessionWebService?wsdl'
# todo handle bad login credentials gracefully
session_client = Savon.client(wsdl: session_url)
response = session_client.call(:log_in, message: {user_name: 'lsimons', password: 'mypassword'})
session_id = response.header[:session_id]
puts "Session ID: #{session_id}"
tracker_client = Savon.client(wsdl: tracker_url, soap_header: {"session" => session_id}, headers: {"sessionID" => session_id})
puts "Requesting Workitem"
begin
tracker_client.call(:get_work_item_by_id, message: {project_id: 'myProject', workitem_id: 'myWorkitem'})
rescue
puts "Client call failed"
end
This code creates the following SOAP request for the tracker_client:
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ins0="http://ws.polarion.com/TrackerWebService-impl" xmlns:ins1="http://ws.polarion.com/types" xmlns:ins2="http://ws.polarion.com/TrackerWebService-types" xmlns:ins3="http://ws.polarion.com/ProjectWebService-types" xmlns:tns1="http://ws.polarion.com/TrackerWebService" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<env:Header>
<session>2164640482421325916</session>
</env:Header>
<env:Body>
<tns1:getWorkItemById>
<ins0:projectId>myProject</ins0:projectId>
<ins0:workitemId>myWorkitem</ins0:workitemId>
</tns1:getWorkItemById>
</env:Body>
</env:Envelope>
However, in the forum discussion, the sessionID element occurs before the header. I didn't think this was possible with standard SOAP? Is there a way to achieve this with Savon or am I misinterpreting the forum discussion?
I faced the same problem following the same thread. This is how I made it work (by replicating the response headers of the log_in request):
tracker_client = Savon.client(
wsdl: tracker_url,
soap_header: {
"ns1:sessionID" => session_id,
:attributes! => {
"ns1:sessionID" => {
"env:actor" => "http://schemas.xmlsoap.org/soap/actor/next",
"env:mustUnderstand" => "0",
"xmlns:ns1" => "http://ws.polarion.com/session"
}
}
}
)
Old question but thought I can add some info to hopefully help somebody.
I am using lolsoap to talk to polarion. In the above resulting document, the sessionID element is wiped off any namespaces and attributes. Also the assessment is right that actor and mustUnderstand attributes seem irrelevant.
To add header properly though with all fluff, one needs to get the Nokogiri::XML::Node and dup it, then add it to the header of the doc. This is a bug in nokogiri/libxml2 that adding child elements can often break namespaces unless Node is cloned before adding [1].
In lolsoap it is done something like:
auth_header = login_response.nokogiri_doc.xpath("//*[local-name()='sessionID']")[0].dup
other_request.header.__node__ << auth_header
Please note the dup operation. header.__node__ is just the header Nokogiri::XML::Element of a random SOAP request.
The dup operation makes adding desired element into another one with all necessary namespaces and attributes properly defined.
I don't know if savon allows one to directly touch request XML but I guess it does. Thus HTH
[1] https://github.com/sparklemotion/nokogiri/issues/1200

Codeigniter API error returning

Hi has anyone any experience using Phil Sturgeons RESTFUL libraries for codeigniter. I've decided to create a web service for our database in order to supply access to the database from multiple applications. The website is currently developed in Codeigniter therefore it was a simple solution to use the rest API libraries.
The problem I have is that I am trying to return specific errors in the event of a problem.
At the moment I am purposely returning an error like so:
require(APPPATH . 'libraries/REST_Controller.php');
class Settings_api extends REST_Controller {
function settings_get()
{
$this->response(NULL, 404);
}
}
If I access the url directly then I am just receiving a blank page, I can return a message if I replace the 'NULL' with a message but there is nothing to say its a 404 error whereas If I call the page via php using the following
$user = json_decode(file_get_contents('http://www.example.co.uk/api/settings_api/settings/'));
echo $user;
then it shows the following line
Message: file_get_contents(http://www.example.co.uk/api/settings_api/settings/) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404
In both instances I would like to return a 404 error along with a message I provide. Is this possible and if so could you point me in the right direction.
Thanks
The error message being generated by PHP, as far as I know, there's nothing you can do about this (other than using the # operator, which I do NOT recommend). So, your only option is to manually check file_get_content()'s return value:
$response = file_get_contents('http://...');
if ($response === false) {
// return whatever you feel is appropriate
} else {
$user = json_decode($response);
echo $user;
}
EDIT
Found this answer here on Stackoverflow which is what you are looking for.

Getting user data is inconsistent on the php and javascript sdk

I've been developing a facebook application that uses a combination of the php sdk and the javascript sdk. It runs in a tabbed iframe on facebook and is hosted on my own server. I'm using the latest php and javascript sdk files as of now (Sept 06, 2011, 2:50PM). The first inconsistency is in the php sdk when getting the user id. This is my code:
require 'fb_php_sdk/facebook.php';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$user = $facebook->getUser();
if ($user) {
$permissions_granted = true;
} else {
$permissions_granted = false;
}
This very frequently returns '0' as the facebook ID, no idea why. Though almost as frequently returns the actual facebook id.
The other issue is with images. I often get images not showing up when calling this url:
<img src="https://graph.facebook.com/' . $uid. '/picture/" />
When I use fql I inconsistently get 'undefined' as a result when performing this query:
FB.api(
{
method: 'fql.query',
query: 'SELECT name,pic FROM user WHERE uid=<? echo $user ?>'
},
function(response)
{
alert(response[0].pic);
}
);
I really don't understand what would cause this inconsistency and it's making bug testing very difficult. If anyone has experienced this kind of behaviour and can point me in the right direction I'd really appreciate it. Thanks!
This very frequently returns '0' as the facebook ID, no idea why. Though almost as frequently returns the actual facebook id.
Of course, because your app needs at least the default permissions. Otherwise you'll get nothing about the user. And same with your images. I bet most time your $uid contains the number zero.
Did you check what facebook returns? It should be something like:
{
"error": {
"type": "OAuthException",
"message": "An active access token must be used to query information about the current user."
}
}
So you need to get permissions of the user to get access to his/her data.
Kind regards,
Jurik

Symfony REST API authentication without sfGuardPlugin

I'm trying to find information on securing a HTTP REST API in a Symfony project, but all I can find is information about using sfGuardPlugin. From what I can see, this plugin isn't very useful for web services. It tries to have user profile models (which aren't always that simple) and have "sign in" and "sign out" pages, which obviously are pointless for a stateless REST API. It does a lot more than I'll ever have need for and I what to keep it simple.
I want to know where to implement my own authorisation method (loosely based on Amazon S3's approach). I know how I want the authorisation method to actually work, I just don't know where I can put code in my Symfony app so that it runs before every request is processed, and lets approved requests continue but unsuccessful requests return a 403.
Any ideas? I can't imagine this is hard, I just don't know where to start looking.
There is a plugin for RESTful authentication -> http://www.symfony-project.org/plugins/sfRestfulAuthenticationPlugin
Not used it though ....
How where you planning to authenticate users ?
The jobeet tutorial uses tokens ... http://www.symfony-project.org/jobeet/1_4/Doctrine/en/15
I ended up finding what I was looking for by digging into the code for sfHttpAuthPlugin. What I was looking for was a "Filter". Some details and an example is described in the Askeet sample project.
Stick a HTTP basicAuth script in your <appname>_dev.php (Symfony 1.4 =<) between the project configuration "require" and the configuration instance creation.
Test it on your dev. If it works, put the code in your index.php (the live equivalent of <appname>_dev.php) and push it live.
Quick and dirty but it works. You may want to protect that username/password in the script though.
e.g.
$realm = 'Restricted area';
//user => password
$users = array('username' => 'password');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// || !isset($users[$data['username']]
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Wrong Credentials!');
}
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Wrong Credentials!');
}
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('#(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))#', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
// ****************************************************************************
// ok, valid username & password.. continue...