Creating a test Facebook user via the Graph API

Hackered
Tuesday, August 12, 2014
by Sean McAlinden

Nearly everything I do nowadays involves Facebook in one guise or another so the ability to generate test users is imperative. Facebook provides an API for accomplishing this very task. The following is a little service I use for wrapping the Facebook Graph API. The code relies on RestSharp, JSON.Net and my JsonSerializer wrapper. Example Usage:

var user = facebookUserService.CreateTestUser("MyAppId", "MyAppSecret");
string accessToken = user.access_token;
string email = user.email;
string id = user.id;
string loginUrl = user.login_url;
string password = user.password;

// to deauthorize the user call the following:
facebookUserService.Deauthorise(accessToken);

Here is the code:

/// 
/// Service for creating Facebook users.
/// 
public class FacebookUserService
{
    private const string BaseUrl = "https://graph.facebook.com";

    /// 
    /// Creates the test user.
    /// 
    ///The application identifier.
    ///The application secret.
    ///if set to true [authorised].
    public FacebookUser CreateTestUser(string appId, string appSecret, bool authorised = true)
    {
        var appAccessToken = GetApplicationAccessToken(appId, appSecret);
        var request = new RestRequest("/{appId}/accounts/test-users", Method.POST);
        request.AddUrlSegment("appId", appId);
        request.AddParameter("installed", authorised.ToString().ToLower());
        request.AddParameter("permissions", "read_stream");
        request.AddParameter("method", "post");
        request.AddParameter("access_token", appAccessToken);

        var restResponse = SendRequest(request);

        if (restResponse.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("Error creating Facebook test user. HttpStatusCode: " + restResponse.StatusCode + ". Message: " + restResponse.ErrorMessage);
        }

        var facebookUser = JsonSerializer.FromJsonString(restResponse.Content);

        return facebookUser;
    }

    /// 
    /// Deauthorises the specified test user by access token.
    /// 
    ///The access token.
    /// 
    /// Error de-authorising Facebook test user. HttpStatusCode:  + restResponse.StatusCode + . Message:  + restResponse.ErrorMessage
    public bool Deauthorise(string accessToken)
    {
        var request = new RestRequest("/me/permissions", Method.DELETE);
        request.AddParameter("access_token", accessToken);
        var restResponse = SendRequest(request);

        if (restResponse.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("Error de-authorising Facebook test user. HttpStatusCode: " + restResponse.StatusCode + ". Message: " + restResponse.ErrorMessage);
        }

        return true;
    }

    private static RestResponse SendRequest(RestRequest request)
    {
        var client = new RestClient { BaseUrl = BaseUrl };

        var response = client.Execute(request);

        return (RestResponse)response;
    }

    private static string GetApplicationAccessToken(string appId, string appSecret)
    {
        var request = new RestRequest("/oauth/access_token", Method.GET);
        request.AddParameter("client_id", appId);
        request.AddParameter("client_secret", appSecret);
        request.AddParameter("grant_type", "client_credentials");

        var restResponse = SendRequest(request);

        if (restResponse.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception(string.Format("Error getting Facebook access token. HttpStatusCode: {0}. Message: {1}", restResponse.StatusCode, restResponse.ErrorMessage));
        }

        return GetAccessToken(restResponse.Content);
    }

    private static string GetAccessToken(string url)
    {
        var regex = new Regex("access_token=(.+)");
        var match = regex.Match(url);
        var value = match.Groups[0].Value;
        var accessToken = value.Split('=').Skip(1).First();
        return accessToken;
    }
}
public class FacebookUser
{
    public string access_token { get; set; }

    public string email { get; set; }

    public string id { get; set; }

    public string login_url { get; set; }

    public string password { get; set; }
}