//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); }
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); } }
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(); } } }); }
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); }
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); }); } } }
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 = "" }); } } }
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; } }
// 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>(); }