Пример #1
0
 public bool UpdateLinkedInAccessToken(LinkedInAccessToken token)
 {
     try
     {
         _linkedInAccessTokenRepository.Update(token);
         return(true);
     } catch (Exception)
     {
         return(false);
     }
 }
Пример #2
0
 public bool CheckForExpiredLinkedInAccessToken(LinkedInAccessToken token)
 {
     if (token.TokenCreation.AddDays(60).CompareTo(DateTime.Now.ToUniversalTime()) <= 0 || token.Expired == true)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #3
0
 public bool InsertLinkedInAccessToken(LinkedInAccessToken token)
 {
     try
     {
         _linkedInAccessTokenRepository.Insert(token);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Пример #4
0
        /// <summary>
        /// 取得LinkedIn 使用者profile
        /// </summary>
        /// <param name="lineAccessToken">AccessToken</param>
        /// <returns></returns>
        public async Task <LinkedInUserProfile> GetProfile(LinkedInAccessToken linkedInAccessToken)
        {
            try {
                Client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", linkedInAccessToken.access_token);

                var req = await Client.GetAsync($"https://api.linkedin.com/v2/me");

                var data = await req.Content.ReadAsStringAsync();

                var resData = JsonSerializer.Deserialize <LinkedInUserProfile> (data);
                return(resData);
            } catch (Exception e) {
                throw e;
            }
        }
Пример #5
0
        /// <summary>
        /// Logic for sharing a post on LinkedIn
        /// </summary>
        /// <param name="linkedInAccessToken">
        /// LinkedIn access token object containing the value of the token itself
        /// </param>
        /// <param name="linkedInPostDTO">
        /// Information about the post that will be submitted
        /// </param>
        /// <returns>
        /// One of the following will be returned:
        /// - Success: (LinkedIn accepted the post request)
        ///     An object containing the response from LinkedIn
        /// - Failure:
        ///     null if the request was rejected
        /// </returns>
        /// <remarks>Author: Luis Guillermo Pedroza-Soto</remarks>
        public Object SharePost(LinkedInAccessToken linkedInAccessToken, LinkedInPostDTO linkedInPostDTO)
        {
            var requestUrl = _defaultAccessGateway + "people/~/shares?format=json";
            var webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);

            webRequest.Method      = "POST";
            webRequest.ContentType = "application/json";
            webRequest.Host        = "api.linkedin.com";
            webRequest.KeepAlive   = true;

            //Build Headers.
            var requestHeaders = new NameValueCollection
            {
                { "x-li-format", "json" },
                { "Authorization", "Bearer " + linkedInAccessToken.Value }, //It is important "Bearer " is included with the access token here.
            };

            webRequest.Headers.Add(requestHeaders);

            //Build JSON request.
            var jsonMsg = new
            {
                comment = linkedInPostDTO.Comment,
                content = new Dictionary <string, string>
                {
                    { "title", linkedInPostDTO.Title },
                    { "description", linkedInPostDTO.Description },
                    { "submitted-url", linkedInPostDTO.SubmittedUrl },
                    { "submitted-image-url", "https://media-exp2.licdn.com/media/AAMABABqAAIAAQAAAAAAAA7yAAAAJGU1OTQ2NGFlLTNjNzEtNGZjOS04NjVkLWIxNjQ4NTY5ZjNlYw.png" }
                },
                visibility = new
                {
                    code = linkedInPostDTO.Code
                }
            };

            var requestJson = new JavaScriptSerializer().Serialize(jsonMsg);

            using (var s = webRequest.GetRequestStream())
            {
                var sw = new StreamWriter(s);
                sw.Write(requestJson);
                sw.Flush();
                sw.Close();
            }

            try
            {
                // Submit request for post submission
                using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    var responseStream = webResponse.GetResponseStream();
                    // Response was not the one expected
                    if (responseStream == null || webResponse.StatusCode != HttpStatusCode.Created)
                    {
                        return(new StatusCodeResult(webResponse.StatusCode, new HttpRequestMessage()));
                    }

                    using (var reader = new StreamReader(responseStream))
                    {
                        var response  = reader.ReadToEnd();
                        var json      = JObject.Parse(response);
                        var updateKey = json.Value <string>("updateKey");
                        var updateUrl = json.Value <string>("updateUrl");
                        // A successful post means the stored token is no longer valid
                        // Thus invalidate it
                        _linkedinLogic.InvalidateLinkedInAccessToken(linkedInAccessToken);

                        return(new { UpdateKey = updateKey, UpdateUrl = updateUrl });
                    }
                }
            }
            // LinkedIn rejected our request
            catch (Exception)
            {
                return(null);
            }
        }
        public IHttpActionResult ExternalLoginCallback(string code, string state)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            string username  = "";
            string returnURI = "";

            // For future user when we integrate with other oauth2 applications
            if (ProviderName == null || ProviderName == "")
            {
                var    nvs        = Request.GetQueryNameValuePairs();
                string stateParam = nvs.LastOrDefault(d => d.Key == "state").Value;
                if (state != null)
                {
                    // We need some variables from our state parameter.
                    NameValueCollection provideritem = HttpUtility.ParseQueryString(stateParam);
                    if (provideritem["__provider__"] != null)
                    {
                        ProviderName = provideritem["__provider__"];
                    }

                    if (provideritem["username"] != null)
                    {
                        username = provideritem["username"];
                        // Check to make sure username exists in database.
                        if (!_accountRepository.Exists(d => d.UserName == username))
                        {
                            return(Unauthorized());
                        }
                    }
                    // No username was provided.
                    else
                    {
                        return(Unauthorized());
                    }

                    if (provideritem["returnURI"] != null)
                    {
                        returnURI = provideritem["returnURI"];
                    }
                }
                else
                {
                    return(BadRequest());
                }
            }
            else
            {
                var    nvs        = Request.GetQueryNameValuePairs();
                string stateParam = nvs.LastOrDefault(d => d.Key == "state").Value;
                if (state != null)
                {
                    // We need some variables from our state parameter.
                    NameValueCollection provideritem = HttpUtility.ParseQueryString(stateParam);

                    if (provideritem["username"] != null)
                    {
                        username = provideritem["username"];
                        // Check to make sure username exists in database.
                        if (!_accountRepository.Exists(d => d.UserName == username))
                        {
                            return(Unauthorized());
                        }
                    }
                    // No username was provided.
                    else
                    {
                        return(Unauthorized());
                    }

                    if (provideritem["returnURI"] != null)
                    {
                        returnURI = provideritem["returnURI"];
                    }
                }
                else
                {
                    return(BadRequest());
                }
            }

            // Rewrite the request to include the requested headers and info for exchanging
            // the authorization code for a LinkedIn access token
            LinkedInOAuth2Client.RewriteRequest();

            // Now that the request has been rewritten, make the call and include the same callback uri provided earlier
            var authResult = OpenAuth.VerifyAuthentication(_externalCallBack);

            // For future user when we integrate with other oauth2 applications
            string providerDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

            //If the verification process failed
            if (!authResult.IsSuccessful)
            {
                return(Unauthorized());
            }
            else
            {
                //Get provider user details
                string providerUserId   = authResult.ProviderUserId;
                string providerUserName = authResult.UserName;
                string firstName        = null;
                string lastName         = null;
                string accessToken      = null;
                string email            = null;

                if (email == null && authResult.ExtraData.ContainsKey("email-address"))
                {
                    email = authResult.ExtraData["email-address"];
                }
                if (firstName == null && authResult.ExtraData.ContainsKey("first-name"))
                {
                    firstName = authResult.ExtraData["first-name"];
                }
                if (lastName == null && authResult.ExtraData.ContainsKey("last-name"))
                {
                    lastName = authResult.ExtraData["last-name"];
                }
                if (accessToken == null && authResult.ExtraData.ContainsKey("accesstoken"))
                {
                    accessToken = authResult.ExtraData["accesstoken"];
                }
                var userInfo = new List <object>();
                userInfo.Add(new
                {
                    ProviderDisplayName = providerDisplayName,
                    ProviderUserId      = providerUserId,
                    FirstName           = firstName,
                    LastName            = lastName,
                    Email       = email,
                    AccessToken = accessToken
                });

                try
                {
                    // If the given user already has a LinkedIn access token
                    if (_linkedInAccessTokenRepository.Exists(d => d.UserName == username, d => d.Account))
                    {
                        LinkedInAccessToken token = _linkedInAccessTokenRepository.GetSingle(d => d.UserName == username, d => d.Account);
                        token.Expired       = false;
                        token.TokenCreation = DateTime.UtcNow;
                        token.Value         = accessToken;
                        _linkedInAccessTokenRepository.Update(token);
                    }
                    else
                    {
                        LinkedInAccessToken token = new LinkedInAccessToken()
                        {
                            UserName      = username,
                            TokenCreation = DateTime.UtcNow,
                            Value         = accessToken
                        };
                        _linkedInAccessTokenRepository.Insert(token);
                    }
                } catch (Exception)
                {
                    return(InternalServerError());
                }

                if (returnURI != "null")
                {
                    // Try the given redirectUri
                    try
                    {
                        return(Redirect(returnURI + "?linkedin=success"));
                    }
                    // If it fails, go with the default
                    catch (Exception)
                    {
                        return(Redirect("http://localhost:8080/Home?linkedin=success"));
                    }
                }

                return(Redirect("http://localhost:8080/Home?linkedin=success"));
            }
        }
Пример #7
0
 public bool InvalidateLinkedInAccessToken(LinkedInAccessToken token)
 {
     token.Expired = true;
     return(UpdateLinkedInAccessToken(token));
 }