public async Task <bool> deleteGoogleAccount(ThirdPartyAuthenticationForView modelData) { bool RetValue = false; ThirdPartyCalendarAuthenticationModel ThirdPartyAuth = db.ThirdPartyAuthentication.Where(obj => obj.ID == modelData.ID).Single(); if (ThirdPartyAuth != null) { UserCredential googleCredential = ThirdPartyAuth.getGoogleOauthCredentials(); try { await googleCredential.RefreshTokenAsync(CancellationToken.None).ConfigureAwait(false); await googleCredential.RevokeTokenAsync(CancellationToken.None).ConfigureAwait(false); db.ThirdPartyAuthentication.Remove(ThirdPartyAuth); RetValue = true; } catch (Exception e) { if (e.Message.Contains("invalid_grant")) { db.ThirdPartyAuthentication.Remove(ThirdPartyAuth); } else { throw e; } } //await ThirdPartyAuth.getGoogleOauthCredentials().RevokeTokenAsync(CancellationToken.None).ConfigureAwait(false); await db.SaveChangesAsync().ConfigureAwait(false); } return(RetValue); }
async Task <bool> PopulateGoogleAuthentication(string TilerUserID, string AccessToken, string RefreshToken, string GoogleEmail, DateTimeOffset ExpirationDate) { //ApplicationDbContext db = new ApplicationDbContext(); TilerUser AppUser = UserManager.FindById(TilerUserID); bool RetValue = false; try { ThirdPartyCalendarAuthenticationModel NewAccountCalendarImportation = new ThirdPartyCalendarAuthenticationModel(); string AuthenticationID = Guid.NewGuid().ToString(); NewAccountCalendarImportation.TilerID = TilerUserID; NewAccountCalendarImportation.ID = AuthenticationID; NewAccountCalendarImportation.Token = AccessToken; NewAccountCalendarImportation.RefreshToken = RefreshToken; NewAccountCalendarImportation.isLongLived = false; NewAccountCalendarImportation.Email = GoogleEmail; NewAccountCalendarImportation.Deadline = ExpirationDate; NewAccountCalendarImportation.ProviderID = ThirdPartyControl.CalendarTool.google.ToString(); //await NewAccountCalendarImportation.refreshAuthenticationToken().ConfigureAwait(false); HttpContext myContext = System.Web.HttpContext.Current; ThirdPartyCalendarAuthenticationModelsController thirdPartyController = new ThirdPartyCalendarAuthenticationModelsController(); await thirdPartyController.CreateGoogle(NewAccountCalendarImportation); RetValue = true; } catch { RetValue = false; } return(RetValue); }
async Task <ThirdPartyCalendarAuthenticationModel> getGoogleAuthenticationData(string TilerUSerID, string EmailID) { Object[] Param = { TilerUSerID, EmailID, TilerElements.ThirdPartyControl.CalendarTool.google.ToString() }; ThirdPartyCalendarAuthenticationModel checkingThirdPartyCalendarAuthentication = await dbContext.ThirdPartyAuthentication.FindAsync(Param); return(checkingThirdPartyCalendarAuthentication); }
public async Task <ActionResult> CreateGoogle([Bind(Include = "ID,isLongLived,Email,Token,RefreshToken,ProviderID,Deadline")] ThirdPartyCalendarAuthenticationModel thirdPartyCalendarAuthentication, bool deletGoogleCalendarFromLog = false) { if (ModelState.IsValid) { bool makeAdditionCall = false; if (!deletGoogleCalendarFromLog) { ThirdPartyCalendarAuthenticationModelsController thirdPartyController = new ThirdPartyCalendarAuthenticationModelsController(); if (System.Web.HttpContext.Current != null)// this helps save the reurn uri for notification { thirdPartyController.initializeCurrentURI(System.Web.HttpContext.Current.Request.Url.Authority); } bool successInCreation = await thirdPartyController.CreateGoogle(thirdPartyCalendarAuthentication).ConfigureAwait(false); if (successInCreation) { ; } else { ; } return(RedirectToAction("ImportCalendar")); } else { Object[] Param = { thirdPartyCalendarAuthentication.TilerID, thirdPartyCalendarAuthentication.Email, thirdPartyCalendarAuthentication.ProviderID }; ThirdPartyCalendarAuthenticationModel checkingThirdPartyCalendarAuthentication = await dbContext.ThirdPartyAuthentication.FindAsync(Param); if (checkingThirdPartyCalendarAuthentication != null) { await deleteGoogleAccount(thirdPartyCalendarAuthentication.getThirdPartyOut()).ConfigureAwait(false); } } return(RedirectToAction("ImportCalendar")); } return(View("ImportCalendar")); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, ThirdPartyCalendarAuthenticationModel ThirdPartyCredentials = null) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Desktop", "Account")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } string[] nameArray = (info.ExternalIdentity.Name ?? "").Split(' '); string LastName = ""; string FirstName = ""; string OtherName = ""; if (nameArray.Length > 0) { FirstName = nameArray[0]; if (nameArray.Length > 1) { LastName = nameArray.Last(); } if (nameArray.Length > 2) { for (var i = 1; i < nameArray.Length - 1; i++) { OtherName = nameArray[i]; if (i + 1 < nameArray.Length - 1) { OtherName += " "; } } } } var user = new TilerUser { UserName = model.Email, Email = model.Email, FirstName = FirstName, LastName = LastName, OtherName = OtherName, EndfOfDay = DateTime.Now }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { user = dbContext.Users.Find(user.Id); await createProcrastinateCalendarEvent(user).ConfigureAwait(false); await createAnalysis(user).ConfigureAwait(false); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); Task SendThirdPartyAuthentication = new Task(() => { }); if (ThirdPartyCredentials != null) { string Email = ThirdPartyCredentials.Email; SendThirdPartyAuthentication = PopulateGoogleAuthentication(user.Id, ThirdPartyCredentials.Token, ThirdPartyCredentials.RefreshToken, Email, ThirdPartyCredentials.Deadline);; } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); /*string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); * var callbackUrl = Url.Action("ConfirmEmail", "Account",new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); * Task SendEmail =UserManager.SendEmailAsync(user.Id,"Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here </a>"); */ Task SendEmail = SendEmailConfirmationAsync(user.Id, "Please Confirm Your Tiler Account!"); await SendThirdPartyAuthentication.ConfigureAwait(false); await SendEmail.ConfigureAwait(false); return(RedirectToAction("Desktop", "Account")); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View("ExternalLoginConfirmation", model)); }
public async Task <ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return(RedirectToAction("Login")); } if (System.Web.HttpContext.Current != null)// this helps save the reurn uri for notification { ThirdPartyCalendarAuthenticationModelsController thirdPartyController = new ThirdPartyCalendarAuthenticationModelsController(); thirdPartyController.initializeCurrentURI(System.Web.HttpContext.Current.Request.Url.Authority); } string ThirdPartyType; var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false).ConfigureAwait(false); switch (result) { case SignInStatus.Success: { ThirdPartyType = loginInfo.ExternalIdentity.FindFirst("ThirdPartyType").Value; DateTimeOffset Now = DateTimeOffset.UtcNow; if (ThirdPartyType == TilerElements.ThirdPartyControl.CalendarTool.google.ToString()) { string RefreshToken = loginInfo.ExternalIdentity.FindFirst("RefreshToken").Value; if (!string.IsNullOrEmpty(RefreshToken)) { TilerUser AppUser = await UserManager.FindAsync(loginInfo.Login).ConfigureAwait(false); string Email = loginInfo.Email; string AccessToken = loginInfo.ExternalIdentity.FindFirst("AccessToken").Value; TimeSpan fiveMin = new TimeSpan(0, -5, 0); TimeSpan Duration = TimeSpan.Parse(loginInfo.ExternalIdentity.FindFirst("ExpiryDuration").Value); Duration = Duration.Add(fiveMin); Now = Now.Add(Duration); await PopulateGoogleAuthentication(AppUser.Id, AccessToken, RefreshToken, Email, Now).ConfigureAwait(false); } } return(RedirectToAction("Desktop", "Account")); } case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false })); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ThirdPartyType = loginInfo.ExternalIdentity.FindFirst("ThirdPartyType").Value; ThirdPartyCalendarAuthenticationModel thirdPartyModel = null; DateTimeOffset Deadline = DateTimeOffset.UtcNow; if (ThirdPartyType == TilerElements.ThirdPartyControl.CalendarTool.google.ToString()) { string RefreshToken = loginInfo.ExternalIdentity.FindFirst("RefreshToken").Value; if (!string.IsNullOrEmpty(RefreshToken)) { TilerUser AppUser = await UserManager.FindAsync(loginInfo.Login).ConfigureAwait(false); string Email = loginInfo.Email; string AccessToken = loginInfo.ExternalIdentity.FindFirst("AccessToken").Value; TimeSpan fiveMin = new TimeSpan(0, -5, 0); TimeSpan Duration = TimeSpan.Parse(loginInfo.ExternalIdentity.FindFirst("ExpiryDuration").Value); Duration = Duration.Add(fiveMin); Deadline = Deadline.Add(Duration); thirdPartyModel = new ThirdPartyCalendarAuthenticationModel(); thirdPartyModel.Deadline = Deadline; thirdPartyModel.Email = Email; thirdPartyModel.Token = AccessToken; thirdPartyModel.RefreshToken = RefreshToken; } else { string Email = loginInfo.Email; string AccessToken = loginInfo.ExternalIdentity.FindFirst("AccessToken").Value; thirdPartyModel = new ThirdPartyCalendarAuthenticationModel(); thirdPartyModel.Deadline = Deadline; thirdPartyModel.Email = Email; thirdPartyModel.Token = AccessToken; thirdPartyModel.RefreshToken = RefreshToken; thirdPartyModel.ID = Email; await thirdPartyModel.revokeAccess().ConfigureAwait(false); } } ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.Login.LoginProvider; if (string.IsNullOrEmpty(loginInfo.Email)) { return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email })); } else { return(await ExternalLoginConfirmation(new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }, returnUrl, thirdPartyModel)); } //return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); } }
public async Task <bool> CreateGoogle(ThirdPartyCalendarAuthenticationModel thirdPartyCalendarAuthentication) { bool RetValue = false; //if (ModelState.IsValid) { bool makeAdditionCall = false; //if (!deletGoogleCalendarFromLog) { bool saveFailed; do { saveFailed = false; try { Object[] Param = { thirdPartyCalendarAuthentication.TilerID, thirdPartyCalendarAuthentication.Email, thirdPartyCalendarAuthentication.ProviderID }; ThirdPartyCalendarAuthenticationModel checkingThirdPartyCalendarAuthentication = await db.ThirdPartyAuthentication.FindAsync(Param); if (checkingThirdPartyCalendarAuthentication != null) { checkingThirdPartyCalendarAuthentication.ID = thirdPartyCalendarAuthentication.ID; checkingThirdPartyCalendarAuthentication.Token = thirdPartyCalendarAuthentication.Token; checkingThirdPartyCalendarAuthentication.RefreshToken = thirdPartyCalendarAuthentication.RefreshToken; checkingThirdPartyCalendarAuthentication.Deadline = thirdPartyCalendarAuthentication.Deadline; db.Entry(checkingThirdPartyCalendarAuthentication).State = EntityState.Modified; await db.SaveChangesAsync().ConfigureAwait(false); RetValue = true; } else { db.ThirdPartyAuthentication.Add(thirdPartyCalendarAuthentication); await db.SaveChangesAsync(); RetValue = true; //if (!(await SendRequestForGoogleNotification(thirdPartyCalendarAuthentication).ConfigureAwait(false))) //{ // await deleteGoogleAccount(thirdPartyCalendarAuthentication.getThirdPartyOut()).ConfigureAwait(false); // RetValue=false; //} } } catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException dbEx) { saveFailed = true; dbEx.Entries.Single().Reload(); RetValue = false; /* * foreach (var validationErrors in dbEx.EntityValidationErrors) * { * foreach (var validationError in validationErrors.ValidationErrors) * { * System.Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); * } * }*/ } } while (saveFailed); } } return(RetValue); }
public async Task <bool> SendRequestForGoogleNotification(ThirdPartyCalendarAuthenticationModel AuthenticationData) { bool RetValue = false; try { var url = string.Format ( "https://www.googleapis.com/calendar/v3/calendars/{0}/events/watch", AuthenticationData.Email ); //url = "https://mytilerkid.azurewebsites.net/api/GoogleNotification/Trigger"; var httpWebRequest = HttpWebRequest.Create(url) as HttpWebRequest; httpWebRequest.Headers["Authorization"] = string.Format("Bearer {0}", AuthenticationData.Token); httpWebRequest.Method = "POST"; // added the character set to the content-type as per David's suggestion httpWebRequest.ContentType = "application/json; charset=UTF-8"; httpWebRequest.CookieContainer = new CookieContainer(); // replaced Environment.Newline by CRLF as per David's suggestion GoogleNotificationRequestModel NotificationRequest = AuthenticationData.getGoogleNotificationCredentials(CurrentURI); var requestText = JsonConvert.SerializeObject(NotificationRequest); using (var stream = httpWebRequest.GetRequestStream()) // replaced Encoding.UTF8 by new UTF8Encoding(false) to avoid the byte order mark using (var streamWriter = new System.IO.StreamWriter(stream, new UTF8Encoding(false))) { streamWriter.Write(requestText); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream())) { string result = streamReader.ReadToEnd(); GoogleNotificationWatchResponseModel NotificationResponse = JsonConvert.DeserializeObject <GoogleNotificationWatchResponseModel>(result); db.GoogleNotificationCredentials.Add(NotificationResponse); await db.SaveChangesAsync().ConfigureAwait(false); } RetValue = true; /* * string url = "https://www.googleapis.com/calendar/v3/calendars/" + AuthenticationData.Email + "/events/watch"; * //url = "https://mytilerkid.azurewebsites.net/api/GoogleNotification/Trigger"; * var httpWebRequest = WebRequest.Create(url); * httpWebRequest.ContentType = "application/json"; * string AuthorizationString = "Bearer " + AuthenticationData.Token; * httpWebRequest.Headers.Add("Authorization", AuthorizationString); * httpWebRequest.Method = "POST"; * * GoogleNotificationRequestModel NotificationRequest = AuthenticationData.getGoogleNotificationCredentials(Ctx.Request.Url.Authority); * * * //GoogleNotificationWatchResponseModel testGoogleResponse = new GoogleNotificationWatchResponseModel(); * //testGoogleResponse.expiration = "98989"; * //testGoogleResponse.id = "jkhj2hkjhkjh"; * //testGoogleResponse.kind = "99898989"; * //testGoogleResponse.resourceUri= "hjhj98878"; * //string JsonString = JsonConvert.SerializeObject(testGoogleResponse); * * * * string JsonString = JsonConvert.SerializeObject(NotificationRequest); * * using (var streamWriter = new System.IO.StreamWriter(httpWebRequest.GetRequestStream())) * { * string json = JsonString; * streamWriter.Write(json); * streamWriter.Flush(); * streamWriter.Close(); * } * * var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); * using (var streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream())) * { * var result = streamReader.ReadToEnd(); * } * RetValue = true; */ } catch (Exception E) { Console.WriteLine(E.Message); } return(RetValue); }
async public Task <ActionResult> ImportGoogle(CancellationToken cancellationToken) { string UserID = User.Identity.GetUserId(); //var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata(UserID)). var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken); Google.Apis.Auth.OAuth2.UserCredential myCredential = result.Credential; if (myCredential != null) { var service = new Oauth2Service(new BaseClientService.Initializer { HttpClientInitializer = myCredential, ApplicationName = "ASP.NET MVC Sample" }); bool ResetThirdparty = false; ThirdPartyCalendarAuthenticationModel thirdpartydata = new ThirdPartyCalendarAuthenticationModel(); Google.Apis.Oauth2.v2.Data.Userinfo userInfo; try { userInfo = service.Userinfo.Get().Execute(); } catch (Exception e) { ResetThirdparty = true; return(RedirectToAction("ImportGoogle")); } string Email = userInfo.Email; if (myCredential.Token.RefreshToken != null) //if user hasn't authenticated tiler before { thirdpartydata.Email = Email; thirdpartydata.TilerID = UserID; thirdpartydata.ID = myCredential.UserId; thirdpartydata.isLongLived = false; double totalSeconds = myCredential.Token.ExpiresInSeconds == null ? 0 : (double)myCredential.Token.ExpiresInSeconds; DateTime myDate = myCredential.Token.Issued.AddSeconds(totalSeconds); thirdpartydata.Deadline = new DateTimeOffset(myDate); thirdpartydata.ProviderID = TilerElements.ThirdPartyControl.CalendarTool.google.ToString(); thirdpartydata.Token = myCredential.Token.AccessToken; thirdpartydata.RefreshToken = myCredential.Token.RefreshToken; return(await CreateGoogle(thirdpartydata).ConfigureAwait(false)); } else //if user hasn authenticated tiler before, then update current credentials { ThirdPartyCalendarAuthenticationModel retrievedAuthentication = await getGoogleAuthenticationData(UserID, Email).ConfigureAwait(false); try { await retrievedAuthentication.refreshAndCommitToken(dbContext).ConfigureAwait(false); } catch { if (retrievedAuthentication != null) { deleteGoogleAccount(retrievedAuthentication.getThirdPartyOut()).RunSynchronously(); } else if (myCredential.Token != null) { thirdpartydata.Email = Email; thirdpartydata.TilerID = UserID; thirdpartydata.ID = myCredential.UserId; thirdpartydata.isLongLived = false; double totalSeconds = myCredential.Token.ExpiresInSeconds == null ? 0 : (double)myCredential.Token.ExpiresInSeconds; DateTime myDate = myCredential.Token.IssuedUtc.AddSeconds(totalSeconds); thirdpartydata.Deadline = new DateTimeOffset(myDate); thirdpartydata.ProviderID = TilerElements.ThirdPartyControl.CalendarTool.google.ToString(); thirdpartydata.Token = myCredential.Token.AccessToken; thirdpartydata.RefreshToken = myCredential.Token.RefreshToken; await thirdpartydata.unCommitAuthentication().ConfigureAwait(false); return(await ImportGoogle(cancellationToken).ConfigureAwait(false)); } } return(RedirectToAction("ImportCalendar")); } } else { //return View(); return(new RedirectResult(result.RedirectUri)); } }