コード例 #1
0
        public async Task <IQueryable <Contest> > QueryContestAsync(string?userId, int groupId)
        {
            var user = await userManager.FindByIdAsync(userId);

            var group = await groupService.GetGroupAsync(groupId);

            if (group is null)
            {
                throw new NotFoundException("找不到该小组");
            }

            if (!PrivilegeHelper.IsTeacher(user?.Privilege))
            {
                if (group.IsPrivate)
                {
                    if (!dbContext.GroupJoin.Any(i => i.GroupId == groupId && i.UserId == userId))
                    {
                        throw new ForbiddenException("未参加该小组");
                    }
                }
            }

            IQueryable <Contest> contests = dbContext.GroupContestConfig
                                            .Where(i => i.GroupId == groupId).OrderByDescending(i => i.Id).Select(i => i.Contest);

            return(contests);
        }
コード例 #2
0
        public async Task <List <UserBasicInfoModel> > QueryUsersAsync(string patterns)
        {
            var userId   = userManager.GetUserId(User);
            var userInfo = await userManager.FindByIdAsync(userId);

            var normalizedPatterns = patterns.ToUpper();

            var users = userManager.Users.Where(i => i.Email.Contains(normalizedPatterns) ||
                                                i.NormalizedUserName.Contains(normalizedPatterns) ||
                                                (i.Name != null && i.Name.Contains(patterns)));

            if (!PrivilegeHelper.IsAdmin(userInfo?.Privilege ?? 0))
            {
                return(await users.Select(i => new UserBasicInfoModel
                {
                    Email = i.Email,
                    UserId = i.Id,
                    UserName = i.UserName
                }).ToListAsync());
            }
            else
            {
                return(await users.Select(i => new UserBasicInfoModel
                {
                    Name = i.Name,
                    Email = i.Email,
                    UserId = i.Id,
                    UserName = i.UserName
                }).ToListAsync());
            }
        }
コード例 #3
0
ファイル: ProblemService.cs プロジェクト: SYSUMSC/MSC-Judge
        public async Task <IQueryable <Problem> > QueryProblemAsync(string?userId, int contestId)
        {
            var user = await userManager.FindByIdAsync(userId);

            var contest = await contestService.GetContestAsync(contestId);

            if (contest is null)
            {
                throw new NotFoundException("找不到该比赛");
            }

            if (!PrivilegeHelper.IsTeacher(user?.Privilege))
            {
                if (contest.Hidden)
                {
                    throw new ForbiddenException();
                }
            }

            IQueryable <Problem> problems = dbContext.ContestProblemConfig
                                            .Where(i => i.ContestId == contestId)
                                            .OrderBy(i => i.Id)
                                            .Select(i => i.Problem);

            return(problems);
        }
コード例 #4
0
ファイル: UtilsController.cs プロジェクト: SYSUMSC/MSC-Judge
        public async Task <UserQueryResultListModel> QueryUser(string patterns)
        {
            var user = await userManager.GetUserAsync(User);

            IQueryable <UserInfo> users;

            if (PrivilegeHelper.IsTeacher(user.Privilege))
            {
                users = userManager.Users.Where(i =>
                                                (i.Name != null && i.Name.Contains(patterns)) ||
                                                i.NormalizedEmail.Contains(patterns.ToUpperInvariant()) ||
                                                i.NormalizedUserName.Contains(patterns.ToUpperInvariant()));
            }
            else
            {
                users = userManager.Users.Where(i => i.NormalizedUserName.Contains(patterns.ToUpper()));
            }

            var result = users.Select(i => new UserQueryResultModel
            {
                UserId   = i.Id,
                UserName = i.UserName,
                Name     = i.Name,
                Email    = i.Email
            });

            return(new UserQueryResultListModel
            {
                Users = await result.ToListAsync(),
                TotalCount = await result.CountAsync()
            });
        }
コード例 #5
0
        protected override void BeginProcessing()
        {
            WriteVerbose("Getting current process handle");
            _process = PrivilegeHelper.GetCurrentProcess();

            WriteVerbose("Getting privilege info for all privileges on the current process");
            _privInfo = PrivilegeHelper.GetAllPrivilegeInfo(_process);
        }
コード例 #6
0
ファイル: Main.cs プロジェクト: Surfndez/desktop-app-ui
        private static void UpgradePrivilegedHelper()
        {
            var flags = AuthorizationFlags.Defaults;

            using (var auth = Authorization.Create(flags)) {
                PrivilegeHelper.Upgrade(auth, flags);
            }
        }
コード例 #7
0
        public async Task <IQueryable <Contest> > QueryContestAsync(string?userId)
        {
            var user = await userManager.FindByIdAsync(userId);

            IQueryable <Contest> contests = dbContext.Contest;

            if (!PrivilegeHelper.IsTeacher(user?.Privilege))
            {
                contests = contests.Where(i => !i.Hidden || (i.SpecifyCompetitors && i.ContestRegister.Any(j => j.ContestId == i.Id && j.UserId == userId)));
            }
            return(contests);
        }
コード例 #8
0
 protected override void EndProcessing()
 {
     if (_setInfo.Count > 0)
     {
         WriteVerbose("Setting token privileges on the current process");
         if (ShouldProcess(String.Join(", ", _setInfo.Keys), $"{Action} the specified privilege(s)"))
         {
             PrivilegeHelper.SetTokenPrivileges(_process, _setInfo);
         }
     }
     _process.Dispose();
 }
コード例 #9
0
ファイル: GroupService.cs プロジェクト: SYSUMSC/MSC-Judge
        public async Task <IQueryable <Group> > QueryGroupAsync(string?userId)
        {
            var user = await userManager.FindByIdAsync(userId);

            IQueryable <Group> groups = dbContext.Group;

            if (!PrivilegeHelper.IsTeacher(user?.Privilege))
            {
                groups = groups.Where(i => (i.IsPrivate && i.GroupJoin.Any(j => j.GroupId == i.Id && j.UserId == userId)) || !i.IsPrivate);
            }

            return(groups);
        }
コード例 #10
0
ファイル: ProblemService.cs プロジェクト: SYSUMSC/MSC-Judge
        public async Task <IQueryable <Problem> > QueryProblemAsync(string?userId)
        {
            var user = await userManager.FindByIdAsync(userId);

            IQueryable <Problem> problems = dbContext.Problem;

            if (!PrivilegeHelper.IsTeacher(user?.Privilege))
            {
                problems = problems.Where(i => !i.Hidden);
            }

            return(problems);
        }
コード例 #11
0
ファイル: Main.cs プロジェクト: Surfndez/desktop-app-ui
        private static bool PartialUpgrade()
        {
            if (!WaitUntilAnotherVersionIsClosed())
            {
                return(false);
            }

            if (PrivilegeHelper.IsHelperUpgradeRequired())
            {
                return(AskAndUpgradeHelper());
            }

            return(true);
        }
コード例 #12
0
ファイル: WindowsRight.cs プロジェクト: jborean93/PSPrivilege
        private CompletionResult ProcessPrivilege(string privilege)
        {
            string displayName;

            if (Lsa.ALL_RIGHTS.ContainsKey(privilege))
            {
                displayName = Lsa.ALL_RIGHTS[privilege];
            }
            else
            {
                displayName = PrivilegeHelper.GetPrivilegeDisplayName(privilege);
            }

            return(new CompletionResult(privilege, privilege, CompletionResultType.ParameterValue, displayName));
        }
コード例 #13
0
        protected override void ProcessRecord()
        {
            WriteVerbose("Getting current process handle");
            using SafeHandle processToken = PrivilegeHelper.GetCurrentProcess();

            WriteVerbose("Getting privilege info for all privileges on the current process");
            Dictionary <string, PrivilegeAttributes> privilegeInfo = PrivilegeHelper.GetAllPrivilegeInfo(processToken);

            if (Name.Length == 0)
            {
                Name = privilegeInfo.Keys.ToArray();
            }

            foreach (string privName in Name)
            {
                if (!PrivilegeHelper.CheckPrivilegeName(privName))
                {
                    ItemNotFoundException exp = new ItemNotFoundException($"Invalid privilege name '{privName}'");
                    WriteError(new ErrorRecord(exp, "PrivilegeNotFound", ErrorCategory.ObjectNotFound, privName));
                    continue;
                }

                string description       = PrivilegeHelper.GetPrivilegeDisplayName(privName);
                bool   enabled           = false;
                bool   enableByDefault   = false;
                PrivilegeAttributes attr = PrivilegeAttributes.Removed;
                bool isRemoved           = true;

                if (privilegeInfo.ContainsKey(privName))
                {
                    attr            = privilegeInfo[privName];
                    enabled         = (attr & PrivilegeAttributes.Enabled) != 0;
                    enableByDefault = (attr & PrivilegeAttributes.EnabledByDefault) != 0;
                    isRemoved       = false;
                }

                WriteObject(new Privilege()
                {
                    Name             = privName,
                    Description      = description,
                    Enabled          = enabled,
                    EnabledByDefault = enableByDefault,
                    Attributes       = attr,
                    IsRemoved        = isRemoved,
                });
            }
        }
コード例 #14
0
        protected override void ProcessRecord()
        {
            foreach (string privName in Name)
            {
                if (!PrivilegeHelper.CheckPrivilegeName(privName))
                {
                    ItemNotFoundException exp = new ItemNotFoundException($"Invalid privilege name '{privName}'");
                    WriteError(new ErrorRecord(exp, "PrivilegeNotFound", ErrorCategory.ObjectNotFound, privName));
                    continue;
                }
                else if (!_privInfo.ContainsKey(privName))
                {
                    if (Action == "remove")
                    {
                        WriteVerbose($"The privilege '{privName}' is already removed, no action necessary");
                    }
                    else
                    {
                        InvalidOperationException exp = new InvalidOperationException(
                            $"Cannot {Action} privilege '{privName}' as it is not set on the current process");
                        WriteError(new ErrorRecord(exp, "", ErrorCategory.InvalidOperation, privName));
                    }
                    continue;
                }

                bool enabled = (_privInfo[privName] & PrivilegeAttributes.Enabled) != 0;
                if (Action == "remove")
                {
                    WriteVerbose($"The privilege '{privName}' is set, removing from process token");
                    _setInfo[privName] = null;
                }
                else if (enabled && Action == "disable")
                {
                    WriteVerbose($"The privilege '{privName}' is enabled, setting new state to disabled");
                    _setInfo[privName] = false;
                }
                else if (!enabled && Action == "enable")
                {
                    WriteVerbose($"The privilege '{privName}' is disabled, setting new state to enabled");
                    _setInfo[privName] = true;
                }
                else
                {
                    WriteVerbose($"The privilege '{privName}' is already {Action}d, no action necessary");
                }
            }
        }
コード例 #15
0
        public Task <ServiceAttachResult> AttachToService()
        {
            __TaskCompletion = new TaskCompletionSource <ServiceAttachResult>();

            PrivilegeHelper.StartAndConnectToLaunchAgent((int connectionPort) => {
                if (connectionPort > 0)
                {
                    __TaskCompletion.SetResult(new ServiceAttachResult(connectionPort));
                }
                else
                {
                    __TaskCompletion.SetResult(new ServiceAttachResult("There was an error launching IVPN Agent."));
                }
            });


            return(__TaskCompletion.Task);
        }
コード例 #16
0
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                var dbContext = context.HttpContext.RequestServices.GetService <WebHostDbContext>();

                var userId   = context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
                var userInfo = await dbContext.Users.FirstOrDefaultAsync(i => i.Id == userId);

                if (userInfo == null)
                {
                    throw new AuthenticationException("没有登录账户");
                }
                if (!PrivilegeHelper.IsTeacher(userInfo?.Privilege ?? 0))
                {
                    throw new ForbiddenException();
                }

                await next();
            }
コード例 #17
0
ファイル: ProblemService.cs プロジェクト: SYSUMSC/MSC-Judge
        public async Task <IQueryable <Problem> > QueryProblemAsync(string?userId, int contestId, int groupId)
        {
            var user = await userManager.FindByIdAsync(userId);

            var contest = await contestService.GetContestAsync(contestId);

            if (contest is null)
            {
                throw new NotFoundException("找不到该比赛");
            }

            var group = await groupService.GetGroupAsync(groupId);

            if (group is null)
            {
                throw new NotFoundException("找不到该小组");
            }

            if (!dbContext.GroupContestConfig.Any(i => i.GroupId == groupId && i.ContestId == contestId))
            {
                throw new NotFoundException("找不到该比赛");
            }

            if (!PrivilegeHelper.IsTeacher(user?.Privilege))
            {
                if (contest.Hidden)
                {
                    throw new ForbiddenException();
                }

                // user was not in this private group
                if (group.IsPrivate && !dbContext.GroupJoin.Any(i => i.GroupId == groupId && i.UserId == userId))
                {
                    throw new ForbiddenException("未参加该小组");
                }
            }

            IQueryable <Problem> problems = dbContext.ContestProblemConfig
                                            .Where(i => i.ContestId == contestId)
                                            .OrderBy(i => i.Id)
                                            .Select(i => i.Problem);

            return(problems);
        }
コード例 #18
0
ファイル: Main.cs プロジェクト: Surfndez/desktop-app-ui
        private static bool FullUpgradeIfRequired()
        {
            if (!IsRunFromApplicationFolder())
            {
                NSAlert alert = NSAlert.WithMessage(
                    "IVPN client can only run from the Applications folder. Please move the IVPN.app into the /Applications folder",
                    "Quit", null, null, "");
                alert.RunModal();

                return(false);
            }
            else
            if (PrivilegeHelper.IsHelperUpgradeRequired())
            {
                return(AskAndUpgradeHelper());
            }

            return(true);
        }
コード例 #19
0
        private bool ApplyPatches(Process process)
        {
            if (process == null)
            {
                return(false);
            }

            TOKEN_PRIVILEGES privilege = PrivilegeHelper.SetPrivilege("SeDebugPrivilege");
            IntPtr           handle    = OpenProcessVirtualAccess(process.Id);
            bool             isOkay    = true;

            isOkay = isOkay && handle != IntPtr.Zero;
            isOkay = isOkay && CheckCrc(handle);
            isOkay = isOkay && ApplyCrcPatch(handle);
            isOkay = isOkay && ApplyCommPatch(handle);
            isOkay = isOkay && ApplyGamePatches(handle);

            Kernel32Imports.CloseHandle(handle);
            PrivilegeHelper.RestorePrivilege(privilege);

            return(isOkay);
        }
コード例 #20
0
        public async Task <UserInfoModel> UserInfo(string?userId = null)
        {
            var signedIn    = signInManager.IsSignedIn(User);
            var userInfoRet = new UserInfoModel
            {
                SignedIn = string.IsNullOrEmpty(userId) && signedIn
            };

            if (string.IsNullOrEmpty(userId))
            {
                userId = userManager.GetUserId(User);
            }
            var user = await userManager.FindByIdAsync(userId);

            var currentUser = string.IsNullOrEmpty(userId) ? user : await userManager.GetUserAsync(User);

            if (userId == null || user == null)
            {
                return(new UserInfoModel());
            }
            userInfoRet.UserId     = user.Id;
            userInfoRet.UserName   = user.UserName;
            userInfoRet.Privilege  = user.Privilege;
            userInfoRet.Coins      = user.Coins;
            userInfoRet.Experience = user.Experience;
            userInfoRet.OtherInfo  = IdentityHelper.GetOtherUserInfo(string.IsNullOrEmpty(user.OtherInfo) ? "{}" : user.OtherInfo);

            if (userInfoRet.SignedIn || PrivilegeHelper.IsTeacher(currentUser?.Privilege))
            {
                userInfoRet.Name                 = user.Name;
                userInfoRet.EmailConfirmed       = user.EmailConfirmed;
                userInfoRet.PhoneNumberConfirmed = user.PhoneNumberConfirmed;
                userInfoRet.Email                = user.Email;
                userInfoRet.PhoneNumber          = user.PhoneNumber;
            }

            return(userInfoRet);
        }
コード例 #21
0
        public async Task <bool> ShowShareUIAsync(ShareUIOptions options, DataPackage dataPackage)
        {
            if (!PrivilegeHelper.IsDeclared(LaunchAppPrivilege))
            {
                if (this.Log().IsEnabled(LogLevel.Error))
                {
                    this.Log().LogError($"The Launch app privilege must be declared ({LaunchAppPrivilege})");
                }
                return(false);
            }

            var appControl = new AppControl
            {
                Operation = AppControlOperations.ShareText,
            };

            var dataPackageView = dataPackage.GetView();

            if (dataPackageView.Contains(StandardDataFormats.Text))
            {
                var text = await dataPackageView.GetTextAsync();

                appControl.ExtraData.Add(AppControlData.Text, text);
            }

            var uri = await DataTransferManager.GetSharedUriAsync(dataPackageView);

            if (uri != null)
            {
                appControl.ExtraData.Add(AppControlData.Url, uri.OriginalString);
            }

            AppControl.SendLaunchRequest(appControl);

            return(true);
        }
コード例 #22
0
        public async Task <ServiceStartResult> StartService()
        {
            if (!PrivilegeHelper.IsHelperInstalled())
            {
                Logging.Info("helper is not installed");

                bool installHelperResults = false;

                await Task.Run(() => {
                    installHelperResults = PrivilegeHelper.InstallHelper();
                });

                HelperMethodInstalled(this, new EventArgs());

                if (!installHelperResults)
                {
                    Logging.Info("helper installation failed!");

                    return(new ServiceStartResult(true, "There was an error during installation of the helper. Please try again and contact support if the problem persists."));
                }
            }

            return(new ServiceStartResult(false));
        }
 public void RegisterUser(User registeredUser)
 {
     PrivilegeHelper.CheckUserPrivilegeForMethod(((Action <User>)_userManagement.RegisterUser).Method);
     _userManagement.RegisterUser(registeredUser);
 }
 public void PromoteUser(User userToPromote, int newPrivilegeLevel)
 {
     PrivilegeHelper.CheckUserPrivilegeForMethod(((Action <User, int>)_userManagement.PromoteUser).Method);
     _userManagement.PromoteUser(userToPromote, newPrivilegeLevel);
 }
 public IEnumerable <User> GetRegisteredUsers()
 {
     PrivilegeHelper.CheckUserPrivilegeForMethod(((Func <IEnumerable <User> >)_userManagement.GetRegisteredUsers).Method);
     return(_userManagement.GetRegisteredUsers());
 }
コード例 #26
0
 public bool IsZoneDisabled(uint zone)
 {
     PrivilegeHelper.CheckUserPrivilegeForMethod(((Func <uint, bool>)_zoneManagement.IsZoneDisabled).Method);
     return(_zoneManagement.IsZoneDisabled(zone));
 }
コード例 #27
0
 public bool IsSensorDisabled(string sensorId)
 {
     PrivilegeHelper.CheckUserPrivilegeForMethod(((Func <string, bool>)_zoneManagement.IsSensorDisabled).Method);
     return(_zoneManagement.IsSensorDisabled(sensorId));
 }
 public void RemoveUser(User userToRemove)
 {
     PrivilegeHelper.CheckUserPrivilegeForMethod(((Action <User>)_userManagement.RemoveUser).Method);
     _userManagement.RemoveUser(userToRemove);
 }
コード例 #29
0
        private bool DoUninstall()
        {
            var flags = GetAuthorizationFlags();

            bool isSuccess = true;

            using (var auth = Authorization.Create(flags)) {
                // disable firewall
                var ret = IVPN.Shell.ShellCommand.RunCommand("/Applications/IVPN.app/Contents/MacOS/cli/ivpn", "firewall -off");
                if (ret.IsAborted || ret.ExitCode != 0)
                {
                    Logging.Info("Failed to disable firewall." + ((string.IsNullOrEmpty(ret.ErrorOutput)) ? "" : ret.ErrorOutput));
                }
                // disconnect (if connected)
                ret = IVPN.Shell.ShellCommand.RunCommand("/Applications/IVPN.app/Contents/MacOS/cli/ivpn", "disconnect");
                if (ret.IsAborted || ret.ExitCode != 0)
                {
                    Logging.Info("Failed to disconnect." + ((string.IsNullOrEmpty(ret.ErrorOutput)) ? "" : ret.ErrorOutput));
                }
                // logout
                ret = IVPN.Shell.ShellCommand.RunCommand("/Applications/IVPN.app/Contents/MacOS/cli/ivpn", "logout");
                if (ret.IsAborted || ret.ExitCode != 0)
                {
                    Logging.Info("Failed to logout." + ((string.IsNullOrEmpty(ret.ErrorOutput)) ? "" : ret.ErrorOutput));
                }

                if (PrivilegeHelper.IsHelperInstalled())
                {
                    // Hack to force "authentication required" window to pop-up;
                    auth.ExecuteWithPrivileges("/bin/echo", flags, new string[] { });

                    if (!PrivilegeHelper.Uninstall(auth))
                    {
                        return(false);
                    }
                }

                const string IVPNAppBundleID = "net.ivpn.client.IVPN";
                // Erasing app NSUserDefaults data
                ret = IVPN.Shell.ShellCommand.RunCommand("defaults", $"delete {IVPNAppBundleID}");
                if (ret.IsAborted || ret.ExitCode != 0)
                {
                    Logging.Info("Failed to delete application user defaults." + ((string.IsNullOrEmpty(ret.ErrorOutput)) ? "" : ret.ErrorOutput));
                    isSuccess = false;
                }

                // Erasing KeyChain
                int i = 0;
                while (IVPN.Shell.ShellCommand.RunCommand("security", $"delete-generic-password -s {IVPNAppBundleID}").ExitCode == 0)
                {
                    if (i++ > 1000) // ensure that we will not have infinite loop
                    {
                        break;
                    }
                }

                string[] filesToRemove = new string[] {
                    "/Library/Logs/IVPN Agent.log",
                    "/Library/Logs/IVPN Agent.log.0",
                    "/Library/Logs/IVPN Agent CrashInfo.log",
                    "/Library/Logs/IVPN Agent CrashInfo.log.0",
                    "/Library/Application Support/net.ivpn.client.Agent/last-btime", // seems, the file created by OS
                    System.IO.Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                        "Library/Preferences/net.ivpn.client.IVPN.plist")
                };

                string[] foldersToRemove = new string[] {
                    "/Applications/IVPN.app",
                    "/Library/Application Support/IVPN/OpenVPN",
                    System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile), "Library/Application Support/IVPN"),
                    "/Library/Application Support/IVPN",
                    "~/Library/Application Support/IVPN",
                    "/Library/Application Support/net.ivpn.client.Agent/LocalMachine", // seems, the folder created by OS
                    "/Library/Application Support/net.ivpn.client.Agent"               // seems, the folder created by OS
                };

                foreach (var file in filesToRemove)
                {
                    if (!MacHelpers.RemoveFile(auth, file))
                    {
                        Logging.Info(String.Format("Cannot remove: {0}", file));
                        isSuccess = false;
                    }
                }

                foreach (var folder in foldersToRemove)
                {
                    if (!MacHelpers.RemoveDirectory(auth, folder))
                    {
                        Logging.Info(String.Format("Cannot remove: {0}", folder));
                        isSuccess = false;
                    }
                }
            }

            return(isSuccess);
        }
コード例 #30
0
 public bool IsSensorDisabled(SensorInfo sensor)
 {
     PrivilegeHelper.CheckUserPrivilegeForMethod(((Func <SensorInfo, bool>)_zoneManagement.IsSensorDisabled).Method);
     return(_zoneManagement.IsSensorDisabled(sensor));
 }