Пример #1
0
        private async Task HandleCommand(SocketMessage messageParam)
        {
            if (!(messageParam is SocketUserMessage message))
            {
                return;
            }

            if (SettingsManager.GetBool("config", "moduleIRC"))
            {
                var module = TickManager.GetModule <IRCModule>();
                module?.SendMessage(message.Channel.Id, message.Author.Id, message.Author.Username, message.Content);
            }

            if (SettingsManager.GetBool("config", "moduleTelegram"))
            {
                TickManager.GetModule <TelegramModule>()?.SendMessage(message.Channel.Id, message.Author.Id, message.Author.Username, message.Content);
            }

            int argPos = 0;

            if (!(message.HasCharPrefix(SettingsManager.Get("config", "botDiscordCommandPrefix")[0], ref argPos) || message.HasMentionPrefix
                      (Client.CurrentUser, ref argPos)))
            {
                return;
            }

            var context = new CommandContext(Client, message);

            await Commands.ExecuteAsync(context, argPos);
        }
Пример #2
0
        private async Task HandleCommand(SocketMessage messageParam)
        {
            await AsyncHelper.RedirectToThreadPool();

            if (!(messageParam is SocketUserMessage message))
            {
                return;
            }

            if (SettingsManager.Settings.Config.ModuleIRC)
            {
                var module = TickManager.GetModule <IRCModule>();
                module?.SendMessage(message.Channel.Id, message.Author.Id, message.Author.Username, message.Content);
            }


            if (SettingsManager.Settings.Config.ModuleTelegram)
            {
                var name = APIHelper.DiscordAPI.GetGuild().GetUser(message.Author.Id)?.Nickname ?? message.Author.Username;
                TickManager.GetModule <TelegramModule>()?.SendMessage(message.Channel.Id, message.Author.Id, name, message.Content);
            }

            int argPos = 0;

            if (!(message.HasCharPrefix(SettingsManager.Settings.Config.BotDiscordCommandPrefix[0], ref argPos) || message.HasMentionPrefix
                      (Client.CurrentUser, ref argPos)))
            {
                return;
            }

            var context = new CommandContext(Client, message);

            await Commands.ExecuteAsync(context, argPos, null);
        }
Пример #3
0
        public override async Task Run(object prm)
        {
            if (IsRunning)
            {
                return;
            }
            if (Settings.Config.ModuleAuthWeb && TickManager.GetModule <WebAuthModule>().IsEntityInitFailed)
            {
                return;
            }
            IsRunning = true;
            var manual = (bool?)prm ?? false;

            try
            {
                if (Settings.WebAuthModule.AuthCheckUnregisteredDiscordUsers)
                {
                    await CheckDiscordUsers(manual);
                }
                await CheckDBUsers(manual);
            }
            finally
            {
                IsRunning = false;
            }
        }
Пример #4
0
        public static bool HasWebAccess(long id, long corpId, long allianceId)
        {
            if (!SettingsManager.Settings.Config.ModuleTimers)
            {
                return(false);
            }
            var module = TickManager.GetModule <TimersModule>();

            return(module.GetAllCharacterIds().Contains(id) || module.GetAllCorporationIds().Contains(corpId) ||
                   module.GetAllAllianceIds().Contains(allianceId));
        }
Пример #5
0
        private async Task HandleCommand(SocketMessage messageParam)
        {
            await Task.Factory.StartNew(async() =>
            {
                if (!(messageParam is SocketUserMessage message))
                {
                    return;
                }
                if (!await Throttle())
                {
                    return;
                }

                try
                {
                    if (SettingsManager.Settings.Config.ModuleIRC)
                    {
                        var module = TickManager.GetModule <IRCModule>();
                        module?.SendMessage(message.Channel.Id, message.Author.Id, message.Author.Username,
                                            message.Content);
                    }

                    if (SettingsManager.Settings.Config.ModuleTelegram)
                    {
                        var name = GetGuildByChannel(messageParam.Channel.Id).GetUser(message.Author.Id)?.Nickname ??
                                   message.Author.Username;
                        TickManager.GetModule <TelegramModule>()
                        ?.SendMessage(message.Channel.Id, message.Author.Id, name, message.Content);
                    }

                    var argPos = 0;

                    if (!(message.HasCharPrefix(SettingsManager.Settings.Config.BotDiscordCommandPrefix[0],
                                                ref argPos) ||
                          message.HasMentionPrefix
                              (Client.CurrentUser, ref argPos)))
                    {
                        return;
                    }

                    var context = new CommandContext(Client, message);
                    await Commands.ExecuteAsync(context, argPos, null);
                }
                catch (Exception ex)
                {
                    await LogHelper.LogEx(nameof(HandleCommand), ex, LogCat.Discord);
                }
            });
        }
        public async Task WebSaveSimplifiedAuth(List <SimplifiedAuthEntity> list)
        {
            //update Roles string
            list.ForEach(a => a.Roles = string.Join(',', a.RolesList));
            //save data
            await SettingsManager.SaveSimplifiedAuthData(list
                                                         .Select(a => $"{a.Name}|{a.Group}|{a.Roles}").ToList());

            //inject updated simplified auth data
            await SettingsManager.LoadSimplifiedAuth();

            //rebuild auth cache
            if (Settings.Config.ModuleAuthWeb)
            {
                await TickManager.GetModule <WebAuthModule>().Initialize();
            }
            await LogHelper.LogInfo("Simplified auth update completed!", Category);
        }
Пример #7
0
        private async Task <bool> OnAuthRequest(HttpListenerRequestEventArgs context)
        {
            if (!Settings.Config.ModuleWebConfigEditor)
            {
                return(false);
            }

            var request  = context.Request;
            var response = context.Response;

            if (request.HttpMethod != HttpMethod.Get.ToString())
            {
                return(false);
            }

            var extIp   = Settings.WebServerModule.WebExternalIP;
            var extPort = Settings.WebServerModule.WebExternalPort;

            try
            {
                RunningRequestCount++;
                if (request.Url.LocalPath == "/callback" || request.Url.LocalPath == $"{extPort}/callback")
                {
                    var clientID = Settings.WebServerModule.CcpAppClientId;
                    var secret   = Settings.WebServerModule.CcpAppSecret;
                    var prms     = request.Url.Query.TrimStart('?').Split('&');
                    if (prms.Length == 0 || prms[0].Split('=').Length == 0 || string.IsNullOrEmpty(prms[0]))
                    {
                        return(false);
                    }
                    var code  = prms[0].Split('=')[1];
                    var state = prms.Length > 1 ? prms[1].Split('=')[1] : null;
                    if (state != "settings")
                    {
                        return(false);
                    }
                    //have code
                    var result = await WebAuthModule.GetCharacterIdFromCode(code, clientID, secret);

                    var characterId = result == null ? 0 : Convert.ToInt64(result[0]);

                    if (characterId == 0)
                    {
                        await WebServerModule.WriteResponce(
                            WebServerModule.GetAccessDeniedPage("Web Config Editor", LM.Get("accessDenied"),
                                                                WebServerModule.GetWebSiteUrl()), response);

                        return(true);
                    }

                    var rChar = await APIHelper.ESIAPI.GetCharacterData(Reason, characterId, true);

                    if (rChar == null)
                    {
                        await response.RedirectAsync(new Uri(WebServerModule.GetWebSiteUrl()));

                        return(true);
                    }

                    if (await CheckAccess(characterId, rChar) == null)
                    {
                        await WebServerModule.WriteResponce(
                            WebServerModule.GetAccessDeniedPage("Web Config Editor", LM.Get("accessDenied"),
                                                                WebServerModule.GetWebSiteUrl()), response);

                        return(true);
                    }

                    var we = new WebEditorAuthEntry
                    {
                        Id = characterId, Code = Guid.NewGuid().ToString("N"), Time = DateTime.Now
                    };
                    await SQLHelper.SaveWebEditorAuthEntry(we);

                    var url = WebServerModule.GetWebEditorUrl(we.Code);
                    await response.RedirectAsync(new Uri(url));

                    return(true);
                }

                if (request.Url.LocalPath == "/settings" || request.Url.LocalPath == $"{extPort}/settings")
                {
                    var prms = request.Url.Query.TrimStart('?').Split('&');
                    if (prms.Length == 0 || prms[0].Split('=').Length == 0 || string.IsNullOrEmpty(prms[0]))
                    {
                        return(false);
                    }
                    var code  = prms.FirstOrDefault(a => a.StartsWith("code"))?.Split('=')[1];
                    var state = prms.FirstOrDefault(a => a.StartsWith("state"))?.Split('=')[1];

                    if (state != "settings" && state != "settings_sa" && state != "settings_ti")
                    {
                        return(false);
                    }
                    if (code == null)
                    {
                        await WebServerModule.WriteResponce(
                            WebServerModule.GetAccessDeniedPage("Web Config Editor", LM.Get("accessDenied"),
                                                                WebServerModule.GetWebSiteUrl()), response);

                        return(true);
                    }

                    var we = await SQLHelper.GetWebEditorAuthEntry(code);

                    if (we == null)
                    {
                        await WebServerModule.WriteResponce(
                            WebServerModule.GetAccessDeniedPage("Web Config Editor", LM.Get("accessDenied"),
                                                                WebServerModule.GetWebSiteUrl()), response);

                        return(true);
                    }

                    var rChar = await APIHelper.ESIAPI.GetCharacterData(Reason, we.Id, true);

                    if (rChar == null)
                    {
                        await response.RedirectAsync(new Uri(WebServerModule.GetWebSiteUrl()));

                        return(true);
                    }

                    var filter = await CheckAccess(we.Id, rChar);

                    if (filter == null)
                    {
                        await WebServerModule.WriteResponce(
                            WebServerModule.GetAccessDeniedPage("Web Config Editor", LM.Get("accessDenied"),
                                                                WebServerModule.GetWebSiteUrl()), response);

                        return(true);
                    }

                    if (state == "settings_sa")
                    {
                        if (!filter.CanEditSimplifiedAuth)
                        {
                            await WebServerModule.WriteResponce("Nope", response);

                            return(true);
                        }

                        var data = prms.FirstOrDefault(a => a.StartsWith("data"))?.Split('=')[1];
                        data = HttpUtility.UrlDecode(data);
                        if (data != null)
                        {
                            //load clean settings from file
                            await SettingsManager.UpdateSettings();

                            var convData = JsonConvert.DeserializeObject <List <SaData> >(data);
                            convData = convData.Where(a =>
                                                      !string.IsNullOrEmpty(a.Name?.Trim()) && !string.IsNullOrEmpty(a.Group?.Trim()) &&
                                                      !string.IsNullOrEmpty(a.Roles?.Trim())).ToList();
                            await SettingsManager.SaveSimplifiedAuthData(convData
                                                                         .Select(a => $"{a.Name}|{a.Group}|{a.Roles}").ToList());

                            //inject updated simplified auth data
                            await SettingsManager.LoadSimplifiedAuth();

                            //rebuild auth cache
                            if (Settings.Config.ModuleAuthWeb)
                            {
                                await TickManager.GetModule <WebAuthModule>().Initialize();
                            }
                            await LogHelper.LogInfo("Simplified auth update completed!", Category);
                        }
                        else
                        {
                            var simplifiedAuthEntities = await SettingsManager.GetSimplifiedAuthData();

                            var x = new
                            {
                                total            = simplifiedAuthEntities.Count,
                                totalNotFiltered = simplifiedAuthEntities.Count,
                                rows             = simplifiedAuthEntities
                            };
                            var json = JsonConvert.SerializeObject(x);
                            await WebServerModule.WriteJsonResponse(json, response);
                        }

                        return(true);
                    }

                    if (state == "settings_ti")
                    {
                        if (!filter.CanEditTimers)
                        {
                            await WebServerModule.WriteResponce("Nope", response);

                            return(true);
                        }

                        var data = prms.FirstOrDefault(a => a.StartsWith("data"))?.Split('=')[1];
                        data = HttpUtility.UrlDecode(data);
                        if (data != null)
                        {
                            var convData = JsonConvert.DeserializeObject <List <TiData> >(data);
                            convData = convData.Where(a =>
                                                      !string.IsNullOrEmpty(a.Name?.Trim()) && !string.IsNullOrEmpty(a.Entities?.Trim()) &&
                                                      !string.IsNullOrEmpty(a.Roles?.Trim())).ToList();
                            await SaveTimersAuthData(convData);
                        }
                        else
                        {
                            var ent = SettingsManager.Settings.TimersModule.AccessList.Select(a => new TiData
                            {
                                Name     = a.Key,
                                Entities = string.Join(",", a.Value.FilterEntities.Select(b => b.ToString())),
                                Roles    = string.Join(",", a.Value.FilterDiscordRoles)
                            }).ToList();
                            var x    = new { total = ent.Count, totalNotFiltered = ent.Count, rows = ent };
                            var json = JsonConvert.SerializeObject(x);
                            await WebServerModule.WriteJsonResponse(json, response);
                        }

                        return(true);
                    }

                    //check in db
                    var timeout = Settings.WebConfigEditorModule.SessionTimeoutInMinutes;
                    if (timeout != 0)
                    {
                        if ((DateTime.Now - we.Time).TotalMinutes > timeout)
                        {
                            await SQLHelper.DeleteWebEditorEntry(we.Id);

                            //redirect to auth
                            await response.RedirectAsync(new Uri(WebServerModule.GetWebConfigAuthURL()));

                            return(true);
                        }

                        //update session overwise
                        we.Time = DateTime.Now;
                        await SQLHelper.SaveWebEditorAuthEntry(we);
                    }

                    //var groups = string.Join(", ", Settings.WebAuthModule.AuthGroups.Keys.Distinct());

                    var sb = new StringBuilder();
                    foreach (var groupName in Settings.WebAuthModule.AuthGroups.Keys.Distinct())
                    {
                        sb.Append($"{{value: '{groupName}', text: '{groupName}'}},");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    var groupList = $"[{sb}]";

                    var timersContent     = string.Empty;
                    var timersScripts     = string.Empty;
                    var simpleAuthContent = string.Empty;
                    var simpleAuthScripts = string.Empty;
                    if (filter.CanEditSimplifiedAuth)
                    {
                        simpleAuthContent = File.ReadAllText(SettingsManager.FileTemplateSettingsPage_SimpleAuth)
                                            .Replace("{saAddEntry}", LM.Get("webSettingsAddEntryButton"))
                                            .Replace("{saDeleteEntry}", LM.Get("webSettingsDeleteEntryButton"))
                                            .Replace("{saSave}", LM.Get("webSettingsSaveEntryButton"))
                                            .Replace("{saTableColumnName}", LM.Get("webSettingsSaColumnName"))
                                            .Replace("{saTableColumnGroup}", LM.Get("webSettingsSaColumnGroup"))
                                            .Replace("{saTableColumnRoles}", LM.Get("webSettingsSaColumnRoles"))

                                            .Replace("{serverAddress}",
                                                     $"{Settings.WebServerModule.WebExternalIP}:{Settings.WebServerModule.WebExternalPort}")
                                            .Replace("{code}", code)
                                            .Replace("{locale}", SettingsManager.Settings.Config.Language)
                        ;

                        simpleAuthScripts = File
                                            .ReadAllText(SettingsManager.FileTemplateSettingsPage_SimpleAuth_Scripts)
                                            .Replace("{saGroupList}", groupList)
                                            .Replace("{postSimplifiedAuthUrl}", WebServerModule.GetWebEditorSimplifiedAuthUrl(code))
                        ;
                    }

                    if (filter.CanEditTimers)
                    {
                        timersContent = File.ReadAllText(SettingsManager.FileTemplateSettingsPage_Timers)
                                        .Replace("{saAddEntry}", LM.Get("webSettingsAddEntryButton"))

                                        .Replace("{saAddEntry}", LM.Get("webSettingsAddEntryButton"))
                                        .Replace("{saDeleteEntry}", LM.Get("webSettingsDeleteEntryButton"))
                                        .Replace("{saSave}", LM.Get("webSettingsSaveEntryButton"))
                                        .Replace("{saTableColumnName}", LM.Get("webSettingsSaColumnName"))
                                        .Replace("{tiTableColumnEntities}", LM.Get("webSettingsTiColumnEntities"))
                                        .Replace("{saTableColumnRoles}", LM.Get("webSettingsSaColumnRoles"))

                                        .Replace("{serverAddress}",
                                                 $"{Settings.WebServerModule.WebExternalIP}:{Settings.WebServerModule.WebExternalPort}")
                                        .Replace("{code}", code)
                                        .Replace("{locale}", SettingsManager.Settings.Config.Language)
                        ;

                        timersScripts = File.ReadAllText(SettingsManager.FileTemplateSettingsPage_Timers_Scripts)
                                        .Replace("{postTimersUrl}", WebServerModule.GetWebEditorTimersUrl(code))
                        ;
                    }

                    var saActive = filter.CanEditSimplifiedAuth ? "active" : null;
                    var tiActive = saActive != null || !filter.CanEditTimers ? null : "active";

                    var text = File.ReadAllText(SettingsManager.FileTemplateSettingsPage)
                               .Replace("{headerContent}", WebServerModule.GetHtmlResourceTables())
                               .Replace("{header}", LM.Get("webSettingsHeader"))
                               .Replace("{Back}", LM.Get("Back"))
                               .Replace("{LogOut}", LM.Get("LogOut"))
                               .Replace("{loggedInAs}", LM.Get("loggedInAs", rChar.name))
                               .Replace("{LogOutUrl}", WebServerModule.GetWebSiteUrl())
                               .Replace("{backUrl}", WebServerModule.GetWebSiteUrl())
                               .Replace("{simpleAuthContent}", simpleAuthContent)
                               .Replace("{simpleAuthScripts}", simpleAuthScripts)
                               .Replace("{timersContent}", timersContent)
                               .Replace("{timersScripts}", timersScripts)
                               .Replace("{code}", code)
                               .Replace("{locale}", SettingsManager.Settings.Config.Language)
                               .Replace("{simpleAuthTabName}", LM.Get("webSettingsSimpleAuthTabName"))
                               .Replace("{timersTabName}", LM.Get("webSettingsTimersTabName"))
                               .Replace("{saPageVisible}", filter.CanEditSimplifiedAuth ? null : "d-none")
                               .Replace("{tiPageVisible}", filter.CanEditTimers ? null : "d-none")
                               .Replace("{saPageActive}", saActive)
                               .Replace("{tiPageActive}", tiActive)
                    ;
                    await WebServerModule.WriteResponce(text, response);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx($"Error: {ex.Message}", ex, Category);
            }
            finally
            {
                RunningRequestCount--;
            }
            return(false);
        }
Пример #8
0
        public async Task UpdateAllUserRoles(Dictionary <int, List <string> > foundList, List <string> exemptRoles)
        {
            var authSettings = TickManager.GetModule <AuthCheckModule>().Settings;
            var discordGuild = GetGuild();
            var discordUsers = discordGuild.Users;

            foreach (var u in discordUsers)
            {
                try
                {
                    if (u.Id == Client.CurrentUser.Id || u.IsBot || u.Roles.Any(r => exemptRoles.Contains(r.Name)))
                    {
                        continue;
                    }

                    await LogHelper.LogInfo($"Running Auth Check on {u.Username}", LogCat.AuthCheck, false);

                    var responce = await SQLHelper.GetAuthUser(u.Id);

                    if (responce.Count > 0)
                    {
                        var characterID = responce.OrderByDescending(x => x["id"]).FirstOrDefault()["characterID"];

                        var characterData = await APIHelper.ESIAPI.GetCharacterData("authCheck", characterID, true);

                        //skip bad requests
                        if (characterData == null)
                        {
                            continue;
                        }
                        var corporationData = await APIHelper.ESIAPI.GetCorporationData("authCheck", characterData.corporation_id, true);

                        var roles     = new List <SocketRole>();
                        var rolesOrig = new List <SocketRole>(u.Roles);
                        var remroles  = new List <SocketRole>();
                        roles.Add(u.Roles.FirstOrDefault(x => x.Name == "@everyone"));
                        bool isInExempt = false;

                        foreach (var role in exemptRoles)
                        {
                            var exemptRole = GetUserRole(u, role);
                            if (exemptRole != null)
                            {
                                roles.Add(exemptRole);
                                isInExempt = true;
                            }
                        }

                        if (foundList.Count == 0)
                        {
                            isInExempt = true;
                        }

                        //Check for Corp roles
                        if (foundList.ContainsKey(characterData.corporation_id))
                        {
                            var cinfo  = foundList[characterData.corporation_id];
                            var aRoles = discordGuild.Roles.Where(a => cinfo.Contains(a.Name)).ToList();
                            if (aRoles.Count > 0)
                            {
                                roles.AddRange(aRoles);
                            }
                        }

                        //Check for Alliance roles
                        if (characterData.alliance_id != null)
                        {
                            if (foundList.ContainsKey(characterData.alliance_id ?? 0))
                            {
                                var ainfo  = foundList[characterData.alliance_id ?? 0];
                                var aRoles = discordGuild.Roles.Where(a => ainfo.Contains(a.Name)).ToList();
                                if (aRoles.Count > 0)
                                {
                                    roles.AddRange(aRoles);
                                }
                            }
                        }

                        bool changed = false;
                        foreach (var role in rolesOrig)
                        {
                            if (roles.FirstOrDefault(x => x.Id == role.Id) == null)
                            {
                                remroles.Add(role);
                                changed = true;
                            }
                        }

                        foreach (var role in roles)
                        {
                            if (rolesOrig.FirstOrDefault(x => x.Id == role.Id) == null)
                            {
                                changed = true;
                            }
                        }

                        if (changed)
                        {
                            roles.Remove(u.Roles.FirstOrDefault(x => x.Name == "@everyone"));
                            if (authSettings.Auth.AuthReportChannel != 0)
                            {
                                var channel = discordGuild.GetTextChannel(authSettings.Auth.AuthReportChannel);
                                await SendMessageAsync(channel, $"{LM.Get("renewingRoles")} {characterData.name} ({u.Username})");
                            }

                            await LogHelper.LogInfo($"Adjusting roles for {characterData.name} ({u.Username})", LogCat.AuthCheck);

                            await u.AddRolesAsync(roles);

                            if (!isInExempt)
                            {
                                await u.RemoveRolesAsync(remroles);
                            }
                            //remove notifications token if user has been stripped of roles
                            // if (!isInExempt && !isAddedRole && isRemovedRole)
                            //    await SQLHelper.SQLiteDataDelete("notificationsList", "characterID", characterID);
                        }

                        var eveName = characterData.name;

                        if (authSettings.Auth.EnforceCorpTickers || authSettings.Auth.EnforceCharName)
                        {
                            var nickname = $"{(authSettings.Auth.EnforceCorpTickers  ? $"[{corporationData.ticker}] " : null)}{(authSettings.Auth.EnforceCharName ? eveName : u.Username)}";
                            if (nickname != u.Nickname && !string.IsNullOrWhiteSpace(u.Nickname) || string.IsNullOrWhiteSpace(u.Nickname) && u.Username != nickname)
                            {
                                await u.ModifyAsync(x => x.Nickname = nickname);

                                await LogHelper.LogInfo($"Changed name of {u.Nickname} to {nickname}", LogCat.AuthCheck);
                            }
                        }
                    }
                    else
                    {
                        var rroles    = new List <SocketRole>();
                        var rolesOrig = new List <SocketRole>(u.Roles);
                        foreach (var rrole in rolesOrig)
                        {
                            var exemptRole = exemptRoles.FirstOrDefault(x => x == rrole.Name);
                            if (exemptRole == null)
                            {
                                rroles.Add(rrole);
                            }
                        }

                        rolesOrig.Remove(u.Roles.FirstOrDefault(x => x.Name == "@everyone"));
                        rroles.Remove(u.Roles.FirstOrDefault(x => x.Name == "@everyone"));

                        bool rchanged = false;

                        if (rroles != rolesOrig)
                        {
                            foreach (var exempt in rroles)
                            {
                                if (exemptRoles.FirstOrDefault(x => x == exempt.Name) == null)
                                {
                                    rchanged = true;
                                }
                            }
                        }

                        if (rchanged)
                        {
                            try
                            {
                                var channel = discordGuild.GetTextChannel(authSettings.Auth.AuthReportChannel);
                                await APIHelper.DiscordAPI.SendMessageAsync(channel, $"{LM.Get("resettingRoles")} {u.Username}");

                                await LogHelper.LogInfo($"Resetting roles for {u.Username}", LogCat.AuthCheck);

                                await u.RemoveRolesAsync(rroles);
                            }
                            catch (Exception ex)
                            {
                                await LogHelper.LogEx($"Error removing roles: {ex.Message}", ex, LogCat.AuthCheck);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    await LogHelper.LogEx($"Fatal Error: {ex.Message}", ex, LogCat.AuthCheck);
                }
            }
        }
Пример #9
0
        private static async Task <bool> AuthGrantRoles(ulong channelId, string characterID, Dictionary <int, List <string> > foundList, JsonClasses.CharacterData characterData, JsonClasses.CorporationData corporationData, string remainder, ulong discordId)
        {
            var rolesToAdd = new List <SocketRole>();

            var allianceID = characterData.alliance_id ?? 0;
            var corpID     = characterData.corporation_id;

            var authSettings = TickManager.GetModule <WebAuthModule>()?.Settings.WebAuthModule;
            var missedRoles  = new List <string>();

            try
            {
                //Check for Corp roles
                if (foundList.ContainsKey(corpID))
                {
                    var cRoles = foundList[corpID];
                    cRoles.ForEach(a =>
                    {
                        var f = APIHelper.DiscordAPI.GetGuildRole(a);
                        if (f != null && !rolesToAdd.Contains(f))
                        {
                            rolesToAdd.Add(f);
                        }
                        else
                        {
                            missedRoles.Add(a);
                        }
                    });
                }

                //Check for Alliance roles
                if (foundList.ContainsKey(allianceID))
                {
                    var cRoles = foundList[allianceID];
                    cRoles.ForEach(a =>
                    {
                        var f = APIHelper.DiscordAPI.GetGuildRole(a);
                        if (f != null && !rolesToAdd.Contains(f))
                        {
                            rolesToAdd.Add(f);
                        }
                        else
                        {
                            missedRoles.Add(a);
                        }
                    });
                }

                var discordUser = APIHelper.DiscordAPI.GetUser(discordId);

                if (authSettings.AuthReportChannel != 0)
                {
                    await APIHelper.DiscordAPI.SendMessageAsync(authSettings.AuthReportChannel, LM.Get("grantRolesMessage", characterData.name))
                    .ConfigureAwait(false);
                }
                await APIHelper.DiscordAPI.AssignRolesToUser(discordUser, rolesToAdd);

                if (missedRoles.Any())
                {
                    await LogHelper.LogWarning($"Missing discord roles: {string.Join(',', missedRoles)}");
                }

                var rolesString = new StringBuilder();
                foreach (var role in discordUser.Roles)
                {
                    if (role.Name.StartsWith("@everyone"))
                    {
                        continue;
                    }
                    rolesString.Append(role.Name.Replace("\"", "&br;"));
                    rolesString.Append(",");
                }
                if (rolesString.Length > 0)
                {
                    rolesString.Remove(rolesString.Length - 1, 1);
                }

                await SQLHelper.SQLiteDataUpdate("pendingUsers", "active", "0", "authString", remainder);

                if (channelId != 0)
                {
                    await APIHelper.DiscordAPI.SendMessageAsync(channelId, LM.Get("msgAuthSuccess", discordUser.Mention, characterData.name));
                }
                var eveName   = characterData.name;
                var discordID = discordUser.Id;
                var addedOn   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                await SQLHelper.SQLiteDataInsertOrUpdate("authUsers", new Dictionary <string, object>
                {
                    { "eveName", eveName },
                    { "characterID", characterID },
                    { "discordID", discordID.ToString() },
                    { "role", rolesString.ToString() },
                    { "active", "yes" },
                    { "addedOn", addedOn }
                });

                if (authSettings.EnforceCorpTickers || authSettings.EnforceCharName)
                {
                    var nickname = "";
                    if (authSettings.EnforceCorpTickers)
                    {
                        nickname = $"[{corporationData.ticker}] ";
                    }
                    if (authSettings.EnforceCharName)
                    {
                        nickname += $"{eveName}";
                    }
                    else
                    {
                        nickname += $"{discordUser.Username}";
                    }

                    try
                    {
                        //will throw ex on admins
                        await discordUser.ModifyAsync(x => x.Nickname = nickname);
                    }
                    catch
                    {
                        //ignore
                    }

                    await APIHelper.DiscordAPI.Dupes(discordUser);
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx($"Failed adding Roles to User {characterData.name}, Reason: {ex.Message}", ex, LogCat.Discord);

                return(false);
            }

            return(true);
        }
Пример #10
0
        internal static async Task AuthUser(ICommandContext context, string remainder, ulong discordId)
        {
            try
            {
                var esiFailed = false;
                var responce  = await SQLHelper.GetPendingUser(remainder);

                if (!responce.Any())
                {
                    await APIHelper.DiscordAPI.ReplyMessageAsync(context, context.Channel, LM.Get("authHasInvalidKey"), true).ConfigureAwait(false);
                }
                else
                {
                    switch (responce[0]["active"].ToString())
                    {
                    case "0":
                        await APIHelper.DiscordAPI.ReplyMessageAsync(context, context.Channel, LM.Get("authHasInactiveKey"), true).ConfigureAwait(false);

                        break;

                    case "1":
                        // var authgroups = SettingsManager.GetSubList("auth", "authgroups");
                        // var corps = new Dictionary<string, string>();
                        // var alliance = new Dictionary<string, string>();

                        var foundList = new Dictionary <int, List <string> >();
                        var groupName = string.Empty;
                        foreach (var group in TickManager.GetModule <WebAuthModule>().Settings.WebAuthModule.AuthGroups)
                        {
                            if (group.Value.CorpIDList.Count > 0)
                            {
                                foreach (var c in group.Value.CorpIDList.Where(a => !foundList.ContainsKey(a)))
                                {
                                    foundList.Add(c, group.Value.MemberRoles);
                                }
                                // groupName = group.Key;
                            }

                            if (group.Value.AllianceIDList.Count > 0)
                            {
                                foreach (var c in group.Value.AllianceIDList.Where(a => !foundList.ContainsKey(a)))
                                {
                                    foundList.Add(c, group.Value.MemberRoles);
                                }
                                // groupName = group.Key;
                            }
                        }

                        var characterID   = responce[0]["characterID"].ToString();
                        var characterData = await APIHelper.ESIAPI.GetCharacterData("WebAuth", characterID, true);

                        if (characterData == null)
                        {
                            esiFailed = true;
                        }

                        var corporationData = await APIHelper.ESIAPI.GetCorporationData("WebAuth", characterData.corporation_id);

                        if (corporationData == null)
                        {
                            esiFailed = true;
                        }

                        var allianceID = characterData.alliance_id ?? 0;
                        var corpID     = characterData.corporation_id;

                        bool enable = foundList.ContainsKey(corpID) || characterData.alliance_id != null && foundList.ContainsKey(allianceID) || foundList.Count == 0;

                        if (!enable)
                        {
                            var grp = SettingsManager.Settings.WebAuthModule.AuthGroups.FirstOrDefault(a => a.Value.CorpIDList.Count == 0 && a.Value.AllianceIDList.Count == 0);
                            if (grp.Value != null)
                            {
                                enable    = true;
                                groupName = grp.Key;
                            }
                        }

                        if (enable && !esiFailed)
                        {
                            var ch = context?.Channel?.Id ?? SettingsManager.Settings.WebAuthModule.AuthReportChannel;
                            await AuthGrantRoles(ch, characterID, foundList, characterData, corporationData, remainder, discordId == 0?context.Message.Author.Id : discordId);

                            var chId = Convert.ToInt32(characterID);
                            if (await SQLHelper.IsEntryExists("userTokens", new Dictionary <string, object> {
                                { "characterID", chId }
                            }))
                            {
                                var discordUser = APIHelper.DiscordAPI.GetUser(discordId == 0 ? context.Message.Author.Id : discordId);
                                // await SQLHelper.SQLiteDataUpdate("userTokens", "groupName", groupName, "characterID", chId);
                                await SQLHelper.SQLiteDataUpdate("userTokens", "discordUserId", discordUser.Id, "characterID", chId);

                                await SQLHelper.SQLiteDataUpdate("userTokens", "authState", 2, "characterID", chId);
                            }
                        }
                        else
                        {
                            await APIHelper.DiscordAPI.SendMessageAsync(context.Channel, LM.Get("ESIFailure")).ConfigureAwait(false);

                            await LogHelper.LogError("ESI Failure", LogCat.AuthWeb);
                        }

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx($"Error: {ex.Message}", ex, LogCat.AuthWeb);
            }
        }
Пример #11
0
        public static async Task ProcessClistCommand(ICommandContext context, KeyValuePair <string, ContractNotifyGroup> groupPair, string mod)
        {
            try
            {
                var group             = groupPair.Value;
                var personalContracts = new List <JsonClasses.Contract>();
                var corpContracts     = new List <JsonClasses.Contract>();

                var chars = TickManager.GetModule <ContractNotificationsModule>().GetParsedCharacters(groupPair.Key);

                foreach (var characterID in chars)
                {
                    if (group.FeedPersonalContracts)
                    {
                        personalContracts.AddRange(await SQLHelper.LoadContracts(characterID, false));
                    }
                    if (group.FeedCorporateContracts)
                    {
                        corpContracts.AddRange(await SQLHelper.LoadContracts(characterID, true));
                    }
                }

                if (mod.Length > 1)
                {
                    var type = mod[1];
                    switch (char.ToLower(type))
                    {
                    case 'c':     //courier
                        personalContracts.RemoveAll(a => !a.type.Equals("courier", StringComparison.OrdinalIgnoreCase));
                        corpContracts.RemoveAll(a => !a.type.Equals("courier", StringComparison.OrdinalIgnoreCase));
                        break;

                    case 'e':     //exchange
                        personalContracts.RemoveAll(a => !a.type.Equals("item_exchange", StringComparison.OrdinalIgnoreCase));
                        corpContracts.RemoveAll(a => !a.type.Equals("item_exchange", StringComparison.OrdinalIgnoreCase));
                        break;

                    case 'a':     //auction
                        personalContracts.RemoveAll(a => !a.type.Equals("auction", StringComparison.OrdinalIgnoreCase));
                        corpContracts.RemoveAll(a => !a.type.Equals("auction", StringComparison.OrdinalIgnoreCase));
                        break;

                    case '0':
                        break;

                    default:
                        await APIHelper.DiscordAPI.ReplyMessageAsync(context, LM.Get("helpClist"), true);

                        return;
                    }

                    if (mod.Length > 2)
                    {
                        var avail = mod[2];
                        switch (char.ToLower(avail))
                        {
                        case 'a':     //alliance
                            personalContracts.RemoveAll(a => !a.availability.Equals("alliance", StringComparison.OrdinalIgnoreCase));
                            corpContracts.RemoveAll(a => !a.availability.Equals("alliance", StringComparison.OrdinalIgnoreCase));
                            break;

                        case 'c':     //exchange
                            personalContracts.RemoveAll(a => !a.availability.Equals("corporation", StringComparison.OrdinalIgnoreCase));
                            corpContracts.RemoveAll(a => !a.availability.Equals("corporation", StringComparison.OrdinalIgnoreCase));
                            break;

                        case 'p':     //public
                            personalContracts.RemoveAll(a => !a.availability.Equals("public", StringComparison.OrdinalIgnoreCase));
                            corpContracts.RemoveAll(a => !a.availability.Equals("public", StringComparison.OrdinalIgnoreCase));
                            break;

                        case '0':
                            break;

                        default:
                            await APIHelper.DiscordAPI.ReplyMessageAsync(context, LM.Get("helpClist"), true);

                            return;
                        }
                    }
                }


                switch (char.ToLower(mod[0]))
                {
                case 'o':
                    personalContracts = personalContracts.Where(a => _activeStatuses.Contains(a.status)).ToList();
                    corpContracts     = corpContracts.Where(a => _activeStatuses.Contains(a.status)).ToList();
                    break;

                case 'c':
                    personalContracts = personalContracts.Where(a => _completeStatuses.Contains(a.status)).ToList();
                    corpContracts     = corpContracts.Where(a => _completeStatuses.Contains(a.status)).ToList();
                    break;

                case 'f':
                    personalContracts = personalContracts.Where(a => _finishedStatuses.Contains(a.status)).ToList();
                    corpContracts     = corpContracts.Where(a => _finishedStatuses.Contains(a.status)).ToList();
                    break;

                case 'r':
                    personalContracts = personalContracts.Where(a => _rejectedStatuses.Contains(a.status)).ToList();
                    corpContracts     = corpContracts.Where(a => _rejectedStatuses.Contains(a.status)).ToList();
                    break;

                case 'a':
                    break;

                default:
                    await APIHelper.DiscordAPI.ReplyMessageAsync(context, LM.Get("helpClist"), true);

                    return;
                }

                var sb = new StringBuilder();
                if (personalContracts.Any())
                {
                    sb.AppendLine("");
                    sb.AppendLine(LM.Get("clistPersonalTitle"));
                    sb.AppendLine("```");
                    //header
                    sb.Append(LM.Get("clistHeaderName").FixedLength(20));
                    sb.Append("  ");
                    sb.Append(LM.Get("clistHeaderType").FixedLength(13));
                    sb.Append("  ");
                    sb.Append(LM.Get("clistHeaderStatus").FixedLength(11));
                    sb.Append("  ");
                    sb.Append(LM.Get("clistHeaderExp").FixedLength(12));
                    sb.Append(Environment.NewLine);

                    foreach (var contract in personalContracts)
                    {
                        sb.Append((string.IsNullOrEmpty(contract.title) ? "-" : contract.title).FixedLength(20));
                        sb.Append("  ");
                        sb.Append(contract.type.FixedLength(13));
                        sb.Append("  ");
                        sb.Append(contract.status.FixedLength(11));
                        sb.Append("  ");
                        if (_activeStatuses.Contains(contract.status))
                        {
                            var value = (contract.DateExpired - DateTime.UtcNow).Value;
                            sb.Append($"{value.Days}d {value.Hours}h {value.Minutes}m");
                        }
                        else
                        {
                            sb.Append(LM.Get("clistExpired"));
                        }
                        sb.Append(Environment.NewLine);
                    }
                    sb.AppendLine("```");
                }
                if (corpContracts.Any())
                {
                    sb.AppendLine("");
                    sb.AppendLine(LM.Get("clistCorpTitle"));
                    sb.AppendLine("```");
                    //header
                    sb.Append(LM.Get("clistHeaderName").FixedLength(20));
                    sb.Append("  ");
                    sb.Append(LM.Get("clistHeaderType").FixedLength(13));
                    sb.Append("  ");
                    sb.Append(LM.Get("clistHeaderStatus").FixedLength(11));
                    sb.Append("  ");
                    sb.Append(LM.Get("clistHeaderExp").FixedLength(12));
                    sb.Append(Environment.NewLine);

                    foreach (var contract in corpContracts)
                    {
                        sb.Append((string.IsNullOrEmpty(contract.title) ? "-" : contract.title).FixedLength(20));
                        sb.Append("  ");
                        sb.Append(contract.type.FixedLength(13));
                        sb.Append("  ");
                        sb.Append(contract.status.FixedLength(11));
                        sb.Append("  ");
                        if (_activeStatuses.Contains(contract.status))
                        {
                            var value = (contract.DateExpired - DateTime.UtcNow).Value;
                            sb.Append($"{value.Days}d {value.Hours}h {value.Minutes}m");
                        }
                        else
                        {
                            sb.Append(LM.Get("clistExpired"));
                        }
                        sb.Append(Environment.NewLine);
                    }
                    sb.AppendLine("```");
                }

                if (!personalContracts.Any() && !corpContracts.Any())
                {
                    sb.Append(LM.Get("clistNoContracts"));
                }

                await APIHelper.DiscordAPI.ReplyMessageAsync(context, sb.ToString(), true);
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx(nameof(ProcessClistCommand), ex, LogCat.ContractNotif);

                await APIHelper.DiscordAPI.ReplyMessageAsync(context, LM.Get("WebRequestUnexpected"));
            }
        }
        public async Task <bool> Auth(HttpListenerRequestEventArgs context)
        {
            if (!Settings.Config.ModuleNotificationFeed)
            {
                return(false);
            }

            var request  = context.Request;
            var response = context.Response;
            var extPort  = Settings.WebServerModule.WebExternalPort;
            var port     = Settings.WebServerModule.WebExternalPort;

            try
            {
                RunningRequestCount++;
                if (request.HttpMethod != HttpMethod.Get.ToString())
                {
                    return(false);
                }
                if ((request.Url.LocalPath == "/callback" || request.Url.LocalPath == $"{extPort}/callback" ||
                     request.Url.LocalPath == $"{port}/callback") &&
                    request.Url.Query.Contains("&state=9"))
                {
                    var prms = request.Url.Query.TrimStart('?').Split('&');
                    var code = prms[0].Split('=')[1];
                    // var state = prms.Length > 1 ? prms[1].Split('=')[1] : null;

                    var result = await WebAuthModule.GetCharacterIdFromCode(code,
                                                                            Settings.WebServerModule.CcpAppClientId, Settings.WebServerModule.CcpAppSecret);

                    if (result == null)
                    {
                        var message = LM.Get("ESIFailure");
                        await WebServerModule.WriteResponce(File.ReadAllText(SettingsManager.FileTemplateAuth3)
                                                            .Replace("{message}", message)
                                                            .Replace("{headerContent}", WebServerModule.GetHtmlResourceDefault(false))
                                                            .Replace("{header}", LM.Get("authTemplateHeader"))
                                                            .Replace("{backUrl}", WebServerModule.GetAuthLobbyUrl())
                                                            .Replace("{backText}", LM.Get("backText")), response);

                        return(true);
                    }

                    var characterID   = result[0];
                    var numericCharId = Convert.ToInt64(characterID);

                    if (string.IsNullOrEmpty(characterID))
                    {
                        await LogHelper.LogWarning("Bad or outdated notify feed request!");

                        await WebServerModule.WriteResponce(File.ReadAllText(SettingsManager.FileTemplateAuthNotifyFail)
                                                            .Replace("{headerContent}", WebServerModule.GetHtmlResourceDefault(false))
                                                            .Replace("{message}", LM.Get("authTokenBadRequest"))
                                                            .Replace("{header}", LM.Get("authTokenHeader"))
                                                            .Replace("{body}", LM.Get("authTokenBodyFail"))
                                                            .Replace("{backText}", LM.Get("backText")),
                                                            response);

                        return(true);
                    }

                    if (!TickManager.GetModule <NotificationModule>().IsValidCharacter(numericCharId))
                    {
                        await LogHelper.LogWarning($"Unathorized notify feed request from {characterID}");

                        await WebServerModule.WriteResponce(File.ReadAllText(SettingsManager.FileTemplateAuthNotifyFail)
                                                            .Replace("{headerContent}", WebServerModule.GetHtmlResourceDefault(false))
                                                            .Replace("{message}", LM.Get("authTokenInvalid"))
                                                            .Replace("{header}", LM.Get("authTokenHeader"))
                                                            .Replace("{body}", LM.Get("authTokenBodyFail"))
                                                            .Replace("{backText}", LM.Get("backText")),
                                                            response);

                        return(true);
                    }

                    var rChar = await APIHelper.ESIAPI.GetCharacterData(Reason, characterID, true);

                    await SQLHelper.InsertOrUpdateTokens(result[1] ?? "", characterID, null, "");

                    await LogHelper.LogInfo($"Notification feed added for character: {characterID}", LogCat.AuthWeb);

                    await WebServerModule.WriteResponce(File.ReadAllText(SettingsManager.FileTemplateAuthNotifySuccess)
                                                        .Replace("{headerContent}", WebServerModule.GetHtmlResourceDefault(false))
                                                        .Replace("{body2}", LM.Get("authTokenRcv2", rChar.name))
                                                        .Replace("{body}", LM.Get("authTokenRcv")).Replace("{header}", LM.Get("authTokenHeader"))
                                                        .Replace("{backText}", LM.Get("backText")), response);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx(ex.Message, ex, Category);
            }
            finally
            {
                RunningRequestCount--;
            }

            return(false);
        }
        public async Task <WebQueryResult> ProcessRequest(string query, CallbackTypeEnum type, string ip, WebAuthUserData data)
        {
            if (!Settings.Config.ModuleNotificationFeed)
            {
                return(WebQueryResult.False);
            }

            try
            {
                RunningRequestCount++;
                if (query.Contains("&state=9"))
                {
                    //var prms = QueryHelpers.ParseQuery(query);
                    var prms = query.TrimStart('?').Split('&');
                    var code = prms[0].Split('=')[1];

                    var result = await WebAuthModule.GetCharacterIdFromCode(code,
                                                                            Settings.WebServerModule.CcpAppClientId, Settings.WebServerModule.CcpAppSecret);

                    if (result == null)
                    {
                        return(WebQueryResult.EsiFailure);
                    }

                    var characterId   = result[0];
                    var numericCharId = Convert.ToInt64(characterId);

                    if (string.IsNullOrEmpty(characterId))
                    {
                        await LogHelper.LogWarning("Bad or outdated notify feed request!");

                        var r = WebQueryResult.BadRequestToSystemAuth;
                        r.Message1 = LM.Get("authTokenBodyFail");
                        r.Message2 = LM.Get("authTokenBadRequest");
                        return(r);
                    }

                    if (!TickManager.GetModule <NotificationModule>().IsValidCharacter(numericCharId))
                    {
                        await LogHelper.LogWarning($"Unauthorized notify feed request from {characterId}");

                        var r = WebQueryResult.BadRequestToSystemAuth;
                        r.Message1 = LM.Get("authTokenBodyFail");
                        return(r);
                    }

                    var rChar = await APIHelper.ESIAPI.GetCharacterData(Reason, characterId, true);

                    await SQLHelper.InsertOrUpdateTokens(result[1] ?? "", characterId, null, "");

                    await LogHelper.LogInfo($"Notification feed added for character: {characterId}", LogCat.AuthWeb);

                    var res = WebQueryResult.GeneralAuthSuccess;
                    res.Message1 = LM.Get("authTokenRcv");
                    res.Message2 = LM.Get("authTokenRcv2", rChar.name);
                    return(res);
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx(ex.Message, ex, Category);
            }
            finally
            {
                RunningRequestCount--;
            }

            return(WebQueryResult.False);
        }
Пример #14
0
        public async Task <bool> Auth(HttpListenerRequestEventArgs context)
        {
            var esiFailure = false;
            var request    = context.Request;
            var response   = context.Response;

            var extIp       = SettingsManager.Get("webServerModule", "webExternalIP");
            var extPort     = SettingsManager.Get("webServerModule", "webExternalPort");
            var port        = SettingsManager.Get("webServerModule", "webListenPort");
            var callbackurl = $"http://{extIp}:{extPort}/callback.php";


            if (request.HttpMethod != HttpMethod.Get.ToString())
            {
                return(false);
            }
            try
            {
                if (request.Url.LocalPath == "/auth.php" || request.Url.LocalPath == $"{extPort}/auth.php" || request.Url.LocalPath == $"{port}/auth.php")
                {
                    response.Headers.ContentEncoding.Add("utf-8");
                    response.Headers.ContentType.Add("text/html;charset=utf-8");
                    var text = File.ReadAllText(SettingsManager.FileTemplateAuth).Replace("{callbackurl}", callbackurl).Replace("{client_id}", Settings.Core.CcpAppClientId)
                               .Replace("{header}", LM.Get("authTemplateHeader")).Replace("{body}", LM.Get("authTemplateInv")).Replace("{backText}", LM.Get("backText"));
                    await response.WriteContentAsync(text);

                    return(true);
                }

                if (request.Url.LocalPath == "/callback.php" || request.Url.LocalPath == $"{extPort}/callback.php" || request.Url.LocalPath == $"{port}/callback.php" &&
                    !request.Url.Query.Contains("&state=11"))
                {
                    var assembly = Assembly.GetEntryAssembly();
                    // var temp = assembly.GetManifestResourceNames();
                    var resource = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.Discord-01.png");
                    var buffer   = new byte[resource.Length];
                    resource.Read(buffer, 0, Convert.ToInt32(resource.Length));
                    var image = Convert.ToBase64String(buffer);
                    var uid   = GetUniqID();
                    var add   = false;

                    if (!string.IsNullOrWhiteSpace(request.Url.Query))
                    {
                        var prms  = request.Url.Query.TrimStart('?').Split('&');
                        var code  = prms[0].Split('=')[1];
                        var state = prms.Length > 1 ? prms[1].Split('=')[1] : null;

                        var result = await GetCHaracterIdFromCode(code, Settings.Core.CcpAppClientId, Settings.Core.CcpAppSecret);

                        if (result == null)
                        {
                            esiFailure = true;
                        }
                        var characterID   = result?[0];
                        var numericCharId = Convert.ToInt32(characterID);

                        var rChar = await APIHelper.ESIAPI.GetCharacterData(Reason, characterID, true);

                        if (state == "9") //refresh token fetch ops
                        {
                            response.Headers.ContentEncoding.Add("utf-8");
                            response.Headers.ContentType.Add("text/html;charset=utf-8");
                            if (string.IsNullOrEmpty(characterID))
                            {
                                await LogHelper.LogWarning("Bad or outdated notify feed request!");

                                await response.WriteContentAsync(File.ReadAllText(SettingsManager.FileTemplateAuthNotifyFail)
                                                                 .Replace("{message}", LM.Get("authTokenBadRequest"))
                                                                 .Replace("{header}", LM.Get("authTokenHeader")).Replace("{body}", LM.Get("authTokenBodyFail")).Replace("{backText}", LM.Get("backText")));

                                return(true);
                            }

                            if (TickManager.GetModule <NotificationModule>().Settings.Core.Groups.Values.All(g => g.CharacterID != numericCharId))
                            {
                                await LogHelper.LogWarning($"Unathorized notify feed request from {characterID}");

                                await response.WriteContentAsync(File.ReadAllText(SettingsManager.FileTemplateAuthNotifyFail)
                                                                 .Replace("{message}", LM.Get("authTokenInvalid"))
                                                                 .Replace("{header}", LM.Get("authTokenHeader")).Replace("{body}", LM.Get("authTokenBodyFail")).Replace("{backText}", LM.Get("backText")));

                                return(true);
                            }

                            await SQLHelper.SQLiteDataInsertOrUpdateTokens(result[1] ?? "", characterID, null);

                            await LogHelper.LogInfo($"Notification feed added for character: {characterID}", LogCat.AuthWeb);

                            await response.WriteContentAsync(File.ReadAllText(SettingsManager.FileTemplateAuthNotifySuccess)
                                                             .Replace("{body2}", string.Format(LM.Get("authTokenRcv2"), rChar.name))
                                                             .Replace("{body}", LM.Get("authTokenRcv")).Replace("{header}", LM.Get("authTokenHeader")).Replace("{backText}", LM.Get("backText")));

                            return(true);
                        }

                        var foundList = new List <int>();
                        foreach (var group in Settings.Core.AuthGroups.Values)
                        {
                            if (group.CorpID != 0)
                            {
                                foundList.Add(group.CorpID);
                            }
                            if (group.AllianceID != 0)
                            {
                                foundList.Add(group.AllianceID);
                            }
                        }

                        if (rChar == null)
                        {
                            esiFailure = true;
                        }
                        var corpID = rChar?.corporation_id ?? 0;

                        var rCorp = await APIHelper.ESIAPI.GetCorporationData(Reason, rChar?.corporation_id, true);

                        if (rCorp == null)
                        {
                            esiFailure = true;
                        }
                        var allianceID = rCorp?.alliance_id ?? 0;

                        if (corpID != 0 && foundList.Contains(corpID) || allianceID != 0 && foundList.Contains(allianceID) || foundList.Count == 0)
                        {
                            add = true;
                        }

                        if (!esiFailure && add)
                        {
                            await SQLHelper.SQLiteDataInsertOrUpdate("pendingUsers", new Dictionary <string, object>
                            {
                                { "characterID", characterID },
                                { "corporationID", corpID.ToString() },
                                { "allianceID", allianceID.ToString() },
                                { "authString", uid },
                                { "active", "1" },
                                { "groups", "[]" },
                                { "dateCreated", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }
                            });

                            response.Headers.ContentEncoding.Add("utf-8");
                            response.Headers.ContentType.Add("text/html;charset=utf-8");

                            await response.WriteContentAsync(File.ReadAllText(SettingsManager.FileTemplateAuth2).Replace("{url}", Settings.Core.DiscordUrl).Replace("{image}", image)
                                                             .Replace("{uid}", uid).Replace("{header}", LM.Get("authTemplateHeader"))
                                                             .Replace("{body}", string.Format(LM.Get("authTemplateSucc1"), rChar.name))
                                                             .Replace("{body2}", LM.Get("authTemplateSucc2")).Replace("{body3}", LM.Get("authTemplateSucc3")).Replace("{backText}", LM.Get("backText")));
                        }
                        else if (!esiFailure)
                        {
                            var message = "ERROR";
                            if (!add)
                            {
                                message = LM.Get("authNonAlly");
                            }
                            response.Headers.ContentEncoding.Add("utf-8");
                            response.Headers.ContentType.Add("text/html;charset=utf-8");
                            await response.WriteContentAsync(File.ReadAllText(SettingsManager.FileTemplateAuth3).Replace("{message}", message)
                                                             .Replace("{header}", LM.Get("authTemplateHeader")).Replace("{backText}", LM.Get("backText")));
                        }
                        else
                        {
                            var message = LM.Get("ESIFailure");
                            response.Headers.ContentEncoding.Add("utf-8");
                            response.Headers.ContentType.Add("text/html;charset=utf-8");
                            await response.WriteContentAsync(File.ReadAllText(SettingsManager.FileTemplateAuth3).Replace("{message}", message)
                                                             .Replace("{header}", LM.Get("authTemplateHeader")).Replace("{backText}", LM.Get("backText")));
                        }

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx($"Error: {ex.Message}", ex, Category);
            }

            return(false);
        }
Пример #15
0
        internal static async Task AuthUser(ICommandContext context, string remainder)
        {
            try
            {
                var esiFailed = false;
                var responce  = await SQLHelper.GetPendingUser(remainder);

                if (!responce.Any())
                {
                    await APIHelper.DiscordAPI.ReplyMessageAsync(context, context.Channel, LM.Get("authHasInvalidKey"), true).ConfigureAwait(false);
                }
                else
                {
                    switch (responce[0]["active"].ToString())
                    {
                    case "0":
                        await APIHelper.DiscordAPI.ReplyMessageAsync(context, context.Channel, LM.Get("authHasInactiveKey"), true).ConfigureAwait(false);

                        break;

                    case "1":
                        // var authgroups = SettingsManager.GetSubList("auth", "authgroups");
                        // var corps = new Dictionary<string, string>();
                        // var alliance = new Dictionary<string, string>();

                        var foundList = new Dictionary <int, List <string> >();
                        foreach (var group in TickManager.GetModule <WebAuthModule>().Settings.Core.AuthGroups.Values)
                        {
                            if (group.CorpID != 0)
                            {
                                foundList.Add(group.CorpID, group.MemberRoles);
                            }
                            if (group.AllianceID != 0)
                            {
                                foundList.Add(group.AllianceID, group.MemberRoles);
                            }
                        }

                        var characterID   = responce[0]["characterID"].ToString();
                        var characterData = await APIHelper.ESIAPI.GetCharacterData("WebAuth", characterID, true);

                        if (characterData == null)
                        {
                            esiFailed = true;
                        }

                        var corporationData = await APIHelper.ESIAPI.GetCorporationData("WebAuth", characterData.corporation_id);

                        if (corporationData == null)
                        {
                            esiFailed = true;
                        }

                        var allianceID = characterData.alliance_id ?? 0;
                        var corpID     = characterData.corporation_id;

                        bool enable = foundList.ContainsKey(corpID) || characterData.alliance_id != null && foundList.ContainsKey(allianceID) || foundList.Count == 0;

                        if (enable && !esiFailed)
                        {
                            await AuthGrantRoles(context, characterID, foundList, characterData, corporationData, remainder);
                        }
                        else
                        {
                            await APIHelper.DiscordAPI.SendMessageAsync(context.Channel, LM.Get("ESIFailure")).ConfigureAwait(false);

                            await LogHelper.LogError("ESI Failure", LogCat.AuthWeb).ConfigureAwait(false);
                        }

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx($"Error: {ex.Message}", ex, LogCat.AuthWeb).ConfigureAwait(false);
            }
        }