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