コード例 #1
0
ファイル: AdminManager.cs プロジェクト: prostickman/sdnuoj
        /// <summary>
        /// 验证是否有指定权限
        /// </summary>
        /// <param name="type">指定权限</param>
        /// <returns>是否有指定权限</returns>
        public static Boolean HasPermission(PermissionType type)
        {
            UserStatus user = UserManager.CurrentUser;
            PermissionType userPermission = (user != null ? UserManager.InternalAdminGetPermissionByName(user.UserName) : PermissionType.None);

            return ((userPermission & type) == type);
        }
コード例 #2
0
ファイル: SKDReportProvider.cs プロジェクト: xbadcode/Rubezh
		public SKDReportProvider(string title, int index, SKDReportGroup? group = null, PermissionType? permission = null)
		{
			Title = title;
			Index = index;
			Group = group;
			Permission = permission;
		}
コード例 #3
0
ファイル: TEUser.aspx.cs プロジェクト: phiree/testttt
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (txtName.Text == "" || cbList.SelectedItem == null)
        {
            ShowNotification("用户名或权限未填写");
            return;
        }
        DJ_User_TourEnterprise mgrUser = new DJ_User_TourEnterprise();
        if (Request.QueryString["userid"] != null)
        {
            mgrUser = blldj_user.GetByMemberId(Guid.Parse(Request.QueryString["userid"]));
        }
        else
        {
            mgrUser.Password = FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "MD5");
        }
        mgrUser.Enterprise = Master.CurrentTE;
        mgrUser.Name = txtName.Text;
        Model.PermissionType sat = 0;
        int result, result2;
        for (int i = 0; i < cbList.Items.Count; i++)
        {
            if (cbList.Items[i].Selected)
            {
                Model.PermissionType permisson = new PermissionType();
                switch (i)
                {
                    case 0: permisson = Model.PermissionType.信息编辑员; sat = sat | permisson; break;
                    case 1: permisson = Model.PermissionType.报表查看员; break;
                    case 2: permisson = Model.PermissionType.用户管理员; break;
                    default:
                        break;
                }
                sat = sat | permisson;
            }
        }
        int.TryParse(mgrUser.PermissionType.ToString(), out result);
        int.TryParse(sat.ToString(), out result2);
        if (result == 7 && result2 != 7)
        {
            IList<DJ_User_TourEnterprise> Listuser = blldj_user.GetUser_TEbyId(Master.CurrentTE.Id, 7);
            if (Listuser != null && Listuser.Count <= 1)
            {
                ShowNotification("目前仅有这一个超级管理员,无法更改权限");
                return;
            }
        }
        mgrUser.PermissionType = sat;

        string message;
        blldj_user.SaveOrUpdate(mgrUser, out message);
        if (message != "")
        {
            ShowNotification(message);
        }
        else
            ShowNotification("提示", "保存成功", "/TourEnterprise/TEUserManager.aspx");
    }
コード例 #4
0
ファイル: NavigationItem.cs プロジェクト: hjlfmy/Rubezh
 public NavigationItem(string title, string icon = null, IList<NavigationItem> childs = null, PermissionType? permission = null)
 {
     Title = title;
     Icon = icon;
     Childs = new ReadOnlyCollection<NavigationItem>(childs ?? new List<NavigationItem>());
     PermissionPredicate = null;
     IsVisible = true;
     IsSelectionAllowed = false;
     SupportMultipleSelect = false;
 }
コード例 #5
0
 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
 internal static void Demand(PermissionType permissionType)
 {
     //    The intent of the method is to be an internal mscorlib helper that Demands a specific permissiontype
     //    without having to create objects.
     //    The security annotation fxcop rule that flags all methods with a Demand() has logic
     //    which checks for methods named Demand in types that implement IPermission or IStackWalk. 
     Contract.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
     
     StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
     CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark);
 }
コード例 #6
0
        static void PlatformEnsureDeclared(PermissionType permission)
        {
            var info = NSBundle.MainBundle.InfoDictionary;

            if (permission == PermissionType.LocationWhenInUse)
            {
                if (!info.ContainsKey(new NSString("NSLocationWhenInUseUsageDescription")))
                {
                    throw new PermissionException("You must set `NSLocationWhenInUseUsageDescription` in your Info.plist file to enable Authorization Requests for Location updates.");
                }
            }
        }
コード例 #7
0
        static Task <PermissionStatus> PlatformCheckStatusAsync(PermissionType permission)
        {
            EnsureDeclared(permission);

            switch (permission)
            {
            case PermissionType.LocationWhenInUse:
                return(Task.FromResult(GetLocationStatus()));
            }

            return(Task.FromResult(PermissionStatus.Granted));
        }
コード例 #8
0
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        internal static void Demand(PermissionType permissionType)
        {
            //    The intent of the method is to be an internal mscorlib helper that Demands a specific permissiontype
            //    without having to create objects.
            //    The security annotation fxcop rule that flags all methods with a Demand() has logic
            //    which checks for methods named Demand in types that implement IPermission or IStackWalk.
            Contract.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");

            StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;

            CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark);
        }
コード例 #9
0
        public static void Seed(ApplicationDbContext database)
        {
            if (!database.Permissions.Any())
            {
                PermissionType permissionType1 = new PermissionType
                {
                    Description = "Enfermedad"
                };

                PermissionType permissionType2 = new PermissionType
                {
                    Description = "Personal"
                };


                PermissionType permissionType3 = new PermissionType
                {
                    Description = "Vacaciones"
                };

                database.PermissionTypes.Add(permissionType1);
                database.PermissionTypes.Add(permissionType2);
                database.PermissionTypes.Add(permissionType3);
                database.SaveChanges();

                Permission permission1 = new Permission
                {
                    ApellidoEmpleado = "De La Cruz",
                    NombreEmpleado   = "Néstor",
                    PermissionTypeId = permissionType1.Id
                };

                Permission permission2 = new Permission
                {
                    ApellidoEmpleado = "Nadal",
                    NombreEmpleado   = "Rafael",
                    PermissionTypeId = permissionType2.Id
                };

                Permission permission3 = new Permission
                {
                    ApellidoEmpleado = "Amanda",
                    NombreEmpleado   = "Lopez",
                    PermissionTypeId = permissionType3.Id
                };

                database.Permissions.Add(permission1);
                database.Permissions.Add(permission2);
                database.Permissions.Add(permission3);

                database.SaveChanges();
            }
        }
コード例 #10
0
        private DMSLogicModel GetDMSAndCheckPermission(string shortCode, PermissionType permissionType)
        {
            var task = m_dbAdapter.Task.GetTask(shortCode);

            CheckPermission(PermissionObjectType.Task, shortCode, permissionType);

            var projectLogicModel = Platform.GetProject(task.ProjectId);

            var dmsJoinLogicModel = new DMSLogicModel(CurrentUserName, projectLogicModel, DMSType.Task, shortCode);

            return(dmsJoinLogicModel);
        }
コード例 #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="permissionType"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public bool UserHasPermission(PermissionType permissionType, string objectType)
        {
            if (!IsAuthenticated())
            {
                return(false);
            }

            //this permissions will be returned from cache based on profile
            var permissions = _securityObjectStorageProvider.GetAllPermissionsForUser(GetCurrentUserProfile());

            return(permissions.Any(x => x.Permission == (int)permissionType && x.ObjectType == objectType));
        }
コード例 #12
0
        public async Task <PermissionType> PostPermission([FromBody] PermissionType permission)
        {
            if (!PermissionValidator.ValidateIsNotEmpty(null, permission.Description)
                .WithRequiredCharacters(permission.Description, 5)
                .IsValid)
            {
                return(await Task.FromResult(new PermissionType()));
            }

            _permissionService.AddPermission(permission);
            return(await Task.FromResult(permission));
        }
コード例 #13
0
        private void SetDefault(PermissionType permission)
        {
            switch (permission)
            {
            case PermissionType.None:
                Forms.SetAll      = false;
                Members.SetAll    = false;
                Admins.SetAll     = false;
                Coaches.SetAll    = false;
                Moderators.SetAll = false;
                break;

            case PermissionType.Coach:
                Members.SetAll    = true;
                Admins.SetAll     = false;
                Coaches.SetAll    = false;
                Moderators.SetAll = false;
                Forms.SetAll      = false;
                Forms.ViewForms.ViewAttendanceForm = true;
                break;

            case PermissionType.Moderator:
                Members.SetAll = true;
                Forms.SetAll   = false;
                Forms.ViewForms.ViewAttendanceForm      = true;
                Forms.Attendance.ViewTrainersAttendance = true;
                Admins.SetAll     = false;
                Coaches.SetAll    = false;
                Moderators.SetAll = false;
                break;

            case PermissionType.Admin:
                Members.SetAll    = true;
                Forms.SetAll      = true;
                Coaches.SetAll    = true;
                Moderators.SetAll = true;
                Admins.SetAll     = false;
                break;

            case PermissionType.SuperAdmin:
                Members.SetAll    = true;
                Forms.SetAll      = true;
                Coaches.SetAll    = true;
                Moderators.SetAll = true;
                Admins.SetAll     = true;
                break;

            default:
                SetDefault(PermissionType.None);
                break;
            }
        }
コード例 #14
0
ファイル: AdminController.cs プロジェクト: 080779/ims.sys
        public async Task <ActionResult> List(string mobile, DateTime?startTime, DateTime?endTime, int pageIndex = 1)
        {
            string            adminMobile = (await adminService.GetModelAsync(Convert.ToInt64(Session["Platform_AdminUserId"]))).Mobile;
            long              id          = (await adminService.GetModelAsync(Convert.ToInt64(Session["Platform_AdminUserId"]))).Id;
            AdminSearchResult result;

            if (adminService.HasPermission(id, "管理员管理_查看其他管理员"))
            {
                result = await adminService.GetModelListHasPerAsync(adminMobile, mobile, startTime, endTime, pageIndex, pageSize);
            }
            else
            {
                result = await adminService.GetModelListAsync(adminMobile, mobile, startTime, endTime, pageIndex, pageSize);
            }
            ListViewModel model = new ListViewModel();

            model.Admins = result.Admins;
            PermissionTypeDTO[] types = await permissionTypeService.GetModelList();

            List <PermissionType> permissionTypes = new List <PermissionType>();

            foreach (var type in types)
            {
                PermissionType permissionType = new PermissionType();
                permissionType.Name = type.Name;
                PermissionDTO[] permissions = await permissionService.GetByTypeIdAsync(type.Id);

                permissionType.Permissions = permissions.ToList();
                permissionTypes.Add(permissionType);
            }
            model.PermissionTypes = permissionTypes;

            Pagination pager = new Pagination();

            pager.PageIndex  = pageIndex;
            pager.PageSize   = pageSize;
            pager.TotalCount = result.TotalCount;

            if (result.TotalCount <= pageSize)
            {
                model.PageHtml = "";
            }
            else
            {
                model.PageHtml = pager.GetPagerHtml();
            }
            model.Pages     = pager.Pages;
            model.PageCount = pager.PageCount;
            return(Json(new AjaxResult {
                Status = 1, Data = model
            }));
        }
コード例 #15
0
        public Permission GetPermission(string userName, string objectUid, PermissionType type)
        {
            var records = m_db.Fetch <ABSMgrConn.TablePermission>(
                "SELECT * FROM " + m_defaultTableName
                + " where user_name = @0 and permission_object_unique_identifier = @1 and permission_type = @2",
                userName, objectUid, (int)type);

            if (records.Count > 0)
            {
                return(new Permission(records.First()));
            }
            return(null);
        }
コード例 #16
0
 public bool Delete(PermissionType model)
 {
     try
     {
         _context.Entry(model).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
         _context.SaveChanges();
     }
     catch (Exception ex)
     {
         return(false);
     }
     return(true);
 }
コード例 #17
0
        public void RequestPermissions(PermissionType permissionType = PermissionType.Always)
        {
            switch (permissionType)
            {
            case PermissionType.Always:
                _locationManager.RequestAlwaysAuthorization();
                break;

            case PermissionType.WhenInUse:
                _locationManager.RequestWhenInUseAuthorization();
                break;
            }
        }
コード例 #18
0
ファイル: PlayerPresenter.cs プロジェクト: AkimiM/stage_360
        void ChangeLayer(PermissionType permissionType)
        {
            switch (permissionType)
            {
            case PermissionType.Performer:
                playerTransform.gameObject.layer = LayerMask.NameToLayer("Performer");
                break;

            case PermissionType.Audience:
                playerTransform.gameObject.layer = LayerMask.NameToLayer("Audience");
                break;
            }
        }
コード例 #19
0
        /// <summary>
        /// 根据Id获取
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public PermissionType GetById(int Id)
        {
            PermissionType obj = NSession.Get <PermissionType>(Id);

            if (obj == null)
            {
                throw new Exception("返回实体为空");
            }
            else
            {
                return(obj);
            }
        }
コード例 #20
0
 public ActionResult Edit(PermissionType obj)
 {
     try
     {
         NSession.Update(obj);
         NSession.Flush();
     }
     catch (Exception ee)
     {
         return(Json(new { IsSuccess = false, ErrorMsg = "出错了" }));
     }
     return(Json(new { IsSuccess = true }));
 }
コード例 #21
0
        public static bool IsAllowed(this IPrincipal user, string section, PermissionType permissionType)
        {
            var perm = from per in user.Permissions()
                       where per.TypeOfPermission == permissionType && per.Section == section
                       select per;
            var isAllowed = false;

            if (perm.Count <PermissionHelper>() > 0)
            {
                isAllowed = true;
            }
            return(isAllowed);
        }
        void ChangeLayer(PermissionType permissionType)
        {
            switch (permissionType)
            {
            case PermissionType.Performer:
                PlayerTransform.gameObject.layer = LayerName.Performer;
                break;

            case PermissionType.Audience:
                PlayerTransform.gameObject.layer = LayerName.Audience;
                break;
            }
        }
コード例 #23
0
        public async Task <string> DeletePermission([FromBody] PermissionType permission)
        {
            if (permission == null)
            {
                var failed = "invalid operation";
                return(await Task.FromResult(failed));
            }

            _permissionService.DeletePermission(permission);
            var ok = $"{permission.Id} Deleted";

            return(await Task.FromResult(ok));
        }
コード例 #24
0
ファイル: UserPlugin.cs プロジェクト: windygu/SeecoolCCTV2
        public bool HasPermission(string category, PermissionType pt)
        {
            //mock
            if (category == "TestPlugin1.TestCommand1" &&
                pt == PermissionType.Operate &&
                _currentUser != null &&
                _currentUser.UserName == "wyj")
            {
                return(false);
            }

            return(true);
        }
コード例 #25
0
        /// <summary>
        /// Returns whether a type of permission has been granted.
        /// </summary>
        /// <param name="type">The permission type.</param>
        /// <returns></returns>
        public bool HasPermissions(PermissionType type)
        {
            switch (type)
            {
            case PermissionType.Camera:
                SetCachedCameraPermissions(aRCameraManager.permissionGranted);
                return(CachedCameraPermissions);

            default:
                Debug.Log("Permission type not supported!");
                return(false);
            }
        }
コード例 #26
0
        private static void VerifyPermissionType(PermissionType permission)
        {
            Assert.NotNull(permission);

            Assert.NotNull(permission.SchemeName);
            Assert.Equal("scheme name", permission.SchemeName);

            Assert.NotNull(permission.Scopes);
            ScopeType scope = Assert.Single(permission.Scopes);

            Assert.Equal("scope name", scope.Scope);
            Assert.Null(scope.RestrictedProperties);
        }
コード例 #27
0
        public bool Exists(long?subjectId, long featureId, PermissionType permissionType)
        {
            using (var uow = this.GetUnitOfWork())
            {
                var alumniFeaturePermissionRepository = uow.GetReadOnlyRepository <AlumniFeaturePermission>();

                if (subjectId == null)
                {
                    return(alumniFeaturePermissionRepository.Get(p => p.Subject == null && p.Feature.Id == featureId && p.PermissionType == permissionType).Count == 1);
                }
                return(alumniFeaturePermissionRepository.Get(p => p.Subject.Id == subjectId && p.Feature.Id == featureId && p.PermissionType == permissionType).Count == 1);
            }
        }
コード例 #28
0
 internal bool AuthenticateAndAuthorize(string apiKey, PermissionType permType, out User user, out ApiKey key, out Permission perm)
 {
     if (String.IsNullOrEmpty(apiKey))
     {
         throw new ArgumentNullException(nameof(apiKey));
     }
     perm = GetPermission(apiKey, permType, out user, out key);
     if (perm != null)
     {
         return(true);
     }
     return(false);
 }
コード例 #29
0
ファイル: PermissionTypeTests.cs プロジェクト: kimduquan/DMIS
        public void PermissionType_CheckSystemStructure()
        {
            Assert.AreEqual(Convert.ToUInt32(Math.Pow(2, 18) - 1), PermissionType.SystemMask);

            int id = 0;

            foreach (string name in PermissionType.SystemPermissionNames)
            {
                PermissionType pt = ActiveSchema.PermissionTypes[name];
                Assert.IsTrue(pt.Id == ++id, "Id is not " + id);
                Assert.IsTrue(pt.IsSystemPermission, name + " is not system permission");
            }
        }
コード例 #30
0
        public bool IsPermissionInRole(PermissionType permission)
        {
            var retVal = false;

            try
            {
                retVal = Role.IsPermissionInRole(permission);
            }
            catch (Exception)
            {
            }
            return(retVal);
        }
コード例 #31
0
        public override void DeletePermissionType(PermissionType permissionType)
        {
            StringBuilder sb = new StringBuilder();

            if (permissionType == null)
            {
                throw new ArgumentNullException("permissionType");
            }
            sb.Append(CreateCommentLine("Delete PermissionType: ", permissionType.Name));
            sb.Append("DELETE FROM [dbo].[SchemaPermissionTypes] WHERE PermissionId = ");
            sb.Append(permissionType.Id).AppendLine(); //@@ PermissionType.Id
            AddScript(sb);
        }
コード例 #32
0
        public CommandStub(string name, string description, string helpTag, PermissionType minPerm, int argCount, Action <CommandArgs> action)
        {
            this.ID = IDGenerator.GenerateRandomCode();

            Do                = action;
            CommandName       = name;
            Description       = description;
            HelpTag           = helpTag;
            MinimumPermission = minPerm;
            ArgCount          = argCount;

            Args = new List <string>();
        }
コード例 #33
0
        private string CreateUniqueToken(PermissionType permissionType, IEntityDefinition definition = null)
        {
            if (permissionType == null || string.IsNullOrWhiteSpace(permissionType.Code))
            {
                return(null);
            }

            if (definition == null)
            {
                return(CreateUniqueToken(permissionType.Code));
            }
            return(CreateUniqueToken(permissionType.Code, definition.EntityDefinitionCode));
        }
コード例 #34
0
        void ChangeLayer(PermissionType permissionType)
        {
            switch (permissionType)
            {
            case PermissionType.Performer:
                desktopPlayerController.gameObject.layer = LayerMask.NameToLayer("Performer");
                break;

            case PermissionType.Audience:
                desktopPlayerController.gameObject.layer = LayerMask.NameToLayer("Audience");
                break;
            }
        }
コード例 #35
0
        public PermissionType GetPermissionType(HttpContext context)
        {
            PermissionType permission = PermissionType.None;

            int?temp = context.Session.GetInt32("permission");

            if (temp != null)
            {
                permission = (PermissionType)temp;
            }

            return(permission);
        }
コード例 #36
0
ファイル: Notification.cs プロジェクト: Xuehuo/SAA-Online
 /// <summary>
 /// Notification constructor (obtain a current one)
 /// </summary>
 /// <param name="id">Notification ID in database</param>
 public Notification(int id)
 {
     var si = new SqlIntegrate(Utility.ConnStr);
     si.AddParameter("@ID", SqlIntegrate.DataType.Int, id);
     var dr = si.Reader("SELECT * FROM Notification WHERE ID = @ID");
     Content = dr["content"].ToString();
     Title = dr["title"].ToString();
     Id = id;
     Type = (PermissionType)int.Parse(dr["type"].ToString());
     _group = -1;
     if (Type == PermissionType.SelfGroupOnly)
         _group = new User(Guid.Parse(dr["UUID"].ToString())).Group;
     NotifyTime = Convert.ToDateTime(dr["notifyTime"].ToString());
 }
コード例 #37
0
ファイル: ClientManager.cs プロジェクト: xbadcode/Rubezh
		public static bool CheckPermission(PermissionType permissionType)
		{
			try
			{
				if (CurrentUser == null)
					return false;
				return CurrentUser.HasPermission(permissionType);
			}
			catch (Exception e)
			{
				Logger.Error(e, "ClientManager.CheckPermission");
				return false;
			}
		}
コード例 #38
0
ファイル: Guest.cs プロジェクト: jackdonders/ICT4Events
 public Guest(int id, string username, string password, string name, string passId, bool paid, int eventID,
     bool present, DateTime startDate, DateTime endDate, int locationID, DateTime regDate = new DateTime(),
     PermissionType permission = PermissionType.User, string surname = "", Country country = Country.Nederland,
     string city = "",
     string postal = "", string address = "", string telephone = "", int leaderID = 0)
     : base(id, username, password, name, surname, country, city, postal, address, telephone, regDate, permission)
 {
     PassID = passId;
     Paid = paid;
     EventID = eventID;
     Present = present;
     StartDate = startDate;
     EndDate = endDate;
     LocationID = locationID;
     LeaderID = leaderID == 0 ? id : leaderID;
 }
コード例 #39
0
ファイル: Notification.cs プロジェクト: Xuehuo/SAA-Online
 /// <summary>
 /// Notification constructor (create a new one)
 /// </summary>
 /// <param name="title">Notification title</param>
 /// <param name="content">Notification content</param>
 /// <param name="type">Notification type</param>
 public Notification(string title, string content, PermissionType type)
 {
     var si = new SqlIntegrate(Utility.ConnStr);
     si.AddParameter("@title", SqlIntegrate.DataType.NVarChar, title, 50);
     si.AddParameter("@content", SqlIntegrate.DataType.Text, content);
     si.AddParameter("@type", SqlIntegrate.DataType.Int, (int)type);
     si.AddParameter("@UUID", SqlIntegrate.DataType.VarChar, User.Current.UUID);
     Id = Convert.ToInt32(si.Query("INSERT INTO Notification ([title], [content], [type], [UUID]) VALUES (@title, @content, @type, @UUID); SELECT @@IDENTITY"));
     Type = type;
     Title = title;
     Content = content;
     _group = -1;
     if (type == PermissionType.SelfGroupOnly)
         _group = User.Current.Group;
     NotifyTime = DateTime.Now;
 }
コード例 #40
0
ファイル: PermissionManager.cs プロジェクト: BEXIS2/Core
        public DataPermission CreateDataPermission(long subjectId, long entityId, long dataId, RightType rightType, PermissionType permissionType = PermissionType.Grant)
        {
            DataPermission dataPermission = new DataPermission()
            {
                Subject = SubjectsRepo.Get(subjectId),
                Entity = EntitiesRepo.Get(entityId),
                DataId = dataId,
                RightType = rightType,
                PermissionType = permissionType
            };

            using (IUnitOfWork uow = this.GetUnitOfWork())
            {
                IRepository<DataPermission> featuresRepo = uow.GetRepository<DataPermission>();
                featuresRepo.Put(dataPermission);

                uow.Commit();
            }

            return (dataPermission);
        }
コード例 #41
0
ファイル: User.cs プロジェクト: GoosvandenBekerom/ICT4Events
        public User(int id, string username, string password, string name, string surname = "", Country country = Country.Nederland, string city = "", string postal = "",
            string address = "", string telephone = "", DateTime regDate = new DateTime(),
            PermissionType permission = PermissionType.User)
        {
            if (!IsValidEmail(username))
            {
                throw new FormatException("Username doesn't contain a valid email address");
            }

            ID = id;
            Username = username;
            Password = password;
            Name = name;
            Surname = surname;
            Country = country;
            City = city;
            Postal = postal;
            Address = address;
            Telephone = telephone;
            RegistrationDate = regDate;
            Permission = permission;
        }
コード例 #42
0
        public void InitialiseDatabase(Result result)
        {
            if (!result.Succeeded)
                return;

            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    SQLiteConnection connection = (SQLiteConnection)DatabaseManager.DatabaseEngine.GetConnection();
                    SQLiteCommand cmd = connection.CreateCommand();
                    cmd.CommandText = ResourceLoader.LoadTextResource("Sprocket.Security.SQLite.schema.sql");
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = procs["Insert First Client"];
                    cmd.Parameters.Add(new SQLiteParameter("@ClientSpaceID", SecurityProvider.ClientSpaceID));
                    int n = cmd.ExecuteNonQuery();

                    if (n > 0) // then a new client was inserted, so insert accompanying data
                    {
                        User user = new User(SecurityProvider.ClientSpaceID, "admin", "password", "System", "Administrator", "user@domain", true, true, false, 0);
                        PermissionType pt1 = new PermissionType(DatabaseManager.DatabaseEngine.GetUniqueID(), PermissionType.SuperUser, "Unrestricted Access", false);
                        PermissionType pt2 = new PermissionType(DatabaseManager.DatabaseEngine.GetUniqueID(), PermissionType.AdministrativeAccess, "Access Admin Area", false);
                        PermissionType pt3 = new PermissionType(DatabaseManager.DatabaseEngine.GetUniqueID(), PermissionType.UserAdministrator, "Create/Modify Users", false);
                        PermissionType pt4 = new PermissionType(DatabaseManager.DatabaseEngine.GetUniqueID(), PermissionType.RoleAdministrator, "Create/Modify Roles", false);
                        user.UserID = DatabaseManager.DatabaseEngine.GetUniqueID();
                        user.Activated = true;
                        Result r = Store(user);
                        if (r.Succeeded)
                        {
                            r = Store(pt1); if (r.Succeeded)
                            {
                                r = Store(pt2); if (r.Succeeded)
                                {
                                    r = Store(pt3); if (r.Succeeded)
                                    {
                                        r = Store(pt4); if (r.Succeeded)
                                        {
                                            r = AssignPermissionToUser(user.UserID, PermissionType.SuperUser);
                                        }
                                    }
                                }
                            }
                        }
                        if (!r.Succeeded)
                            result.SetFailed(r.Message);
                    }
                    if (result.Succeeded)
                        scope.Complete();
                }
            }
            catch (Exception ex)
            {
                result.SetFailed("Unable to initialise SQLite database for SecurityProvider: " + ex.Message);
            }
            finally
            {
                DatabaseManager.DatabaseEngine.ReleaseConnection();
            }
        }
コード例 #43
0
		public PermissionViewModel(PermissionType permissionType)
		{
			PermissionType = permissionType;
		}
コード例 #44
0
 [System.Security.SecurityCritical]  // auto-generated
 internal static void ReflectionTargetDemandHelper(PermissionType permission, PermissionSet targetGrant)
 {
     ReflectionTargetDemandHelper((int)permission, targetGrant);
 }
コード例 #45
0
 internal static extern void SpecialDemand(PermissionType whatPermission, ref StackCrawlMark stackMark);
コード例 #46
0
        // true - Check passes
        // false - Check may fail, do a stackwalk
		// It may look like we dont need three arguments here, but this is being done to 
		// avoid "is instance of" checks and casting
        private bool PreCheck(  CodeAccessPermission permObj, 
                                PermissionSet permSetObj, 
                                int capOrSet, 
                                ref StackCrawlMark stackMark,
                                PermissionType permType)
        {
            //return false;
            int status=0;
            PermissionListSet psl;
            if (capOrSet == CHECK_CAP)
                psl = GetDomainPermissionListSet(out status, permObj, capOrSet, permType);
            else
                psl = GetDomainPermissionListSet(out status, permSetObj, capOrSet, permType);

            if (status == NEED_UPDATED_PLS)
                psl = UpdateDomainPermissionListSet(out status);

			if (status == DEMAND_PASSES || status == SECURITY_OFF)
				return true;

            if (status == FULLY_TRUSTED)
            {
                if (capOrSet == CHECK_CAP)
                {
                    if (permObj is IUnrestrictedPermission)
                        return true;
                }
                else
                {
                    if (permSetObj.CanUnrestrictedOverride() == 1)
                        return true;
                }
            }

            if (status == CONTINUE || status == FULLY_TRUSTED)
			{
                if (capOrSet == CHECK_CAP)
                    return psl.CheckDemandNoThrow( permObj );
                else
                    return psl.CheckSetDemandNoThrow( permSetObj );
			}

            if (status == PLS_IS_BUSY)
                return false;

            if (status == BELOW_THRESHOLD) 
                return false;

            if (status == MULTIPLE_DOMAINS)
                return false;

            if (status == OVERRIDES_FOUND)
            {
                UpdateOverridesCount(ref stackMark); 
                return false;
            }

            if (status == NEED_STACKWALK)
                return false;
                
            BCLDebug.Assert(false,"Unexpected status from GetDomainPermissionListSet");
            return false;
        }
コード例 #47
0
        public List<PermissionTypeState> ListAllPermissionTypesAgainstUser(long userID)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    SQLiteConnection connection = (SQLiteConnection)DatabaseManager.DatabaseEngine.GetConnection();
                    SQLiteCommand cmd = connection.CreateCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = procs["ListPermissionsAndRolesForUser"];
                    cmd.Parameters.Add(new SQLiteParameter("@UserID", userID));
                    Dictionary<long, PermissionType> types = new Dictionary<long, PermissionType>();
                    Dictionary<long, Role> roles = new Dictionary<long, Role>();
                    Dictionary<long, PermissionTypeState> final = new Dictionary<long, PermissionTypeState>();
                    Dictionary<long, List<long>> role2role = new Dictionary<long, List<long>>();
                    Dictionary<long, List<long>> rolePermissions = new Dictionary<long, List<long>>();
                    SQLiteDataReader reader = cmd.ExecuteReader();
                    // permissions
                    while (reader.Read())
                    {
                        PermissionType pt = new PermissionType(reader);
                        types[pt.PermissionTypeID] = pt;
                    }
                    // roles
                    reader.NextResult();
                    while (reader.Read())
                    {
                        Role role = new Role(reader);
                        roles.Add(role.RoleID, role);
                    }
                    // role to role
                    reader.NextResult();
                    while (reader.Read())
                    {
                        long roleID = (long)reader["RoleID"];
                        long inheritsRoleID = (long)reader["InheritsRoleID"];
                        if (!role2role.ContainsKey(roleID))
                            role2role.Add(roleID, new List<long>());
                        role2role[roleID].Add(inheritsRoleID);
                    }
                    // role permissions
                    reader.NextResult();
                    while (reader.Read())
                    {
                        long roleID = (long)reader["RoleID"];
                        long ptid = (long)reader["PermissionTypeID"];
                        if (!rolePermissions.ContainsKey(roleID))
                            rolePermissions.Add(roleID, new List<long>());
                        rolePermissions[roleID].Add(ptid);
                    }
                    // user permissions
                    reader.NextResult();
                    while (reader.Read())
                    {
                        long id = (long)reader["PermissionTypeID"];
                        final.Add(id, new PermissionTypeState(types[id], PermissionState.Specified));
                    }
                    // user roles (the following code block simulates the T-SQL set-based solution
                    reader.NextResult();
                    List<List<long>> inherits = new List<List<long>>();
                    List<long> r = new List<long>();
                    while (reader.Read()) // first get the roles that this user is a member of
                    {
                        long roleID = (long)reader["RoleID"];
                        r.Add(roleID);
                    }
                    reader.Close();
                    if(r.Count > 0) // if this user was a member of any roles
                    {
                        inherits.Add(r); // add the roles as the first level of inheritances
                        while (true) // starting at the base ancestor generation of 0
                        {
                            r = new List<long>(); // start a list of roles that are inherited
                            foreach (long roleID in inherits[inherits.Count-1]) // for each role in the current generation
                                foreach (long inheritsRoleID in role2role[roleID]) // for each role _that_ role inherits
                                    if (!r.Contains(inheritsRoleID)) // if we haven't already noted down that role id
                                        r.Add(inheritsRoleID); // add the role to the list of roles inherited by this generation
                            if (r.Count == 0) // if none were inherited, we're done
                                break;
                            inherits.Add(r); // add the list of roles for this generation to the stack
                        }
                    }
                    foreach (List<long> roleIDs in inherits) // for each ancestor generation of role inheritances
                        foreach (long roleID in roleIDs) // for each set of roles that each ancestor inherits
                            if (rolePermissions.ContainsKey(roleID)) // if the role has any specific permissions
                                foreach (long ptid in rolePermissions[roleID]) // for each permission that the role has
                                    if (!final.ContainsKey(ptid)) // if we haven't already noted down that permission
                                        final.Add(ptid, new PermissionTypeState(types[ptid], PermissionState.Inherited)); // add the permission to the list

                    List<PermissionTypeState> list = new List<PermissionTypeState>();
                    list.AddRange(final.Values);
                    scope.Complete();
                    return list;
                }
            }
            finally
            {
                DatabaseManager.DatabaseEngine.ReleaseConnection();
            }
        }
コード例 #48
0
		public PermissionViewModel(PermissionType permissionType)
		{
			Name = permissionType.ToString();
			Desciption = permissionType.ToDescription();
		}
コード例 #49
0
ファイル: SecurityPageBase.cs プロジェクト: SPKT/MHX2
 void SecurityPageBase_Load(object sender, EventArgs e)
 {
     _Permission = InitPermistionBeforPageLoad();
 }
コード例 #50
0
 private static extern void SetResult(PermissionType whatPermission, int timeStamp);
コード例 #51
0
        internal static void DemandInternal(PermissionType permissionType)
        {
            CodeAccessSecurityEngine codeAccessSE = 
                (CodeAccessSecurityEngine) SecurityManager.GetCodeAccessSecurityEngine();

            if (commonSecObj == null)
            {
                // These correspond to SharedPermissionObjects in security.h, that is instances of commonly needed
                // permissions. From managed code, we regularly need Serialization and reflection emit permission.
                // The enum which acts as index into this array is same in EE and BCL. Thats why first 5 entries are null.

                // There is no synchronization on this call since the worse thing
                // that happens is that we create it multiple times (assuming that
                // assignment is atomic).

                commonSecObj =
                    new CodeAccessPermission[] {
                        null,   // Unmanaged code access permission
                        null,   // Skip verification permission
                        null,   // Reflection type info permission
                        null,   // Assert permission
                        null,   // Reflection member access permission
                        new SecurityPermission(SecurityPermissionFlag.SerializationFormatter),               
                        new ReflectionPermission(ReflectionPermissionFlag.ReflectionEmit)
                    };
            }

            BCLDebug.Assert(commonSecObj[(int)permissionType] != null,"Uninitialized commonSecObj in CodeAccessPermission");

            if (codeAccessSE != null)
            {
                StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
                codeAccessSE.Check(commonSecObj[(int)permissionType], ref stackMark, permissionType);
            }
        }
コード例 #52
0
 private static extern bool GetResult(PermissionType whatPermission, out int timeStamp);
コード例 #53
0
ファイル: UserManager.cs プロジェクト: prostickman/sdnuoj
        /// <summary>
        /// 更新指定ID的用户的用户权限
        /// </summary>
        /// <param name="userNames">用户名</param>
        /// <param name="permission">权限类型</param>
        /// <returns>是否成功更新</returns>
        internal static IMethodResult InternalAdminUpdatePermission(String userName, PermissionType permission)
        {
            if (!AdminManager.HasPermission(PermissionType.SuperAdministrator))
            {
                throw new NoPermissionException();
            }

            if (!RegexVerify.IsUserName(userName))
            {
                return MethodResult.InvalidRequest(RequestType.User);
            }

            Boolean success = UserRepository.Instance.UpdateEntityPermision(userName, permission) > 0;

            if (!success)
            {
                return MethodResult.FailedAndLog("Failed to update user's permission!");
            }

            return MethodResult.Success();
        }
コード例 #54
0
        // This is a special version of Check that knows whats the permission being demanded.
        // We first check if we know the result from last time, if not do the regular thing
        // Looks similar to COMCodeAccessSecurityEngine::SpecialDemand in the EE
        internal virtual void Check(CodeAccessPermission cap, ref StackCrawlMark stackMark, PermissionType permType)
        {

            int timeStamp = 0;

            if (GetResult(permType, out timeStamp) == true)
                return;

            if (PreCheck(cap, null, CHECK_CAP, ref stackMark, permType) == true)
            {
                SetResult(permType, timeStamp);
                return;
            }

            Check(PermissionToken.GetToken(cap),
                  cap,
                  ref stackMark,
                  DeepCheckCount,
                  (cap is IUnrestrictedPermission) ? 1 : 0);
        }
コード例 #55
0
 public Result Delete(PermissionType permissionType)
 {
     Result result = new Result();
     if (OnBeforeDeletePermissionType != null)
         OnBeforeDeletePermissionType(permissionType, result);
     if (result.Succeeded)
     {
         using (SQLiteConnection connection = new SQLiteConnection(DatabaseManager.DatabaseEngine.ConnectionString))
         {
             connection.Open();
             using (TransactionScope scope = new TransactionScope())
             {
                 try
                 {
                     SQLiteCommand cmd = connection.CreateCommand();
                     cmd.CommandText = "DELETE FROM PermissionTypes WHERE PermissionTypeID = @PermissionTypeID";
                     cmd.Parameters.Add(new SQLiteParameter("@PermissionTypeID", permissionType.PermissionTypeID));
                     cmd.ExecuteNonQuery();
                     scope.Complete();
                 }
                 catch (Exception ex)
                 {
                     return new Result("Unable to delete PermissionType: " + ex.Message);
                 }
             }
         }
         if (OnPermissionTypeDeleted != null)
             OnPermissionTypeDeleted(permissionType);
     }
     return result;
 }
コード例 #56
0
 public Result Store(PermissionType permissionType)
 {
     try
     {
         using (TransactionScope scope = new TransactionScope())
         {
             SQLiteConnection connection = (SQLiteConnection)DatabaseManager.DatabaseEngine.GetConnection();
             SQLiteCommand cmd = connection.CreateCommand();
             cmd.CommandText = procs["Store PermissionType"];
             cmd.Parameters.Add(new SQLiteParameter("@PermissionTypeID", permissionType.PermissionTypeID));
             cmd.Parameters.Add(new SQLiteParameter("@PermissionTypeCode", permissionType.PermissionTypeCode));
             cmd.Parameters.Add(new SQLiteParameter("@Description", permissionType.Description));
             cmd.Parameters.Add(new SQLiteParameter("@DefaultValue", permissionType.DefaultValue));
             cmd.ExecuteNonQuery();
             scope.Complete();
         }
     }
     catch (Exception ex)
     {
         return new Result("Unable to store PermissionType: " + ex.Message);
     }
     finally
     {
         DatabaseManager.DatabaseEngine.ReleaseConnection();
     }
     return new Result();
 }
コード例 #57
0
 /// <summary>
 /// 根据权限类型判断是否具备权限
 /// </summary>
 /// <param name="category">权限类型View/Change</param>
 /// <returns>True/False</returns>
 private bool CheckIP(PermissionType category)
 {
     bool validate = false;
     switch (category)
     {
         case PermissionType.View:
             validate = ValidateIPAddress(ipViewList);
             break;
         case PermissionType.Change:
             validate = ValidateIPAddress(ipChangeList) || ValidateIPAddress(ipChangeMemoryList);
             break;
     }
     return validate;
 }
コード例 #58
0
ファイル: House.cs プロジェクト: mynew4/DAoC
		public bool AddPermission(string targetName, PermissionType permType, int permLevel)
		{
			//  check to make sure an existing mapping doesn't exist.
			foreach (DBHouseCharsXPerms perm in _housePermissions.Values)
			{
				// fast expression to evaluate to match appropriate permissions
				if (perm.PermissionType == (int) permType)
				{
					// make sure it's not identical, which would mean we couldn't add!
					if (perm.TargetName == targetName)
						return false;
				}
			}

			// no matching permissions, create a new one and add it.
			var housePermission = new DBHouseCharsXPerms(HouseNumber, targetName, targetName, permLevel, (int) permType);
			GameServer.Database.AddObject(housePermission);

			// add it to our list
			_housePermissions.Add(GetOpenPermissionSlot(), housePermission);

			return true;
		}
コード例 #59
0
 private static extern PermissionListSet GetDomainPermissionListSet(out int status, Object demand, int capOrSet, PermissionType permType);
コード例 #60
0
ファイル: UserLogic.cs プロジェクト: WesselKuipers/ICT4Events
 /// <summary>
 /// Changes the user accounts permission level
 /// </summary>
 /// <param name="user">user to change permission level of</param>
 /// <param name="newPermissionType">PermissionType to change permission level to</param>
 public void ChangePermissionType(User user, PermissionType newPermissionType) => user.Permission = newPermissionType;