示例#1
0
        private string DeleteGroup()
        {
            var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey,
                                          Passphrase, JwtPublicKey);
            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.UserToken(UserId);
            var client     = boxJWT.AdminClient(adminToken);

            var groupId = GetGroupIdByGroupName(client, GroupName);

            if (groupId == null)
            {
                return("Group not found.");
            }

            var res = client.GroupsManager.DeleteAsync(groupId);

            res.Wait();
            if (res.Exception != null)
            {
                return(res.Exception.Message);
            }

            return("Success");
        }
        private string DeleteUser()
        {
            var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey,
                                          Passphrase, JwtPublicKey);
            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.UserToken(UserId);
            var client     = boxJWT.AdminClient(adminToken);

            var usersRes = client.UsersManager.GetEnterpriseUsersAsync();

            usersRes.Wait();

            foreach (var user in usersRes.Result.Entries)
            {
                if (user.Login == UserIdToDelete)
                {
                    var delUserRes = client.UsersManager.DeleteEnterpriseUserAsync(user.Id, false, false);

                    delUserRes.Wait();

                    return("Success");
                }
            }
            return("User Not Found");
        }
示例#3
0
        private string AddUser()
        {
            var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey,
                                          Passphrase, JwtPublicKey);

            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.UserToken(UserId);
            var client     = boxJWT.AdminClient(adminToken);

            var userRes = client.UsersManager.CreateEnterpriseUserAsync(new BoxUserRequest()
            {
                Name  = UserName,
                Login = Login
            });

            userRes.Wait();

            if (userRes.Exception != null)
            {
                return(userRes.Exception.Message);
            }

            return("Success");
        }
        public async Task <ICustomActivityResult> Execute()
        {
            var Message = string.Empty;

            var boxConfig   = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT      = new BoxJWTAuth(boxConfig);
            var adminToken  = boxJWT.UserToken(USER_ID);
            var adminClient = boxJWT.AdminClient(adminToken);

            using (FileStream fileStream = new FileStream(FilePath, FileMode.Open))
            {
                BoxFileRequest requestParams = new BoxFileRequest()
                {
                    Name   = NameFile,
                    Parent = new BoxRequestEntity()
                    {
                        Id = FolderID
                    }
                };
                BoxFile file = await adminClient.FilesManager.UploadAsync(requestParams, fileStream);

                Message = file.Id;
            }
            return(this.GenerateActivityResult(Message));
        }
示例#5
0
        public static void Initialize(TestContext testContext)
        {
            jsonConfig = Environment.GetEnvironmentVariable("JSON_CONFIG");

            if (string.IsNullOrEmpty(jsonConfig))
            {
                Debug.WriteLine("No json config found!");
            }
            else
            {
                Debug.WriteLine("json config content length : " + jsonConfig.Length);

                var config  = BoxConfig.CreateFromJsonString(jsonConfig);
                var session = new BoxJWTAuth(config);

                // create a new app user
                // client with permissions to manage application users
                var adminToken = session.AdminToken();
                adminClient = session.AdminClient(adminToken);

                var user = CreateNewUser(adminClient).Result;

                userId = user.Id;

                Debug.WriteLine("New app user created : " + userId);

                // user client with access to user's data (folders, files, etc)
                userToken  = session.UserToken(userId);
                userClient = session.UserClient(userToken, userId);
            }
        }
示例#6
0
        private async Task ExecuteMainAsync()
        {
            var config  = ConfigureBoxApi();
            var session = new BoxJWTAuth(config);

            // client with permissions to manage application users
            var adminToken = session.AdminToken();
            var client     = session.AdminClient(adminToken);

            var user = await CreateNewUser(client);

            Console.WriteLine("New app user created with Id = {0}", user.Id);

            // user client with access to user's data (folders, files, etc)
            var userToken  = session.UserToken(user.Id);
            var userClient = session.UserClient(userToken, user.Id);

            // root folder has id = 0
            var newFolder = await CreateNewFolder(userClient);

            Console.WriteLine("New folder created with Id = {0}", newFolder.Id);

            var timer    = Stopwatch.StartNew();
            var file     = File.OpenRead("box_logo.png");
            var uploaded = await UploadFile(newFolder, userClient, file);

            Console.WriteLine("New file uploaded with Id = {0} in {1} ms", uploaded.Id, timer.ElapsedMilliseconds);
        }
        public static async Task AssemblyInitialize(TestContext testContext)
        {
            var jsonConfig = Environment.GetEnvironmentVariable("INTEGRATION_TESTING_CONFIG");

            if (string.IsNullOrEmpty(jsonConfig))
            {
                Debug.WriteLine("No json config found in environment variables Reading from config.json.");
                jsonConfig = ReadFromJson("config.json");
            }

            var config = BoxConfigBuilder.CreateFromJsonString(jsonConfig)
                         .Build();
            var session = new BoxJWTAuth(config);

            var json       = JObject.Parse(jsonConfig);
            var adminToken = await session.AdminTokenAsync();

            AdminClient = session.AdminClient(adminToken);

            if (json["userID"] != null && json["userID"].ToString().Length != 0)
            {
                UserId = json["userID"].ToString();
            }
            else
            {
                var user = await CreateNewUser(AdminClient);

                UserId = user.Id;
            }
            var userToken = await session.UserTokenAsync(UserId);

            UserClient = session.UserClient(userToken, UserId);

            EnterpriseId = config.EnterpriseId;
        }
        public void retriesWithNewJWTAssertionOnErrorResponseAndSucceeds()
        {
            var config     = new BoxConfig(ClientId, ClientSecret, EnterpriseId, privateKey, passphrase, publicKeyID);
            var session    = new BoxJWTAuth(config);
            var adminToken = session.AdminToken();

            adminClient = session.AdminClient(adminToken);
        }
示例#9
0
        static async Task MainAsync()
        {
            // rename the private_key.pem.example to private_key.pem and put your JWT private key in the file
            var privateKey = File.ReadAllText("private_key.pem");

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);

            // Proxy configuration - set isProxyEnabled = true if using Fiddler!!
            if (isProxyEnabled != false)
            {
                System.Net.WebProxy webProxy   = new System.Net.WebProxy("http://127.0.0.1:8888");
                NetworkCredential   credential = new NetworkCredential("testUser", "testPass");
                webProxy.Credentials = credential;
                boxConfig.WebProxy   = webProxy;
            }

            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();

            Console.WriteLine("Admin Token: " + adminToken);
            Console.WriteLine();

            var adminClient = boxJWT.AdminClient(adminToken);

            var adminFunc = new Func(adminClient);

            adminFunc.GetFolderItems();

            var       userId     = "3768478578";
            var       userToken  = boxJWT.UserToken(userId); // valid for 60 minutes so should be cached and re-used
            BoxClient userClient = boxJWT.UserClient(userToken, userId);

            var userFunc = new Func(userClient);

            userFunc.GetFolderItems();

            // Stream fileContents = await userClient.FilesManager.DownloadStreamAsync(id: "675996854920"); // Download the file 675996854920

            // var userRequest = new BoxUserRequest() { Name = "test appuser", IsPlatformAccessOnly = true };
            // var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);
            // Console.WriteLine("Created App User");

            // var userToken = boxJWT.UserToken(appUser.Id);
            // var userClient = boxJWT.UserClient(userToken, appUser.Id);

            // var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();
            // Console.WriteLine("\nApp User Details:");
            // Console.WriteLine("\tId: {0}", userDetails.Id);
            // Console.WriteLine("\tName: {0}", userDetails.Name);
            // Console.WriteLine("\tStatus: {0}", userDetails.Status);
            // Console.WriteLine();

            // await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true);
            // Console.WriteLine("Deleted App User");
        }
示例#10
0
        private static async Task MainAsync()
        {
            // rename the private_key.pem.example to private_key.pem and put your JWT private key in the file
            var privateKey = File.ReadAllText("private_key.pem.example");

            var boxConfig = new BoxConfigBuilder(_clientId, _clientSecret, _enterpriseId, privateKey, _jwtPrivateKeyPassword, _jwtPublicKeyId)
                            .Build();
            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = await boxJWT.AdminTokenAsync();

            Console.WriteLine("Admin Token: " + adminToken);
            Console.WriteLine();

            var adminClient = boxJWT.AdminClient(adminToken);

            Console.WriteLine("Admin root folder items");
            var items = await adminClient.FoldersManager.GetFolderItemsAsync("0", 500);

            items.Entries.ForEach(i =>
            {
                Console.WriteLine("\t{0}", i.Name);
                //if (i.Type == "file")
                //{
                //    var previewLink = adminClient.FilesManager.GetPreviewLinkAsync(i.Id).Result;
                //    Console.WriteLine("\tPreview Link: {0}", previewLink.ToString());
                //    Console.WriteLine();
                //}
            });
            Console.WriteLine();

            var userRequest = new BoxUserRequest()
            {
                Name = "test appuser", IsPlatformAccessOnly = true
            };
            var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);

            Console.WriteLine("Created App User");

            var userToken = await boxJWT.UserTokenAsync(appUser.Id);

            var userClient = boxJWT.UserClient(userToken, appUser.Id);

            var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("\nApp User Details:");
            Console.WriteLine("\tId: {0}", userDetails.Id);
            Console.WriteLine("\tName: {0}", userDetails.Name);
            Console.WriteLine("\tStatus: {0}", userDetails.Status);
            Console.WriteLine();

            await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true);

            Console.WriteLine("Deleted App User");
        }
示例#11
0
        static async Task MainAsync()
        {
            var privateKey = File.ReadAllText("private_key.pem");

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT    = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();

            Console.WriteLine("Admin Token: " + adminToken);
            Console.WriteLine();

            var adminClient = boxJWT.AdminClient(adminToken);

            Console.WriteLine("Admin root folder items");
            var items = await adminClient.FoldersManager.GetFolderItemsAsync("0", 500);

            items.Entries.ForEach(i =>
            {
                Console.WriteLine("\t{0}", i.Name);
                //if (i.Type == "file")
                //{
                //    var preview_link = adminClient.FilesManager.GetPreviewLinkAsync(i.Id).Result;
                //    Console.WriteLine("\tPreview Link: {0}", preview_link.ToString());
                //    Console.WriteLine();
                //}
            });
            Console.WriteLine();

            var userRequest = new BoxUserRequest()
            {
                Name = "test appuser", IsPlatformAccessOnly = true
            };
            var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);

            Console.WriteLine("Created App User");

            var userToken  = boxJWT.UserToken(appUser.Id);
            var userClient = boxJWT.UserClient(userToken, appUser.Id);

            var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("\nApp User Details:");
            Console.WriteLine("\tId: {0}", userDetails.Id);
            Console.WriteLine("\tName: {0}", userDetails.Name);
            Console.WriteLine("\tStatus: {0}", userDetails.Status);
            Console.WriteLine();

            await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true);

            Console.WriteLine("Deleted App User");
        }
示例#12
0
        public async Task <ICustomActivityResult> Execute()
        {
            var Message = string.Empty;

            var boxConfig   = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT      = new BoxJWTAuth(boxConfig);
            var adminToken  = boxJWT.UserToken(USER_ID);
            var adminClient = boxJWT.AdminClient(adminToken);

            await adminClient.FilesManager.DeleteAsync(id : FileID);

            Message = "Success";
            return(this.GenerateActivityResult(Message));
        }
示例#13
0
        private static void Main()
        {
            var boxConfig = BoxConfigBuilder.CreateFromJsonString(GetConfigJson())
                            // Set web proxy
                            .SetWebProxy(new BoxHttpProxy())
                            .Build();

            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken  = boxJWT.AdminTokenAsync().Result;
            var adminClient = boxJWT.AdminClient(adminToken);

            _ = adminClient.FoldersManager.GetFolderItemsAsync("0", 500).Result;
        }
示例#14
0
        static void Main(string[] args)
        {
            var boxConfig = BoxConfig.CreateFromJsonString(GetConfigJson());

            // Set web proxy
            boxConfig.WebProxy = new BoxHttpProxy();

            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken  = boxJWT.AdminToken();
            var adminClient = boxJWT.AdminClient(adminToken);

            var items = adminClient.FoldersManager.GetFolderItemsAsync("0", 500).Result;
        }
示例#15
0
        static void Main(string[] args)
        {
            var appConfig  = new ConfigurationBuilder().AddUserSecrets <Program>().Build();
            var configJson = appConfig["BoxConfigJson"];

            Console.WriteLine($"Creating a Box Admin Client");
            var config     = BoxConfig.CreateFromJsonString(configJson);
            var auth       = new BoxJWTAuth(config);
            var adminToken = auth.AdminToken();
            var boxClient  = auth.AdminClient(adminToken);

            Console.WriteLine($"Created a Box Admin Client");
            GetUser(config, boxClient);
        }
示例#16
0
        public static async Task FindAppUsersAsync()
        {
            Console.WriteLine("FindAppUsersAsync Start");

            // BOX API実行用のClientを準備
            var config     = Program.ConfigureBoxApi();
            var boxJwt     = new BoxJWTAuth(config);
            var adminToken = boxJwt.AdminToken();
            var saClient   = boxJwt.AdminClient(adminToken);

            // サービスアカウントが取れているかチェック
            var sa = await saClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("SA user ID:{0}, Login:{1}, Name:{2}", sa.Id, sa.Login, sa.Name);

            // 非同期処理の同時実行数を制限
            var throttling = new SemaphoreSlim(Config.ApiRateLimit);


            var users = await saClient.UsersManager.GetEnterpriseUsersAsync(limit : 1000);

            var appUserList = new List <string>();
            var listSize    = users.Entries.Count;

            for (int i = 0; i < listSize; i++)
            {
                Console.Write("user {0}/{1}", i, listSize);
                Console.SetCursorPosition(0, Console.CursorTop);

                var user = users.Entries[i];

                if (user.Name.StartsWith("ST_APP_USER_") && user.Login.StartsWith("AppUser_"))
                {
                    if (user.Name == "ST_APP_USER_SEARCH")
                    {
                        Console.WriteLine("Search appUser ID: {0} ", user.Id);
                    }

                    appUserList.Add(user.Id);
                }
            }

            Console.WriteLine($"Found AppUser {appUserList.Count}");

            // ファイルに書き出す
            await File.WriteAllTextAsync(PathToAppUserIDsForTest, JsonSerializer.Serialize(appUserList));

            Console.WriteLine("FindAppUsersAsync Done");
        }
示例#17
0
        private string AddUserToGroup()
        {
            var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey,
                                          Passphrase, JwtPublicKey);
            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.UserToken(UserId);
            var client     = boxJWT.AdminClient(adminToken);

            var groupId = GetGroupIdByGroupName(client, GroupName);

            if (groupId == null)
            {
                return("Group not found.");
            }

            var usersRes = client.UsersManager.GetEnterpriseUsersAsync();

            usersRes.Wait();

            foreach (var user in usersRes.Result.Entries)
            {
                if (user.Login == UserIdToBeAdded)
                {
                    var memberResult = client.GroupsManager.AddMemberToGroupAsync(new BoxGroupMembershipRequest
                    {
                        User = new BoxRequestEntity {
                            Id = user.Id
                        },
                        Group = new BoxGroupRequest {
                            Id = groupId
                        }
                    });

                    memberResult.Wait();

                    memberResult.Wait();
                    if (memberResult.Exception != null)
                    {
                        return(memberResult.Exception.Message);
                    }

                    return("Success");
                }
            }
            return("User Not Found");
        }
示例#18
0
        static async Task MainAsync()
        {
            string CLIENT_ID                = Configuration["Config:ClientID"];
            string CLIENT_SECRET            = Configuration["Config:ClientSecret"];
            string ENTERPRISE_ID            = Configuration["Config:EnterpriseID"];
            string JWT_PRIVATE_KEY_PATH     = Configuration["Config:PrivateKeyPath"];
            string JWT_PRIVATE_KEY_PASSWORD = Configuration["Config:PrivateKeyPass"];
            string JWT_PUBLIC_KEY_ID        = Configuration["Config:PublicKeyID"];

            var privateKey = File.ReadAllText(JWT_PRIVATE_KEY_PATH);

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT    = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();

            Console.WriteLine("Admin Token: " + adminToken);

            var adminClient = boxJWT.AdminClient(adminToken);

            var userRequest = new BoxUserRequest
            {
                Name = "John Smith",
                IsPlatformAccessOnly = true
            };
            var user = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);

            Console.Write("New app user created with Id = {0}", user.Id);

            /*BoxFile newFile;
             *
             * // Create request object with name and parent folder the file should be uploaded to
             * using (FileStream stream = new FileStream(@"/Users/jleblanc/localhost/box/net-jwt/tax.txt", FileMode.Open))
             * {
             *  BoxFileRequest req = new BoxFileRequest()
             *  {
             *      Name = "tax.txt",
             *      Parent = new BoxRequestEntity() { Id = "0" }
             *  };
             *  newFile = await adminClient.FilesManager.UploadAsync(req, stream);
             * }*/
        }
示例#19
0
    static async Task validateUser(string name, string sub)
    {
        // Configure Box SDK instance
        var       reader = new StreamReader("config.json");
        var       json   = reader.ReadToEnd();
        var       config = BoxConfig.CreateFromJsonString(json);
        var       sdk    = new BoxJWTAuth(config);
        var       token  = sdk.AdminToken();
        BoxClient client = sdk.AdminClient(token);

        // Search for matching Box app user for Okta ID
        BoxCollection <BoxUser> users = await client.UsersManager.GetEnterpriseUsersAsync(externalAppUserId : sub);

        System.Diagnostics.Debug.WriteLine(users.TotalCount);

        if (users.TotalCount > 0)
        {
            // Box user found, get token
            var       userId     = users.Entries[0].Id;
            var       userToken  = sdk.UserToken(userId);
            BoxClient userClient = sdk.UserClient(userToken, userId);

            // Get current user
            BoxUser currentUser = await userClient.UsersManager.GetCurrentUserInformationAsync();

            System.Diagnostics.Debug.WriteLine("Current user name: " + currentUser.Name);
        }
        else
        {
            // No associated user found, create app user
            var userRequest = new BoxUserRequest()
            {
                Name = name,
                ExternalAppUserId    = sub,
                IsPlatformAccessOnly = true
            };
            var user = await client.UsersManager.CreateEnterpriseUserAsync(userRequest);

            System.Diagnostics.Debug.WriteLine("New user created: " + user.Name);
        }
    }
示例#20
0
        /// <summary>
        /// Get an authenticated client for the JWT app service account.
        /// </summary>
        /// <param name="pathToConfigJson">The path to the JWT app configuration JSON file.</param>
        /// <returns>An authenticated Box client</returns>
        private static BoxClient GetAuthenticatedClient(string pathToConfigJson)
        {
            if (string.IsNullOrWhiteSpace(pathToConfigJson) || !File.Exists(pathToConfigJson))
            {
                throw new Exception("Please set 'pathToConfigJson' with the path to your JWT app config JSON file.");
            }

            // Read the configuration from the file.
            IBoxConfig config;

            using (var configStream = File.OpenRead(pathToConfigJson))
                config = BoxConfig.CreateFromJsonFile(configStream);

            Console.Out.WriteLine("Authenticating...");

            // Create a Box client and authenticate as the service account
            var boxJwtAuth = new BoxJWTAuth(config);
            var adminToken = boxJwtAuth.AdminToken();

            return(boxJwtAuth.AdminClient(adminToken));
        }
示例#21
0
        public async Task <ICustomActivityResult> Execute()
        {
            var Message       = string.Empty;
            var boxConfig     = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT        = new BoxJWTAuth(boxConfig);
            var adminToken    = boxJWT.UserToken(USER_ID);
            var adminClient   = boxJWT.AdminClient(adminToken);
            var requestParams = new BoxFileRequest()
            {
                Id     = FileID,
                Parent = new BoxRequestEntity()
                {
                    Id = FolderID
                },
                Name = Name
            };
            BoxFile fileCopy = await adminClient.FilesManager.CopyAsync(requestParams);

            Message = "Success";
            return(this.GenerateActivityResult(Message));
        }
        public BoxClient AdminClient(string asUser = null)
        {
            //check cache for existing admin token
            var cacheKey   = $"/box/{_boxConfig.ClientId}/admin-token";
            var adminToken = _distributedCache.GetString(cacheKey);

            if (string.IsNullOrEmpty(adminToken))
            {
                //fetch a new admin token from Box
                adminToken = _boxJWTAuth.AdminToken();

                //store the token in the cache with a 45 minute expiration
                var options = new DistributedCacheEntryOptions()
                {
                    AbsoluteExpirationRelativeToNow = CACHE_ITEM_TTL
                };
                _distributedCache.SetString(cacheKey, adminToken, options);
            }

            return(_boxJWTAuth.AdminClient(adminToken, asUser: asUser));
        }
示例#23
0
        public async Task <ICustomActivityResult> Execute()
        {
            var    Message      = string.Empty;
            var    boxConfig    = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var    boxJWT       = new BoxJWTAuth(boxConfig);
            var    adminToken   = boxJWT.UserToken(USER_ID);
            var    adminClient  = boxJWT.AdminClient(adminToken);
            Stream fileContents = await adminClient.FilesManager.DownloadAsync(FileID);

            using (Stream file = File.Create(FilePath))
            {
                byte[] buffer = new byte[8 * 1024];
                int    len;
                while ((len = fileContents.Read(buffer, 0, buffer.Length)) > 0)
                {
                    file.Write(buffer, 0, len);
                }
            }
            Message = "Success";
            return(this.GenerateActivityResult(Message));
        }
示例#24
0
        private string AddGroup()
        {
            var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey,
                                          Passphrase, JwtPublicKey);
            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.UserToken(UserId);
            var client     = boxJWT.AdminClient(adminToken);

            var res = client.GroupsManager.CreateAsync(new BoxGroupRequest()
            {
                Name = GroupName
            });

            res.Wait();
            if (res.Exception != null)
            {
                return(res.Exception.Message);
            }

            return("Success");
        }
        private string RemoveUserFromGroup()
        {
            var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey,
                                          Passphrase, JwtPublicKey);
            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.UserToken(UserId);
            var client     = boxJWT.AdminClient(adminToken);

            var groupId = GetGroupIdByGroupName(client, GroupName);

            if (groupId == null)
            {
                return("Group not found.");
            }

            var membersResult = client.GroupsManager.GetAllGroupMembershipsForGroupAsync(groupId);

            membersResult.Wait();

            foreach (var member in membersResult.Result.Entries)
            {
                if (member.User.Login == UserIdToBeRemoved)
                {
                    var res = client.GroupsManager.DeleteGroupMembershipAsync(member.Id);

                    res.Wait();
                    if (res.Exception != null)
                    {
                        return(res.Exception.Message);
                    }

                    return("Success");
                }
            }

            return("User Not Found");
        }
示例#26
0
        static void test_app_mycapp_2()
        {
            IBoxConfig config = null;

            using (FileStream fs = new FileStream("87881712_nqkf95rj_config.json", FileMode.Open))
            {
                config = BoxConfig.CreateFromJsonFile(fs);
            }

            var boxJWT = new BoxJWTAuth(config);

            var adminToken  = boxJWT.AdminToken();
            var adminClient = boxJWT.AdminClient(adminToken);
            var user_info   = adminClient.UsersManager.GetCurrentUserInformationAsync().Result;
            var items       = adminClient.FoldersManager.GetFolderItemsAsync("0", 100).Result;
            var users       = adminClient.UsersManager.GetEnterpriseUsersAsync().Result;

            user_info = adminClient.UsersManager.GetUserInformationAsync("224172711").Result;

            var client_token = boxJWT.UserToken("224172711");
            var client       = boxJWT.UserClient(client_token, "224172711");

            items = client.FoldersManager.GetFolderItemsAsync("0", 100).Result;
        }
示例#27
0
        public async void ImportFiles(string basePath)
        {
            try
            {
                // Get Box Auth Token
                if (!string.IsNullOrEmpty(Settings.PrivateKey))
                {
                    Settings.PrivateKey = Settings.PrivateKey.Replace("\\n", "\n");
                }

                var boxConfig = new BoxConfig(
                    Settings.ClientID,
                    Settings.ClientSecret,
                    Settings.EnterpriceId,
                    Settings.PrivateKey,
                    Settings.JwtPrivateKeyPassword,
                    Settings.JwtPublicKeyId);

                var boxJWTAuth = new BoxJWTAuth(boxConfig);
                var adminToken = boxJWTAuth.AdminToken();
                var client     = boxJWTAuth.AdminClient(adminToken);
                boxManager = new BoxManager(adminToken);

                var enrolledServices = repositoryEnrolledService.GetServicesByImportMode(ServiceReportImportModes.BoxAPI);

                if (enrolledServices.Model == null || enrolledServices.Model.List.Count() == 0)
                {
                    return;
                }

                foreach (var listItem in enrolledServices.Model.List)
                {
                    string importPath = Path.Combine(basePath, listItem.BusinessId.ToString(), "Sales", listItem.ServiceName);

                    BoxItem sharedItemInServiceFolder = await client.SharedItemsManager.SharedItemsAsync(listItem.BoxUrl);

                    var sharedServiceEnties = await client.FoldersManager.GetFolderItemsAsync(sharedItemInServiceFolder.Id, 100, 0,
                                                                                              new List <string>
                    {
                        BoxFolder.FieldName,
                        BoxFolder.FieldPathCollection,
                        BoxFolder.FieldModifiedAt,
                        BoxFolder.FieldItemCollection
                    }
                                                                                              );

                    foreach (var sharedEntry in sharedServiceEnties.Entries)
                    {
                        if (sharedEntry.Type.ToLower() == "file")
                        {
                            bool isFileExists = new RepositorySales().IsSalesFileExists(sharedEntry.Name, listItem.BusinessId, listItem.Id) || File.Exists(Path.Combine(importPath, sharedEntry.Name));
                            if (isFileExists)
                            {
                                continue;
                            }

                            if (!Directory.Exists(importPath))
                            {
                                Directory.CreateDirectory(importPath);
                            }

                            using (FileStream fileStream = new FileStream(Path.Combine(importPath, sharedEntry.Name), FileMode.CreateNew, System.IO.FileAccess.Write))
                            {
                                using (Stream stream = await client.FilesManager.DownloadStreamAsync(sharedEntry.Id))
                                {
                                    int bytesRead;
                                    var buffer = new byte[8192];
                                    do
                                    {
                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);

                                        await fileStream.WriteAsync(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                            }

                            // Move download file to archive folder

                            var subfolder  = new BoxApi.V2.Model.Folder();
                            var folderInfo = await client.FoldersManager.GetInformationAsync(sharedItemInServiceFolder.Id);

                            if (folderInfo.ItemCollection.Entries.OfType <BoxFolder>().Count() > 0)
                            {
                                var foundFolder = folderInfo.ItemCollection.Entries.OfType <BoxFolder>().Any((f) => f.Name == "Archive");
                                // var foundFolder = entryItems.Parent.ItemCollection.Entries.OfType<BoxFolder>().First((a) => a.Name == "my subfolder");
                                if (foundFolder == false)
                                {
                                    subfolder = boxManager.CreateFolder(sharedItemInServiceFolder.Id, "Archive");
                                    boxManager.MoveFile(sharedEntry.Id, subfolder.Id);
                                }
                                // Move the file to the subfolder
                                var foundFolderDetails = folderInfo.ItemCollection.Entries.OfType <BoxFolder>().First((f) => f.Name == "Archive");
                                boxManager.MoveFile(sharedEntry.Id, foundFolderDetails.Id);
                                // getfolderDetails(folderItems.Id, path);
                            }
                            else
                            {
                                subfolder = boxManager.CreateFolder(sharedItemInServiceFolder.Id, "Archive");
                                boxManager.MoveFile(sharedEntry.Id, subfolder.Id);
                            }
                        }
                        //else case entry type is 'folder'
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Log();
                throw ex;
            }
        }
示例#28
0
        public static async Task CheckAppUsersAndFolders()
        {
            Console.WriteLine("CheckAppUsersAndFolders Start");

            // サービスアカウントのClientを準備
            var config     = Program.ConfigureBoxApi();
            var boxJwt     = new BoxJWTAuth(config);
            var adminToken = boxJwt.AdminToken();
            var saClient   = boxJwt.AdminClient(adminToken);

            // サービスアカウントが取れているかチェック
            var sa = await saClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("SA user ID:{0}, Login:{1}, Name:{2}", sa.Id, sa.Login, sa.Name);

            // AppUser毎の処理
            var totalAppUsers = Config.AppUsers.Length;

            for (var i = 0; i < totalAppUsers; i++)
            {
                var appUserCounter = i + 1;
                var appUserId      = Config.AppUsers[i];

                Console.WriteLine($"AppUser:{appUserId} {appUserCounter}/{totalAppUsers} Start");

                // 検索用ユーザーだった場合は何もしない
                if (appUserId == Config.SearchUserId)
                {
                    Console.WriteLine($"Skip. AppUser:{appUserId} is Search User");
                    continue;
                }

                // RateLimit対応スロットリング
                var throttle = TimeLimiter.GetFromMaxCountByInterval(Config.ApiRateLimit, TimeSpan.FromSeconds(1));


                // AppUser専用のClientを用意
                var auClient = new BoxClient(saClient.Config, saClient.Auth, asUser: appUserId);


                // ユーザーが所有するトップレベルのフォルダのリストを取得
                var topFolders = await GetFolders(auClient, "0", 100, throttle);

                // フォルダが1つだけでない、または、フォルダ名が指定と異なる場合
                if (topFolders.Count != 1 || topFolders.First().Name != Config.TopFolderName)
                {
                    Console.WriteLine(
                        $"ERROR トップフォルダが間違っている。 appUserId = {appUserId}, founder count = {topFolders.Count}, folder name = {topFolders.First().Name}");
                    return;
                }


                // トップフォルダのフォルダチェック
                BoxFolder topFolder = (BoxFolder)topFolders.First();

                // トップフォルダに検索ユーザーが招待されているか
                // フォルダのコラボレーションを一覧
                await throttle;
                var   topCollabs = await auClient.FoldersManager
                                   .GetCollaborationsAsync(topFolder.Id);

                var topCollab = topCollabs.Entries.SingleOrDefault(c => c.AccessibleBy.Id == Config.SearchUserId);
                if (topCollab == null)
                {
                    Console.WriteLine($"ERROR トップフォルダに検索ユーザーが招待されていない。appUserId = {appUserId}");
                    return;
                }

                // トップフォルダ下のサブフォルダをチェック
                var subFolders = await GetFolders(auClient, topFolder.Id, 1000, throttle);

                Console.WriteLine($"AppUser:{appUserId} {appUserCounter}/{totalAppUsers} number of subfolder = {subFolders.Count}");

                // タスクの待ち合わせ用リスト
                var folderTasks = new List <Task>();

                var forLock    = new object();
                var checkCount = 0;
                // サブフォルダに検索ユーザーがついていないこと
                foreach (var subItem in subFolders)
                {
                    var task = Task.Run(async() =>
                    {
                        BoxFolder subFolder = (BoxFolder)subItem;
                        // フォルダのコラボレーションを一覧
                        await throttle;
                        var subCollabs = await auClient.FoldersManager
                                         .GetCollaborationsAsync(subFolder.Id);

                        var subCollabListForSearch =
                            subCollabs.Entries.Where(c => c.AccessibleBy.Id == Config.SearchUserId);

                        // サブフォルダについている、検索用ユーザーのコラボレーションが1つだけかチェック
                        if (subCollabListForSearch.Count() != 1)
                        {
                            Console.WriteLine(
                                $"ERROR サブフォルダにコラボレーションが残っている。appUserId = {appUserId} subFolderId = {subFolder.Id} subFolderName = {subFolder.Name}");
                            return;
                        }

                        // サブフォルダについている唯一のコラボレーションが、トップフォルダについているコラボレーションと同じものか
                        var subCollabForSearch = subCollabListForSearch.First();

                        if (subCollabForSearch.Id != topCollab.Id)
                        {
                            // トップフォルダとサブフォルダで異なるコラボレーションがついている
                            Console.WriteLine(
                                $"ERROR サブフォルダとトップフォルダのコラボレーションが異なる。appUserId = {appUserId} subFolderId = {subFolder.Id} subFolderName = {subFolder.Name}");
                        }

                        lock (forLock)
                        {
                            checkCount++;
                            Console.Write("folder checked {0}", checkCount);
                            Console.SetCursorPosition(0, Console.CursorTop);
                        }
                    }); // end Task.Run
                    folderTasks.Add(task);
                } // end foreach on sub folders

                await Task.WhenAll(folderTasks);

                Console.WriteLine($"AppUser:{appUserId} {appUserCounter}/{totalAppUsers} folder check done");
            } // end for on appUsers

            Console.WriteLine("CheckAppUsersAndFolders Done");
        }
        static async Task MainAsync()
        {
            try
            {
                /* Read the config file that is provided when an application is
                 * created in the Box Dev Consolse
                 * */

                string jsonConfig = System.IO.File.ReadAllText(configFile());
                var    config     = BoxConfig.CreateFromJsonString(jsonConfig);
                /* Authenticate. This will provide access to the service account */
                var boxJWT     = new BoxJWTAuth(config);
                var adminToken = "";
                adminToken = boxJWT.AdminToken();
                Console.WriteLine("Admin Token:" + adminToken);

                /*
                 * Searching for a particular user from the enterprise given the login name
                 */
                BoxClient boxClient = boxJWT.AdminClient(adminToken);
                BoxCollection <BoxUser> boxUserCollection = await boxClient.UsersManager.GetEnterpriseUsersAsync(userLogin(), 0, 100, null, "managed", null, false);

                List <BoxUser> userList = boxUserCollection.Entries;
                Console.WriteLine("Entries:" + userList.Count);
                if (userList.Count > 0)
                {
                    foreach (var user in userList)
                    {
                        Console.WriteLine("User Login:"******" ID:" + user.Id);
                    }
                }

                /* Replace this variable for the user you want. This is the users
                 * internal Box ID and is all numbers e.g. 3445252385. Suggest that
                 * the list of users in the system is cached in the Token Factory
                 * and synced perdiodically.
                 */
                var userId = userInformation();
                /* Ask box for a token for the user */
                var userToken = boxJWT.UserToken(userId);

                Console.WriteLine("User Token:" + userToken);
                /* Generate a downscoped token to the ITEM_PREVIEW scope */
                var exchanger = new TokenExchange(adminToken, "item_preview");

                /*Optionally you can downscope to a particular resource. Omitting this will downscope
                 * all resources to the scope set above regardless of resource.
                 * exchanger.SetResource("https://api.box.com/2.0/files/123456789");
                 */
                string downscopedToken = exchanger.Exchange();
                Console.WriteLine("Downscoped ITEM_PREVIEW Token:" + downscopedToken);
                /* Print out some user information for the demo */
                var userClient = boxJWT.UserClient(userToken, userId);

                var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();

                Console.WriteLine("\n User Details:");
                Console.WriteLine("\tId: {0}", userDetails.Id);
                Console.WriteLine("\tName: {0}", userDetails.Name);
                Console.WriteLine("\tStatus: {0}", userDetails.Status);
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
示例#30
0
 public static BoxClient AdminClient()
 {
     return(BOX_JWT_HELPER.AdminClient(EnterpriseToken()));
 }