Skip to content

Instantly share code, notes, and snippets.

@lazypower
Created February 11, 2012 05:40
Show Gist options
  • Save lazypower/1796750 to your computer and use it in GitHub Desktop.
Save lazypower/1796750 to your computer and use it in GitHub Desktop.
Facebook OAUTH controller for MVC3 projects
using System;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using PennyAuction.Models;
using System.Linq;
namespace MyProject.Controllers
{
public class FacebookController : Controller
{
/// <summary>
/// Initiate the Facebook Login Sequence
/// </summary>
public void fbLogin()
{
oAuthFacebook oauth = new oAuthFacebook();
Response.Redirect(oauth.AuthorizationLinkGet());
}
public void fbCallback()
{
string url = "";
// cache the Request code, since LINQ does not evaluate at runtime properly
string authCode = Request["code"];
oAuthFacebook oAuth = new oAuthFacebook();
if (authCode == null)
{
//Redirect the user back to Facebook for authorization.
Response.Redirect(oAuth.AuthorizationLinkGet());
}
else
{
//Get the access token and secret.
oAuth.AccessTokenGet(authCode);
if (oAuth.Token.Length > 0)
{
//We now have the credentials, so we can start making API calls
url = "https://graph.facebook.com/me/?access_token=" + oAuth.Token;
string json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty);
if (json != null)
{
// parse the response object first, we may want to create a user from it.
JObject o = JObject.Parse(json);
// get a data-set to populate
using (var context = new AuctionDataContainer())
{
// query the database for users containing the facebook token, ordered by firstname
var users = context.SiteUsers
.Where(u => u.FacebookToken == authCode)
.ToList();
if (users.Count == 0) // we have no users in the database. Migrate them into the DB
{
// this was throwing errors, creating a guid prior to population then
Guid id = Guid.NewGuid();
SiteUsers newUser = SiteUsers.CreateSiteUsers(id,
(string)o["first_name"],
(string)o["last_name"],
(string)o["email"],
DateTime.Now,
DateTime.Now);
newUser.FacebookToken = authCode;
context.SiteUsers.AddObject(newUser);
context.SaveChanges(); // commit our user to the database
} // TODO: if user exists and decides they want to add facebook -- update their info
// by default we should update their last login time.
var thisUser = context.SiteUsers
.Where(u => u.FacebookToken == authCode)
.FirstOrDefault();
thisUser.LastLogin = DateTime.Now;
context.SaveChanges();
}// end of using
}
} // if our token was blank we have failure
else
{
Response.Redirect("/"); // TODO: set an error code and display it on the main site
}
Response.Redirect("/");
}
} // end of fb callback method
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment