Ejemplo n.º 1
0
        private void RegisterContentDirectory(IApplicationBuilder app, IHostingEnvironment env)
        {
            var contentPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(),
                                                            EnvVarManager.GetOrThrow("CONTENT_DIRECTORY")));

            if (!Directory.Exists(contentPath))
            {
                Console.WriteLine("Creating CONTENT_DIRECTORY: " + contentPath);
                Directory.CreateDirectory(contentPath);
            }

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider          = new PhysicalFileProvider(contentPath),
                RequestPath           = "/content",
                ServeUnknownFileTypes = true
            });
            if (env.IsDevelopment())
            {
                app.UseDirectoryBrowser(new DirectoryBrowserOptions
                {
                    FileProvider = new PhysicalFileProvider(contentPath),
                    RequestPath  = "/content"
                });
            }
        }
Ejemplo n.º 2
0
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var instanceTeamKey = EnvVarManager.Get("TEAM_KEY");

            if (string.IsNullOrEmpty(instanceTeamKey))
            {
                SetCustomResponse(context,
                                  "TEAM_KEY Environment variable not set on this API instance. Please ask the organizer to set it",
                                  500);
                return;
            }

            var headerTeamKey = context.HttpContext.Request.Headers["TEAM_KEY"];

            if (string.IsNullOrEmpty(headerTeamKey))
            {
                SetCustomResponse(context,
                                  "TEAM_KEY header not provided. This key is specific to your team and you should receive it from the organizers.",
                                  401);
                return;
            }

            if (headerTeamKey != instanceTeamKey)
            {
                SetCustomResponse(context,
                                  "Invalid TEAM_KEY header value. The provided TEAM_KEY header value differs from the TEAM_KEY set on this instance.",
                                  401);
            }
        }
Ejemplo n.º 3
0
//string connectionString = null
        public ApiBuilder UseMySql <T>() where T : DbContext
        {
            if (_useMySql)
            {
                throw new InvalidOperationException("UseMySql<T> already called on this ApiBuilder");
            }

            _useMySql = true;

            var connectionString =
                $"server={EnvVarManager.GetOrThrow("DB_SERVER")};" +
                $"port={EnvVarManager.GetOrThrow("DB_PORT")};" +
                $"database={EnvVarManager.GetOrThrow("DB_DATABASE")};" +
                $"uid={EnvVarManager.GetOrThrow("DB_USER")};" +
                $"password={EnvVarManager.Get("DB_PASSWORD")}";


            _connectionString = connectionString + (connectionString.EndsWith(";") ? "" : ";") +
                                "Persist Security Info=True;Convert Zero Datetime=True;charset=utf8";

            _addDbContextAction = services =>
            {
                services.AddDbContext <T>(optionsBuilder =>
                {
                    if (_useMySql)
                    {
                        PutMysql(optionsBuilder);
                    }

                    BaseDbContext.ConfigureBuilder = _registerEntityTypes;
                });
            };
            return(this);
        }
Ejemplo n.º 4
0
        private void AddCorsFromEnv(IApplicationBuilder app)
        {
            var corsHostsStr = EnvVarManager.Get("ALLOWED_CORS_HOSTS");

            if (string.IsNullOrEmpty(corsHostsStr))
            {
                return;
            }

            var corsHosts = corsHostsStr.Split(';');

            app.UseCors(builder =>
            {
                foreach (var corsHost in corsHosts)
                {
                    if (corsHost == "*")
                    {
                        builder = builder.AllowAnyOrigin().AllowAnyHeader();
                    }
                    else
                    {
                        builder = builder.WithOrigins(corsHost.Trim()).AllowAnyHeader();
                    }
                }
            });
        }
Ejemplo n.º 5
0
        private static string BuildBaseUrl(string path)
        {
            if (path == null || !Regex.IsMatch(path, @"^\/([a-zA-Z-]*\/)*$"))
            {
                throw new KnownException("invalid path prefix header (must have leading and trailing slash)", 400);
            }

            return($"{EnvVarManager.GetOrThrow("EXTERNAL_URL")}{path}");
        }
        public async Task <IActionResult> CreateCheckout([FromBody] CreateCheckoutRequestModel model,
                                                         [FromQuery] bool force = false)
        {
            var order = await GetOrderForBuyerToPayOrThrow(model);

            if (!string.IsNullOrEmpty(order.WePayCheckoutId) && !force)
            {
                throw new KnownException(
                          "Nu poți plăti această comandă. Există deja o cerere de plată asociată pe WePay.");
            }

            var wePayRequestBody = new
            {
                account_id        = WePayAccountId,
                amount            = order.TotalPrice / 4.33,
                short_description = "iTEC Shop: payment for order " + order.Id,
                type            = "goods",
                currency        = "USD",
                hosted_checkout = new
                {
                    redirect_uri = EnvVarManager.GetOrThrow("EXTERNAL_URL") + "/payment-redirect"
                }
            };
            var wePayRequestBodyJson =
                new StringContent(JsonConvert.SerializeObject(wePayRequestBody), Encoding.UTF8, "application/json");

            var response =
                await WePayHttpClient.PostAsync("https://stage.wepayapi.com/v2/checkout/create", wePayRequestBodyJson);

            var responseText = await response.Content.ReadAsStringAsync();

            try
            {
                response.EnsureSuccessStatusCode();
                var responseJson = JsonConvert.DeserializeObject <Dictionary <string, object> >(responseText);

                var checkoutId  = responseJson["checkout_id"].ToString();
                var checkoutUri = (responseJson["hosted_checkout"] as JObject)?["checkout_uri"].ToString();

                order.WePayCheckoutId = checkoutId;
                order.State           = OrderState.WaitingPayment;
                await DataLayer.SaveChangesAsync();

                return(Ok(new { checkoutId, checkoutUri }));
            }
            catch
            {
                Console.WriteLine(responseText);
                throw;
            }
        }
Ejemplo n.º 7
0
 public FrmEditEnvVarsTest()
 {
     varManager = new EnvVarManager();
     varManager.SetEnvironmentVariable(SYS_VAR_NAME, VAR_VALUE, EnvironmentVariableTarget.Machine);
     frmEdit           = new FrmEditEnvVar(SYS_VAR_NAME, EnvironmentVariableTarget.Machine);
     dgv               = frmEdit.DgView;
     btnTestDown       = new ButtonTester("btnMoveDown", frmEdit.Name);
     btnTestUp         = new ButtonTester("btnMoveUp", frmEdit.Name);
     btnTestSave       = new ButtonTester("btnSave", frmEdit.Name);
     btnTestMoveBottom = new ButtonTester("btnMoveBottom", frmEdit.Name);
     btnTestMoveTop    = new ButtonTester("btnMoveTop", frmEdit.Name);
     btnTestUndo       = new ButtonTester("btnUndo", frmEdit.Name);
     btnTestRedo       = new ButtonTester("btnRedo", frmEdit.Name);
     btnTestDelete     = new ButtonTester("btnDelete", frmEdit.Name);
     btnTestBrowse     = new ButtonTester("btnBrowse", frmEdit.Name);
     frmEdit.Show();
 }
        protected virtual void AddTmpViewsDirectory(IServiceCollection services)
        {
            var tmpViewsPath         = EnvVarManager.GetOrThrow("TEMPORARY_VIEWS_PATH");
            var sharedViewsDirectory = Path.Combine(tmpViewsPath, "Views", "Shared");

            if (!Directory.Exists(sharedViewsDirectory))
            {
                Console.WriteLine("Creating directory " + sharedViewsDirectory);
                Directory.CreateDirectory(sharedViewsDirectory);
            }

            var path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), tmpViewsPath));

//            Console.WriteLine("Temporary views in " + path);
            var fileProvider = new PhysicalFileProvider(path);

            services.Configure <RazorViewEngineOptions>(options => { options.FileProviders.Add(fileProvider); });
        }
Ejemplo n.º 9
0
        public override void ConfigureServices(IServiceCollection services)
        {
            base.ConfigureServices(services);
            services.AddTransient <IEmailSender, EmailSender.EmailSender>();
            services.AddTransient <IEmailHelper, EmailHelper>();

            services.AddOptions <SendGridCredentials>().Configure(sgc =>
            {
                var key = EnvVarManager.Get("SENDGRID_KEY");
                if (!string.IsNullOrEmpty(key))
                {
                    sgc.Key = key;
                }
                else
                {
                    sgc.Simulate = true;
                }
            });
        }
        private string GetViewDirectory(IGenerableView generableView)
        {
            var dir = "Views/" + generableView.GetType().Name.Replace("Controller", "");
            var assemblyShortName = generableView.GetType().Assembly.GetName().Name;
            var viewsAndWwwPaths  = EnvVarManager.Get("VIEWS_AND_WWW_PATHS");

            if (!string.IsNullOrEmpty(viewsAndWwwPaths))
            {
                foreach (var projectDirectory in viewsAndWwwPaths.Split(',', StringSplitOptions.RemoveEmptyEntries))
                {
                    if (Path.GetFileName(projectDirectory) == assemblyShortName)
                    {
                        dir = Path.Combine(projectDirectory, dir);
                    }
                }
            }

            return(dir);
        }
        public async Task <string> WriteAndGetViewName(string razorViewContent, string viewDirectory = null,
                                                       string viewName = null)
        {
            viewName      = viewName ?? "generated_" + DateTime.Now.Ticks + "_" + Utilis.GenerateRandomHexString(25);
            viewDirectory = viewDirectory ??
                            Path.Combine(EnvVarManager.GetOrThrow("TEMPORARY_VIEWS_PATH"), "Views/Shared");
            var viewPath =
                Path.Combine(viewDirectory, viewName + ".cshtml")
                .Replace("\\", "/");

            _generatedViewPath = viewPath;
            using (var fs = new FileStream(viewPath, FileMode.Create))
                using (var sw = new StreamWriter(fs))
                {
                    await sw.WriteAsync(razorViewContent);
                }

            return(viewName);
        }
Ejemplo n.º 12
0
        private void ConfigureJwtServices(IServiceCollection services)
        {
//            Console.WriteLine("AuthApiSpecifications.ConfigureJwtServices");
            services.AddSingleton <IJwtFactory, JwtFactory>();


            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(EnvVarManager.GetOrThrow("JWT_SECURITY_KEY")));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var audience = "http://localhost:5020";
            var issuer   = "http://localhost:5020";

            services.Configure <JwtOptions>(options =>
            {
                options.Audience          = audience;
                options.Issuer            = issuer;
                options.SignInCredentials = creds;
            });

//            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
            services.AddAuthentication()
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken            = false;
                options.Audience             = audience;

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = false,
                    ValidIssuer              = issuer,
                    ValidateAudience         = false,
                    ValidAudience            = audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    RequireExpirationTime    = false,
                    ValidateLifetime         = false,
                    ClockSkew = TimeSpan.FromMinutes(5)
                };
            });
//                .AddCookie(options => options.SlidingExpiration = true);
        }
Ejemplo n.º 13
0
        private void AddViewsFromEnvVar(IServiceCollection services)
        {
            var viewsAndWwwPaths = EnvVarManager.Get("VIEWS_AND_WWW_PATHS");

            if (!string.IsNullOrEmpty(viewsAndWwwPaths))
            {
                foreach (var projectDirectory in viewsAndWwwPaths.Split(',', StringSplitOptions.RemoveEmptyEntries))
                {
                    var path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), projectDirectory));
                    if (!Directory.Exists(path))
                    {
                        continue;
                    }

//                    Console.WriteLine("Views in " + path);
                    var fileProvider = new PhysicalFileProvider(path);
                    services.Configure <RazorViewEngineOptions>(options => { options.FileProviders.Add(fileProvider); });
                }
            }
        }
Ejemplo n.º 14
0
        public async Task <FileEntity> Upload(IFormFile file)
        {
            var subDir = "upload/files";
            var uploadedFilesDirectory =
                Path.Combine(EnvVarManager.GetOrThrow("CONTENT_DIRECTORY"), subDir).Replace("\\", "/");

//            Console.WriteLine("Creating directory...");
            if (!Directory.Exists(uploadedFilesDirectory))
            {
                Logger.LogInfo("Creating files directory: " + uploadedFilesDirectory);
                Directory.CreateDirectory(uploadedFilesDirectory);
            }

            var fileEntity = new FileEntity
            {
                Name         = SanitizeFileName(file.FileName) + "_" + Utilis.GenerateRandomHexString(10),
                Extension    = Path.GetExtension(file.FileName).Substring(1).ToLower(),
                OriginalName = file.FileName,
                Size         = (int)file.Length,
                SubDirectory = subDir
            };


            var filePath = Path.Combine(uploadedFilesDirectory, $"{fileEntity.Name}.{fileEntity.Extension}")
                           .Replace("\\", "/");

//            Console.WriteLine("Saving file...");
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            fileEntity.Path = filePath;

            await DataLayer.Repo <FileEntity>().Add(fileEntity);

            return(fileEntity);
        }
Ejemplo n.º 15
0
        private void AddWwwRootsFromEnvVar(IApplicationBuilder app)
        {
            var viewsAndWwwPaths = EnvVarManager.Get("VIEWS_AND_WWW_PATHS");

            if (!string.IsNullOrEmpty(viewsAndWwwPaths))
            {
                foreach (var projectDirectory in viewsAndWwwPaths.Split(',', StringSplitOptions.RemoveEmptyEntries))
                {
                    var path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), projectDirectory,
                                                             "wwwroot"));
                    if (!Directory.Exists(path))
                    {
                        continue;
                    }

//                    Console.WriteLine("using: " + path);
                    app.UseStaticFiles(new StaticFileOptions()
                    {
                        FileProvider = new PhysicalFileProvider(path), RequestPath = ""
                    });
                }
            }
        }
Ejemplo n.º 16
0
        internal LogManager()
        {
            _directory = EnvVarManager.Get("LOGS_DIRECTORY") ?? "../logs";
            _logQueue  = new ConcurrentQueue <string>();
            try
            {
//                Console.WriteLine("using log directory: " + _directory);
                if (!Directory.Exists(_directory))
                {
                    Console.WriteLine($"creating dir: '{_directory}'");
                    Directory.CreateDirectory(_directory);
                }

                CreateStreamWriter();
                _flushThread = new Thread(async() => { await WorkerMethod(); });
                _flushThread.Start();
            }
            catch (Exception exc)
            {
                Console.WriteLine($"LogManager.constructor Exception: {exc.Message} for dir '{_directory}'");
                throw;
            }
        }
Ejemplo n.º 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString =
                $"server={EnvVarManager.GetOrThrow("DB_SERVER")};" +
                $"port={EnvVarManager.GetOrThrow("DB_PORT")};" +
                $"database={EnvVarManager.GetOrThrow("DB_DATABASE")};" +
                $"uid={EnvVarManager.GetOrThrow("DB_USER")};" +
                $"password={EnvVarManager.Get("DB_PASSWORD")}";

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <ApplicationDbContext>(op => op.UseMySql(connectionString));
            services.AddDefaultIdentity <User>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "iTEC Mobile API", Version = "v1.0"
                });

                c.SchemaFilter <ReadOnlyFilter>();

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description =
                        "JWT Authorization header using Bearer scheme ('Bearer {token}' - don't forget the prefix!)",
                    Name = "Authorization",
                    In   = "header",
                    Type = "apiKey",
                });

                c.AddSecurityDefinition("TEAM_KEY", new ApiKeyScheme
                {
                    Description = "This key is specific to your team and you should receive it from the organizers.",
                    Name        = "TEAM_KEY",
                    In          = "header",
                    Type        = "apiKey",
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
                c.EnableAnnotations();

                c.OperationFilter <AuthorizationHeaderParameterOperationFilter>();
                c.OperationFilter <TeamKeyHeaderOperationFilter>();
            });

            // Ensure JWT
            var jwtOptions = new JwtOptions();

            Configuration.Bind(nameof(jwtOptions), jwtOptions);
            services.AddSingleton(jwtOptions);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtOptions.Secret)),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    RequireExpirationTime    = false,
                    ValidateLifetime         = true
                };
            });
            // END JWT

            services.AddMvc(options => { options.Filters.Add <TeamKeyAuthorizationFilter>(); })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));
            services.AddScoped <IIdentityService, IdentityService>();
        }
Ejemplo n.º 18
0
 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
 .UseStartup <Startup>()
 .ConfigureAppConfiguration((context, builder) => { builder.AddJsonFile("appsettings.json", false); })
 .UseUrls("http://0.0.0.0:" + EnvVarManager.GetOrThrow("LISTEN_PORT"));
Ejemplo n.º 19
0
        public ApiBuilder BuildApp(IApplicationBuilder app, IHostingEnvironment env,
                                   IApplicationLifetime applicationLifetime, IDataSeeder seeder, IServiceProvider serviceProvider)
        {
            if (_useSwagger)
            {
                new ApiBuilderSwaggerHelper(_swaggerSpecs).Bind(app, env);
            }

            foreach (var apiSpecifications in _specifications)
            {
                apiSpecifications.ConfigureApp(app, serviceProvider);
            }

            var shouldMigrate  = _configuration.GetValue <bool>("migrate");
            var shouldLoadSeed = _configuration.GetValue <bool>("seed");

            if (shouldMigrate)
            {
                Console.WriteLine("Migrating...");
                seeder.MigrateDatabase().Wait();
                Console.WriteLine("Migrating done.");
                if (!shouldLoadSeed)
                {
                    applicationLifetime.StopApplication();
                }
            }
            else
            {
                seeder.EnsureMigrated().Wait();
            }

            if (shouldLoadSeed)
            {
                Console.WriteLine("Seeding data...");
                seeder.LoadSeed().Wait();
                Console.WriteLine("Seeding done.");
                applicationLifetime.StopApplication();
            }


            var generateSeed = _configuration.GetValue <string>("generate-seed");

            if (generateSeed != null)
            {
                Console.WriteLine("Generating seed...");
                seeder.SeedToFile(generateSeed).Wait();
                Console.WriteLine("Generating seed done.");
                applicationLifetime.StopApplication();
            }

            var adminEmail = _configuration.GetValue <string>("give-admin");

            if (adminEmail != null)
            {
                Console.WriteLine("Giving admin to " + adminEmail + "...");
                var userManager = serviceProvider.GetService <UserManager <User> >();
                var user        = userManager.FindByEmailAsync(adminEmail).Result;
                userManager.AddToRoleAsync(user, "Admin").Wait();
                userManager.AddToRoleAsync(user, "Staff").Wait();
                userManager.AddToRoleAsync(user, "Moderator").Wait();
                userManager.AddToRoleAsync(user, "User").Wait();
                Console.WriteLine("Done.");

                applicationLifetime.StopApplication();
            }

            // assert that variable is set correctly
            if (EnvVarManager.GetOrThrow("EXTERNAL_URL").EndsWith('/') ||
                !EnvVarManager.GetOrThrow("EXTERNAL_URL").Contains("http"))
            {
                throw new Exception("EXTERNAL_URL must include protocol and must not end with /");
            }

            return(this);
        }