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

Last change on this file since 15628 was 15628, checked in by jzenisek, 20 months ago

#2839

  • updated TaskDao towards independency of the formerly used Task-Resource assignment entity
  • updated several permission/assignment handling service methods for client
  • added AssignedJobResource DTO
File size: 8.4 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
40    private IPersistenceManager PersistenceManager {
41      get { return ServiceLocator.Instance.PersistenceManager; }
42    }
43
44    private IUserManager UserManager {
45      get { return ServiceLocator.Instance.UserManager; }
46    }
47
48    private IRoleVerifier RoleVerifier {
49      get { return ServiceLocator.Instance.RoleVerifier; }
50    }
51
52    public void Authorize(Guid userId) {
53      if (userId != ServiceLocator.Instance.UserManager.CurrentUserId)
54        throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
55    }
56
57    public void AuthorizeForTask(Guid taskId, DT.Permission requiredPermission) {
58      if (ServiceLocator.Instance.RoleVerifier.IsInRole(HiveRoles.Slave)) return; // slave-users can access all tasks
59      var pm = PersistenceManager;
60      var taskDao = pm.TaskDao;
61      pm.UseTransaction(() => {
62        var task = taskDao.GetById(taskId);
63        if (task == null) throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
64        AuthorizeJob(pm, task.JobId, requiredPermission);
65      });
66    }
67
68    public void AuthorizeForJob(Guid jobId, DT.Permission requiredPermission) {
69      var pm = PersistenceManager;
70      pm.UseTransaction(() => {
71        AuthorizeJob(pm, jobId, requiredPermission);
72      });
73    }
74
75    // authorize if user is admin or resource owner
76    public void AuthorizeForResourceAdministration(Guid resourceId) {
77      var currentUserId = UserManager.CurrentUserId;
78      var pm = PersistenceManager;
79      var resourceDao = pm.ResourceDao;
80      pm.UseTransaction(() => {
81        var resource = resourceDao.GetById(resourceId);
82        if (resource == null) throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
83
84        if (resource.OwnerUserId != currentUserId
85            && !RoleVerifier.IsInRole(HiveRoles.Administrator)) {
86          throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
87        }
88      });
89    }
90
91    // authorize if user is admin, project owner or owner of a parent project
92    public void AuthorizeForProjectAdministration(Guid projectId) {
93      if (projectId == null) return;
94      var currentUserId = UserManager.CurrentUserId;
95      var pm = PersistenceManager;
96      var projectDao = pm.ProjectDao;
97      pm.UseTransaction(() => {
98        var projectBranch = projectDao.GetCurrentAndParentProjectsById(projectId).ToList();
99        if(!projectBranch.Select(x => x.OwnerUserId).Contains(currentUserId)
100            && !RoleVerifier.IsInRole(HiveRoles.Administrator)) {
101          throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
102        }
103      });
104    }
105
106    // authorize if user is admin, or owner of a parent project, for which the resources are assigned to
107    public void AuthorizeForProjectResourceAdministration(Guid projectId, IEnumerable<Guid> resourceIds) {
108      if (projectId == null) return;
109      var currentUserId = UserManager.CurrentUserId;
110      var pm = PersistenceManager;
111      var projectDao = pm.ProjectDao;
112      var resourceDao = pm.ResourceDao;
113      var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
114      pm.UseTransaction(() => {
115        // check if project exists (not necessary)
116        var project = projectDao.GetById(projectId);
117        if (project == null) throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
118
119        // check if resourceIds exist
120        if (resourceIds != null && resourceIds.Any() && !resourceDao.CheckExistence(resourceIds))
121          throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
122
123        // check if user is admin
124        if (RoleVerifier.IsInRole(HiveRoles.Administrator)) return;
125
126        // check if user is owner of a parent project
127        var projectBranch = projectDao.GetParentProjectsById(projectId).ToList();
128        if (!projectBranch.Select(x => x.OwnerUserId).Contains(currentUserId)
129            && !RoleVerifier.IsInRole(HiveRoles.Administrator)) {
130          throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
131        }
132
133        // check if the all argument resourceIds are among the assigned resources of the owned projects
134        var grantedResourceIds = assignedProjectResourceDao.GetAllGrantedResourceIdsOfOwnedParentProjects(projectId, currentUserId).ToList();
135        if(resourceIds.Except(grantedResourceIds).Any()) {
136          throw new SecurityException(NOT_AUTHORIZED_USERRESOURCE);
137        }
138      });
139    }
140
141    // Check if a project is authorized to use a list of resources
142    public void AuthorizeProjectForResourcesUse(Guid projectId, IEnumerable<Guid> resourceIds) {
143      if (projectId == null || resourceIds == null || !resourceIds.Any()) return;
144      var pm = PersistenceManager;
145      var assignedProjectResourceDao = pm.AssignedProjectResourceDao;
146      if (!assignedProjectResourceDao.CheckProjectGrantedForResources(projectId, resourceIds))
147        throw new SecurityException(NOT_AUTHORIZED_PROJECTRESOURCE);
148    }
149
150    // Check if current user is authorized to use an explicit project (e.g. in order to add a job)
151    // note: administrators and project owner are NOT automatically granted
152    public void AuthorizeUserForProjectUse(Guid userId, Guid projectId) {
153      if (userId == null || projectId == null) return;
154      var pm = PersistenceManager;
155      // collect current and group membership Ids
156      var userAndGroupIds = new List<Guid>() { userId };
157      userAndGroupIds.AddRange(UserManager.GetUserGroupIdsOfUser(userId));
158      // perform the actual check
159      var projectPermissionDao = pm.ProjectPermissionDao;
160      if (!projectPermissionDao.CheckUserGrantedForProject(projectId, userAndGroupIds)) {
161        throw new SecurityException(NOT_AUTHORIZED_USERPROJECT);
162      }
163    }
164
165    private DA.Permission GetPermissionForJob(IPersistenceManager pm, Guid jobId, Guid userId) {
166      var jobDao = pm.JobDao;
167      var jobPermissionDao = pm.JobPermissionDao;
168      var job = jobDao.GetById(jobId);
169      if (job == null) return DA.Permission.NotAllowed;
170      if (job.OwnerUserId == userId) return DA.Permission.Full;
171      var jobPermission = jobPermissionDao.GetByJobAndUserId(jobId, userId);
172      if (jobPermission == null) return DA.Permission.NotAllowed;
173      return jobPermission.Permission;
174    }
175
176    private void AuthorizeJob(IPersistenceManager pm, Guid jobId, DT.Permission requiredPermission) {
177      var currentUserId = UserManager.CurrentUserId;
178      var requiredPermissionEntity = requiredPermission.ToEntity();
179      DA.Permission permission = GetPermissionForJob(pm, jobId, currentUserId);
180      if (permission == Permission.NotAllowed
181          || ((permission != requiredPermissionEntity) && requiredPermissionEntity == Permission.Full)) {
182        throw new SecurityException(NOT_AUTHORIZED_USERJOB);
183      }
184    }
185  }
186}
Note: See TracBrowser for help on using the repository browser.