Beispiel #1
0
        public async Task <VkNet.VkApi> GetGroupVkApi(long idGroup)
        {
            if (GroupsVkApis.ContainsKey(idGroup))
            {
                return(GroupsVkApis[idGroup]);
            }

            var groupAccessToken = await _context.Groups
                                   .Where(x => x.IdVk == idGroup)
                                   .Select(x => x.AccessToken)
                                   .FirstOrDefaultAsync();

            if (string.IsNullOrWhiteSpace(groupAccessToken))
            {
                return(null);
            }

            var groupVkApi = new VkNet.VkApi();
            await groupVkApi.AuthorizeAsync(new VkNet.Model.ApiAuthParams()
            {
                AccessToken   = groupAccessToken,
                ApplicationId = _configuration.GetValue <ulong>("VkApplicationId"),
                Settings      = VkNet.Enums.Filters.Settings.All
            });

            GroupsVkApis.TryAdd(idGroup, groupVkApi);

            return(groupVkApi);
        }
Beispiel #2
0
        public async Task <VkNet.VkApi> GetUserVkApi(long idVkUser)
        {
            if (UsersVkApis.ContainsKey(idVkUser))
            {
                return(UsersVkApis[idVkUser]);
            }

            var idUser = await _context.Users
                         .Where(x => x.IdVk == idVkUser)
                         .Select(x => x.Id)
                         .FirstOrDefaultAsync();

            var userAccessToken = await _context.UserTokens
                                  .Where(x => x.LoginProvider == "Vkontakte")
                                  .Where(x => x.UserId == idUser)
                                  .Where(x => x.Name == "access_token")
                                  .Select(x => x.Value)
                                  .FirstOrDefaultAsync();

            if (string.IsNullOrWhiteSpace(userAccessToken))
            {
                return(null);
            }

            var userVkApi = new VkNet.VkApi();

            try
            {
                await userVkApi.AuthorizeAsync(new VkNet.Model.ApiAuthParams()
                {
                    AccessToken   = userAccessToken,
                    ApplicationId = _configuration.GetValue <ulong>("VkApplicationId"),
                    Settings      = VkNet.Enums.Filters.Settings.All
                });
            }
            catch { }
            UsersVkApis.TryAdd(idVkUser, userVkApi);

            return(userVkApi);
        }
Beispiel #3
0
        private void TwoFactorAuth()
        {
            var api = new VkNet.VkApi();

            if (twoAuthorize == false)
            {
                var Awaiter = api.AuthorizeAsync(new VkNet.Model.ApiAuthParams()
                {
                    Password               = PasswordTextbox.Text,
                    Login                  = LoginTextBox.Text,
                    TwoFactorSupported     = true,
                    ApplicationId          = 6121396,
                    Settings               = Settings.Audio | Settings.Friends | Settings.Offline,
                    TwoFactorAuthorization = () =>
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            ShowTwoAuthComponents();
                        });
                        string code = "";
                        try
                        {
                            twoAuthorize = true;
                            while (codeSended != true)
                            {
                                Thread.Sleep(1000);
                            }
                            this.Dispatcher.Invoke(() =>
                            {
                                codeSended = false;
                                code       = TwoFactorCodeTextBox.Text;
                                TwoFactorCodeTextBox.Text = "";
                            });
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                        return(code);
                    }
                }).GetAwaiter();
                Awaiter.OnCompleted(() =>
                {
                    try
                    {
                        Awaiter.GetResult();
                        if (api.IsAuthorized == true)
                        {
                            SaveAuthData(api);
                            ShowActiveAccounts();
                            showAccountList();
                        }
                    }
                    catch (VkNet.Exception.VkAuthorizationException ex)
                    {
                        this.PreviewErrorBorder            = LoginBorder;
                        this.PreviewErrorBorder.Visibility = Visibility.Collapsed;
                        this.AuthErrorBorder.Visibility    = Visibility.Visible;


                        this.AuthErrorTextRun.Text = ex.Message;


                        Debug.WriteLine(ex.StackTrace);
                    }
                    catch (VkNet.Exception.UserAuthorizationFailException ex)
                    {
                        this.PreviewErrorBorder = LoginBorder;

                        this.AuthErrorBorder.Visibility = Visibility.Visible;

                        this.AuthErrorCodeTextRun.Text = "Код:" + ex.ErrorCode;
                        this.AuthErrorTextRun.Text     = ex.Message;


                        Debug.WriteLine(ex.StackTrace);
                    }
                });
            }
            else
            {
                codeSended = true;
            }
        }
Beispiel #4
0
        private async Task <bool> GetVkontakteApiAsync()
        {
            bool result = false;

            if (!string.IsNullOrEmpty(UserAccessFlowApiKey) && !string.IsNullOrEmpty(ServiceApiKey))
            {
                var userApi = new VkNet.VkApi();

                try
                {
                    await userApi.AuthorizeAsync(new ApiAuthParams
                    {
                        AccessToken = UserAccessFlowApiKey,
                        Settings    = Settings.All | Settings.Offline
                    });
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error authorizing vkontakte api via user access flow key: " + e);
                }

                if (userApi.IsAuthorized)
                {
                    UserApi = userApi;
                    UserApi.SetLanguage(Language.Ru);
                }

                var serviceApi = new VkNet.VkApi();

                try
                {
                    await serviceApi.AuthorizeAsync(new ApiAuthParams
                    {
                        AccessToken   = ServiceApiKey,
                        ApplicationId = AppId,
                        Settings      = Settings.All | Settings.Offline
                    });
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error authorizing vkontakte api via service key: " + e);
                }

                if (serviceApi.IsAuthorized)
                {
                    ServiceApi = serviceApi;
                    ServiceApi.SetLanguage(Language.Ru);
                }

                if (UserApi != null && ServiceApi != null)
                {
                    ApiVersion = userApi.VkApiVersion.Version;
                    result     = true;
                }
            }
            else
            {
                Console.WriteLine("Error connecting to Vkontakte: no access keys available.");
            }

            return(result);
        }
Beispiel #5
0
        public async Task <IActionResult> ConnectCallback(string code)
        {
            string url = $"https://oauth.vk.com/access_token?" +
                         $"client_id={_configuration.GetValue<long>("VkApplicationId")}" +
                         $"&client_secret={_configuration.GetValue<string>("VkApplicationPassword")}" +
                         $"&redirect_uri={$"{_configuration.GetValue<string>("SiteUrl")}/Groups/ConnectCallback"}" +
                         $"&code={code}";

            string result = null;

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(url, null);

                result = await response.Content.ReadAsStringAsync();

                Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(result);
                //TODO: Добавить проверку на null у token
                var    token      = obj.Properties().FirstOrDefault(x => x.Name.StartsWith("access_token_"));
                var    idGroup    = long.Parse(token.Name.Split('_').Last());
                string tokenValue = token.Value.ToString();

                var group = await _context.Groups.Where(x => x.IdVk == idGroup).FirstOrDefaultAsync();

                if (group == null)
                {
                    group = new Groups()
                    {
                        IdVk = idGroup
                    };
                    await _context.Groups.AddAsync(group);
                }

                group.AccessToken = tokenValue;

                using (var vkGroupApi = new VkNet.VkApi())
                {
                    await vkGroupApi.AuthorizeAsync(new VkNet.Model.ApiAuthParams()
                    {
                        AccessToken = tokenValue,
                        Settings    = VkNet.Enums.Filters.Settings.Groups
                    });

                    group.CallbackConfirmationCode = await vkGroupApi.Groups.GetCallbackConfirmationCodeAsync((ulong)idGroup);

                    var groups = await vkGroupApi.Groups.GetByIdAsync(null, idGroup.ToString(), VkNet.Enums.Filters.GroupsFields.Description);

                    var groupInfo = groups.FirstOrDefault();

                    group.Name  = groupInfo.Name;
                    group.Photo = groupInfo.Photo50.ToString();
                }
                await _context.SaveChangesAsync();

                var idUser = _userHelperService.GetUserId(User);

                var groupAdmin = await _context.GroupAdmins.Where(x => x.IdUser == idUser && x.IdGroup == idGroup).FirstOrDefaultAsync();

                if (groupAdmin == null)
                {
                    groupAdmin = new GroupAdmins()
                    {
                        IdGroup   = idGroup,
                        IdUser    = idUser,
                        DtConnect = DateTime.UtcNow
                    };
                    await _context.GroupAdmins.AddAsync(groupAdmin);
                }
                else
                {
                    groupAdmin.DtConnect = DateTime.UtcNow;
                }
                await _context.SaveChangesAsync();

                url = $"https://api.vk.com/method/groups.getCallbackServers?" +
                      $"access_token={tokenValue}" +
                      $"&group_id={idGroup}" +
                      $"&v={AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion}";

                response = await client.PostAsync(url, null);

                result = await response.Content.ReadAsStringAsync();

                var callbackServers = new VkResponse(result).ToVkCollectionOf <VkNet.Model.CallbackServerItem>(x => x);

                long idServer           = -1;
                var  callbackServerUrl  = _configuration.GetValue <string>("CallbackServerUrl");
                var  callbackServerInfo = callbackServers.FirstOrDefault(x => x.Url == callbackServerUrl);
                if (callbackServerInfo == null)
                {
                    url = $"https://api.vk.com/method/groups.addCallbackServer?" +
                          $"access_token={tokenValue}" +
                          $"&group_id={idGroup}" +
                          $"&url={_configuration.GetValue<string>("SiteUrl")}{callbackServerUrl}" +
                          $"&title={_configuration.GetValue<string>("CallbackServerName")}" +
                          $"&v={AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion}";
                    response = await client.PostAsync(url, null);

                    result = await response.Content.ReadAsStringAsync();

                    var json = Newtonsoft.Json.Linq.JObject.Parse(result);
                    idServer = new VkResponse(json[propertyName: "response"])
                    {
                        RawJson = result
                    }[key: "server_id"];
                }
                else
                {
                    idServer = callbackServerInfo.Id;
                }

                var callbackProperties = new VkNet.Model.CallbackSettings();
                foreach (var property in callbackProperties.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
                {
                    property.SetValue(callbackProperties, true);
                }
                var parameters = VkNet.Model.RequestParams.CallbackServerParams.ToVkParameters(new VkNet.Model.RequestParams.CallbackServerParams()
                {
                    GroupId          = (ulong)idGroup,
                    ServerId         = idServer,
                    CallbackSettings = callbackProperties
                });
                parameters.Add("access_token", tokenValue);
                parameters.Add("v", AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion);
                url = "https://api.vk.com/method/groups.setCallbackSettings";

                HttpContent content = new FormUrlEncodedContent(parameters);
                response = await client.PostAsync(url, content);

                result = await response.Content.ReadAsStringAsync();
            }
            return(RedirectToAction(nameof(IndexConnected), "Groups"));
        }