private async Task <LinkedProfile> GetProfileInfo(string accessToken, string logFileName, bool writeLog) { LinkedProfile profile = null; string file = logFileName; try { Uri uri = new Uri("https://api.linkedin.com/v1/people/~?format=json"); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { profile = new LinkedProfile(); string content = await response.Content.ReadAsStringAsync(); profile = Newtonsoft.Json.JsonConvert.DeserializeObject <LinkedProfile>(content); } } } catch (Exception ex) { if (writeLog) { System.IO.File.AppendAllText(file, Environment.NewLine + System.DateTime.Now.ToString() + "| Exception during getting linkedin profile " + ex.ToString()); } } return(profile); }
public async Task <ActionResult> AuthCallBack(string code, string state) { string rootPath = ""; bool writeLog = false; if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null) { if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false) { rootPath = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString(); writeLog = true; } } string file = rootPath + System.DateTime.Now.ToString("yyyyMMddhhmm") + "LNK_AuthCallBack.txt"; _linkedInAuthClient = this._authenticationRepository.GetDbContext().LinkedInAuthClients.Where(_linked => _linked.Active).SingleOrDefault(); if (Session["LinkedInState"] != null) { if (writeLog) { System.IO.File.AppendAllText(file, System.DateTime.Now.ToString() + " Start Callback Linked Process..."); } string stateOriginal = Session["LinkedInState"].ToString(); if (stateOriginal == state) { LinkedInExternalAccessToken verifiedAccessToken = await VerifyExternalAccessToken(code, file, writeLog); if (verifiedAccessToken == null) { if (writeLog) { System.IO.File.AppendAllText(file, Environment.NewLine + System.DateTime.Now.ToString() + " Linked In External Access Token not found"); } return(Content("Error in validating response. Please close window and try again.")); } else { if (writeLog) { System.IO.File.AppendAllText(file, Environment.NewLine + System.DateTime.Now.ToString() + " start to read profile from linkedin..."); } } if (verifiedAccessToken != null) { LinkedProfile profileInfo = await GetProfileInfo(verifiedAccessToken.access_token, file, writeLog); if (profileInfo != null) { User user = await this._authenticationRepository.FindAsync(new UserLoginInfo("linkedin", profileInfo.id)); bool hasRegistered = user != null; if (hasRegistered == false) { if (writeLog) { System.IO.File.AppendAllText(file, System.Environment.NewLine + System.DateTime.Now.ToString() + " local account is NOT FOUND for given linked in provider key..."); } } else { if (writeLog) { System.IO.File.AppendAllText(file, System.Environment.NewLine + System.DateTime.Now.ToString() + " local account FOUND for given linked in provider key..."); } } ViewBag.Result = true; ViewBag.ErrorMessage = ""; ViewBag.haslocalaccount = hasRegistered.ToString(); ViewBag.Id = profileInfo.id; ViewBag.Token = verifiedAccessToken.access_token; return(View()); } } } else { ViewBag.Result = false; ViewBag.ErrorMessage = "Invalid state for linkedin response. Please close window and try again to login."; return(View()); } } ViewBag.Result = false; ViewBag.ErrorMessage = "Error during validating response. Please close window and try again to login."; return(View()); }
public async Task <IHttpActionResult> ObtainLocalAccessToken(string provider, string externalAccessToken) { string path = ""; bool writeLog = false; if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null) { if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false) { path = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString(); writeLog = true; } } if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " start of ObtainLocalAccessToken"); } if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(externalAccessToken)) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " ObtainLocalAccessToken : Provider or external access token is not sent"); } return(BadRequest("Provider or external access token is not sent")); } string providerId = string.Empty; if (provider.ToLower() == "google") { ParsedExternalAccessToken verifyGoogleAccessToken = await VerifyGoogleExternalAccessToken(externalAccessToken); if (verifyGoogleAccessToken == null) { return(BadRequest("Invalid Provider or External Access Token")); } providerId = verifyGoogleAccessToken.user_id; } if (provider.ToLower() == "facebook") { var fb = new Facebook.FacebookClient(); fb.AccessToken = externalAccessToken; dynamic me = fb.Get("me?fields=first_name,last_name,id,email"); if (string.IsNullOrEmpty(me.email) == true) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " ObtainLocalAccessToken : email not setup in Facebook."); } return(BadRequest("Email is not setup or registered in Facebook.")); } providerId = me.id; } if (provider.ToLower() == "linkedin") { LinkedProfile profileInfo = await GetProfileInfo(externalAccessToken, path, writeLog); if (profileInfo == null) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "- 1 obtain access token Linkedin..profile into not found ... "); return(BadRequest("Invalid Provider or External Access Token")); } providerId = profileInfo.id; } User user = await this._authenticationRepository.FindAsync(new UserLoginInfo(provider, providerId)); bool hasRegistered = user != null; if (hasRegistered == false) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " ObtainLocalAccessToken : External user is not registered.."); } return(BadRequest("External user is not registered")); } if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " ObtainLocalAccessToken : start generating local access token.."); } JObject accessTokenResponse = this.GenerateLocalAccessTokenResponse(user); return(Ok(accessTokenResponse)); }
public async Task <IHttpActionResult> RegisterExternal(ExternalUserBinding model) { string path = ""; bool writeLog = false; if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null) { if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false) { path = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString(); writeLog = true; } } if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " called..RegisterExternal..."); } if (ModelState.IsValid == false) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " modelstate is invalid..."); } return(BadRequest(ModelState)); } if (model.Provider.ToLower() == "google") { ParsedExternalAccessToken googleVerifiedAccessToken = await VerifyGoogleExternalAccessToken(model.ExternalAccessToken); if (googleVerifiedAccessToken == null) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " google provider or external access token is not valid..."); } return(BadRequest("Invalid Provider or External Access Token")); } } var providerId = string.Empty; string email = string.Empty; string firstName = string.Empty; string lastName = string.Empty; if (model.Provider.ToLower() == "facebook") { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " provider is facebook checking to get client info..."); } FacebookClient facebookClient = new FacebookClient(model.ExternalAccessToken); dynamic facebookUserInfo = facebookClient.Get("/me?fields=email,first_name,last_name,id"); if (String.IsNullOrEmpty(facebookUserInfo.email) == true) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " email is not configured in fb so not proceed..."); } return(BadRequest("The user has not configured an email address in Facebook.")); } providerId = facebookUserInfo.id; email = facebookUserInfo.email; firstName = String.IsNullOrEmpty(facebookUserInfo.first_name) ? null : facebookUserInfo.first_name; lastName = String.IsNullOrEmpty(facebookUserInfo.last_name) ? null : facebookUserInfo.last_name; } if (model.Provider.ToLower() == "google") { GoogleUserOutputData userData = await GetGoogleUserInfo(model.ExternalAccessToken); if (userData != null) { providerId = userData.id; email = userData.email; firstName = userData.given_name; lastName = userData.family_name; } } if (model.Provider.ToLower() == "linkedin") { LinkedProfile profileInfo = await GetProfileInfo(model.ExternalAccessToken, path, writeLog); if (profileInfo != null) { providerId = profileInfo.id; firstName = profileInfo.firstName; lastName = profileInfo.lastName; email = model.UserName; } } if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " provider id is.." + providerId + " - " + model.Provider); } User user = await this._authenticationRepository.FindAsync(new UserLoginInfo(model.Provider, providerId)); bool hasRegistered = user != null; JObject accessTokenResponse = null; if (hasRegistered == true) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " has registered already...generate local access token..."); } accessTokenResponse = this.GenerateLocalAccessTokenResponse(user); return(Ok(accessTokenResponse)); } IdentityResult result; ExternalLoginInfo externalLoginInfo = new ExternalLoginInfo() { DefaultUserName = email, Login = new UserLoginInfo(model.Provider, providerId) }; if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " find by email... " + email + " - " + model.Provider); } user = this._authenticationRepository.FindUserByUserName(email); bool hasRegisteredLocally = user != null; if (hasRegisteredLocally == true) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " registered locaslly so... adding login ..." + email + "-" + model.Provider); } if (model.Provider.ToLower() == "linkedin") { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " email already exist error..." + email + "-" + model.Provider); } return(BadRequest("User already exist with given email address.")); } result = await this._authenticationRepository.AddLoginAsync(user.Id, externalLoginInfo.Login); if (!result.Succeeded) { return(this.GetErrorResult(result)); } if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " adding login222222 success 3333 so generating access token LOCAL....." + email); } accessTokenResponse = this.GenerateLocalAccessTokenResponse(user); return(Ok(accessTokenResponse)); } RegisterExternalUserDTO registerExternalUserDTO = new RegisterExternalUserDTO() { Email = email, FirstName = firstName, LastName = lastName }; if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " registered new external user..." + email); } result = await this._authenticationRepository.RegisterNewExternalUser(registerExternalUserDTO); if (!result.Succeeded) { return(this.GetErrorResult(result)); } if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " registered success so getting user again...by FindUserByUserName-" + email); } user = this._authenticationRepository.FindUserByUserName(email); result = await this._authenticationRepository.AddLoginAsync(user.Id, externalLoginInfo.Login); if (!result.Succeeded) { return(this.GetErrorResult(result)); } if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " generating..local access token user..." + email); } //generate access token response accessTokenResponse = this.GenerateLocalAccessTokenResponse(email); /* * string apiKey = SENDGRID_API_KEY; * SendGridClient sendGridClient = new SendGridClient(apiKey, "https://api.sendgrid.com"); * EmailAddress emailSender = new EmailAddress("*****@*****.**", "Carlito"); * String subject = "Welcome to Carlito."; * EmailAddress emailRecipient = new EmailAddress(user.Email); * Content content = new Content("text/html", "Hello world!"); * SendGridMessage mail = MailHelper.CreateSingleEmail(emailSender, emailRecipient, subject, "", ""); * * mail.TemplateId = "e69e88c0-facf-4512-9e23-d1214e4765a3"; * * dynamic response = sendGridClient.SendEmailAsync(mail); */ return(Ok(accessTokenResponse)); }