public ActionResult LogOff()
 {
     // Remove all cached tokens if the user signs out.
     // This action is only necessary if using ASP.Net session state or cookies to cache tokens.
     // If the application is using a database to cache tokens, you don't need to clear them when the user signs out.
     OAuthController.RemoveAllFromCache();
     AuthenticationManager.SignOut();
     return(RedirectToAction("Index", "Home"));
 }
예제 #2
0
        public async Task <List <string> > GetAvailableEngines()
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // define Engines API
            Page <string> engines = await _designAutomation.GetEnginesAsync();

            engines.Data.Sort();

            return(engines.Data); // return list of engines
        }
        // If you are adapting an application that authenticates Azure AD users using Windows Identity Foundation,
        // you can get the user's Tenant ID from ClaimsPrincipal.Current.  Otherwise, this sample caches the user's
        // Tenant ID when it is obtained during the OAuth authorization flow.
        // private const string TenantIdClaimType = "http://schemas.microsoft.com/identity/claims/tenantid";

        //
        // GET: /UserProfile/
        public async Task <ActionResult> Index()
        {
            //
            // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API.
            //
            UserProfile profile     = null;
            string      accessToken = null;

            // If you authenticated an Azure AD user using Windows Identity Foundation, you can use ClaimsPrincipal.Current to get the user's Tenant ID.
            // string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;
            string tenantId = (string)OAuthController.GetFromCache("TenantId");

            if (tenantId != null)
            {
                accessToken = OAuthController.GetAccessTokenFromCacheOrRefreshToken(tenantId, graphResourceId);
            }

            //
            // If the user doesn't have an access token, they need to re-authorize.
            //
            if (accessToken == null)
            {
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                //

                // Remember where to bring the user back to in the application after the authorization code response is handled.
                OAuthController.SaveInCache("RedirectTo", Request.Url);

                profile                  = new UserProfile();
                profile.DisplayName      = " ";
                profile.GivenName        = " ";
                profile.Surname          = " ";
                ViewBag.ErrorMessage     = "AuthorizationRequired";
                ViewBag.AuthorizationUrl = OAuthController.GetAuthorizationUrl(graphResourceId, this.Request);

                return(View(profile));
            }

            //
            // Call the Graph API and retrieve the user's profile.
            //
            string requestUrl = String.Format(
                CultureInfo.InvariantCulture,
                graphUserUrl,
                HttpUtility.UrlEncode(tenantId));
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = await client.SendAsync(request);

            //
            // Return the user's profile in the view.
            //
            if (response.IsSuccessStatusCode)
            {
                string responseString = await response.Content.ReadAsStringAsync();

                profile = JsonConvert.DeserializeObject <UserProfile>(responseString);
            }
            else
            {
                //
                // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again.
                //
                OAuthController.RemoveAccessTokenFromCache(graphResourceId);

                profile              = new UserProfile();
                profile.DisplayName  = " ";
                profile.GivenName    = " ";
                profile.Surname      = " ";
                ViewBag.ErrorMessage = "UnexpectedError";
            }

            return(View(profile));
        }
예제 #4
0
        public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input)
        {
            // basic input validation
            JObject workItemData       = JObject.Parse(input.data);
            string  activityName       = string.Format("{0}.{1}", NickName, input.activityName);
            string  browerConnectionId = input.browerConnectionId;

            // save the file on the server
            var fileSavePath = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName));

            using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream);

            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            // upload file to OSS Bucket
            // 1. ensure bucket existis
            string     bucketKey = NickName.ToLower() + "_designautomation";
            BucketsApi buckets   = new BucketsApi();

            buckets.Configuration.AccessToken = oauth.access_token;
            try
            {
                PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                await buckets.CreateBucketAsync(bucketPayload, "US");
            }
            catch { };                                                                                                                                         // in case bucket already exists
                                                                                                                                                               // 2. upload inputFile
            string     inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding
            ObjectsApi objects          = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;
            using (StreamReader streamReader = new StreamReader(fileSavePath))
                await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
            System.IO.File.Delete(fileSavePath);// delete server copy


            // prepare workitem arguments
            // 1. input file
            XrefTreeArgument inputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS),
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };
            // 2. input json
            XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
            {
                Url = "data:application/json, " + workItemData.ToString(Formatting.None).Replace("\"", "'")
            };
            // 3. output file
            //string outputFileNameOSS = string.Format("{0}_output_{1}.rfa", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileNameWithoutExtension(input.inputFile.FileName)); // avoid overriding
            string fileName = workItemData["FileName"].Value <string>();

            XrefTreeArgument outputFileArgument = new XrefTreeArgument()
            {
                Url     = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, fileName),
                Verb    = Verb.Put,
                Headers = new Dictionary <string, string>()
                {
                    { "Authorization", "Bearer " + oauth.access_token }
                }
            };

            // prepare & submit workitem
            // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem
            string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_CALLBACK_HOST"), browerConnectionId, fileName);

            Console.WriteLine(callbackUrl);
            WorkItem workItemSpec = new WorkItem()
            {
                ActivityId = activityName,
                Arguments  = new Dictionary <string, IArgument>()
                {
                    { "inputFile", inputFileArgument },
                    { "inputJson", inputJsonArgument },
                    { "outputFile", outputFileArgument },
                    { "onComplete", new XrefTreeArgument {
                          Verb = Verb.Post, Url = callbackUrl
                      } }
                }
            };
            WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec);

            return(Ok(new { WorkItemId = workItemStatus.Id }));
        }