Beispiel #1
0
        public override void ProcessRequest(HttpContext context)
        {
            using (_tracer.Step("RpcService.ReceivePack"))
            {
                _deploymentLock.LockOperation(() =>
                {
                    string username = null;
                    if (AuthUtility.TryExtractBasicAuthUser(context.Request, out username))
                    {
                        _gitServer.SetDeployer(username);
                    }

                    UpdateNoCacheForResponse(context.Response);

                    context.Response.ContentType = "application/x-git-receive-pack-result";

                    using (_deploymentManager.CreateTemporaryDeployment(Resources.ReceivingChanges))
                    {
                        _gitServer.Receive(GetInputStream(context.Request), context.Response.OutputStream);
                    }
                },
                                              () =>
                {
                    context.Response.StatusCode = 409;
                    context.ApplicationInstance.CompleteRequest();
                });
            }
        }
Beispiel #2
0
        public void Test(AuthorizationLevel principalLevel, AuthorizationLevel requiredLevel, bool expectSuccess)
        {
            ClaimsPrincipal principal = CreatePrincipal(principalLevel);
            bool            result    = AuthUtility.PrincipalHasAuthLevelClaim(principal, requiredLevel);

            Assert.Equal(expectSuccess, result);
        }
Beispiel #3
0
        public void Deploy(string id)
        {
            JObject result = GetJsonContent();

            // Just block here to read the json payload from the body
            using (_tracer.Step("DeploymentService.Deploy(id)"))
            {
                _deploymentLock.LockHttpOperation(() =>
                {
                    try
                    {
                        bool clean = false;

                        if (result != null)
                        {
                            clean = result.Value <bool>("clean");
                        }

                        string username = null;
                        AuthUtility.TryExtractBasicAuthUser(Request, out username);

                        _deploymentManager.Deploy(id, username, clean);
                    }
                    catch (FileNotFoundException ex)
                    {
                        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                    }
                });
            }
        }
Beispiel #4
0
		///参见文档:http://btcchina.org/api-trade-documentation-zh
		///1. 使用如下强制的参数创建签名字符串。将键值对使用“&”符号按照下面列表的顺序连接在一起。请注意连接顺序很重要。所有的键名必须添加,但是键值可以为空 (例如 params)。
		///tonce (以毫秒为单位的时间戳,请确保您的系统时间准确)
		///accesskey (访问密匙,您可以在您的账户管理页面申请)
		///method (HTTP 请求方法,目前仅支持“post”)
		///id (JSON-RPC 请求 id)
		///method method (JSON-RPC 方法名称)
		///params (JSON-RPC 方法参数)

		public string AuthQuery(string method, Dictionary<string, string> postDict)
		{
			string tonce = GetTonce();
			Dictionary<string, string> parameters = new Dictionary<string, string>() { 
				{ "tonce", tonce },
				{ "accesskey",AuthKey.PublicKey },
				{ "requestmethod", "post" },
				{ "id", "1" },
				{ "method", method }				
			};

			string paramText = "";
			foreach (var item in postDict)
			{
				paramText += item.Value;
				paramText += ",";
			}
			paramText = paramText.Trim(',');
			parameters.Add("params", paramText);

			// bug:如果用了UrlEncode,将params中的“,”翻译掉了!会导致授权不成功!           
			string post = AuthUtility.ToPost(parameters, false);
			string sign = GetSign(post, AuthKey.PrivateKey);
			string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(AuthKey.PublicKey + ':' + sign));
			string postData = "{\"method\": \"" + method + "\", \"params\": [" + paramText + "], \"id\": 1}";

			HttpWebRequest webRequest = GetWebRequest(base64String, tonce, postData);
			string json = AuthUtility.GetResponseJson(webRequest);
			return json;
		}
Beispiel #5
0
        /// <summary>
        /// Creates a result model with a bearer token
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        private WorkflowIdentityResultDto CreateActionResult(ActionActivityResult result)
        {
            Debug.Assert(result != null);

            if (result.Ticket != null)
            {
                return(new WorkflowIdentityResultDto
                {
                    TokenType = "Bearer",
                    AccessToken = AuthUtility.Protect(result.Ticket),
                    Identity = result.Ticket
                });
            }

            if (Request.Headers.Authorization != null)
            {
                return(new WorkflowIdentityResultDto
                {
                    TokenType = Request.Headers.Authorization.Scheme,
                    AccessToken = Request.Headers.Authorization.Parameter,
                    Identity = result.Ticket
                });
            }

            return(null);
        }
Beispiel #6
0
        public void ProcessRequest(HttpContext context)
        {
            using (_tracer.Step("RpcService.ReceivePack"))
            {
                _deploymentLock.LockOperation(() =>
                {
                    string username = null;
                    if (AuthUtility.TryExtractBasicAuthUser(context.Request, out username))
                    {
                        _gitServer.SetDeployer(username);
                    }

                    context.Response.Buffer       = false;
                    context.Response.BufferOutput = false;

                    context.Response.ContentType = "application/x-git-receive-pack-result";
                    context.Response.AddHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT");
                    context.Response.AddHeader("Pragma", "no-cache");
                    context.Response.AddHeader("Cache-Control", "no-cache, max-age=0, must-revalidate");

                    _gitServer.Receive(GetInputStream(context.Request), context.Response.OutputStream);
                },
                                              () =>
                {
                    context.Response.StatusCode = 409;
                    context.ApplicationInstance.CompleteRequest();
                });
            }
        }
Beispiel #7
0
        public void Deploy(HttpRequestMessage request, string id)
        {
            // Just block here to read the json payload from the body
            var result = request.Content.ReadAsAsync <JsonValue>().Result;

            using (_tracer.Step("DeploymentService.Deploy(id)"))
            {
                _deploymentLock.LockHttpOperation(() =>
                {
                    try
                    {
                        bool clean = false;

                        if (result != null)
                        {
                            JsonValue cleanValue = result["clean"];
                            clean = cleanValue != null && cleanValue.ReadAs <bool>();
                        }

                        string username = null;
                        AuthUtility.TryExtractBasicAuthUser(request, out username);

                        _deploymentManager.Deploy(id, username, clean);
                    }
                    catch (FileNotFoundException ex)
                    {
                        var response     = new HttpResponseMessage(HttpStatusCode.NotFound);
                        response.Content = new StringContent(ex.Message);
                        throw new HttpResponseException(response);
                    }
                });
            }
        }
Beispiel #8
0
        /// <summary>
        /// Remove an IP Address in the Whitelist
        /// </summary>
        /// <param name="entryId">Required parameter: a unique identifier for the IP Address; opaque but likely a GUID</param>
        /// <param name="body">Required parameter: Example: </param>
        /// <return>Returns the Models.RemoveResponse response from the API call</return>
        public async Task <Models.RemoveResponse> RemoveAsync(string entryId, Models.IPAddress body)
        {
            //the base uri for api requests
            string _baseUri = Configuration.GetBaseURI();

            //prepare query string for API call
            StringBuilder _queryBuilder = new StringBuilder(_baseUri);

            _queryBuilder.Append("/v1.1/whitelists/ipaddresses/{entry_id}/delete");

            //process optional template parameters
            APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary <string, object>()
            {
                { "entry_id", entryId }
            });


            //validate and preprocess url
            string _queryUrl = APIHelper.CleanUrl(_queryBuilder);

            //append request with appropriate headers and parameters
            var _headers = new Dictionary <string, string>()
            {
                { "user-agent", "APIMATIC 2.0" },
                { "accept", "application/json" },
                { "content-type", "application/json; charset=utf-8" }
            };

            //append body params
            var _body = APIHelper.JsonSerialize(body);

            //prepare the API call request to fetch the response
            HttpRequest _request = ClientInstance.DeleteBody(_queryUrl, _headers, _body);

            //Custom Authentication to be added for authorization
            AuthUtility.AppendCustomAuthParams(_request);

            //invoke request and get response
            HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false);

            HttpContext _context = new HttpContext(_request, _response);

            //Error handling using HTTP status codes
            if (_response.StatusCode == 400)
            {
                throw new ReturnException(@"Unexpected error in API call. See HTTP response body for details.", _context);
            }

            //handle errors defined at the API level
            base.ValidateResponse(_response, _context);

            try
            {
                return(APIHelper.JsonDeserialize <Models.RemoveResponse>(_response.Body));
            }
            catch (Exception _ex)
            {
                throw new APIException("Failed to parse the response: " + _ex.Message, _context);
            }
        }
Beispiel #9
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /*AuthUtility.checkSN()获取数据库sn号,然后进行验证*/
            if (ConfUtility.isTrial == false && AuthUtility.checkSN() == false)
            {
                SignForm signForm = new SignForm();
                signForm.ShowDialog();
                if (signForm.DialogResult != DialogResult.OK)
                {
                    return;
                }
            }

            /*AuthUtility.checkSN()获取数据库sn号,然后进行验证*/
            if (ConfUtility.isTrial == true)
            {
                if (DateTime.Compare(DateTime.Now, ConfUtility.dateLine) >= 0)
                {
                    MessageBox.Show("试用期已过!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            LoginForm loginForm = new LoginForm();

            loginForm.ShowDialog();
            if (loginForm.DialogResult == DialogResult.OK)
            {
                Application.Run(new MainForm());
            }
        }
Beispiel #10
0
        IEnumerable <ProjectDto> GetProjects4CurrentUser()
        {
            var list = new List <ProjectDto>();

            try
            {
                var userId = AuthUtility.GetUserId(User);//User.Identity.GetUserId();
                var projs  = _projectMemberService.GetProjectsByUser(userId);
                Log.InfoFormat("用户({0})获取项目总数:{1}", AuthUtility.GetUserName(User), projs.Count);
                foreach (var m in projs)
                {
                    var proj = _projService.GetProjectById(m.ProjectId);
                    if (proj == null)
                    {
                        //    Log.WarnFormat("项目({0})已被删除", m.ProjectId);
                        continue;
                    }
                    var vault = _mfvaultService.GetVaultById(proj.VaultId);
                    if (vault == null)
                    {
                        //   Log.WarnFormat("文档库({0})已被删除", proj.VaultId);
                        continue;
                    }

                    var projDto = proj.ToDto(vault, false);
                    list.Add(projDto);
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("获取用户项目异常:{0}", ex.Message), ex);
            }
            return(list);
        }
Beispiel #11
0
        private IEnumerable <Qa> GetQaList(string guid, string classAlias, string state)
        {
            var res = new List <Qa>();

            try
            {
                var server = _mFilesVaultService.GetServer();
                Log.Info("GetQaList-server Ip:" + server.Ip);
                var userName = AuthUtility.GetUserName(User);
                Log.Info("GetQaList-userName:"******"GetQaList-password:"******"GetQaList-vault Guid:" + guid);
                var vault = app.LogInToVault(guid);
                var qas   = MFModelUtil.GetQaList(vault, classAlias, state).ToList();
                Log.Info("GetQaList-qas Count:" + qas.Count);
                res.AddRange(qas);
                vault.LogOutSilent();
                app.Disconnect();
            }
            catch (Exception ex)
            {
                Log.Error("GetQaList:" + ex.Message);
            }
            return(res);
        }
        private async Task <IActionResult> GetResultAsync(HttpContext context, IFunctionExecutionFeature functionExecution)
        {
            if (functionExecution.Descriptor == null)
            {
                return(new NotFoundResult());
            }

            if (context.Request.IsColdStart() && !context.Items.ContainsKey(ScriptConstants.AzureFunctionsColdStartKey))
            {
                // for cold start requests we want to measure the request
                // pipeline dispatch time
                // important that this stopwatch is started as early as possible
                // in the pipeline (in this case, in our first middleware)
                var sw = new Stopwatch();
                sw.Start();
                context.Items[ScriptConstants.AzureFunctionsColdStartKey] = sw;
            }

            PopulateRouteData(context);

            bool authorized = await AuthenticateAndAuthorizeAsync(context, functionExecution.Descriptor);

            if (!authorized)
            {
                return(new UnauthorizedResult());
            }

            // If the function is disabled, return 'NotFound', unless the request is being made with Admin credentials
            if (functionExecution.Descriptor.Metadata.IsDisabled() &&
                !AuthUtility.PrincipalHasAuthLevelClaim(context.User, AuthorizationLevel.Admin))
            {
                return(new NotFoundResult());
            }

            if (functionExecution.CanExecute)
            {
                // Add the request to the logging scope. This allows the App Insights logger to
                // record details about the request.
                ILoggerFactory loggerFactory = context.RequestServices.GetService <ILoggerFactory>();
                ILogger        logger        = loggerFactory.CreateLogger(LogCategories.CreateFunctionCategory(functionExecution.Descriptor.Name));
                var            scopeState    = new Dictionary <string, object>()
                {
                    [ScriptConstants.LoggerHttpRequest] = context.Request,
                };

                using (logger.BeginScope(scopeState))
                {
                    var applicationLifetime             = context.RequestServices.GetService <IApplicationLifetime>();
                    CancellationToken cancellationToken = applicationLifetime != null ? applicationLifetime.ApplicationStopping : CancellationToken.None;
                    await functionExecution.ExecuteAsync(context.Request, cancellationToken);
                }
            }

            if (context.Items.TryGetValue(ScriptConstants.AzureFunctionsHttpResponseKey, out object result) && result is IActionResult actionResult)
            {
                return(actionResult);
            }

            return(new OkResult());
        }
Beispiel #13
0
        public async Task <string> GenerateClientAccessTokenAsync(string hubName = null, IEnumerable <Claim> claims = null, TimeSpan?lifetime = null)
        {
            var audience = $"{_endpoint}/{ClientPath}";
            await _accessKey.AuthorizedTask;

            return(AuthUtility.GenerateAccessToken(_accessKey, audience, claims, lifetime ?? _accessTokenLifetime, _algorithm));
        }
Beispiel #14
0
        //[AllowAnonymous]
        public ActionResult Invitelogin(int inviterId, int projectId)
        {
            string tempIp           = Request.UserHostAddress;
            var    loginStatusModel = new LoginStatusModel {
                Ip = tempIp, LoginDateUtc = DateTime.UtcNow
            };

            Api.AccountController.UpdateLoginInfo(loginStatusModel, AuthUtility.GetUserId(User),
                                                  _userManager, _userService);

            var res  = GetUserProfile(_userManager);
            var user = res;

            Session["UserId"] = user.Id;
            Session["Email"]  = user.Email;

            var host       = Utility.GetHost(Request.Url);
            var roles      = AuthUtility.GetUserRoles(User.Identity);
            var userId     = AuthUtility.GetUserId(User);
            var userEntity = _userManager.FindById(userId);
            //获取邀请人名字和项目内容
            var appModel = Api.CloudController.GetClouds(userEntity,
                                                         _uservaultService, _cloudService, _vaultTemplateService, _vaultService, _mfvaultService, host, roles); //_usercloudService,

            Session["userApp"] = appModel;
            var inviterRes     = GetUserProfile(_userManager, inviterId);
            var inviterProfile = inviterRes;
            var projectRes     = Api.ProjectController.GetProject(projectId, _projService, _mfvaultService,
                                                                  _vaultTemplateService);
            var project   = projectRes;
            var returnStr = "{'state':'success','inviter':'" + inviterProfile.UserName + "','projectName':'" + project.Name + "','projectDes':'" + project.Description + "'}";

            return(Content(returnStr));
        }
        public void PrincipalHasAuthLevelClaim_WithRequiredLevel_ReturnsExpectedResult(AuthorizationLevel[] principalLevel, AuthorizationLevel requiredLevel, bool expectSuccess)
        {
            ClaimsPrincipal principal = CreatePrincipal(principalLevel);
            bool            result    = AuthUtility.PrincipalHasAuthLevelClaim(principal, requiredLevel);

            Assert.Equal(expectSuccess, result);
        }
Beispiel #16
0
 public SignForm()
 {
     InitializeComponent();
     this.textBox1.Text = AuthUtility.getCPU();
     this.toolStripStatusLabel1.Text = ConfUtility.GetSoftName();
     this.label4.Text = ConfUtility.GetProductName();
 }
Beispiel #17
0
        public async Task Deploy(string id = null)
        {
            JObject result = GetJsonContent();

            // Just block here to read the json payload from the body
            using (_tracer.Step("DeploymentService.Deploy(id)"))
            {
                await _deploymentLock.LockHttpOperationAsync(async() =>
                {
                    try
                    {
                        if (_autoSwapHandler.IsAutoSwapOngoing())
                        {
                            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, Resources.Error_AutoSwapDeploymentOngoing));
                        }

                        bool clean          = false;
                        bool needFileUpdate = true;

                        if (result != null)
                        {
                            clean = result.Value <bool>("clean");
                            JToken needFileUpdateToken;
                            if (result.TryGetValue("needFileUpdate", out needFileUpdateToken))
                            {
                                needFileUpdate = needFileUpdateToken.Value <bool>();
                            }
                        }

                        string username = null;
                        AuthUtility.TryExtractBasicAuthUser(Request, out username);

                        IRepository repository = _repositoryFactory.GetRepository();
                        if (repository == null)
                        {
                            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, Resources.Error_RepositoryNotFound));
                        }
                        ChangeSet changeSet = null;
                        if (!String.IsNullOrEmpty(id))
                        {
                            changeSet = repository.GetChangeSet(id);
                            if (changeSet == null)
                            {
                                string message = String.Format(CultureInfo.CurrentCulture, Resources.Error_DeploymentNotFound, id);
                                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
                            }
                        }

                        await _deploymentManager.DeployAsync(repository, changeSet, username, clean, needFileUpdate);

                        _autoSwapHandler.HandleAutoSwap(verifyActiveDeploymentIdChanged: false);
                    }
                    catch (FileNotFoundException ex)
                    {
                        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
                    }
                });
            }
        }
Beispiel #18
0
        /// <summary>
        /// TODO: type endpoint description here
        /// </summary>
        /// <param name="webhookId">Required parameter: Example: </param>
        /// <return>Returns the string response from the API call</return>
        public async Task <string> DestroyAsync(int webhookId)
        {
            //the base uri for api requestss
            string _baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder _queryBuilder = new StringBuilder(_baseUri);

            _queryBuilder.Append("/webhooks/{webhook_id}");

            //process optional template parameters
            APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary <string, object>()
            {
                { "webhook_id", webhookId }
            });


            //validate and preprocess url
            string _queryUrl = APIHelper.CleanUrl(_queryBuilder);

            //append request with appropriate headers and parameters
            var _headers = new Dictionary <string, string>()
            {
                { "user-agent", "APIMATIC 2.0" }
            };

            _headers.Add("X-API-TOKEN", Configuration.XAPITOKEN);
            _headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL);

            //prepare the API call request to fetch the response
            HttpRequest _request = ClientInstance.Delete(_queryUrl, _headers, null);

            //Custom Authentication to be added for authorization
            AuthUtility.AppendCustomAuthParams(_request);

            //invoke request and get response
            HttpStringResponse _response = (HttpStringResponse)await ClientInstance.ExecuteAsStringAsync(_request);

            HttpContext _context = new HttpContext(_request, _response);

            //return null on 404
            if (_response.StatusCode == 404)
            {
                return(null);
            }

            //handle errors defined at the API level
            base.ValidateResponse(_response, _context);

            try
            {
                return(_response.Body);
            }
            catch (Exception _ex)
            {
                throw new APIException("Failed to parse the response: " + _ex.Message, _context);
            }
        }
Beispiel #19
0
        // GET: Login
        public ActionResult Index()
        {
            string token = HttpContext.GetAuthToken();

            if (AuthUtility.IsAuthorized(token, true))
            {
                return(RedirectToAction("Index", "Home"));
            }
            return(View());
        }
Beispiel #20
0
        public override void ProcessRequestBase(HttpContextBase context)
        {
            using (Tracer.Step("RpcService.ReceivePack"))
            {
                // Ensure that the target directory does not have a non-Git repository.
                IRepository repository = _repositoryFactory.GetRepository();
                if (repository != null && repository.RepositoryType != RepositoryType.Git)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    if (context.ApplicationInstance != null)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                    return;
                }

                bool acquired = DeploymentLock.TryLockOperation(() =>
                {
                    context.Response.ContentType = "application/x-git-receive-pack-result";

                    if (_autoSwapHandler.IsAutoSwapOngoing())
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Conflict;
                        context.Response.Write(Resources.Error_AutoSwapDeploymentOngoing);
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }

                    string username = null;
                    if (AuthUtility.TryExtractBasicAuthUser(context.Request, out username))
                    {
                        GitServer.SetDeployer(username);
                    }

                    UpdateNoCacheForResponse(context.Response);

                    // This temporary deployment is for ui purposes only, it will always be deleted via finally.
                    ChangeSet tempChangeSet;
                    using (DeploymentManager.CreateTemporaryDeployment(Resources.ReceivingChanges, out tempChangeSet))
                    {
                        GitServer.Receive(context.Request.GetInputStream(), context.Response.OutputStream);
                    }

                    // TODO: Currently we do not support auto-swap for git push due to an issue where we already sent the headers at the
                    // beginning of the deployment and cannot flag at this point to make the auto swap (by sending the proper headers).
                    //_autoSwapHandler.HandleAutoSwap(verifyActiveDeploymentIdChanged: true);
                }, TimeSpan.Zero);

                if (!acquired)
                {
                    context.Response.StatusCode = 409;
                    context.ApplicationInstance.CompleteRequest();
                }
            }
        }
Beispiel #21
0
 /// <summary>
 /// Gets an authentication ticket from the given HTTP header
 /// </summary>
 private static AuthTicket GetTicketFromHeader(AuthenticationHeaderValue header)
 {
     if (header == null ||
         string.IsNullOrEmpty(header.Scheme) ||
         string.IsNullOrEmpty(header.Parameter) ||
         "Bearer".Equals(header.Scheme, System.StringComparison.OrdinalIgnoreCase) == false)
     {
         return(null);
     }
     return(AuthUtility.Unprotect(header.Parameter));
 }
Beispiel #22
0
        private IEnumerable <VaultKey> GetCurrentVaultsEx()
        {
            var userId     = AuthUtility.GetUserId(User);
            var userName   = AuthUtility.GetUserName(User);
            var password   = DBWorldCache.Get(userId.ToString());
            var isAdUser   = !String.IsNullOrEmpty(AuthUtility.GetUserDomain(User.Identity));
            var server     = _vaultServer.GetServer();
            var vaultGuids = _workHourService.GetCurrentVaults(userName, password, isAdUser, server);

            return(vaultGuids);
        }
Beispiel #23
0
        public override void ProcessRequestBase(HttpContextBase context)
        {
            using (Tracer.Step("RpcService.ReceivePack"))
            {
                // Ensure that the target directory does not have a non-Git repository.
                IRepository repository = _repositoryFactory.GetRepository();
                if (repository != null && repository.RepositoryType != RepositoryType.Git)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    if (context.ApplicationInstance != null)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                    return;
                }

                try
                {
                    DeploymentLock.LockOperation(() =>
                    {
                        context.Response.ContentType = "application/x-git-receive-pack-result";

                        if (_autoSwapHandler.IsAutoSwapOngoing())
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Conflict;
                            context.Response.Write(Resources.Error_AutoSwapDeploymentOngoing);
                            context.ApplicationInstance.CompleteRequest();
                            return;
                        }

                        string username = null;
                        if (AuthUtility.TryExtractBasicAuthUser(context.Request, out username))
                        {
                            GitServer.SetDeployer(username);
                        }

                        UpdateNoCacheForResponse(context.Response);

                        // This temporary deployment is for ui purposes only, it will always be deleted via finally.
                        ChangeSet tempChangeSet;
                        using (DeploymentManager.CreateTemporaryDeployment(Resources.ReceivingChanges, out tempChangeSet))
                        {
                            GitServer.Receive(context.Request.GetInputStream(), context.Response.OutputStream);
                        }
                    }, "Handling git receive pack", TimeSpan.Zero);
                }
                catch (LockOperationException ex)
                {
                    context.Response.StatusCode = 409;
                    context.Response.Write(ex.Message);
                    context.ApplicationInstance.CompleteRequest();
                }
            }
        }
Beispiel #24
0
            public void FailsToParseIfHeaderIsSchemeNotBasic()
            {
                // Arrange
                string username;

                // Act
                var result = AuthUtility.TryExtractBasicAuthUserFromHeader("Digest: something", out username);

                // Assert
                Assert.False(result);
                Assert.Null(username);
            }
Beispiel #25
0
            public void FailsToParseIfHeaderIsNull()
            {
                // Arrange
                string username;

                // Act
                var result = AuthUtility.TryExtractBasicAuthUserFromHeader(null, out username);

                // Assert
                Assert.False(result);
                Assert.Null(username);
            }
Beispiel #26
0
        public bool ValidateToken(string token)
        {
            long userId = AuthUtility.ValidateJwtToken(token);

            if (userId == 0)
            {
                return(false);
            }

            Global.UserId = userId;
            return(true);
        }
        private async Task <bool> AuthenticateAndAuthorizeAsync(HttpContext context, FunctionDescriptor descriptor)
        {
            var policyEvaluator        = context.RequestServices.GetRequiredService <IPolicyEvaluator>();
            AuthorizationPolicy policy = AuthUtility.CreateFunctionPolicy();

            // Authenticate the request
            var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context);

            // Authorize using the function policy and resource
            var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, descriptor);

            return(authorizeResult.Succeeded);
        }
Beispiel #28
0
            public void FailsToParseIfNoUsername()
            {
                // Arrange
                var    payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(":password"));
                string username;

                // Act
                var result = AuthUtility.TryParseBasicAuthUserFromHeaderParameter(payload, out username);

                // Assert
                Assert.False(result);
                Assert.Null(username);
            }
Beispiel #29
0
            public void ParsesUsername()
            {
                // Arrange
                var    payload = Convert.ToBase64String(Encoding.UTF8.GetBytes("user:password"));
                string username;

                // Act
                var result = AuthUtility.TryParseBasicAuthUserFromHeaderParameter(payload, out username);

                // Assert
                Assert.True(result);
                Assert.Equal("user", username);
            }
        private async Task <IActionResult> GetResultAsync(HttpContext context, IFunctionExecutionFeature functionExecution)
        {
            if (functionExecution.Descriptor == null)
            {
                return(new NotFoundResult());
            }

            // Add route data to request info
            // TODO: Keeping this here for now as other code depend on this property, but this can be done in the HTTP binding.
            var routingFeature = context.Features.Get <IRoutingFeature>();

            context.Items.Add(HttpExtensionConstants.AzureWebJobsHttpRouteDataKey, new Dictionary <string, object>(routingFeature.RouteData.Values));

            bool authorized = await AuthenticateAndAuthorizeAsync(context, functionExecution.Descriptor);

            if (!authorized)
            {
                return(new UnauthorizedResult());
            }

            // If the function is disabled, return 'NotFound', unless the request is being made with Admin credentials
            if (functionExecution.Descriptor.Metadata.IsDisabled &&
                !AuthUtility.PrincipalHasAuthLevelClaim(context.User, AuthorizationLevel.Admin))
            {
                return(new NotFoundResult());
            }

            if (functionExecution.CanExecute)
            {
                // Add the request to the logging scope. This allows the App Insights logger to
                // record details about the request.
                ILogger logger     = _loggerFactory.CreateLogger(LogCategories.Function);
                var     scopeState = new Dictionary <string, object>()
                {
                    [ScriptConstants.LoggerHttpRequest] = context.Request
                };

                using (logger.BeginScope(scopeState))
                {
                    // TODO: Flow cancellation token from caller
                    await functionExecution.ExecuteAsync(context.Request, CancellationToken.None);
                }
            }

            if (context.Items.TryGetValue(ScriptConstants.AzureFunctionsHttpResponseKey, out object result) && result is IActionResult actionResult)
            {
                return(actionResult);
            }

            return(new OkResult());
        }