ProjectController.cs 26.1 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
                        (from projectResource in resource.ProjectResources
148
149
150
151
152
                         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
            var resourceTypes = _resourceTypeModel.GetAllWhere(x => x.Enabled.HasValue && x.Enabled.Value);
199
200
201
202
203
204
205

            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
                    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) =>
220
                        (from projectResource in resource.ProjectResources
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
                         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

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

            var resourceType = _resourceTypeModel.GetById(resourceTypeGuid);

264
            if (resourceType == null || !resourceType.Enabled.HasValue || !resourceType.Enabled.Value)
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
            {
                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);

319
            if (resourceType == null || !resourceType.Enabled.HasValue || !resourceType.Enabled.Value)
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
            {
                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);

363
            if (resourceType == null || !resourceType.Enabled.HasValue || !resourceType.Enabled.Value)
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
            {
                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}).");
            }

381
            if(updateProjectQuotaObject.Allocated > _maxAvailable)
382
            {
383
                return BadRequest($"Cannot set quota to {updateProjectQuotaObject.Allocated}. It would exceed the limit of {_maxAvailable}");
384
385
386
387
388
389
            }

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

            return NoContent();
390
        }
391

392
393
394
395
396
        /// <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
397
398
399
        [HttpPost("[controller]/{id}")]
        public IActionResult Update(string id)
        {
400
401
402
            var user = _authenticator.GetUser();
            var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
            var project = _projectModel.GetById(Guid.Parse(id));
403
            if (_projectModel.HasAccess(user, project, UserRoles.Owner))
404
            {
405
                LogAnalytics("Edit Project", null, null, id, user);
406
407
408
409
410
411
                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
412
413
        }

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

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

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

Marcel Nellesen's avatar
Marcel Nellesen committed
471
            if (isHard)
472
            {
Marcel Nellesen's avatar
Marcel Nellesen committed
473
                var projectResourceModel = new ProjectResourceModel();
474
475
                var resourceModel = new ResourceModel();
                var resourceTypeModel = new ResourceTypeModel();
Marcel Nellesen's avatar
Marcel Nellesen committed
476
                foreach (var projectResource in projectResourceModel.GetAllWhere((projectResource) => projectResource.ProjectId == project.Id))
477
                {
478
479
480
481
                    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);
482
                    projectResourceModel.Delete(projectResource);
483
                    resourceModel.Delete(resource);
484
                }
485

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

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

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

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

Marcel Nellesen's avatar
Marcel Nellesen committed
509
510
                _activatedFeaturesModel.DeactivateAllFeatures(project);

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

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

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

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

544
            var project = _projectModel.StoreFromObject(projectObject, user, isRWTHMember);
545

546
            if (projectObject.ParentId != new Guid()
547
548
549
550
551
552
553
554
555
556
557
558
559
                // 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
            });

560
561
            LogAnalytics("Add Project", null, null, project.Id.ToString(), user);

562
            return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
Benedikt Heinrichs's avatar
Benedikt Heinrichs committed
563
        }
564

565
566
567
568
569
        /// <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>
570
571
572
573
574
575
576
577
578
579
580
        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)
            {
581
                externalIdList.Add(externalId.ExternalId1);
582
            }
583
            return new RdfStoreConnector(Program.Configuration.GetStringAndWait("coscine/local/virtuoso/additional/url")).GetTriples(new Uri("https://ror.org/04xfq0f34"), null, null, 1, externalIdList).Count() != 0;
584
585
        }

586
587
588
589
590
591
592
593
        /// <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>
594
595
596
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
        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
635
636
    }
}