Inheritance: MonoBehaviour
        public Facebook()
        {
            _secrets = SecretsClient.Get("facebook");
            _restClient = new RestClient("https://graph.facebook.com");

            AccessToken = Configuration.FacebookToken;
        }
Beispiel #2
0
 public void Setup() {
     secrets = Secrets.LoadFromFile("aws.secrets");
     var config = new SimolConfig {
         AutoCreateDomains = true,
         Cache = null,
         ReadConsistency = ConsistencyBehavior.Immediate
     };
     simolClient = new SimolClient(secrets.AwsAccessKeyId, secrets.AwsSecretAccessKey, config);
 }
Beispiel #3
0
        public void Secrets_werden_gelesen() {
            var sut = new Secrets {
                AwsAccessKeyId = "xyz",
                AwsSecretAccessKey = "abc"
            };

            sut.SaveToFile("aws.secrets");

            var secrets = Secrets.LoadFromFile("aws.secrets");

            Assert.That(secrets.AwsAccessKeyId, Is.EqualTo("xyz"));
            Assert.That(secrets.AwsSecretAccessKey, Is.EqualTo("abc"));
        }
Beispiel #4
0
 public void Setup() {
     secrets = Secrets.LoadFromFile("aws.secrets");
     simolClient = new SimolClient(secrets.AwsAccessKeyId, secrets.AwsSecretAccessKey);
 }
 public ARMValidator(IRestValidateCheck restChecker, ITemplateBuilder templateBuilder, IOptions <Secrets> options)
 {
     _restChecker     = restChecker;
     _templateBuilder = templateBuilder;
     _secrets         = options.Value;
 }
 public RedditService(Secrets secrets)
 {
     _client = new RedditClient(secrets.RedditAppID, secrets.RefreshToken, secrets.RedditAppSecret, secrets.AccessToken);
     exurb1a = _client.Subreddit("Exurb1a").About();
     Configure();
 }
Beispiel #7
0
        public async Task RunAtTimeOf(DateTime now)
        {
            var config = _ctx.JobGettingConfig.FirstOrDefault();

            if (config == null)
            {
                return;
            }
            _logger.LogInformation("KeyPhraseGeneratorJob Job Starts... ");

            string connectionString = Secrets.GetDBConnectionString(_configuration);

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                MySqlCommand command = new MySqlCommand(@"
                   SELECT `JobPostings`.Id, `JobPostings`.Description FROM `jobtransparency`.`JobPostings`
                  WHERE `JobPostings`.Id NOT IN(SELECT `KeyPhrase`.JobPostingId FROM `jobtransparency`.`KeyPhrase`)", connection);
                command.CommandTimeout = config.SQLCommandTimeOut;

                try
                {
                    connection.Open();
                    var reader = await command.ExecuteReaderAsync();

                    while (reader.Read())
                    {
                        var Description = (string)reader[1];
                        var Id          = (int)reader[0];
                        if (Description.Length <= 5)
                        {
                            continue;
                        }

                        Description = new string(Description.Where(c => !char.IsPunctuation(c)).ToArray());

                        KeyPhrasesWrapperDTO wrapper = await _NLTKService.ExtractKeyPhrases(Description);

                        if (wrapper != null && wrapper.rank_list != null && wrapper.rank_list.Count > 0)
                        {
                            List <KeyPhrase> ListKeyPhrase = new List <KeyPhrase>();
                            _logger.LogInformation("List<KeyPhrase> ListKeyPhrase");
                            foreach (KeyPhraseDTO item in wrapper.rank_list)
                            {
                                if (item.Affinty > config.MinAffintyScore)
                                {
                                    ListKeyPhrase.Add(new KeyPhrase
                                    {
                                        Affinty      = item.Affinty,
                                        Text         = item.Text,
                                        JobPostingId = Id
                                    });
                                }


                                _logger.LogInformation($"item.Affinty {item.Affinty}");
                                _logger.LogInformation($"item.Text {item.Text}");
                            }

                            _KeyPharseRepository.CreateKeyPhrases(ListKeyPhrase);
                            _logger.LogInformation("_KeyPharseRepository.CreateKeyPhrases(ListKeyPhrase);");
                        }
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "KeyPhraseGeneratorJob Ends... ");
                }
            }

            _logger.LogInformation("KeyPhraseGeneratorJob Ends... ");
        }
        static void FullClientExample()
        {
            //Create a new DiscordRpcClient. We are filling some of the defaults as examples.
            using (client = new DiscordRpcClient("424087019149328395",                              //The client ID of your Discord Application
                                                 pipe: discordPipe,                                 //The pipe number we can locate discord on. If -1, then we will scan.
                                                 logger: new Logging.ConsoleLogger(logLevel, true), //The loger to get information back from the client.
                                                 autoEvents: true,                                  //Should the events be automatically called?
                                                 client: new IO.ManagedNamedPipeClient()            //The pipe client to use. Required in mono to be changed.
                                                 ))
            {
                //If you are going to make use of the Join / Spectate buttons, you are required to register the URI Scheme with the client.
                client.RegisterUriScheme();

                //Set the logger. This way we can see the output of the client.
                //We can set it this way, but doing it directly in the constructor allows for the Register Uri Scheme to be logged too.
                //System.IO.File.WriteAllBytes("discord-rpc.log", new byte[0]);
                //client.Logger = new Logging.FileLogger("discord-rpc.log", DiscordLogLevel);

                //Register to the events we care about. We are registering to everyone just to show off the events

                client.OnReady += OnReady;                                      //Called when the client is ready to send presences
                client.OnClose += OnClose;                                      //Called when connection to discord is lost
                client.OnError += OnError;                                      //Called when discord has a error

                client.OnConnectionEstablished += OnConnectionEstablished;      //Called when a pipe connection is made, but not ready
                client.OnConnectionFailed      += OnConnectionFailed;           //Called when a pipe connection failed.

                client.OnPresenceUpdate += OnPresenceUpdate;                    //Called when the presence is updated

                client.OnSubscribe   += OnSubscribe;                            //Called when a event is subscribed too
                client.OnUnsubscribe += OnUnsubscribe;                          //Called when a event is unsubscribed from.

                client.OnJoin          += OnJoin;                               //Called when the client wishes to join someone else. Requires RegisterUriScheme to be called.
                client.OnSpectate      += OnSpectate;                           //Called when the client wishes to spectate someone else. Requires RegisterUriScheme to be called.
                client.OnJoinRequested += OnJoinRequested;                      //Called when someone else has requested to join this client.

                //Before we send a initial presence, we will generate a random "game ID" for this example.
                // For a real game, this "game ID" can be a unique ID that your Match Maker / Master Server generates.
                // This is used for the Join / Specate feature. This can be ignored if you do not plan to implement that feature.
                presence.Secrets = new Secrets()
                {
                    //These secrets should contain enough data for external clients to be able to know which
                    // game to connect too. A simple approach would be just to use IP address, but this is highly discouraged
                    // and can leave your players vulnerable!
                    JoinSecret     = "join_myuniquegameid",
                    SpectateSecret = "spectate_myuniquegameid"
                };

                //We also need to generate a initial party. This is because Join requires the party to be created too.
                // If no party is set, the join feature will not work and may cause errors within the discord client itself.
                presence.Party = new Party()
                {
                    ID   = Secrets.CreateFriendlySecret(new Random()),
                    Size = 1,
                    Max  = 4
                };

                //Give the game some time so we have a nice countdown
                presence.Timestamps = new Timestamps()
                {
                    Start = DateTime.UtcNow,
                    End   = DateTime.UtcNow + TimeSpan.FromSeconds(15)
                };

                //Subscribe to the join / spectate feature.
                //These require the RegisterURI to be true.
                client.SetSubscription(EventType.Join | EventType.Spectate | EventType.JoinRequest);        //This will alert us if discord wants to join a game

                //Set some new presence to tell Discord we are in a game.
                // If the connection is not yet available, this will be queued until a Ready event is called,
                // then it will be sent. All messages are queued until Discord is ready to receive them.
                client.SetPresence(presence);

                //Initialize the connection. This must be called ONLY once.
                //It must be called before any updates are sent or received from the discord client.
                client.Initialize();

                //Start our main loop. In a normal game you probably don't have to do this step.
                // Just make sure you call .Invoke() or some other dequeing event to receive your events.
                MainLoop();
            }
        }
Beispiel #9
0
 public AuthorizeMiddleware(IOptions <Secrets> secrets, RequestDelegate next)
 {
     _secrets = secrets.Value;
     _next    = next;
 }
Beispiel #10
0
 public void ClearSecrets()
 {
     Secrets.Clear();
     Log.Info("Cleared secrets");
 }
Beispiel #11
0
 public override void Reset()
 {
     base.Reset();
     Secrets.Clear();
     OnSecretsChanged?.Invoke(new List <Card>());
 }
Beispiel #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var config = new Secrets();

            config.JWTSecret     = Configuration["JwtSecret"];
            config.SmtpEmailFrom = Configuration["SmtpEmailFrom"];
            config.SmtpHost      = Configuration["SmtpHost"];
            config.SmtpPort      = Configuration["SmtpPort"];
            config.SmtpUser      = Configuration["SmtpUser"];
            config.SmtpPass      = Configuration["SmtpPass"];
            config.DatoCmsBearer = Configuration["DatoCmsBearer"];
            services.AddSingleton <Secrets>(config);

            // Connection string
            var builder = new Npgsql.NpgsqlConnectionStringBuilder(
                Configuration.GetConnectionString("DefaultConnection"));

            builder.Password = Configuration["DbPassword"];
            builder.Username = Configuration["DBUserId"];
            builder.Database = Configuration["DBDatabase"];
            builder.Port     = int.Parse(Configuration["DBPort"]);
            builder.Pooling  = bool.Parse(Configuration["DBPooling"]);
            builder.Host     = Configuration["DBServer"];
            _connection      = builder.ConnectionString;

            services.AddControllers().AddNewtonsoftJson(s =>
            {
                s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddScoped <IOrganisationService, OrganisationService>();
            services.AddScoped <IAuthService, AuthService>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ILeagueService, LeagueService>();
            services.AddScoped <IFreehandMatchService, FreehandMatchService>();
            services.AddScoped <IFreehandGoalsService, FreehandGoalsService>();
            services.AddScoped <IFreehandDoubleMatchService, FreehandDoubleMatchService>();
            services.AddScoped <IFreehandDoubleGoalService, FreehandDoubleGoalService>();
            services.AddScoped <ISingleLeagueMatchService, SingleLeagueMatchService>();
            services.AddScoped <ISingleLeagueGoalService, SingleLeagueGoalService>();
            services.AddScoped <IDoubleLeagueTeamService, DoubleLeagueTeamService>();
            services.AddScoped <IDoubleLeaugeMatchService, DoubleLeaugeMatchService>();
            services.AddScoped <IDoubleLeaguePlayerService, DoubleLeaguePlayerService>();
            services.AddScoped <IDoubleLeagueGoalService, DoubleLeagueGoalService>();
            services.AddScoped <ICmsService, CmsService>();
            services.AddDbContext <DataContext>(p => p.UseNpgsql(builder.ConnectionString));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Foosball Api", Version = "v1"
                });

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "JWT Authorization header using the Bearer scheme."
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });
            });

            var key = Encoding.ASCII.GetBytes(config.JWTSecret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
                        var userId      = int.Parse(context.Principal.Identity.Name);
                        var user        = userService.GetUserById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return(Task.CompletedTask);
                    }
                };
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
        }
Beispiel #13
0
        public static void Main(string[] args)
        {
            IConfiguration configuration = null;

            try
            {
                configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json", optional: false)
                                .Build();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri($"{Secrets.GetConnectionString(configuration, "ElasticIndexBaseUrl")}"))
            {
                AutoRegisterTemplate     = true,
                ModifyConnectionSettings = x => x.BasicAuthentication(
                    Secrets.GetAppSettingsValue(configuration, "ELASTIC_USERNAME_Search"), Secrets.GetAppSettingsValue(configuration, "ELASTIC_PASSWORD_Search")),
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
                IndexFormat = $"{Secrets.GetAppSettingsValue(configuration, "AppName")}" + "-{0:yyyy.MM}"
            })
                         .CreateLogger();

            try
            {
                Log.Information("Starting up");
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Beispiel #14
0
        void SetStatus(DiscordState state, string details = null, string secret = null, int?players = null, int?slots = null)
        {
            if (currentState == state)
            {
                return;
            }

            if (instance == null)
            {
                return;
            }

            string   stateText;
            DateTime?timestamp = null;
            Party    party     = null;
            Secrets  secrets   = null;

            switch (state)
            {
            case DiscordState.InMenu:
                stateText = "In menu";
                break;

            case DiscordState.InMapEditor:
                stateText = "In Map Editor";
                break;

            case DiscordState.InSkirmishLobby:
                stateText = "In Skirmish Lobby";
                break;

            case DiscordState.InMultiplayerLobby:
                stateText = "In Multiplayer Lobby";
                timestamp = DateTime.UtcNow;
                party     = new Party
                {
                    ID   = Secrets.CreateFriendlySecret(new Random()),
                    Size = players.Value,
                    Max  = slots.Value
                };
                secrets = new Secrets
                {
                    JoinSecret = secret
                };
                break;

            case DiscordState.PlayingMultiplayer:
                stateText = "Playing Multiplayer";
                timestamp = DateTime.UtcNow;
                break;

            case DiscordState.PlayingCampaign:
                stateText = "Playing Campaign";
                timestamp = DateTime.UtcNow;
                break;

            case DiscordState.WatchingReplay:
                stateText = "Watching Replay";
                timestamp = DateTime.UtcNow;
                break;

            case DiscordState.PlayingSkirmish:
                stateText = "Playing Skirmish";
                timestamp = DateTime.UtcNow;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(state), state, null);
            }

            var richPresence = new RichPresence
            {
                Details = details,
                State   = stateText,
                Assets  = new Assets
                {
                    LargeImageKey  = "large",
                    LargeImageText = Game.ModData.Manifest.Metadata.Title,
                },
                Timestamps = timestamp.HasValue ? new Timestamps(timestamp.Value) : null,
                Party      = party,
                Secrets    = secrets
            };

            client.SetPresence(richPresence);
            currentState = state;
        }
Beispiel #15
0
        public ActionResult Hook()
        {
            var eventType = Request.Headers["X-Github-Event"];
            var signature = Request.Headers["X-Hub-Signature"].Substring(5);


            var ms = new MemoryStream();

            Request.InputStream.CopyTo(ms);
            byte[] data = ms.ToArray();

            var secretKey = new Secrets().GetGithubHookKey();
            var hash      = new HMACSHA1(Encoding.ASCII.GetBytes(secretKey)).ComputeHash(data);

            if (!string.Equals(hash.ToHex(), signature, StringComparison.InvariantCultureIgnoreCase))
            {
                return(Content("Signature does not match"));
            }

            dynamic payload = JObject.Parse(Encoding.UTF8.GetString(data));

            string text    = null;
            string channel = "zkdev";

            Object[] values;

            switch (eventType)
            {
            case "issues":
                if (payload.action == "labeled")
                {
                    break;
                }
                if (payload.repository.name == "CrashReports")
                {
                    channel = "crashreports";
                }
                values = new [] { payload.repository.name, payload.sender.login, payload.action, payload.issue.title, payload.issue.html_url };
                text   = string.Format("[{0}] {1} has {2} issue {3} <{4}>", values);
                break;

            case "pull_request":
                values = new [] { payload.repository.name, payload.sender.login, payload.action, payload.number, payload.pull_request.title, payload.pull_request.html_url, payload.pull_request.body };
                text   = string.Format("[{0}] {1} has {2} pull request #{3}: {4} <{5}>\n{6}", values);
                break;

            case "push":
                if (payload["ref"] != "refs/heads/master" &&
                    payload["ref"] != "refs/heads/stable")
                {
                    break;
                }

                var     sb      = new StringBuilder();
                int     count   = 0;
                dynamic commits = payload.commits;
                foreach (dynamic commit in commits)
                {
                    sb.AppendFormat("\n {0} <{1}>", commit.message, commit.url);
                    count++;
                }
                if (count > 0)
                {
                    text = $"[{payload.repository.name}] {payload.sender.login} has pushed {count} commits: {sb}";
                }
                break;
            }

            if (text != null)
            {
                Global.Server.GhostChanSay(channel, text);
            }

            return(Content(""));
        }
Beispiel #16
0
 public AuthService(DataContext context, Secrets secrets)
 {
     _context = context;
     _secrets = secrets;
 }
Beispiel #17
0
 public UnicornHabit(Secrets secrets, CancellationToken cancel)
 {
     this.cancel      = cancel;
     this.redisPool   = new RedisManagerPool(secrets.RedisToken);
     this.rabbitToken = secrets.RabbitToken;
 }