protected override UserInfo ParseUserInfo(string content) {
            try {
                var cnt = JObject.Parse(content);
                var names = (cnt["name"].SafeGet(x => x.Value<string>()) ?? string.Empty).Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
                const string avatarUriTemplate = "{0}&s={1}";
                var avatarUri = cnt["avatar_url"].Value<string>();
                var result = new UserInfo {
                    Email = cnt["email"].SafeGet(x => x.Value<string>()),
                    ProviderName = this.Name,
                    Id = cnt["id"].Value<string>(),
                    FirstName = names.Count > 0 ? names.First() : cnt["login"].Value<string>(),
                    LastName = names.Count > 1 ? names.Last() : string.Empty,
                    AvatarUri = {
                        Small = !string.IsNullOrWhiteSpace(avatarUri) ? string.Format(avatarUriTemplate, avatarUri, 36) : string.Empty,
                        Normal = avatarUri,
                        Large = !string.IsNullOrWhiteSpace(avatarUri) ? string.Format(avatarUriTemplate, avatarUri, 300) : string.Empty
                    }
                };

                return result;
            } catch (Exception ex) {
                Log.Error().Exception(ex).Critical().Tag("GitHub").Property("Content", content).Write();
                throw;
            }
        }
        public void Login(IOAuthProvider provider)
        {
            var userInfo = new UserInfo();

            // Is the access token already set? (i.e. Remember me next time)
            if (!string.IsNullOrWhiteSpace (provider.AccessToken))
            {
                try
                {
                    // Get the user information from the OAuth provider.
                    userInfo = provider.VerifyTokenAndGetUserInfo ();
                }
                catch(UnexpectedResponseException ex)
                {
                    logger.Warn ("An unexpected exception occurred looking up the user's information", ex);
                }

                // If the token is invalid, the userinfo will be
                //  non-null, but the Id will be null
                if (userInfo.Id == null)
                {
                    // Run through the authorize procedure
                    PerformProviderAuthorization (provider);
                }
                else
                {
                    // Look up the user's TempusGameIt information
                    GetTempusGameItUserInfo (provider.LoginUri, userInfo);
                }
            }
            else
            {
                PerformProviderAuthorization (provider);
            }
        }
예제 #3
0
        /// <summary>
        /// Should return parsed <see cref="UserInfo"/> from content received from third-party service.
        /// </summary>
        /// <param name="content">The content which is received from third-party service.</param>
        protected override UserInfo ParseUserInfo(string content)
        {
            var cnt = JObject.Parse(content);
            var names = (cnt["name"].SafeGet(x => x.Value<string>()) ?? string.Empty).Split(new []{ " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
            const string avatarUriTemplate = "{0}&s={1}";
            var avatarUri = cnt["avatar_url"].Value<string>();
            var result = new UserInfo
                {
                    Email = cnt["email"].SafeGet(x => x.Value<string>()),
                    ProviderName = this.Name,
                    Id = cnt["id"].Value<string>(),
                    FirstName = names.Count > 0 ? names.First() : cnt["login"].Value<string>(),
                    LastName = names.Count > 1 ? names.Last() : string.Empty,
                    AvatarUri =
                        {
                            Small = !string.IsNullOrWhiteSpace(avatarUri) ? string.Format(avatarUriTemplate, avatarUri, AvatarInfo.SmallSize) : string.Empty,
                            Normal = avatarUri,
                            Large = !string.IsNullOrWhiteSpace(avatarUri) ? string.Format(avatarUriTemplate, avatarUri, AvatarInfo.LargeSize) : string.Empty
                        }
                };

            return result;
        }
예제 #4
0
파일: BNCClient.cs 프로젝트: jjaffe/OAuth2
 /// <summary>
 /// Should return parsed <see cref="UserInfo"/> from content received from third-party service.
 /// </summary>
 /// <param name="content">The content which is received from third-party service.</param>
 protected override UserInfo ParseUserInfo(string content)
 {
     var cnt = JObject.Parse(content);
     //var names = cnt["name"].Value<string>().Split(' ').ToList();
     //const string avatarUriTemplate = "{0}&s={1}";
     //var avatarUri = cnt["avatar_url"].Value<string>();
     JArray roles = cnt["roles"].SafeGet(x => x.Value<JArray>());
     var result = new UserInfo
         {
             Email = cnt["email"].SafeGet(x => x.Value<string>()),
             VerifiedEmail = cnt["verifiedEmailAddress"].SafeGet(x => x.Value<bool>()),
             //ProviderName = this.Name,
             Id = cnt["userId"].SafeGet(x => x.Value<string>()),
             FirstName = cnt["firstName"].SafeGet(x => x.Value<string>()),
             LastName = cnt["lastName"].SafeGet(x => x.Value<string>()),
             userName = cnt["username"].SafeGet(x => x.Value<string>()),
             Roles = roles.Select(r => r.ToString()).ToArray()
             //AvatarUri =
             //    {
             //        Small = !string.IsNullOrWhiteSpace(avatarUri) ? string.Format(avatarUriTemplate, avatarUri, AvatarInfo.SmallSize) : string.Empty,
             //        Normal = avatarUri,
             //        Large = !string.IsNullOrWhiteSpace(avatarUri) ? string.Format(avatarUriTemplate, avatarUri, AvatarInfo.LargeSize) : string.Empty
             //    }
         };
     return result;
 }
예제 #5
0
        public UserInfo VerifyTokenAndGetUserInfo(string token)
        {
            var request = new RestRequest ("/v2.5/me", Method.GET);
            request.AddQueryParameter ("fields", "name,picture,email");
            request.AddQueryParameter ("access_token", token);

            var response = _restClient.Execute<FacebookUserInfoResponse> (request);

            var userInfo = new UserInfo();

            if (response.StatusCode == HttpStatusCode.OK && response.Data != null)
            {
                userInfo.Id = response.Data.id;
            }

            return userInfo;
        }
예제 #6
0
        /// <summary>
        /// Should return parsed <see cref="UserInfo"/> from content received from third-party service.
        /// </summary>
        /// <param name="content">The content which is received from third-party service.</param>
        protected override UserInfo ParseUserInfo(string content)
        {
            var response = JObject.Parse(content);
            var userInfo = new UserInfo();
            JToken firstName, lastName, email, picture;
            if (response.TryGetValue("first_name", StringComparison.OrdinalIgnoreCase, out firstName))
            {
                userInfo.FirstName = firstName.ToString();
            }

            if (response.TryGetValue("last_name", StringComparison.OrdinalIgnoreCase, out lastName))
            {
                userInfo.LastName = lastName.ToString();
            }

            if (response.TryGetValue("email", StringComparison.OrdinalIgnoreCase, out email))
            {
                userInfo.Email = email.ToString();
            }

            if (response.TryGetValue("picture", StringComparison.OrdinalIgnoreCase, out picture))
            {
                var pictureUri = picture.ToString();
                userInfo.AvatarUri.Small = pictureUri;
                userInfo.AvatarUri.Normal = pictureUri;
                userInfo.AvatarUri.Large = pictureUri;
            }

            return userInfo;
        }
예제 #7
0
        private User AddExternalLogin(UserInfo userInfo) {
            ExceptionlessClient.Default.CreateFeatureUsage("External Login").AddObject(userInfo).Submit();
            User existingUser = _userRepository.GetUserByOAuthProvider(userInfo.ProviderName, userInfo.Id);

            // Link user accounts.
            if (ExceptionlessUser != null) {
                if (existingUser != null) {
                    if (existingUser.Id != ExceptionlessUser.Id) {
                        // Existing user account is not the current user. Remove it and we'll add it to the current user below.
                        if (!existingUser.RemoveOAuthAccount(userInfo.ProviderName, userInfo.Id))
                            return null;

                        _userRepository.Save(existingUser);
                    } else {
                        // User is already logged in.
                        return ExceptionlessUser;
                    }
                }

                // Add it to the current user if it doesn't already exist and save it.
                ExceptionlessUser.AddOAuthAccount(userInfo.ProviderName, userInfo.Id, userInfo.Email);
                _userRepository.Save(ExceptionlessUser);
                return ExceptionlessUser;
            }

            // Create a new user account or return an existing one.
            if (existingUser != null) {
                if (!existingUser.IsEmailAddressVerified) {
                    existingUser.IsEmailAddressVerified = true;
                    _userRepository.Save(existingUser);
                }

                return existingUser;
            }

            // Check to see if a user already exists with this email address.
            User user = !String.IsNullOrEmpty(userInfo.Email) ? _userRepository.GetByEmailAddress(userInfo.Email) : null;
            if (user == null) {
                user = new User { FullName = userInfo.GetFullName(), EmailAddress = userInfo.Email };
                AddGlobalAdminRoleIfFirstUser(user);
            }
            
            user.IsEmailAddressVerified = true;
            user.AddOAuthAccount(userInfo.ProviderName, userInfo.Id, userInfo.Email);
            return _userRepository.Save(user);
        }
예제 #8
0
        /// <inheritdoc cref="OAuthClient.ParseUserInfo" />
        protected override UserInfo ParseUserInfo(string content)
        {
            var users = JsonConvert.DeserializeObject<UserContainer>(content);
            var userInfo = new UserInfo();

            if (users != null && users.Users != null && users.Users.Count > 0)
            {
                userInfo.Id = users.Users[0].Id;
                userInfo.FirstName = users.Users[0].FirstName;
                userInfo.LastName = users.Users[0].LastName;
                userInfo.Email = users.Users[0].Email;
                if (users.Users[0].PhotoUrls != null)
                {
                    userInfo.AvatarUri.Small = users.Users[0].PhotoUrls.Small;
                    userInfo.AvatarUri.Normal = users.Users[0].PhotoUrls.Normal;
                    userInfo.AvatarUri.Large = users.Users[0].PhotoUrls.Large;
                }
            }

            return userInfo;
        }
        void GetTempusGameItUserInfo(string loginUri, UserInfo userInfo)
        {
            var request = new RestRequest(Method.POST)
            {
                Resource = loginUri,
                RequestFormat = DataFormat.Json
            };

            request.AddParameter("application/json", string.Format("{{\"id\" : \"{0}\"}}", userInfo.Id),
                                 ParameterType.RequestBody);

            var client = new TempusGameItRestClient();

            var response = client.Execute<AccessToken>(request);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new AuthenticationException (response.Data == null ? "An unexpected error occurred logging in" : response.Data.message);
            }
            else
            {
                _token = response.Data.token;

                var userRequest = new RestRequest (string.Format ("/api/users/{0}", response.Data.username), Method.GET);

                _user = client.Execute<User>(userRequest).Data;
            }
        }
예제 #10
0
        private void SetUserInfo()
        {
            try
            {
                if (Request.Cookies["auth"] != null)
                {
                    UserInfo = new UserInfo
                    {
                        Email = Request.Cookies["auth"].Value
                    };
                    return;
                }

                var nameValueCollection = new NameValueCollection();

                if (Request.QueryString["code"] != null)
                {
                    nameValueCollection = Request.QueryString;
                    Logger.Trace($"nameValueCollection заполняем из Request.QueryString[code].");
                }
                else
                {
                    var authCodeCookie = Request.Cookies["auth_code"];
                    if (authCodeCookie != null)
                    {
                        Logger.Trace($"Устанавливаем code: {authCodeCookie.Value}.");
                        nameValueCollection.Add("code", authCodeCookie.Value);
                    }
                }

                Logger.Trace($"nameValueCollection: {nameValueCollection}.");
                var client = GetClient();
                Logger.Trace($"Cервис авторизации: {client}. ProviderName:{ProviderName}.");

                var userInfo = client?.GetUserInfo(nameValueCollection);
                if (userInfo != null)
                {
                    Logger.Trace($"Cервис авторизации: {client.Name}. Пользователь: {userInfo.Email}.");
                    UserInfo = userInfo;
                }
                else
                {
                    Logger.Trace("Не удалось получить пользователя.");
                    UserInfo = new UserInfo();
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }
        }
예제 #11
0
        /// <summary>
        /// Should return parsed <see cref="UserInfo"/> from content received from third-party service.
        /// </summary>
        /// <param name="content">The content which is received from third-party service.</param>
        protected override UserInfo ParseUserInfo(string content)
        {
            var response = JObject.Parse(content);
            var userInfo = new UserInfo();
            userInfo.AvatarUri.Normal =
                userInfo.AvatarUri.Large =
                userInfo.AvatarUri.Small = response.SelectToken("profile.image.imageUrl")?.ToString();

            userInfo.FirstName = response.SelectToken("profile.givenName")?.ToString();
            userInfo.LastName = response.SelectToken("profile.familyName")?.ToString();
            userInfo.Id = this._userProfileGUID;
            userInfo.Email = response.SelectToken("emails")?.ToString();
            userInfo.ProviderName = this.Name;
            return userInfo;
        }
예제 #12
0
        /// <summary>
        /// Should return parsed <see cref="UserInfo"/> from content received from third-party service.
        /// </summary>
        /// <param name="content">The content which is received from third-party service.</param>
        protected override UserInfo ParseUserInfo(string content)
        {
            var response = JObject.Parse(content);
            var userInfo = new UserInfo();
            userInfo.AvatarUri.Normal =
                userInfo.AvatarUri.Large =
                userInfo.AvatarUri.Small = response.SelectToken("images[0].url")?.ToString();

            userInfo.FirstName = response.SelectToken("display_name")?.ToString();
            userInfo.Id = response.SelectToken("id")?.ToString();
            userInfo.Email = response.SelectToken("email")?.ToString();
            userInfo.ProviderName = this.Name;
            return userInfo;
        }