Example #1
0
        private async Task <ApiErrorModel> ExecuteHandlerTest(AuthorizationLevel authLevel, bool includeDetails)
        {
            var handler          = new ExceptionProcessingHandler(_config);
            var requestId        = Guid.NewGuid().ToString();
            var exception        = new Exception("TestException");
            var exceptionContext = new ExceptionContext(exception, ExceptionCatchBlocks.HttpServer)
            {
                Request = new HttpRequestMessage()
            };

            exceptionContext.Request.SetAuthorizationLevel(authLevel);
            exceptionContext.Request.SetConfiguration(_config);
            exceptionContext.Request.Properties.Add(ScriptConstants.AzureFunctionsRequestIdKey, requestId);
            exceptionContext.RequestContext = new System.Web.Http.Controllers.HttpRequestContext();

            var context = new ExceptionHandlerContext(exceptionContext);

            context.RequestContext.IncludeErrorDetail = includeDetails;

            handler.Handle(context);

            HttpResponseMessage response = await context.Result.ExecuteAsync(CancellationToken.None);

            ApiErrorModel error = await response.Content.ReadAsAsync <ApiErrorModel>();

            Assert.Equal(requestId, error.RequestId);

            return(error);
        }
Example #2
0
        private void SetCsla4Options()
        {
            UseCsla4 = false;
            UseDal   = false;
            _generateDalInterface = false;
            _generateDalObject    = false;

            if (TargetIsCsla4All)
            {
                UseCsla4           = true;
                _activeObjects     = false;
                _useSingleCriteria = false;
            }
            else
            {
                _generateQueriesWithSchema     = true;
                _useBypassPropertyChecks       = false;
                _usePublicPropertyInfo         = false;
                _useChildFactory               = true;
                _usesCslaAuthorizationProvider = true;
                _generateAuthorization         = AuthorizationLevel.ObjectLevel;
                _usesCslaAuthorizationProvider = true;
            }

            if (TargetIsCsla4DAL)
            {
                UseDal = true;
                _generateDalInterface     = true;
                _generateDalObject        = true;
                _silverlightUsingServices = false;
                _generateDatabaseClass    = false;
            }
        }
        public static bool PrincipalHasAuthLevelClaim(ClaimsPrincipal principal, AuthorizationLevel requiredLevel, string keyName = null)
        {
            // If the required auth level is anonymous, the requirement is met
            if (requiredLevel == AuthorizationLevel.Anonymous)
            {
                return(true);
            }

            var claimLevels = principal
                              .FindAll(SecurityConstants.AuthLevelClaimType)
                              .Select(c => Enum.TryParse(c.Value, out AuthorizationLevel claimLevel) ? claimLevel : AuthorizationLevel.Anonymous)
                              .ToArray();

            if (claimLevels.Length > 0)
            {
                // If we have a claim with Admin level, regardless of whether a name is required, return true.
                if (claimLevels.Any(claimLevel => claimLevel == AuthorizationLevel.Admin))
                {
                    return(true);
                }

                // Ensure we match the expected level and key name, if one is required
                if (claimLevels.Any(l => l == requiredLevel) &&
                    (keyName == null || string.Equals(principal.FindFirstValue(SecurityConstants.AuthLevelKeyNameClaimType), keyName, StringComparison.OrdinalIgnoreCase)))
                {
                    return(true);
                }
            }

            return(false);
        }
        public AuthenticationToken(AuthorizationLevel level)
        {
            // TODO: review, bad performance (check is done via reflection)
            Debug.Assert(Enum.IsDefined(typeof(AuthorizationLevel), level), "Enum value not supported");

            AuthenticationLevel = level;
        }
        /// <summary>
        /// Returns true if the specified request is authorized at a level equal to or greater than
        /// the specified level.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="level">The level to check.</param>
        /// <param name="keyName">Optional key name if key based auth is being used</param>
        /// <returns>True if the request is authorized at the specified level,
        /// false otherwise.</returns>
        public static bool HasAuthorizationLevel(this HttpRequestMessage request, AuthorizationLevel level, string keyName = null)
        {
            if (request.IsAuthDisabled())
            {
                return(true);
            }

            var authorizationLevel = request.GetAuthorizationLevel();

            if (authorizationLevel == AuthorizationLevel.Admin)
            {
                // requests authorized at admin level are always allowed
                return(true);
            }

            if (keyName != null)
            {
                // if a key name is specified, make sure we have a match
                string requestKeyName = request.GetPropertyOrDefault <string>(ScriptConstants.AzureFunctionsHttpRequestKeyNameKey);
                if (string.Compare(keyName, requestKeyName) != 0)
                {
                    return(false);
                }
            }

            // otherwise, the request level must exactly match the required level
            return(authorizationLevel == level);
        }
Example #6
0
 public FPUCashier(string id, string name, string password, AuthorizationLevel level)
 {
     this.id       = id;
     this.name     = name;
     this.password = password;
     this.level    = level;
 }
Example #7
0
        public async override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }

            AuthorizationLevel requestAuthorizationLevel = actionContext.Request.GetAuthorizationLevel();

            // If the request has not yet been authenticated, authenticate it
            if (requestAuthorizationLevel == AuthorizationLevel.Anonymous)
            {
                // determine the authorization level for the function and set it
                // as a request property
                var secretManager = actionContext.ControllerContext.Configuration.DependencyResolver.GetService <ISecretManager>();

                requestAuthorizationLevel = await GetAuthorizationLevelAsync(actionContext.Request, secretManager, EvaluateKeyMatch);

                actionContext.Request.SetAuthorizationLevel(requestAuthorizationLevel);
            }

            var settings = actionContext.ControllerContext.Configuration.DependencyResolver.GetService <WebHostSettings>();

            if (settings.IsAuthDisabled || SkipAuthorization(actionContext) || Level == AuthorizationLevel.Anonymous)
            {
                return;
            }

            if (requestAuthorizationLevel < Level)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
        }
Example #8
0
        private void InitHandler(Object o, EventArgs e)
        {
            // Recupero il tag
            _loginInformation = _view.RetrieveTagInformation <ILoginInformation>("loginInformation");
            string username = _loginInformation.Username;

            // Recupero la tipologia di utente
            ILoginUser user = _userRetriever(username);

            _authLevel = user == null ? AuthorizationLevel.GUEST : user.AuthorizationLevel;
            _loginName = user?.FirstName ?? " opsite";

            SharedInit();

            // Inizializzo in base alla tipologia di utente
            if (user == null || user.AuthorizationLevel == AuthorizationLevel.GUEST)
            {
                GuestInit();
            }
            else if (user.AuthorizationLevel == AuthorizationLevel.CUSTOMER)
            {
                CustomerInit();
            }
            else if (user.AuthorizationLevel > AuthorizationLevel.CUSTOMER)
            {
                StaffInit();
            }
        }
Example #9
0
        public bool GenerateCashierLine(string name, string id, AuthorizationLevel auth,
                                        string passcode, int disPercent, Decimal disAmount,
                                        bool valid, out string line)
        {
            bool retVal = true;

            try
            {
                line = String.Format(
                    "{0:D1}{1:D4}{2}{3:-6}{4:1}{5:D2}{6:D10}\r\n",
                    valid ? "1" : "0",
                    id,
                    name.PadRight(20, ' '),
                    passcode,
                    (auth == AuthorizationLevel.Seller) ? " " : auth.ToString(),
                    (disPercent == 100) ? 0 : disPercent,
                    (disAmount * 100 == Decimal.MaxValue)? 0 : (long)(disAmount * 100)
                    );
            }
            catch (Exception exc)
            {
                Log(exc);
                line   = "";
                retVal = false;
            }

            return(retVal);
        }
        public static bool PrincipalHasAuthLevelClaim(ClaimsPrincipal principal, AuthorizationLevel requiredLevel, string keyName = null)
        {
            // If the required auth level is anonymous, the requirement is met
            if (requiredLevel == AuthorizationLevel.Anonymous)
            {
                return(true);
            }

            AuthorizationLevel level = AuthorizationLevel.Anonymous;

            if (Enum.TryParse(principal.FindFirstValue(SecurityConstants.AuthLevelClaimType), out level))
            {
                // True if the identity is authenticated with Admin level, regardless of whether a name is required.
                if (level == AuthorizationLevel.Admin)
                {
                    return(true);
                }

                // Ensure we match the expected level and key name, if one is required
                if (level == requiredLevel &&
                    (keyName == null || string.Equals(principal.FindFirstValue(SecurityConstants.AuthLevelKeyNameClaimType), keyName, StringComparison.OrdinalIgnoreCase)))
                {
                    return(true);
                }
            }

            return(false);
        }
 public RequestContext Authorize(AuthorizationLevel authorizationLevel)
 {
     //TODO: Load required data to perform authenticationa nd authorization
     // For now just to have a place holder I created this
     _authorizationLevel = authorizationLevel;
     return(this);
 }
Example #12
0
        public void Test(AuthorizationLevel principalLevel, AuthorizationLevel requiredLevel, bool expectSuccess)
        {
            ClaimsPrincipal principal = CreatePrincipal(principalLevel);
            bool            result    = AuthUtility.PrincipalHasAuthLevelClaim(principal, requiredLevel);

            Assert.Equal(expectSuccess, result);
        }
        /// <inheritdoc />
        public async Task <string> RenderOAuth2RedirectAsync(string endpoint, AuthorizationLevel authLevel = AuthorizationLevel.Anonymous, string authKey = null)
        {
            var html = await Task.Factory
                       .StartNew(() => this.RenderOAuth2Redirect(endpoint, authLevel, authKey))
                       .ConfigureAwait(false);

            return(html);
        }
Example #14
0
 public User(string username, string password)
 {
     this.username = username;
     this.password = password;
     friends = new List<string>();
     this.level = AuthorizationLevel.GUEST;
     currentState = UserState.Active;
 }
Example #15
0
        public static string GetPermissionNameWithAuthLevel(string serviceName, AuthorizationLevel authorizationLevel)
        {
            var permissionName = string.Join(".", new List <string> {
                ApplicationKey, serviceName, authorizationLevel.ToString()
            });

            return(permissionName);
        }
 public string Generate(AuthorizationLevel authorizationLevel)
 {
     if (authorizationLevel == AuthorizationLevel.Admin)
     {
         return(Generate(10, CharType.UpperCaseLetter, CharType.LowerCaseLetter, CharType.Digit, CharType.SpecialSymbol));
     }
     return(Generate(7, CharType.UpperCaseLetter, CharType.LowerCaseLetter, CharType.Digit));
 }
 public SettingsAuthorizationException(AuthorizationScope scope, AuthorizationLevel level, string objectName, int identity)
     : base(string.Format("{0} {1} {2}: {3}.", level, scope, objectName ?? "unknown", Constants.ERROR_ACCESS_DENIED))
 {
     _scope = scope;
     _level = level;
     _objectName = objectName;
     _identity = identity;
 }
Example #18
0
        public AuthorizationLevel ValidateEmployee(string strEmployeeName)
        {
            var repo = CreateOperatorRepository();
            AuthorizationLevel authLvl = AuthorizationLevel.InvalidUser;

            authLvl = repo.Object.ValidateEmployee(strEmployeeName);
            return(authLvl);
        }
 public SettingsAuthorizationException(AuthorizationScope scope, AuthorizationLevel level, string objectName, int identity)
     : base(string.Format("{0} {1} {2}: {3}.", level, scope, objectName ?? "unknown", Constants.ERROR_ACCESS_DENIED))
 {
     _scope      = scope;
     _level      = level;
     _objectName = objectName;
     _identity   = identity;
 }
        public void GetAuthorizationLevel_ValidCodeQueryParam_MasterKey_ReturnsAdmin()
        {
            Uri uri = new Uri(string.Format("http://functions/api/foo?code={0}", testMasterKeyValue));
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

            AuthorizationLevel level = AuthorizationLevelAttribute.GetAuthorizationLevel(request, _mockSecretManager.Object);

            Assert.Equal(AuthorizationLevel.Admin, level);
        }
Example #21
0
        public void GetAuthorizationLevel_InvalidKeyQueryParam_ReturnsAnonymous()
        {
            Uri uri = new Uri(string.Format("http://functions/api/foo?key={0}", "invalid"));
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

            AuthorizationLevel level = AuthorizationLevelAttribute.GetAuthorizationLevel(request, _mockSecretManager.Object);

            Assert.Equal(AuthorizationLevel.Anonymous, level);
        }
        private Mock <FunctionDescriptor> CreateDefaultDescriptor(AuthorizationLevel triggerLevel)
        {
            var descriptor = new Mock <FunctionDescriptor>();

            descriptor.Setup(d => d.GetTriggerAttributeOrNull <HttpTriggerAttribute>())
            .Returns(new HttpTriggerAttribute(triggerLevel));

            return(descriptor);
        }
        public void GetAuthorizationLevel_ValidKeyHeader_MasterKey_ReturnsAdmin()
        {
            HttpRequestMessage request = new HttpRequestMessage();
            request.Headers.Add(AuthorizationLevelAttribute.FunctionsKeyHeaderName, testMasterKeyValue);

            AuthorizationLevel level = AuthorizationLevelAttribute.GetAuthorizationLevel(request, _mockSecretManager.Object);

            Assert.Equal(AuthorizationLevel.Admin, level);
        }
Example #24
0
        public async Task GetAuthorizationLevel_InvalidCodeQueryParam_ReturnsAnonymous()
        {
            Uri uri = new Uri(string.Format("http://functions/api/foo?code={0}", "invalid"));
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

            AuthorizationLevel level = await AuthorizationLevelAttribute.GetAuthorizationLevelAsync(request, MockSecretManager.Object);

            Assert.Equal(AuthorizationLevel.Anonymous, level);
        }
Example #25
0
        public async Task GetAuthorizationLevel_ValidCodeQueryParam_SystemKey_ReturnsSystem()
        {
            Uri uri = new Uri(string.Format("http://functions/api/foo?code={0}", TestSystemKeyValue1));
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

            AuthorizationLevel level = await AuthorizationLevelAttribute.GetAuthorizationLevelAsync(request, MockSecretManager.Object);

            Assert.Equal(AuthorizationLevel.System, level);
        }
        public void GetAuthorizationLevel_InvalidKeyHeader_ReturnsAnonymous()
        {
            HttpRequestMessage request = new HttpRequestMessage();
            request.Headers.Add(AuthorizationLevelAttribute.FunctionsKeyHeaderName, "invalid");

            AuthorizationLevel level = AuthorizationLevelAttribute.GetAuthorizationLevel(request, _mockSecretManager.Object);

            Assert.Equal(AuthorizationLevel.Anonymous, level);
        }
Example #27
0
        public void Create(string levelName)
        {
            var level = new AuthorizationLevel {
                Name = levelName
            };

            Database.AuthorizationLevelsTbl.Add(level);
            Database.SaveChanges();
        }
Example #28
0
        public void ValidateEmployee_ExpectInvalid()
        {
            string             operatorName    = "ZahirHaqueXYZ";
            AuthorizationLevel expectedAuthLvl = AuthorizationLevel.InvalidUser;
            //Initialize_True();
            var returnAuthLvl = _mesService.ValidateEmployee(operatorName);

            Assert.AreEqual(returnAuthLvl, expectedAuthLvl);
        }
Example #29
0
        public void ValidateEmployee_ExpectAdministrator()
        {
            string             operatorName    = "Mike";
            AuthorizationLevel expectedAuthLvl = AuthorizationLevel.Administrator;
            //Initialize_True();
            var returnAuthLvl = _mesService.ValidateEmployee(operatorName);

            Assert.IsTrue(returnAuthLvl == expectedAuthLvl);
        }
Example #30
0
        public void ValidateEmployee_ExpectValid()
        {
            string             operatorName    = "zahir.haque";
            AuthorizationLevel expectedAuthLvl = AuthorizationLevel.Engineer;
            //Initialize_True();
            var returnAuthLvl = _mesService.ValidateEmployee(operatorName);

            Assert.IsTrue(returnAuthLvl == expectedAuthLvl);
        }
Example #31
0
        private ClaimsPrincipal CreatePrincipal(AuthorizationLevel level)
        {
            var claims = new List <Claim>
            {
                new Claim(SecurityConstants.AuthLevelClaimType, level.ToString())
            };

            return(new ClaimsPrincipal(new ClaimsIdentity(claims, "Test")));
        }
Example #32
0
        private void updateOperatorMsgHandler(OperatorResponseMessage msg)
        {
            if (msg.PortNo != thisPortNo)
            {
                return;
            }
            AuthorizationLevel authLevel = msg.authLevel;

            BusyOp         = false;
            OperatorStatus = authLevel == AuthorizationLevel.InvalidUser ? "../Images/CheckBoxRed.png" : "../Images/CheckBoxGreen.png";
            if (authLevel == AuthorizationLevel.InvalidUser)
            {
                if (!string.IsNullOrEmpty(OperatorID))
                {
                    Application.Current.Dispatcher.Invoke((Action) delegate
                    {
                        var vm = new DialogViewModel($"Invalid Operator ID {OperatorID} entered! Please re-enter", "", "Ok");
                        dialogService.ShowDialog(vm);
                        _operatorID = "";
                        Messenger.Default.Send(new ReFocusMessage("OperatorField", null));
                        Engineer = false;
                    });
                }
            }
            else if (authLevel == AuthorizationLevel.Engineer)
            {
                IsRecipeOverridable = true;
                Engineer            = true;
                Messenger.Default.Send(new ReFocusMessage("ToolField", null));
                RaisePropertyChanged(nameof(OperatorID));
                RaisePropertyChanged(nameof(OperatorLevel));
            }
            else
            {
                IsRecipeOverridable = false;
                Engineer            = false;
                RaisePropertyChanged(nameof(OperatorID));
                RaisePropertyChanged(nameof(OperatorLevel));
            }

            if (authLevel != AuthorizationLevel.InvalidUser)
            {
                Messenger.Default.Send(new CurrentOperatorMessage(thisPortNo, OperatorID, authLevel));
            }

            OperatorLevel = authLevel.ToString();
            MyLog.Debug($"MES->ValidateEmployee->UpdateOperatorMsgHandler sets OperatorLevel=({OperatorLevel})");

            //RaisePropertyChanged(nameof(OperatorID));
            //RaisePropertyChanged(nameof(OperatorLevel));

            //if (string.IsNullOrEmpty(_operatorID))
            //    Messenger.Default.Send(new ReFocusMessage("OperatorField", null));
            //else
            //    Messenger.Default.Send(new ReFocusMessage(string.Empty, null));
        }
        public static bool IsAuthorized(HttpRequestMessage request, AuthorizationLevel level, SecretManager secretManager, string functionName = null)
        {
            if (level == AuthorizationLevel.Anonymous)
            {
                return true;
            }

            AuthorizationLevel requestLevel = GetAuthorizationLevel(request, secretManager, functionName);
            return requestLevel >= level;
        }
 public AuthorizationLevelAttribute(AuthorizationLevel level)
 {
     Level = level;
 }