source: branches/HiveProjectManagement/HeuristicLab.Services.Hive/3.3/Manager/AuthorizationManager.cs @ 15737

Last change on this file since 15737 was 15737, checked in by jzenisek, 2 years ago

#2839

  • updated sql scripts (necessary foreign key option alterations & introduction of statistic tables)
  • updated HiveService according to changed client side (deletion-routine, permission checking,...)
File size: 8.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Security;
24using HeuristicLab.Services.Access;
25using HeuristicLab.Services.Hive.DataAccess;
26using HeuristicLab.Services.Hive.DataAccess.Interfaces;
27using DA = HeuristicLab.Services.Hive.DataAccess;
28using DT = HeuristicLab.Services.Hive.DataTransfer;
29using System.Collections.Generic;
30using System.Linq;
31
32namespace HeuristicLab.Services.Hive {
33  public class AuthorizationManager : IAuthorizationManager {
34
35    private const string NOT_AUTHORIZED_USERRESOURCE = "Current user is not authorized to access the requested resource";
36    private const string NOT_AUTHORIZED_USERPROJECT = "Current user is not authorized to access the requested project";
37    private const string NOT_AUTHORIZED_USERJOB = "Current user is not authorized to access the requested job";
38    private const string NOT_AUTHORIZED_PROJECTRESOURCE = "Selected project is not authorized to access the requested resource";
39    private const string USER_NOT_IDENTIFIED = "User could not be identified";
40    private const string TASK_NOT_EXISTENT = "Queried task could not be found";
41
42    private IPersistenceManager PersistenceManager {
43      get { return ServiceLocator.Instance.PersistenceManager; }
44    }
45
46    private IUserManager UserManager {
47      get { return ServiceLocator.Instance.UserManager; }
48    }
49
50    private IRoleVerifier RoleVerifier {
51      get { return ServiceLocator.Instance.RoleVerifier; }
52    }
53
54    public void Authorize(Guid userId) {
55      if (userId != ServiceLocator.Instance.UserManager.CurrentUserId)
56        throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
57    }
58
59    public void AuthorizeForTask(Guid taskId, DT.Permission requiredPermission) {
60      if (ServiceLocator.Instance.RoleVerifier.IsInRole(HiveRoles.Slave)) return; // slave-users can access all tasks
61      var pm = PersistenceManager;
62      var taskDao = pm.TaskDao;
63      pm.UseTransaction(() => {
64        var task = taskDao.GetById(taskId);
65        if (task == null) throw new SecurityException(TASK_NOT_EXISTENT);
66        AuthorizeJob(pm, task.JobId, requiredPermission);
67      });
68    }
69
70    public void AuthorizeForJob(Guid jobId, DT.Permission requiredPermission) {
71      var pm = PersistenceManager;
72      pm.UseTransaction(() => {
73        AuthorizeJob(pm, jobId, requiredPermission);
74      });
75    }
76
77    // authorize if user is admin or resource owner
78    public void AuthorizeForResourceAdministration(Guid resourceId) {
79      var currentUserId = UserManager.CurrentUserId;
80      var pm = PersistenceManager;
81      var resourceDao = pm.ResourceDao;
82      pm.UseTransaction(() => {
83        var resource = resourceDao.GetById(resourceId);
84        if (resource == null) throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
85
86        if (resource.OwnerUserId != currentUserId
87            && !RoleVerifier.IsInRole(HiveRoles.Administrator)) {
88          throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
89        }
90      });
91    }
92
93    // authorize if user is admin, project owner or owner of a parent project
94    public void AuthorizeForProjectAdministration(Guid projectId, bool parentalOwnership) {
95      if (projectId == null) return;
96      var currentUserId = UserManager.CurrentUserId;
97      var pm = PersistenceManager;
98      var projectDao = pm.ProjectDao;
99      pm.UseTransaction(() => {
100        List<Project> projectBranch = null;
101        if(parentalOwnership) projectDao.GetParentProjectsById(projectId).ToList();
102        else projectBranch = projectDao.GetCurrentAndParentProjectsById(projectId).ToList();
103
104        if(!RoleVerifier.IsInRole(HiveRoles.Administrator)
105            && !projectBranch.Select(x => x.OwnerUserId).Contains(currentUserId)) {
106          throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
107        }
108      });
109    }
110
111    // authorize if user is admin, or owner of a parent project, for which the resources are assigned to
112    public void AuthorizeForProjectResourceAdministration(Guid projectId, IEnumerable<Guid> resourceIds) {
113      if (projectId == null) return;
114      var currentUserId = UserManager.CurrentUserId;
115      var pm = PersistenceManager;
116      var projectDao = pm.ProjectDao;
117      var resourceDao = pm.ResourceDao;
118      var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
119      pm.UseTransaction(() => {
120        // check if project exists (not necessary)
121        var project = projectDao.GetById(projectId);
122        if (project == null) throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
123
124        // check if resourceIds exist
125        if (resourceIds != null && resourceIds.Any() && !resourceDao.CheckExistence(resourceIds))
126          throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
127
128        // check if user is admin
129        if (RoleVerifier.IsInRole(HiveRoles.Administrator)) return;
130
131        // check if user is owner of a parent project
132        var projectBranch = projectDao.GetParentProjectsById(projectId).ToList();
133        if (!projectBranch.Select(x => x.OwnerUserId).Contains(currentUserId)
134            && !RoleVerifier.IsInRole(HiveRoles.Administrator)) {
135          throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
136        }
137
138        // check if the all argument resourceIds are among the assigned resources of the owned projects
139        var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourceIdsOfOwnedParentProjects(projectId, currentUserId).ToList();
140        if(resourceIds.Except(grantedResourceIds).Any()) {
141          throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
142        }
143      });
144    }
145
146    // Check if a project is authorized to use a list of resources
147    public void AuthorizeProjectForResourcesUse(Guid projectId, IEnumerable<Guid> resourceIds) {
148      if (projectId == null || resourceIds == null || !resourceIds.Any()) return;
149      var pm = PersistenceManager;
150      var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
151      if (!assignedProjectResourceDao.CheckProjectGrantedForResources(projectId, resourceIds))
152        throw new SecurityException(NOT_AUTHORIZED_PROJECTRESOURCE);
153    }
154
155    // Check if current user is authorized to use an explicit project (e.g. in order to add a job)
156    // note: administrators and project owner are NOT automatically granted
157    public void AuthorizeUserForProjectUse(Guid userId, Guid projectId) {
158      if(userId == null || userId == Guid.Empty) {
159        throw new SecurityException(USER_NOT_IDENTIFIED);
160      }
161      if(projectId == null) return;
162
163      var pm = PersistenceManager;
164      // collect current and group membership Ids
165      var userAndGroupIds = new List<Guid>() { userId };
166      userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(userId));
167      // perform the actual check
168      var projectPermissionDao = pm.ProjectPermissionDao;
169      if (!projectPermissionDao.CheckUserGrantedForProject(projectId, userAndGroupIds)) {
170        throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
171      }
172    }
173
174    private DA.Permission GetPermissionForJob(IPersistenceManager pm, Guid jobId, Guid userId) {
175      var jobDao = pm.JobDao;
176      var jobPermissionDao = pm.JobPermissionDao;
177      var job = jobDao.GetById(jobId);
178      if (job == null) return DA.Permission.NotAllowed;
179      if (job.OwnerUserId == userId) return DA.Permission.Full;
180      var jobPermission = jobPermissionDao.GetByJobAndUserId(jobId, userId);
181      if (jobPermission == null) return DA.Permission.NotAllowed;
182      return jobPermission.Permission;
183    }
184
185    private void AuthorizeJob(IPersistenceManager pm, Guid jobId, DT.Permission requiredPermission) {
186      var currentUserId = UserManager.CurrentUserId;
187      var requiredPermissionEntity = requiredPermission.ToEntity();
188      DA.Permission permission = GetPermissionForJob(pm, jobId, currentUserId);
189      if (permission == Permission.NotAllowed
190          || ((permission != requiredPermissionEntity) && requiredPermissionEntity == Permission.Full)) {
191        throw new SecurityException(NOT_AUTHORIZED_USERJOB);
192      }
193    }
194  }
195}
Note: See TracBrowser for help on using the repository browser.