Example #1
0
        //[ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            ViewBag.Title = "Logout";
            var header = new System.Collections.Specialized.NameValueCollection
            {
                { "Authorization", "token " + CommonUtility.LoggedInUser.authtoken }
            };

            using (var objApiClient = new RestAPIClient
            {
                requestUriString = CommonUtility.GetAppSettingKey("RestServiceURL") + "security/revokeAuthToken",
                contentType = "application/x-www-form-urlencoded",
                headerNameValueCollection = header,
                postDataString = ""
            })
            {
                var apiResponse = objApiClient.Get();
                ViewBag.Title = apiResponse.message;
                FormsAuthentication.SignOut();
                // clear authentication cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
                {
                    Expires = DateTime.Now.AddYears(-1)
                };
                Response.Cookies.Add(cookie);
            }

            return(RedirectToAction("Login", "Account"));
        }
Example #2
0
        public async Task GetRecommendationsWithEncryptedCredentials()
        {
            var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj"));
            var portNumber  = 4000;

            var aes = Aes.Create();

            aes.GenerateKey();
            aes.GenerateIV();

            using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ResolveCredentials, aes);

            InMemoryInteractiveService interactiveService = new InMemoryInteractiveService();
            var keyInfo = new EncryptionKeyInfo
            {
                Version = EncryptionKeyInfo.VERSION_1_0,
                Key     = Convert.ToBase64String(aes.Key),
                IV      = Convert.ToBase64String(aes.IV)
            };
            var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo)));
            await interactiveService.StdInWriter.WriteAsync(keyInfoStdin);

            await interactiveService.StdInWriter.FlushAsync();

            var serverCommand = new ServerModeCommand(interactiveService, portNumber, null, false);
            var cancelSource  = new CancellationTokenSource();

            var serverTask = serverCommand.ExecuteAsync(cancelSource.Token);

            try
            {
                var restClient = new RestAPIClient($"http://localhost:{portNumber}/", httpClient);
                await WaitTillServerModeReady(restClient);

                var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput
                {
                    AwsRegion   = _awsRegion,
                    ProjectPath = projectPath
                });

                var sessionId = startSessionOutput.SessionId;
                Assert.NotNull(sessionId);

                var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId);

                Assert.NotEmpty(getRecommendationOutput.Recommendations);
                Assert.Equal("AspNetAppElasticBeanstalkLinux", getRecommendationOutput.Recommendations.FirstOrDefault().RecipeId);

                var listDeployStdOut = interactiveService.StdOutReader.ReadAllLines();
                Assert.Contains("Waiting on symmetric key from stdin", listDeployStdOut);
                Assert.Contains("Encryption provider enabled", listDeployStdOut);
            }
            finally
            {
                cancelSource.Cancel();
            }
        }
        private RestAPIClient BuildJiraApiClientByPath(string path)
        {
            var encodedCredentials = GetEncodedCredentials(UserName.Text, Password.Password);
            var url = new StringBuilder()
                      .Append(ConfigurationManager.AppSettings[AppSettingStatic.JIRA_HOST])
                      .Append(path).ToString();
            var client = new RestAPIClient(url);

            client.AddCustomHeader("Authorization", string.Format("Basic {0}", encodedCredentials));
            client.ContentType = "application/json";
            return(client);
        }
Example #4
0
        private async Task <DeploymentStatus> WaitForDeployment(RestAPIClient restApiClient, string sessionId)
        {
            // Do an initial delay to avoid a race condition of the status being checked before the deployment has kicked off.
            await Task.Delay(TimeSpan.FromSeconds(3));

            await WaitUntilHelper.WaitUntil(async() =>
            {
                DeploymentStatus status = (await restApiClient.GetDeploymentStatusAsync(sessionId)).Status;;
                return(status != DeploymentStatus.Executing);
            }, TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(15));

            return((await restApiClient.GetDeploymentStatusAsync(sessionId)).Status);
        }
        public bool TryGetRestAPIClient(Func <Task <AWSCredentials> > credentialsGenerator, out IRestAPIClient?restApiClient)
        {
            if (_baseUrl == null || _aes == null)
            {
                restApiClient = null;
                return(false);
            }

            var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(credentialsGenerator, _aes);

            restApiClient = new RestAPIClient(_baseUrl, httpClient);
            return(true);
        }
Example #6
0
        private async Task WaitTillServerModeReady(RestAPIClient restApiClient)
        {
            await WaitUntilHelper.WaitUntil(async() =>
            {
                SystemStatus status = SystemStatus.Error;
                try
                {
                    status = (await restApiClient.HealthAsync()).Status;
                }
                catch (Exception)
                {
                }

                return(status == SystemStatus.Ready);
            }, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10));
        }
Example #7
0
        public ActionResult Login(CurrentLogedInUser model, string returnUrl)
        {
            var header = new System.Collections.Specialized.NameValueCollection
            {
                { "IsAdmin", "true" }
            };

            using (var objApiClient = new RestAPIClient
            {
                requestUriString = CommonUtility.GetAppSettingKey("RestServiceURL") + "security/obtainAuthToken",
                contentType = "application/x-www-form-urlencoded",
                headerNameValueCollection = header,
                postDataString = CommonUtility.Serialize <CurrentLogedInUser>(model)
            })
            {
                var apiResponse = objApiClient.Post();
                if (!apiResponse.type.Contains("error") && apiResponse.body != null && apiResponse.code != -3)
                {
                    CommonUtility.DoLogin(CommonUtility.Deserialize <CurrentLogedInUser>(apiResponse.body.ToString()), this.HttpContext);
                }
                else
                {
                    ViewBag.Title = "Login";
                    ModelState.AddModelError("error_msg", apiResponse.message ?? "Login failed. Please enter valid userid and password");
                    if (apiResponse.code == 1 || apiResponse.code == 2)
                    {
                        ViewBag.Error = apiResponse.message;
                    }
                    else
                    {
                        ViewBag.Error = "Login failed, please try again";
                    }
                    return(View(model));
                }
            }
            ViewBag.Error = "";
            return(RedirectToAction("Index", "Home"));
        }
Example #8
0
        public async Task GetRecommendations()
        {
            var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj"));
            var portNumber  = 4000;

            using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ResolveCredentials);

            var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService <IToolInteractiveService>(), portNumber, null, true);
            var cancelSource  = new CancellationTokenSource();

            var serverTask = serverCommand.ExecuteAsync(cancelSource.Token);

            try
            {
                var restClient = new RestAPIClient($"http://localhost:{portNumber}/", httpClient);
                await WaitTillServerModeReady(restClient);

                var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput
                {
                    AwsRegion   = _awsRegion,
                    ProjectPath = projectPath
                });

                var sessionId = startSessionOutput.SessionId;
                Assert.NotNull(sessionId);

                var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId);

                Assert.NotEmpty(getRecommendationOutput.Recommendations);
                Assert.Equal("AspNetAppElasticBeanstalkLinux", getRecommendationOutput.Recommendations.FirstOrDefault().RecipeId);
            }
            finally
            {
                cancelSource.Cancel();
            }
        }
Example #9
0
        public async Task WebFargateDeploymentNoConfigChanges()
        {
            _stackName = $"ServerModeWebFargate{Guid.NewGuid().ToString().Split('-').Last()}";

            var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj"));
            var portNumber  = 4001;

            using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ResolveCredentials);

            var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService <IToolInteractiveService>(), portNumber, null, true);
            var cancelSource  = new CancellationTokenSource();

            var serverTask = serverCommand.ExecuteAsync(cancelSource.Token);

            try
            {
                var baseUrl    = $"http://localhost:{portNumber}/";
                var restClient = new RestAPIClient(baseUrl, httpClient);

                await WaitTillServerModeReady(restClient);

                var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput
                {
                    AwsRegion   = _awsRegion,
                    ProjectPath = projectPath
                });

                var sessionId = startSessionOutput.SessionId;
                Assert.NotNull(sessionId);

                var signalRClient = new DeploymentCommunicationClient(baseUrl);
                await signalRClient.JoinSession(sessionId);

                var logOutput = new StringBuilder();
                signalRClient.ReceiveLogAllLogAction = (line) =>
                {
                    logOutput.AppendLine(line);
                };

                var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId);

                Assert.NotEmpty(getRecommendationOutput.Recommendations);

                var fargateRecommendation = getRecommendationOutput.Recommendations.FirstOrDefault(x => string.Equals(x.RecipeId, "AspNetAppEcsFargate"));
                Assert.NotNull(fargateRecommendation);

                await restClient.SetDeploymentTargetAsync(sessionId, new SetDeploymentTargetInput
                {
                    NewDeploymentName     = _stackName,
                    NewDeploymentRecipeId = fargateRecommendation.RecipeId
                });

                await restClient.StartDeploymentAsync(sessionId);

                await WaitForDeployment(restClient, sessionId);

                var stackStatus = await _cloudFormationHelper.GetStackStatus(_stackName);

                Assert.Equal(StackStatus.CREATE_COMPLETE, stackStatus);

                Assert.True(logOutput.Length > 0);
                Assert.Contains("Initiating deployment", logOutput.ToString());
            }
            finally
            {
                cancelSource.Cancel();
                await _cloudFormationHelper.DeleteStack(_stackName);

                _stackName = null;
            }
        }