Created
May 24, 2011 14:58
-
-
Save possan/988864 to your computer and use it in GitHub Desktop.
Zitiz OAuth code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading; | |
using System.Web; | |
using JsonFx.Json; | |
using log4net; | |
using OAuth; | |
using Zitiz.Types.Interfaces.IO; | |
using Zitiz.Types.Interfaces.Security; | |
using Zitiz.Types.Interfaces.UI; | |
using Zitiz.Types.Interfaces.User; | |
using Zitiz.Util; | |
namespace Zitiz.Security.Twitter | |
{ | |
// | |
// Twitter OAuth authentication: | |
// http://dev.twitter.com/pages/auth | |
// | |
class TwitterAuthentication : IExternalAuthenticationManager | |
{ | |
private readonly IStateVariableManager _svm; | |
private readonly IExternalLoginManager _elm; | |
private readonly ITemporaryMessageManager _pagemessages; | |
private readonly IAuthenticationUtilities _auth; | |
private readonly ISignatureRepository _sr; | |
private ILog logger = LogManager.GetLogger(typeof(TwitterAuthentication)); | |
public string ID | |
{ | |
get | |
{ | |
return "twitter"; | |
} | |
} | |
string ConsumerKey | |
{ | |
get | |
{ | |
return System.Configuration.ConfigurationManager.AppSettings["Twitter.ConsumerKey"]; | |
} | |
} | |
string CallbackUrl | |
{ | |
get | |
{ | |
return System.Configuration.ConfigurationManager.AppSettings["Twitter.CallbackUrl"]; | |
} | |
} | |
string ConsumerSecret | |
{ | |
get | |
{ | |
return System.Configuration.ConfigurationManager.AppSettings["Twitter.ConsumerSecret"]; | |
} | |
} | |
string RequestTokenUrl | |
{ | |
get | |
{ | |
return "http://api.twitter.com/oauth/request_token"; | |
} | |
} | |
string AccessTokenUrl | |
{ | |
get | |
{ | |
return "https://api.twitter.com/oauth/access_token"; | |
} | |
} | |
string AuthorizeUrl | |
{ | |
get | |
{ | |
// return "https://api.twitter.com/oauth/authorize"; | |
return "https://api.twitter.com/oauth/authenticate"; | |
} | |
} | |
public TwitterAuthentication(IStateVariableManager svm, IExternalLoginManager elm, ITemporaryMessageManager pagemessages, IAuthenticationUtilities auth, ISignatureRepository sr) | |
{ | |
_svm = svm; | |
_elm = elm; | |
_pagemessages = pagemessages; | |
_auth = auth; | |
_sr = sr; | |
} | |
void SaveRedirectUrl(string id, string url) | |
{ | |
_svm.Set(".tempauth." + id + ".redirect", url); | |
} | |
void SaveTokenSecret(string oauthtoken, string secret) | |
{ | |
_svm.Set(".tempauth." + oauthtoken + ".secret", secret); | |
} | |
string GetRedirectUrl(string id) | |
{ | |
return _svm.Get(".tempauth." + id + ".redirect", ""); | |
} | |
string GetTokenSecret(string oauthtoken) | |
{ | |
return _svm.Get(".tempauth." + oauthtoken + ".secret", ""); | |
} | |
public string GetTranslatedName(string languagecode) | |
{ | |
return "Twitter"; | |
} | |
void SaveAction(string id, string action) | |
{ | |
_svm.Set(".tempauth." + id + ".action", action); | |
} | |
string GetAction(string id) | |
{ | |
return _svm.Get(".tempauth." + id + ".action", ""); | |
} | |
public void Login(HttpContext context, string returnurl) | |
{ | |
innerLogin(returnurl, "login", context); | |
} | |
private void innerLogin(string returnurl, string action, HttpContext context) | |
{ | |
string callback = CallbackUrl; | |
var cfg = new OAuthConfig("console"); | |
cfg.AccessTokenUrl = AccessTokenUrl; | |
cfg.RequestTokenUrl = RequestTokenUrl; | |
cfg.ConsumerKey = ConsumerKey; | |
cfg.ConsumerSecret = ConsumerSecret; | |
cfg.OauthVersion = "1.0"; | |
cfg.OauthSignatureMethod = "HMAC-SHA1"; | |
cfg.UserAuthorizationUrl = AuthorizeUrl; | |
var ac = new OAuthConsumer(cfg, "console"); | |
var rt = ""; | |
int retries = 0; | |
while (string.IsNullOrEmpty(rt) && retries < 5) | |
{ | |
rt = ac.getRequestTokenRedirectUrl(null, "oauth_callback=" + OAuthBase.UrlEncode(callback)); | |
logger.Debug("rt = " + rt + "<br/>"); | |
if (string.IsNullOrEmpty(rt)) | |
Thread.Sleep(500); // försök igen om några ms. | |
retries++; | |
} | |
logger.Debug("OauthToken = " + cfg.OauthToken + "<br/>"); | |
logger.Debug("OauthTokenSecret = " + cfg.OauthTokenSecret + "<br/>"); | |
SaveTokenSecret(cfg.OauthToken, cfg.OauthTokenSecret); | |
SaveRedirectUrl(cfg.OauthToken, returnurl); | |
SaveAction(cfg.OauthToken, action); | |
ContextUtilities.ReturnRedirect(context, rt); | |
} | |
public void Attach(HttpContext context, string returnurl) | |
{ | |
innerLogin(returnurl, "attach", context); | |
} | |
public void HandleRequest(HttpContext context, string relativepath) | |
{ | |
// var m = Regex.Match(relativepath, "(.+)/login"); | |
// if (!m.Success) | |
// return; | |
// var temptokenid = m.Groups[1].Value; | |
string loggedintext = Possan.Localization.Translate.ID(typeof(TwitterAuthentication), "loggedin", "Du har loggats in"); | |
if (context.Request["oauth_token"] != null && context.Request["oauth_verifier"] != null) | |
{ | |
string token = context.Request["oauth_token"]; | |
string verifier = context.Request["oauth_verifier"]; | |
string secret = GetTokenSecret(token); | |
string redirect = GetRedirectUrl(token); | |
string action = GetAction(token); | |
// string callback = PathUtilities.CombineURL(CallbackUrl, "login/"); | |
var cfg = new OAuthConfig("console"); | |
cfg.AccessTokenUrl = AccessTokenUrl; | |
cfg.RequestTokenUrl = RequestTokenUrl; | |
cfg.ConsumerKey = ConsumerKey; | |
cfg.ConsumerSecret = ConsumerSecret; | |
cfg.OauthVersion = "1.0"; | |
cfg.OauthSignatureMethod = "HMAC-SHA1"; | |
cfg.UserAuthorizationUrl = AuthorizeUrl; | |
cfg.OauthToken = token; | |
cfg.OauthTokenSecret = secret; | |
// cfg.SiteUrl = callback; | |
var ac = new OAuthConsumer(cfg, "console"); | |
string atoken = ac.getAccessToken(verifier); | |
logger.Info("atoken = " + atoken + "<br/>"); | |
logger.Debug("OauthToken = " + cfg.OauthToken + "<br/>"); | |
logger.Debug("OauthTokenSecret = " + cfg.OauthTokenSecret + "<br/>"); | |
// SaveTokenSecret(token, cfg.OauthTokenSecret); | |
// redirect away.... | |
// ac.getAccessToken(cfg.OauthTokenSecret); | |
string mejson = ""; | |
int retries = 0; | |
while (string.IsNullOrEmpty(mejson) && retries < 5) | |
{ | |
mejson = (string)ac.request("http://api.twitter.com/1/account/verify_credentials.json", "GET", null, "PLAIN"); | |
logger.Info("mejson = " + mejson + "<br/>"); | |
if (string.IsNullOrEmpty(mejson)) | |
Thread.Sleep(500); // försök igen om några ms. | |
retries++; | |
} | |
/** {"lang":"en","profile_background_color":"1A1B1F", | |
* "verified":false, | |
* "profile_background_image_url":"http:\/\/a3.twimg.com\/images\/themes\/theme1\/bg.png", | |
* "description":"a systems architect who likes to make creative diy stuff","location":"Stockholm, Sweden", | |
* "default_profile_image":false,"followers_count":97, | |
* | |
* "id_str":"13766772", | |
* | |
* "show_all_inline_media":false,"geo_enabled":true,"friends_count":223, | |
* "profile_text_color":"666666", | |
* | |
* "url":"http:\/\/www.possan.se", | |
* | |
* "profile_sidebar_fill_color":"252429","follow_request_sent":null,"following":null,"notifications":null, | |
* "profile_background_tile":false, | |
* "created_at":"Thu Feb 21 11:37:57 +0000 2008","is_translator":false, | |
* "statuses_count":560,"favourites_count":21,"default_profile":false, | |
* "profile_link_color":"ff420f","protected":false, | |
* | |
* "profile_image_url":"http:\/\/a1.twimg.com\/profile_images\/61907977\/avatar-ny_normal.jpg", | |
* | |
* "profile_sidebar_border_color":"181A1E","name":"possan","listed_count":3,"contributors_enabled":false, | |
* "time_zone":"Greenland", | |
* | |
* "screen_name":"possan", | |
* | |
* "id":13766772, | |
* | |
* "profile_use_background_image":false,"utc_offset":-10800}*/ | |
try | |
{ | |
var jr = new JsonReader(mejson); | |
var o = jr.Deserialize() as Dictionary<string, object>; | |
string uid = o["id"].ToString(); | |
string photo = o["profile_image_url"].ToString(); | |
string name = o["screen_name"].ToString(); | |
string locale = o["lang"].ToString(); | |
var eli = _elm.FindByServiceAndServiceUserID("twitter", uid); | |
if (eli != null) | |
{ | |
eli.SetMetadataProperty("access_token", token); | |
eli.SetMetadataProperty("last_secret", secret); | |
eli.SetMetadataProperty("last_verifier", verifier); | |
eli.Save(); | |
if (action == "login") | |
{ | |
var rosig = _sr.PrimaryByUsername(eli.Username); | |
if (!rosig.SquareAvatar.Contains("zitiz")) | |
{ | |
// uppdatera endast om domänen är twitters, annars kan vi ha bytt på zitiz då ska vi inte ersätta den | |
if (photo != rosig.SquareAvatar) | |
{ | |
var edsig = _sr.GetItemForEditing(rosig.Id); | |
edsig.SquareAvatar = photo; | |
edsig.Save(); | |
} | |
} | |
_pagemessages.RegisterMessage(loggedintext); | |
_auth.SetCookieAndLogin(HttpContext.Current, eli.Username, true, "user/login/twitter"); | |
if (_auth.SSOEnabled) | |
{ | |
string newtoken = _auth.CreateSSOToken(eli.Username); | |
redirect = PathUtilities.AppendQueryString(redirect, "ssotoken", newtoken); | |
} | |
// logger.Debug("Redirect to: " + redirect); | |
CurrentContextUtilities.ReturnRedirect(redirect); | |
} | |
if (action == "attach") | |
{ | |
// logger.Debug("Redirect to: " + redirect); | |
CurrentContextUtilities.ReturnRedirect(redirect); | |
} | |
} | |
else | |
{ | |
if (action == "login") | |
{ | |
string regtoken = Guid.NewGuid().ToString().Replace("-", ""); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "service_name", "twitter"); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "service_user_id", uid); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "name", name); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "avatar", photo); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "firstname", ""); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "lastname", ""); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "link", "http://twitter.com/" + name); | |
_auth.SetTemporaryRegistrationInfo(regtoken, "locale", locale); | |
_auth.RedirectToRegisterExternalPage(context, regtoken, redirect); | |
} | |
if (action == "attach") | |
{ | |
if (HttpContext.Current.User.Identity.IsAuthenticated) | |
{ | |
var eli2 = _elm.Connect(HttpContext.Current.User.Identity.Name, "twitter", uid); | |
eli2.SetMetadataProperty("originalname", name); | |
eli2.SetMetadataProperty("link", "http://twitter.com/" + name); | |
// eli.SetMetadataProperty("linkname", auth.GetTemporaryRegistrationInfo(token, "linkname")); | |
eli2.SetMetadataProperty("access_token", token); | |
// eli2.SetMetadataProperty("session", auth.GetTemporaryRegistrationInfo(token, "session")); | |
// eli2.SetMetadataProperty("secret", auth.GetTemporaryRegistrationInfo(token, "secret")); | |
eli2.Save(); | |
} | |
CurrentContextUtilities.ReturnRedirect(redirect); | |
} | |
} | |
} | |
catch (Exception e) | |
{ | |
logger.Error(e); | |
CurrentContextUtilities.ReturnRedirect(redirect); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment