/// <summary> /// User authentication check for Twitter /// </summary> private void CheckTwitterConnectedUser() { var ctx = Request.GetOwinContext(); var authenticatedUser = ctx.Authentication.User; var result = ctx.Authentication.AuthenticateAsync(UserAccountType.Twitter).Result; if (authenticatedUser.Identity.IsAuthenticated) { if (authenticatedUser.Identity.AuthenticationType == UserAccountType.Twitter) { string screenname = authenticatedUser.Claims.FirstOrDefault(x => x.Type == "urn:twitter:screenname").Value; string socialid = authenticatedUser.Claims.FirstOrDefault(x => x.Type == "urn:twitter:userid").Value; string accessToken = authenticatedUser.Claims.FirstOrDefault(x => x.Type == "urn:twitter:accesstoken").Value; string accessTokenSecret = authenticatedUser.Claims.FirstOrDefault(x => x.Type == "urn:twitter:accesstokensecret").Value; string useravatar = GetTwitterProfileImage(accessToken, accessTokenSecret); try { OAuthAccount account = OAuthAccount.SingleOrDefault(p => p.user_id == long.Parse(socialid)); if (account != null) { account.screen_name = screenname; account.oauth_token = accessToken; account.oauth_token_secret = accessTokenSecret; account.profile_image_url = useravatar; account.LastAccessedOn = DateTime.UtcNow; account.TokenExpiry = result.Properties.ExpiresUtc.Value.DateTime; account.Update(); ViewBag.id = account.Id; } else { OAuthAccount newAccount = new OAuthAccount(); newAccount.user_id = long.Parse(socialid); newAccount.screen_name = screenname; newAccount.oauth_token = accessToken; newAccount.oauth_token_secret = accessTokenSecret; newAccount.profile_image_url = useravatar; newAccount.CreatedOn = DateTime.UtcNow; newAccount.LastAccessedOn = DateTime.UtcNow; newAccount.TokenExpiry = result.Properties.ExpiresUtc.Value.DateTime; newAccount.oauth_service_id = 1; newAccount.UserAccess = 0; newAccount.UserRole = 0; newAccount.Save(); ViewBag.id = account.Id; } } catch (Exception) { } ViewBag.screenname = screenname; ViewBag.socialid = socialid; ViewBag.accessToken = accessToken; ViewBag.accessTokenSecret = accessTokenSecret; ViewBag.useravatar = useravatar; ViewBag.Logged = true; } else { ViewBag.Logged = false; ctx.Authentication.SignOut(authenticatedUser.Identity.AuthenticationType); Redirect("/"); } } else { ViewBag.Logged = false; ViewBag.screenname = null; ViewBag.socialid = null; ViewBag.id = null; } }
public ActionResult Authenticate(string appId, string format, string oauth_token, string oauth_token_secret) { OAuthClientApp app = OAuthClientApp.Find(c => c.Guid.Equals(appId)).SingleOrDefault(); if (app == null) { HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { error = "Invalid or unknown appId" }, JsonRequestBehavior.AllowGet); } OAuthAccount account = null; bool tokenExpired = TokenExpired(oauth_token, out account); // Check for UserAccess if (account != null) { if ((DataEnums.UserAccess)account.UserAccess != DataEnums.UserAccess.Normal) { HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden; return Json(new { }, JsonRequestBehavior.AllowGet); } } // Check for token expiry if (tokenExpired) { HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { error = "Expired token." }, JsonRequestBehavior.AllowGet); } // verify credentials with Twitter var verify = OAuth.GetProtectedResource(TwitterVerifyCredentialsUrl, "GET", app.ConsumerKey, app.ConsumerSecret, oauth_token, oauth_token_secret); HttpContext.Response.StatusCode = (int)NUrl.LastResponseStatusCode.GetValueOrDefault(); JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary<string, object> obj = serializer.DeserializeObject(verify) as Dictionary<string, object>; if (HttpContext.Response.StatusCode == (int)HttpStatusCode.OK) { // Update/Add TwitterAccount // reset the expiry token using (TransactionScope ts = new TransactionScope()) using (SharedDbConnectionScope sharedConnectionScope = new SharedDbConnectionScope()) { try { if (account == null) { account = new OAuthAccount(); account.CreatedOn = DateTime.UtcNow; long tokenExpiryMinutes = 20; long.TryParse(CloudSettingsResolver.GetConfigSetting("tokenExpiryMinutes"), out tokenExpiryMinutes); account.TokenExpiry = DateTime.UtcNow.AddMinutes(tokenExpiryMinutes); } // the deserializer always boxes it to int (so far), but just in case in the future its > int long user_id = 0; if (obj.ContainsKey(kTwitterUserId)) { if (obj[kTwitterUserId] is int) { int user_id_int = (int)obj[kTwitterUserId]; user_id = user_id_int; } else if (obj[kTwitterUserId] is long) { user_id = (long)obj[kTwitterUserId]; } } string screen_name = obj[kTwitterScreenName] as string; account.user_id = user_id; account.screen_name = screen_name; account.LastAccessedOn = DateTime.UtcNow; account.oauth_token = oauth_token; account.oauth_token_secret = oauth_token_secret; account.oauth_service_id = app.Id; account.profile_image_url = obj[kTwitterProfileImageUrl] as string; var atu = CloudSettingsResolver.GetConfigSetting("AdminTwitterUser"); if (!string.IsNullOrEmpty(atu) && atu == screen_name) account.UserRole = 2; account.Save(); ts.Complete(); } catch (Exception ex) { HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(CreateErrorObject(ex), JsonRequestBehavior.AllowGet); } } // Authenticate Session HttpContext.Session.RemoveAll(); FormsAuthentication.SetAuthCookie(account.user_id.ToString(), false); HttpContext.Session[kAccountId] = account.Id; HttpContext.Session[kTwitterScreenName] = account.screen_name; HttpContext.Session[kTwitterUserId] = account.user_id; } return Json(account, JsonRequestBehavior.AllowGet); }
public static void Setup(int testItems) { SetTestRepo(); for(int i=0;i<testItems;i++){ OAuthAccount item=new OAuthAccount(); _testRepo._items.Add(item); } }
private bool TokenExpired(string oauth_token, out OAuthAccount account) { var expired = false; account = null; try { account = OAuthAccount.Find(c => c.oauth_token == oauth_token).SingleOrDefault(); if (account != null) { bool useTokenExpiry = false; bool.TryParse(CloudSettingsResolver.GetConfigSetting("UseTokenExpiry"), out useTokenExpiry); if (useTokenExpiry) { expired = (DateTime.UtcNow.Ticks - account.TokenExpiry.ToUniversalTime().Ticks) >= 0; } } } catch (Exception ex) { Trace.WriteLine(ex.StackTrace); } return expired; }
public static void Setup(OAuthAccount item) { SetTestRepo(); _testRepo._items.Add(item); }