ProjectController.cs 26.3 KB
Newer Older
1
using Coscine.Action;
2
using Coscine.Action.EventArgs;
3
4
using Coscine.Api.Project.ParameterObjects;
using Coscine.Api.Project.ReturnObjects;
5
6
using Coscine.ApiCommons;
using Coscine.ApiCommons.Factories;
7
using Coscine.Configuration;
8
9
10
using Coscine.Database.DataModel;
using Coscine.Database.Models;
using Coscine.Database.ReturnObjects;
Marcel Nellesen's avatar
Marcel Nellesen committed
11
using Coscine.Database.Util;
12
using Coscine.Logging;
13
14
15
16
using Coscine.Metadata;
using Coscine.ResourceLoader;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
17
using Microsoft.Extensions.Logging;
18
using System;
19
using System.Collections.Generic;
20
using System.Linq;
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
21
22
23

namespace Coscine.Api.Project.Controllers
{
24
25
26
27

    /// <summary>
    ///  /// This controller represents the actions which can be taken with a project object.
    /// </summary>
28
    [Authorize]
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
29
30
31
    public class ProjectController : Controller
    {
        private readonly Authenticator _authenticator;
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
32
        private readonly ProjectModel _projectModel;
33
        private readonly IConfiguration _configuration;
34
        private readonly Emitter _emitter;
Marcel Nellesen's avatar
Marcel Nellesen committed
35
        private readonly ActivatedFeaturesModel _activatedFeaturesModel;
36
        private readonly ProjectRoleModel _projectRoleModel;
37
38
39
        private readonly ProjectQuotaModel _projectQuotaModel;
        private readonly ResourceTypeModel _resourceTypeModel;
        private readonly ResourceModel _resourceModel;
40
41
        private readonly CoscineLogger _coscineLogger;
        private readonly AnalyticsLogObject _analyticsLogObject;
42
        private readonly int _maxAvailable = 100;
43

44
45
46
47
        /// <summary>
        /// ProjectController constructor
        /// </summary>
        /// <param name="logger">Logger</param>
48
        public ProjectController(ILogger<ProjectController> logger)
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
49
        {
50
            _authenticator = new Authenticator(this, Program.Configuration);
51
            _configuration = Program.Configuration;
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
52
            _projectModel = new ProjectModel();
53
            _emitter = new Emitter(_configuration);
Marcel Nellesen's avatar
Marcel Nellesen committed
54
            _activatedFeaturesModel = new ActivatedFeaturesModel();
55
            _projectRoleModel = new ProjectRoleModel();
56
57
58
            _resourceTypeModel = new ResourceTypeModel();
            _resourceModel = new ResourceModel();
            _projectQuotaModel = new ProjectQuotaModel();
59
60
            _coscineLogger = new CoscineLogger(logger);
            _analyticsLogObject = new AnalyticsLogObject();
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
61
        }
62
63
64
65
66

        /// <summary>
        /// Returns all available projects (including sub projects)
        /// </summary>
        /// <returns>Ok</returns>
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
67
        [Route("[controller]")]
68
        public ActionResult<IEnumerable<ProjectObject>> Index()
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
69
        {
70
            var user = _authenticator.GetUser();
71
            var result = _projectModel.GetWithAccess(user, UserRoles.Member, UserRoles.Owner).ToList()
72
                .Select((project) => _projectModel.CreateReturnObjectFromDatabaseObject(project))
73
74
                .OrderBy(element => element.DisplayName);

75
            if (Request.Query != null && Request.Query["noanalyticslog"] != "true")
76
77
78
79
80
81
82
            {
                LogAnalytics("List Projects", result);
            }

            return Ok(result);
        }

83
84
85
86
        /// <summary>
        /// Retrieves all top level projects
        /// </summary>
        /// <returns>Ok</returns>
87
        [Route("[controller]/-/topLevel")]
88
        public ActionResult<IEnumerable<ProjectObject>> GetTopLevelProjects()
89
90
91
92
93
94
95
        {
            var user = _authenticator.GetUser();
            var result = _projectModel.GetTopLevelWithAccess(user, UserRoles.Member, UserRoles.Owner).ToList()
                .Select((project) => _projectModel.CreateReturnObjectFromDatabaseObject(project))
                .OrderBy(element => element.DisplayName);

            if (Request.Query != null && Request.Query["noanalyticslog"] != "true")
96
97
98
            {
                LogAnalytics("View Home", result);
            }
99
100

            return Ok(result);
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
101
102
        }

103
104
105
106
107
        /// <summary>
        /// This returns the the project if the user has access to it
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Ok or Statuscode 401</returns>
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
108
        [HttpGet("[controller]/{id}")]
109
        public ActionResult<ProjectObject> Get(string id)
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
110
        {
111
112
113
114
            var user = _authenticator.GetUser();
            var project = _projectModel.GetById(Guid.Parse(id));
            if (_projectModel.HasAccess(user, project, UserRoles.Member, UserRoles.Owner))
            {
115
                SubProjectModel subProjectModel = new SubProjectModel();
116
                var subProjectRel = subProjectModel.GetAllWhere((subProject) => subProject.SubProjectId == project.Id && project.Deleted == false);
117
118
119
120
121
122
                
                var parentProjectRelation = subProjectRel.FirstOrDefault();
                if (parentProjectRelation != null && _projectModel.HasAccess(user, parentProjectRelation.ProjectId, UserRoles.Member, UserRoles.Owner))
                {
                    return Ok(_projectModel.CreateReturnObjectFromDatabaseObject(project, parentProjectRelation.ProjectId));
                }
123
124
125
126
127
128
                return Ok(_projectModel.CreateReturnObjectFromDatabaseObject(project));
            }
            else
            {
                return Unauthorized($"User is not allowed to see given the project {id}");
            }
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
129
130
        }

131
132
133
134
135
        /// <summary>
        /// Gets the resources
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Json object or Statuscode 401</returns>
136
        [HttpGet("[controller]/{id}/resources")]
137
        public ActionResult<IEnumerable<ResourceObject>> GetResources(string id)
138
        {
139
140
141
142
143
144
145
            var project = _projectModel.GetById(Guid.Parse(id));
            var user = _authenticator.GetUser();

            var resourceModel = new ResourceModel();
            var resourceTypeModel = new ResourceTypeModel();
            if (_projectModel.HasAccess(user, project, UserRoles.Member, UserRoles.Owner))
            {
146
                var resources = resourceModel.GetAllWhere((resource) =>
147
148
149
150
151
152
                        (from projectResource in resource.ProjectResourceResourceIdIds
                         where projectResource.ProjectId == project.Id
                         select projectResource).Any())
                        .Select((resource) =>
                        {
                            return resourceModel.CreateReturnObjectFromDatabaseObject(resource);
153
                        }).OrderBy(element => element.DisplayName);
154
155
156
157
                if (Request.Query != null && Request.Query["noanalyticslog"] != "true")
                {
                    LogAnalytics("View Project", null, resources, id, user); // intentionally log as view project to help identify the related user action
                }
158
                return Json(resources);
159
160
161
162
163
            }
            else
            {
                return Unauthorized($"User is not allowed to see given the project {id}");
            }
164
165
        }

166
        /// <summary>
167
        /// Retrieves the quota for the selected project.
168
        /// </summary>
169
170
171
172
        /// <param name="projectId">Id of the project.</param>
        /// <returns>List of project quotas</returns>
        [HttpGet("[controller]/{projectId}/quota/-/all")]
        public ActionResult<IEnumerable<ProjectQuota>> Quotas(string projectId)
173
174
        {
            var user = _authenticator.GetUser();
175
176
177
178
179
180
181
182
183

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
            }

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
184
            {
185
186
187
188
189
190
191
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }
192

193
194
195
196
            var projectQuotas =
                _projectQuotaModel.GetAllWhere((projectQuota) =>
                    projectQuota.ProjectId == projectGuid
                    && projectQuota.ResourceType.Enabled == true);
197

198
199
200
201
202
203
204
205
            var resourceTypes = _resourceTypeModel.GetAllWhere(x => x.Enabled);

            return Json(resourceTypes.Select(x => 
            {
                var projectQuota = _projectQuotaModel.GetWhere((y) =>
                        y.ProjectId == projectGuid &&
                        y.ResourceTypeId == x.Id);
                return new ProjectQuotaReturnObject
206
                {
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
                    Id = x.Id,
                    Name = x.DisplayName,
                    Used = CalculateUsed(x, projectGuid),
                    Allocated = projectQuota == null ? 0 : projectQuota.Quota
                };
            }));
        }

        private int CalculateUsed(ResourceType resourceType, Guid projectId)
        {
            var resourceTypeDefinition = ResourceTypeFactory.CreateResourceTypeObject(resourceType.DisplayName, _configuration);

            var resources = _resourceModel.GetAllWhere((resource) =>
                        (from projectResource in resource.ProjectResourceResourceIdIds
                         where projectResource.ProjectId == projectId
                         select projectResource).Any() &&
                         resource.TypeId == resourceType.Id);

            var used = resources.Sum(y => resourceTypeDefinition.GetResourceQuotaAvailable(y.Id.ToString(), _resourceModel.GetResourceTypeOptions(y.Id)).Result);
            return (int)used;
        }

        /// <summary>
        /// Retrieves the quota for the selected project and resource Type.
        /// </summary>
        /// <param name="projectId">Id of the project</param>
        /// <param name="resourceTypeId">Id of the resource type</param>
        /// <returns>The project quota for the resource type.</returns>
        [HttpGet("[controller]/{projectId}/quota/{resourceTypeId}")]
        public ActionResult<ProjectQuotaReturnObject> Quota(string projectId, string resourceTypeId)
        {
            var user = _authenticator.GetUser();

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
243
            }
244
245
246
247
248
249
250
251
252

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
            {
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
253
254
255
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

            if (!Guid.TryParse(resourceTypeId, out Guid resourceTypeGuid))
            {
                return BadRequest($"{resourceTypeId} is not a guid.");
            }

            var resourceType = _resourceTypeModel.GetById(resourceTypeGuid);

            if (resourceType == null || !resourceType.Enabled)
            {
                return NotFound($"Could not find resourceType with id: {resourceTypeId}");
            }

            var projectQuota =
                _projectQuotaModel.GetWhere((x) =>
                    x.ProjectId == projectGuid &&
                    x.ResourceTypeId == resourceTypeGuid);

            var projectQuotaReturnObject = new ProjectQuotaReturnObject 
            { 
                Id = resourceTypeGuid, 
                Name = resourceType.DisplayName, 
                Used = CalculateUsed(resourceType, projectGuid), 
                Allocated = projectQuota.Quota};

            return Json(projectQuotaReturnObject);
        }

        /// <summary>
        /// Get the max quota for a resource type.
        /// </summary>
        /// <param name="projectId">Id of the project.</param>
        /// <param name="resourceTypeId">Id of the resource</param>
        /// <returns>The maximum value for the quota.</returns>
        [HttpGet("[controller]/{projectId}/quota/{resourceTypeId}/max")]
        public ActionResult<MaxProjectQuota> GetQuotaMax(string projectId, string resourceTypeId)
        {
            var user = _authenticator.GetUser();

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
            }

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
            {
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }

            if (!Guid.TryParse(resourceTypeId, out Guid resourceTypeGuid))
            {
                return BadRequest($"{resourceTypeId} is not a guid.");
            }

            var resourceType = _resourceTypeModel.GetById(resourceTypeGuid);

            if (resourceType == null || !resourceType.Enabled)
            {
                return NotFound($"Could not find resourceType with id: {resourceTypeId}");
            }

            return Json(new MaxProjectQuota { Id = resourceTypeGuid, Available = _maxAvailable });
        }

        /// <summary>
        /// Update the project quota.
        /// </summary>
        /// <param name="projectId">Id of the project.</param>
        /// <param name="resourceTypeId">Id of the resource.</param>
        /// <param name="updateProjectQuotaObject">Object containing the update values.</param>
        /// <returns>NoContent (204).</returns>
        [HttpPost("[controller]/{projectId}/quota/{resourceTypeId}")]
        public IActionResult UpdateQuota(string projectId, string resourceTypeId, [FromBody]UpdateProjectQuotaObject updateProjectQuotaObject)
        {
            var user = _authenticator.GetUser();

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                return BadRequest($"{projectId} is not a guid.");
            }

            var project = _projectModel.GetById(projectGuid);

            if (project == null)
            {
                return NotFound($"Could not find project with id: {projectId}");
            }

            if (!_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
                return Unauthorized("The user is not authorized to perform a get on the selected project!");
            }

            if (!Guid.TryParse(resourceTypeId, out Guid resourceTypeGuid))
            {
                return BadRequest($"{resourceTypeId} is not a guid.");
            }

            var resourceType = _resourceTypeModel.GetById(resourceTypeGuid);

            if (resourceType == null || !resourceType.Enabled)
            {
                return NotFound($"Could not find resourceType with id: {resourceTypeId}");
            }

            if (updateProjectQuotaObject.Allocated < 0)
            {
                return BadRequest($"Allocated {updateProjectQuotaObject.Allocated}. Cannot be less than 0.");
            }

            var projectQuotaForCurrent = _projectQuotaModel.GetWhere(x => x.ProjectId == projectGuid && x.ResourceTypeId == resourceTypeGuid);
            var used = CalculateUsed(resourceType, projectGuid);

            if(used > updateProjectQuotaObject.Allocated)
            {
                return BadRequest($"Cannot set quota ({updateProjectQuotaObject.Allocated}) below the used value ({used}).");
            }

            var projectQuotaForAll = _projectQuotaModel.GetAllWhere(x => x.ProjectId == projectGuid).Sum(x => x.Quota);

            if(projectQuotaForAll - projectQuotaForCurrent.Quota + updateProjectQuotaObject.Allocated > _maxAvailable)
            {
                return BadRequest($"Cannot set quota to {updateProjectQuotaObject.Allocated}. In combination with the other quotas ({projectQuotaForAll - projectQuotaForCurrent.Quota}), it would exceed the limit of {_maxAvailable}");
            }

            projectQuotaForCurrent.Quota = updateProjectQuotaObject.Allocated;
            _projectQuotaModel.Update(projectQuotaForCurrent);

            return NoContent();
392
        }
393

394
395
396
397
398
        /// <summary>
        /// Updates the selected project 
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Ok or Statuscode 401</returns>
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
399
400
401
        [HttpPost("[controller]/{id}")]
        public IActionResult Update(string id)
        {
402
403
404
            var user = _authenticator.GetUser();
            var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
            var project = _projectModel.GetById(Guid.Parse(id));
405
            if (_projectModel.HasAccess(user, project, UserRoles.Owner))
406
            {
407
                LogAnalytics("Edit Project", null, null, id, user);
408
409
410
411
412
413
                return Ok(_projectModel.UpdateByObject(project, projectObject));
            }
            else
            {
                return Unauthorized("The user is not authorized to perform an update on the selected project!");
            }
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
414
415
        }

416
417
418
419
420
        /// <summary>
        /// Deletes the selected project
        /// </summary>
        /// <param name="id">Id of the resource</param>
        /// <returns>Json object or Statuscode 401</returns>
421
422
423
        [HttpDelete("[controller]/{id}")]
        public IActionResult Delete(string id)
        {
424
425
426
427
            var user = _authenticator.GetUser();
            var project = _projectModel.GetById(Guid.Parse(id));
            if (_projectModel.HasAccess(user, project, UserRoles.Owner))
            {
428
                LogAnalytics("Delete Project", null, null, id, user);
429
430
431
432
433
434
435
                DeleteProject(project);
                return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
            }
            else
            {
                return Unauthorized("The user is not authorized to perform an update on the selected project!");
            }
436
437
        }

438
439
440
441
442
443
        /// <summary>
        /// Deletes the project
        /// </summary>
        /// <param name="project">Project</param>
        /// <param name="isHard">isHard</param>
        /// <param name="propegateAction">propegate Action</param>
Marcel Nellesen's avatar
Marcel Nellesen committed
444
        public void DeleteProject(Database.DataModel.Project project, bool isHard = false, bool propegateAction = true)
445
        {
446
            var subProjectModel = new SubProjectModel();
447
448
449
450
            foreach (var subProject in subProjectModel.GetAllWhere(
                (subProject) => subProject.ProjectId == project.Id
                                && (subProject.SubProject_FK.Deleted == false || isHard)
            ))
451
            {
Marcel Nellesen's avatar
Marcel Nellesen committed
452
                Database.DataModel.Project subProjectObject;
453
454
455
                if (isHard)
                {
                    subProjectObject = _projectModel.GetByIdIncludingDeleted(subProject.SubProjectId);
456
                    subProjectModel.Delete(subProject);
457
458
459
460
461
462
                }
                else
                {
                    subProjectObject = _projectModel.GetById(subProject.SubProjectId);
                }
                DeleteProject(subProjectObject, isHard, propegateAction);
463
464
465
466
            }

            foreach (var subProject in subProjectModel.GetAllWhere((subProject) => subProject.SubProjectId == project.Id))
            {
467
468
469
470
                if (isHard)
                {
                    subProjectModel.Delete(subProject);
                }
471
472
            }

Marcel Nellesen's avatar
Marcel Nellesen committed
473
            if (isHard)
474
            {
Marcel Nellesen's avatar
Marcel Nellesen committed
475
                var projectResourceModel = new ProjectResourceModel();
476
477
                var resourceModel = new ResourceModel();
                var resourceTypeModel = new ResourceTypeModel();
Marcel Nellesen's avatar
Marcel Nellesen committed
478
                foreach (var projectResource in projectResourceModel.GetAllWhere((projectResource) => projectResource.ProjectId == project.Id))
479
                {
480
481
482
483
                    var resource = resourceModel.GetById(projectResource.ResourceId);
                    var resourceTypeOptions = resourceModel.GetResourceTypeOptions(projectResource.ResourceId);
                    var resourceTypeDefinition = ResourceTypeFactory.CreateResourceTypeObject(resourceTypeModel.GetById(resource.TypeId).DisplayName, _configuration);
                    resourceTypeDefinition.DeleteResource(projectResource.ResourceId.ToString(), resourceTypeOptions);
484
                    projectResourceModel.Delete(projectResource);
485
                    resourceModel.Delete(resource);
486
                }
487

Marcel Nellesen's avatar
Marcel Nellesen committed
488
489
                var projectRoleModel = new ProjectRoleModel();
                foreach (var projectRole in projectRoleModel.GetAllWhere((projectRole) => projectRole.ProjectId == project.Id))
490
491
492
                {
                    projectRoleModel.Delete(projectRole);
                }
493

Marcel Nellesen's avatar
Marcel Nellesen committed
494
495
                var projectDisciplineModel = new ProjectDisciplineModel();
                foreach (var projectDiscipline in projectDisciplineModel.GetAllWhere((projectDiscipline) => projectDiscipline.ProjectId == project.Id))
496
497
498
                {
                    projectDisciplineModel.Delete(projectDiscipline);
                }
499

Marcel Nellesen's avatar
Marcel Nellesen committed
500
501
                var projectInstituteModel = new ProjectInstituteModel();
                foreach (var projectInstitute in projectInstituteModel.GetAllWhere((projectInstitute) => projectInstitute.ProjectId == project.Id))
502
                {
Marcel Nellesen's avatar
Marcel Nellesen committed
503
504
505
                     projectInstituteModel.Delete(projectInstitute);
                }

506
                foreach (var projectQuota in _projectQuotaModel.GetAllWhere((Quota) => Quota.ProjectId == project.Id))
Marcel Nellesen's avatar
Marcel Nellesen committed
507
                {
508
                    _projectQuotaModel.Delete(projectQuota);
509
                }
510

Marcel Nellesen's avatar
Marcel Nellesen committed
511
512
                _activatedFeaturesModel.DeactivateAllFeatures(project);

513
514
515
516
517
518
519
                if (propegateAction)
                {
                    _emitter.EmitProjectDelete(new ProjectEventArgs(_configuration)
                    {
                        Project = project
                    });
                }
520

521
                _projectModel.HardDelete(project);
Marcel Nellesen's avatar
Marcel Nellesen committed
522
            }
523
524
525
526
            else
            {
                _projectModel.Delete(project);
            }
527
528
        }

529
530
531
532
        /// <summary>
        /// Creates a project
        /// </summary>
        /// <returns>Json object or Statuscode 401</returns>
533
        [HttpPost("[controller]")]
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
534
535
        public IActionResult Store()
        {
536
            var user = _authenticator.GetUser();
537
            var isRWTHMember = IsRWTHMember(user);
538
539
            var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);

540
            if (projectObject?.ParentId != new Guid()
541
542
543
544
545
                && !_projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
            {
                return Unauthorized("User is not allowed to create SubProjects.");
            }

546
            var project = _projectModel.StoreFromObject(projectObject, user, isRWTHMember);
547

548
            if (projectObject.ParentId != null
549
550
551
552
553
554
555
556
557
558
559
560
561
562
                && projectObject.ParentId != new Guid()
                // for now, only an owner can add subprojects to projects
                && _projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
            {
                var subProjectModel = new SubProjectModel();
                subProjectModel.LinkSubProject(projectObject.ParentId, project.Id);
            }

            _emitter.EmitProjectCreate(new ProjectEventArgs(_configuration)
            {
                Project = project,
                ProjectOwner = user
            });

563
564
            LogAnalytics("Add Project", null, null, project.Id.ToString(), user);

565
            return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
566
        }
567

568
569
570
571
572
        /// <summary>
        /// Checks if the given user is a member of the RWTH 
        /// </summary>
        /// <param name="user">User object</param>
        /// <returns>True, if member of RWTH or false, if not a member of RWTH</returns>
573
574
575
576
577
578
579
580
581
582
583
584
585
        private bool IsRWTHMember(User user)
        {
            var externalIds = new ExternalIdModel().GetAllWhere((externalId) => externalId.UserId == user.Id);
            if(externalIds.Count() == 0)
            {
                return false;
            }
            var externalIdList = new List<string>();
            
            foreach (var externalId in externalIds)
            {
                externalIdList.Add(externalId.ExternalIdColumn);
            }
586
            return new RdfStoreConnector(Program.Configuration.GetStringAndWait("coscine/local/virtuoso/additional/url")).GetTriples(new Uri("https://ror.org/04xfq0f34"), null, null, 1, externalIdList).Count() != 0;
587
588
        }

589
590
591
592
593
594
595
596
        /// <summary>
        /// LogAnalytics
        /// </summary>
        /// <param name="operation">Operation</param>
        /// <param name="projects">Projects</param>
        /// <param name="resources">Resources</param>
        /// <param name="projectId">Id of the project</param>
        /// <param name="user">User object</param>
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
        private void LogAnalytics(string operation,
            IEnumerable<ProjectObject> projects = null,
            IEnumerable<ResourceObject> resources = null,
            string projectId = null,
            User user = null
        )
        {
            if (CoscineLoggerConfiguration.IsLogLevelActivated(LogType.Analytics))
            {
                _analyticsLogObject.Type = "Action";
                _analyticsLogObject.Operation = operation;

                if (projects != null)
                {
                    List<string> projectList = new List<string>();
                    foreach (var entry in projects)
                    {
                        projectList.Add(entry.Id.ToString());
                    }
                    _analyticsLogObject.ProjectList = projectList;
                }
                if (resources != null)
                {
                    List<string> shownResources = new List<string>();
                    foreach (var entry in resources)
                    {
                        shownResources.Add(entry.Id.ToString());
                    }
                    _analyticsLogObject.ResourceList = shownResources;
                }
                if (projectId != null)
                {
                    _analyticsLogObject.ProjectId = projectId;
                    if (user != null)
                    {
                        _analyticsLogObject.RoleId = _projectRoleModel.GetGetUserRoleForProject(new Guid(_analyticsLogObject.ProjectId), user.Id).ToString();
                    }
                }
                _coscineLogger.AnalyticsLog(_analyticsLogObject);
            }
        }
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
638
639
    }
}