Example #1
0
        public void CanWeAuthorizeStatic()
        {
            var result = B2Client.Authorize(Options);

            Console.WriteLine(JsonConvert.SerializeObject(result));
            Assert.IsFalse(string.IsNullOrEmpty(result.AuthorizationToken));
        }
Example #2
0
        public void CanWeAuthorizeNonMasterKey()
        {
            var result = B2Client.Authorize(applicationKeyId, applicationKey);

            Console.WriteLine(JsonConvert.SerializeObject(result));
            Assert.IsFalse(string.IsNullOrEmpty(result.AuthorizationToken));
        }
Example #3
0
        public void CreateBucketWithCacheControlTest()
        {
            var name   = "B2NETTestingBucket";
            var client = new B2Client(Options);

            Options = client.Authorize().Result;

            var bucket = client.Buckets.Create(name, new B2BucketOptions()
            {
                CacheControl = 600
            }).Result;

            // Get bucket to check for info
            var bucketList = client.Buckets.GetList().Result;

            // Clean up
            if (!string.IsNullOrEmpty(bucket.BucketId))
            {
                client.Buckets.Delete(bucket.BucketId).Wait();
            }

            var savedBucket = bucketList.FirstOrDefault(b => b.BucketName == bucket.BucketName);

            Assert.IsNotNull(savedBucket, "Retreived bucket was null");
            Assert.IsNotNull(savedBucket.BucketInfo, "Bucekt info was null");
            Assert.IsTrue(savedBucket.BucketInfo.ContainsKey("cache-control"), "Bucket info did not contain Cache-Control");
            Assert.AreEqual("max-age=600", savedBucket.BucketInfo["cache-control"], "Cache-Control values were not equal.");
        }
Example #4
0
        public void UpdateBucketTest()
        {
            var name   = "B2NETUpdateBucket";
            var client = new B2Client(Options);

            Options = client.Authorize().Result;

            //Creat a bucket to delete
            var bucket = client.Buckets.Create(name, BucketTypes.allPrivate).Result;

            try {
                if (!string.IsNullOrEmpty(bucket.BucketId))
                {
                    var updatedBucket = client.Buckets.Update(BucketTypes.allPublic, bucket.BucketId).Result;
                    Assert.AreEqual(BucketTypes.allPublic.ToString(), updatedBucket.BucketType);
                }
                else
                {
                    Assert.Fail("The bucket was not deleted. The response did not contain a bucketid.");
                }
            } catch (Exception ex) {
                Assert.Fail(ex.Message);
            } finally {
                client.Buckets.Delete(bucket.BucketId).Wait();
            }
        }
Example #5
0
        public B2StorageProvider(IConfiguration config, ILogger <B2StorageProvider> logger)
        {
            _b2Options = new B2Options()
            {
                AccountId      = config["Auth:B2:AccountId"],
                KeyId          = config["Auth:B2:KeyId"],
                ApplicationKey = config["Auth:B2:AppKey"],
                BucketId       = config["Auth:B2:BucketId"],
                PersistBucket  = true
            };

            // if backblaze isn't fully configured
            if (string.IsNullOrEmpty(_b2Options.AccountId) ||
                string.IsNullOrEmpty(_b2Options.KeyId) ||
                string.IsNullOrEmpty(_b2Options.ApplicationKey) ||
                string.IsNullOrEmpty(_b2Options.BucketId))
            {
                throw new InvalidOperationException("Backblaze not fully configured.");
            }

            _client = new B2Client(B2Client.Authorize(_b2Options));
            _logger = logger;

            _bucketName = _client.Buckets.GetList().Result
                          .Single(b => b.BucketId == _b2Options.BucketId)
                          .BucketName;
        }
Example #6
0
        public void Initialize()
        {
            Client  = new B2Client(Options);
            Options = Client.Authorize().Result;

            var      buckets        = Client.Buckets.GetList().Result;
            B2Bucket existingBucket = null;

            foreach (B2Bucket b2Bucket in buckets)
            {
                if (b2Bucket.BucketName == "B2NETTestingBucket")
                {
                    existingBucket = b2Bucket;
                }
            }

            if (existingBucket != null)
            {
                TestBucket = existingBucket;
            }
            else
            {
                TestBucket = Client.Buckets.Create("B2NETTestingBucket", BucketTypes.allPrivate).Result;
            }
        }
Example #7
0
        private async Task AuthorizeInner()
        {
            await _b2Client.Authorize().ConfigureAwait(false);

            lock (_authorizingLock) {
                _authorizing = null;
            }
        }
Example #8
0
        public void CanWeAuthorize()
        {
            var client = new B2Client(Options);

            var result = client.Authorize().Result;

            Assert.IsFalse(string.IsNullOrEmpty(result.AuthorizationToken));
        }
Example #9
0
 public void BadInitialization()
 {
     // Missing AccountId
     var client = new B2Client(B2Client.Authorize(new B2Options()
     {
         KeyId          = applicationKeyId,
         ApplicationKey = applicationKey
     }));
 }
Example #10
0
        public void DoWeGetCapabilitiesOnApplicationKey()
        {
            var result = B2Client.Authorize(applicationKeyId, applicationKey);

            Assert.IsFalse(string.IsNullOrEmpty(result.AuthorizationToken));

            Assert.IsNotNull(result.Capabilities);
            Assert.IsNotNull(result.Capabilities.Capabilities);
        }
Example #11
0
 public void BadInitialization()
 {
     // Missing AccountId
     var client = new B2Client(B2Client.Authorize(new B2Options()
     {
         KeyId          = "00151189a8b4c7a0000000006",
         ApplicationKey = "K001+GGkBNcbJVj3LD4+e3s5pCUMQ7U"
     }));
 }
Example #12
0
        public void DoWeGetOptionsBack()
        {
            var result = B2Client.Authorize(Options);

            Assert.AreNotEqual("0", result.AbsoluteMinimumPartSize);
            Assert.AreNotEqual("0", result.MinimumPartSize);
            Assert.AreNotEqual("0", result.RecommendedPartSize);
            Assert.IsFalse(string.IsNullOrEmpty(result.DownloadUrl));
            Assert.IsFalse(string.IsNullOrEmpty(result.ApiUrl));
        }
Example #13
0
        public async Task GetBucketListTest()
        {
            // Key that is restricted to a specific bucket name above.
            var client = new B2Client(B2Client.Authorize(new B2Options()
            {
                KeyId          = restrictedApplicationKeyId,
                ApplicationKey = restrictedApplicationKey
            }));

            BucketName = $"B2NETTestingBucket-{Path.GetRandomFileName().Replace(".", "").Substring(0, 6)}";

            var bucket = await client.Buckets.Create(BucketName, BucketTypes.allPrivate);
        }
Example #14
0
        public void UpdateBucketWithLifecycleRulesTest()
        {
            var name   = "B2NETTestingBucket";
            var client = new B2Client(Options);

            Options = client.Authorize().Result;

            var bucket = client.Buckets.Create(name, new B2BucketOptions()
            {
                LifecycleRules = new System.Collections.Generic.List <B2BucketLifecycleRule>()
                {
                    new B2BucketLifecycleRule()
                    {
                        DaysFromHidingToDeleting  = 30,
                        DaysFromUploadingToHiding = 15,
                        FileNamePrefix            = "testing"
                    }
                }
            }).Result;

            // Update bucket with new info
            bucket = client.Buckets.Update(new B2BucketOptions()
            {
                LifecycleRules = new System.Collections.Generic.List <B2BucketLifecycleRule>()
                {
                    new B2BucketLifecycleRule()
                    {
                        DaysFromHidingToDeleting  = 10,
                        DaysFromUploadingToHiding = 10,
                        FileNamePrefix            = "tested"
                    }
                }
            }, bucket.BucketId).Result;

            // Get bucket to check for info
            var bucketList = client.Buckets.GetList().Result;

            // Clean up
            if (!string.IsNullOrEmpty(bucket.BucketId))
            {
                client.Buckets.Delete(bucket.BucketId).Wait();
            }

            var savedBucket = bucketList.FirstOrDefault(b => b.BucketName == bucket.BucketName);

            Assert.IsNotNull(savedBucket, "Retreived bucket was null");
            Assert.IsNotNull(savedBucket.BucketInfo, "Bucekt info was null");
            Assert.AreEqual(savedBucket.LifecycleRules.Count, 1, "Lifecycle rules count was " + savedBucket.LifecycleRules.Count);
            Assert.AreEqual("tested", savedBucket.LifecycleRules.First().FileNamePrefix, "File name prefixes in the first lifecycle rule were not equal.");
        }
Example #15
0
        public void GetBucketListTest()
        {
            var client = new B2Client(Options);

            Options = client.Authorize().Result;

            var bucket = client.Buckets.Create("B2NETTestingBucket", BucketTypes.allPrivate).Result;

            var list = client.Buckets.GetList().Result;

            var deletedBucket = client.Buckets.Delete(bucket.BucketId).Result;

            Assert.AreNotEqual(0, list.Count);
        }
Example #16
0
        public async Task GetBucketListTest()
        {
            // Key that is restricted to RestrictedBucketName above.
            var client = new B2Client(B2Client.Authorize(new B2Options()
            {
                AccountId      = TestConstants.AccountId,
                KeyId          = "00151189a8b4c7a0000000006",
                ApplicationKey = "K001+GGkBNcbJVj3LD4+e3s5pCUMQ7U"
            }));

            BucketName = $"B2NETTestingBucket-{Path.GetRandomFileName().Replace(".", "").Substring(0, 6)}";

            var bucket = await client.Buckets.Create(BucketName, BucketTypes.allPrivate);
        }
Example #17
0
        /// <summary>
        /// connect to b2.
        /// </summary>
        public void authorize()
        {
            var opts = new B2Net.Models.B2Options
            {
                KeyId            = _opts.AccountId
                , ApplicationKey = _opts.ApplicationKey
            };

            _client = new B2Client(opts);

            _opts = _client.Authorize().Result;
            account.auth["AuthorizationToken"]  = _opts.AuthorizationToken;
            account.auth["DownloadUrl"]         = _opts.DownloadUrl;
            account.auth["ApiUrl"]              = _opts.ApiUrl;
            account.auth["MinPartSize"]         = string.Format("{0:n}", _opts.AbsoluteMinimumPartSize);
            account.auth["RecommendedPartSize"] = string.Format("{0:n}", _opts.RecommendedPartSize);
        }
Example #18
0
        public void CreateBucketTest()
        {
            var name   = "B2NETTestingBucket";
            var client = new B2Client(Options);

            Options = client.Authorize().Result;

            var bucket = client.Buckets.Create(name, BucketTypes.allPrivate).Result;

            // Clean up
            if (!string.IsNullOrEmpty(bucket.BucketId))
            {
                client.Buckets.Delete(bucket.BucketId).Wait();
            }

            Assert.AreEqual(name, bucket.BucketName);
        }
Example #19
0
        public void DeleteBucketTest()
        {
            var name   = "B2NETDeleteBucket";
            var client = new B2Client(Options);

            Options = client.Authorize().Result;

            //Creat a bucket to delete
            var bucket = client.Buckets.Create(name, BucketTypes.allPrivate).Result;

            if (!string.IsNullOrEmpty(bucket.BucketId))
            {
                var deletedBucket = client.Buckets.Delete(bucket.BucketId).Result;
                Assert.AreEqual(name, deletedBucket.BucketName);
            }
            else
            {
                Assert.Fail("The bucket was not deleted. The response did not contain a bucketid.");
            }
        }
Example #20
0
        public void Initialize()
        {
            Client     = new B2Client(B2Client.Authorize(Options));
            BucketName = $"B2NETTestingBucket-{Path.GetRandomFileName().Replace(".", "").Substring(0, 6)}";
            var      buckets        = Client.Buckets.GetList().Result;
            B2Bucket existingBucket = null;

            foreach (B2Bucket b2Bucket in buckets)
            {
                if (b2Bucket.BucketName == BucketName)
                {
                    existingBucket = b2Bucket;
                }
            }

            if (existingBucket != null)
            {
                TestBucket = existingBucket;
            }
            else
            {
                TestBucket = Client.Buckets.Create(BucketName, BucketTypes.allPrivate).Result;
            }
        }
Example #21
0
        public void ErrorAuthorizeNonMasterKeyWithMissingKeyID()
        {
            var key = "K001LarMmmWDIveFaZz3yvB4uattO+Q";

            var result = B2Client.Authorize("", key);
        }
Example #22
0
        public void CanWeAuthorizeNonMasterKey()
        {
            var result = B2Client.Authorize(TestConstants.AccountId, applicationKey, applicationKeyId);

            Assert.IsFalse(string.IsNullOrEmpty(result.AuthorizationToken));
        }
Example #23
0
        public void CanWeAuthorizeStatic()
        {
            var result = B2Client.Authorize(Options);

            Assert.IsFalse(string.IsNullOrEmpty(result.AuthorizationToken));
        }
Example #24
0
 public void Initialize()
 {
     Client     = new B2Client(B2Client.Authorize(Options));
     BucketName = $"B2NETTestingBucket-{Path.GetRandomFileName().Replace(".", "").Substring(0, 6)}";
 }
Example #25
0
        public void CanWeAuthorizeNonMasterKey()
        {
            var result = B2Client.Authorize(applicationKeyId, applicationKey);

            Assert.IsTrue(string.IsNullOrEmpty(result.AuthorizationToken));
        }
Example #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options => options.UseNpgsql(
                                                             Environment.GetEnvironmentVariable("DATABASE_URL") ?? Configuration.GetConnectionString("DbConnection")
                                                             ));
            services.AddDatabaseDeveloperPageExceptionFilter();

            // Repositories
            services.AddScoped <UserRepository>();
            services.AddScoped <ClubRepository>();
            services.AddScoped <ThreadRepository>();
            services.AddScoped <StoriesRepository>();
            services.AddScoped <TagsRepository>();
            services.AddScoped <ChaptersRepository>();
            services.AddScoped <BlogpostsRepository>();
            services.AddScoped <CommentsRepository>();
            services.AddScoped <FoldersRepository>();
            services.AddScoped <NotificationsRepository>();

            // Custom persistent config
            services.AddSingleton(OgmaConfig.Init("config.json"));

            // Routing
            services.AddRouting(options => options.LowercaseUrls = true);

            // HttpContextAccessor
            services.AddHttpContextAccessor();

            // ActionContextAccessor
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            // UrlHelperFactory
            services.AddSingleton <IUrlHelperFactory, UrlHelperFactory>();

            // Identity
            services.AddIdentity <OgmaUser, OgmaRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail   = true;
                config.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_ ";
                config.User.RequireUniqueEmail        = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddUserManager <OgmaUserManager>()
            .AddDefaultTokenProviders()
            .AddUserStore <UserStore <OgmaUser, OgmaRole, ApplicationDbContext, long, IdentityUserClaim <long>, UserRole, IdentityUserLogin <long>, IdentityUserToken <long>, IdentityRoleClaim <long> > >()
            .AddRoleStore <RoleStore <OgmaRole, ApplicationDbContext, long, UserRole, IdentityRoleClaim <long> > >();

            // Logged in user service
            services.AddTransient <IUserService, UserService>();

            // Claims
            services.AddScoped <IUserClaimsPrincipalFactory <OgmaUser>, OgmaClaimsPrincipalFactory>();
            services.AddScoped(s => s.GetService <IHttpContextAccessor>()?.HttpContext?.User);

            // Argon2 hasher
            services.UpgradePasswordSecurity().UseArgon2 <OgmaUser>();

            // Email
            services.AddTransient <IEmailSender, EmailSender>();
            services.Configure <AuthMessageSenderOptions>(Configuration);

            // Backblaze
            var b2Options = Configuration.GetSection("B2").Get <B2Options>();
            var b2Client  = new B2Client(B2Client.Authorize(b2Options));

            services.AddSingleton <IB2Client>(b2Client);

            // File uploader
            services.AddSingleton <ImageUploader>();

            // ReCaptcha
            services.Configure <RecaptchaSettings>(Configuration.GetSection("RecaptchaSettings"));
            services.AddTransient <IRecaptchaService, RecaptchaService>();

            // Seeding
            services.AddAsyncInitializer <DbSeedInitializer>();

            // Auth
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);

            // Auth
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
            });


            // Cookies
            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath           = new PathString("/login");
                options.LogoutPath          = new PathString("/logout");
                options.AccessDeniedPath    = new PathString("/login");
                options.Cookie.SameSite     = SameSiteMode.Lax;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;

                options.Events.OnRedirectToLogin =
                    HandleApiRequest(StatusCodes.Status401Unauthorized, options.Events.OnRedirectToLogin);
                options.Events.OnRedirectToAccessDenied =
                    HandleApiRequest(StatusCodes.Status403Forbidden, options.Events.OnRedirectToLogin);
            });

            // Compression
            services.AddResponseCompression();

            // Cache
            services.AddMemoryCache();

            // Automapper
            services.AddAutoMapper(typeof(AutoMapperProfile));

            // Runtime compilation
            services.AddControllersWithViews().AddRazorRuntimeCompilation();

            // Razor
            services.AddRazorPages().AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeAreaFolder("Admin", "/", "RequireAdminRole");
                options.Conventions
                .AddPageRoute("/Club/Index", "/club/{slug}-{id}")
                .AddAreaPageRoute("Identity", "/Account/Manage/ChangePassword", "/.well-known/change-password");
            });

            // MVC
            services
            .AddMvc(options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });

            // SignalR
            services.AddSignalR();
        }
Example #27
0
        public void ErrorAuthorizeNonMasterKeyWithAccountID()
        {
            var key = "K001LarMmmWDIveFaZz3yvB4uattO+Q";

            var result = B2Client.Authorize(Options.AccountId, key);
        }
Example #28
0
 public void Initialize()
 {
     Client = new B2Client(B2Client.Authorize(Options));
 }
Example #29
0
        /// <summary>
        /// Authorize with the Backblaze api.
        /// </summary>
        public static async Task Authorize()
        {
            await _TempBucketClient.Authorize();

            await _AvatarBucketClient.Authorize();
        }
Example #30
0
        public void DoWeGetCapabilitiesOnClientWithApplicationKey()
        {
            var client = new B2Client(B2Client.Authorize(applicationKeyId, applicationKey));

            Assert.IsNotNull(client.Capabilities.Capabilities);
        }