Skip to content
Snippets Groups Projects
Commit 9f1b6ccf authored by Marcel Nellesen's avatar Marcel Nellesen
Browse files

New: Included the ResourceCreator Role (coscine/issues#530)

New: Included Search Api (coscine/issues#533)
New: Included metadata in the resource view (coscine/issues#566)
New: Corrected user authentication (coscine/issues#529)
parent b0dcbc30
No related branches found
No related tags found
1 merge request!58Update: Get correct projects and sub projects
Showing
with 749 additions and 579 deletions
......@@ -13,6 +13,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Security.Claims;
namespace Coscine.Api.Project.Tests
{
......@@ -257,6 +258,11 @@ namespace Coscine.Api.Project.Tests
var context = new Mock<HttpContext>();
context.SetupGet(x => x.Request).Returns(request.Object);
var claimsPrincipal = new Mock<ClaimsPrincipal>();
Claim claim = new Claim("UserID", user.Id.ToString());
context.SetupGet(x => x.User).Returns(claimsPrincipal.Object);
context.Setup(x => x.User.FindFirst("UserID")).Returns(claim);
if (stream != null)
{
context.SetupGet(x => x.Request.Method).Returns("POST");
......
......@@ -56,17 +56,17 @@
<Reference Include="Consul, Version=0.7.2.6, Culture=neutral, PublicKeyToken=20a6ad9a81df1d95, processorArchitecture=MSIL">
<HintPath>..\packages\Consul.0.7.2.6\lib\net45\Consul.dll</HintPath>
</Reference>
<Reference Include="Coscine.Action, Version=1.7.0.0, Culture=neutral, processorArchitecture=AMD64">
<HintPath>..\packages\Coscine.Action.1.7.0\lib\net461\Coscine.Action.dll</HintPath>
<Reference Include="Coscine.Action, Version=1.7.1.0, Culture=neutral, processorArchitecture=AMD64">
<HintPath>..\packages\Coscine.Action.1.7.1\lib\net461\Coscine.Action.dll</HintPath>
</Reference>
<Reference Include="Coscine.ApiCommons, Version=1.3.1.0, Culture=neutral, PublicKeyToken=af4c1345df96546b, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.ApiCommons.1.3.1\lib\net461\Coscine.ApiCommons.dll</HintPath>
<Reference Include="Coscine.ApiCommons, Version=1.4.0.0, Culture=neutral, PublicKeyToken=af4c1345df96546b, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.ApiCommons.1.4.0\lib\net461\Coscine.ApiCommons.dll</HintPath>
</Reference>
<Reference Include="Coscine.Configuration, Version=1.4.0.0, Culture=neutral, PublicKeyToken=ce3d7a32d7dc1e5a, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.Configuration.1.4.0\lib\net461\Coscine.Configuration.dll</HintPath>
</Reference>
<Reference Include="Coscine.Database, Version=1.12.1.0, Culture=neutral, PublicKeyToken=767d77427707b70a, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.Database.1.12.1\lib\net461\Coscine.Database.dll</HintPath>
<Reference Include="Coscine.Database, Version=1.13.0.0, Culture=neutral, PublicKeyToken=767d77427707b70a, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.Database.1.13.0\lib\net461\Coscine.Database.dll</HintPath>
</Reference>
<Reference Include="Coscine.Logging, Version=1.0.1.0, Culture=neutral, PublicKeyToken=e1ed402bc3f6525e, processorArchitecture=MSIL">
<HintPath>..\packages\Coscine.Logging.1.0.1\lib\net461\Coscine.Logging.dll</HintPath>
......@@ -107,12 +107,18 @@
<Reference Include="Microsoft.AspNetCore.Antiforgery, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Antiforgery.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Antiforgery.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authentication.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authentication.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication.Core, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authentication.Core.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication.JwtBearer, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authentication.JwtBearer.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.JwtBearer.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authorization, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authorization.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authorization.dll</HintPath>
</Reference>
......@@ -371,6 +377,12 @@
<Reference Include="Microsoft.IdentityModel.Logging, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Logging.5.6.0\lib\net461\Microsoft.IdentityModel.Logging.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Protocols, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Protocols.5.3.0\lib\net461\Microsoft.IdentityModel.Protocols.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Protocols.OpenIdConnect.5.3.0\lib\net461\Microsoft.IdentityModel.Protocols.OpenIdConnect.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Tokens, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Tokens.5.6.0\lib\net461\Microsoft.IdentityModel.Tokens.dll</HintPath>
</Reference>
......
......@@ -25,8 +25,8 @@ namespace Coscine.Api.Project.Tests
public void OwnsTest()
{
ProjectModel projectModel = new ProjectModel();
Assert.IsTrue(projectModel.OwnsProject(Users[0], Projects[0]));
Assert.IsFalse(projectModel.OwnsProject(Users[0], Projects[1]));
Assert.IsTrue(projectModel.HasAccess(Users[0], Projects[0], UserRoles.Owner));
Assert.IsFalse(projectModel.HasAccess(Users[0], Projects[1], UserRoles.Owner));
var all = projectModel.GetAllWhere((project) =>
(from projectRole in project.ProjectRolesProjectIdIds
......@@ -87,15 +87,8 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
try
{
Controller.Update(Projects[1].Id.ToString());
Assert.Fail();
}
catch (Exception e)
{
Assert.IsTrue(e.GetType() == typeof(NotAuthorizedException));
}
actionResult = Controller.Update(Projects[1].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(UnauthorizedObjectResult));
// Cleanup
stream.Close();
......@@ -114,12 +107,12 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
var actionResult = Controller.Store();
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ProjectObject));
JsonResult jsonResult = (JsonResult)actionResult;
Assert.IsTrue(jsonResult.Value.GetType() == typeof(ProjectObject));
ProjectObject createdProjectObject = (ProjectObject)okObjectResult.Value;
ProjectObject createdProjectObject = (ProjectObject)jsonResult.Value;
Assert.IsTrue(createdProjectObject.Description == newProjectObject.Description);
Assert.IsTrue(createdProjectObject.DisplayName == newProjectObject.DisplayName);
......@@ -149,12 +142,12 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
var actionResult = Controller.Store();
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ProjectObject));
JsonResult result = (JsonResult)actionResult;
Assert.IsTrue(result.Value.GetType() == typeof(ProjectObject));
ProjectObject createdProjectObject = (ProjectObject)okObjectResult.Value;
ProjectObject createdProjectObject = (ProjectObject)result.Value;
stream.Close();
stream = ObjectFactory<ProjectObject>.SerializeToStream(createdProjectObject);
......@@ -162,10 +155,10 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
actionResult = Controller.Delete(createdProjectObject.Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ProjectObject));
result = (JsonResult)actionResult;
Assert.IsTrue(result.Value.GetType() == typeof(ProjectObject));
stream.Close();
}
......@@ -184,8 +177,8 @@ namespace Coscine.Api.Project.Tests
var actionResult = Controller.Store();
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
ProjectObject createdProjectObject = (ProjectObject)okObjectResult.Value;
JsonResult result = (JsonResult)actionResult;
ProjectObject createdProjectObject = (ProjectObject)result.Value;
stream.Close();
newProjectObject = new ProjectObject(Guid.NewGuid(), "NewProject", "NewDisplayName", DateTime.Now, DateTime.Now.AddYears(1), "test2;test3", "abc", "investigator", "grandId",
......@@ -205,10 +198,10 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
actionResult = Controller.Delete(createdProjectObject.Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ProjectObject));
result = (JsonResult)actionResult;
Assert.IsTrue(result.Value.GetType() == typeof(ProjectObject));
stream.Close();
}
......@@ -225,8 +218,8 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
var actionResult = Controller.Store();
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
ProjectObject createdProjectObject = (ProjectObject)okObjectResult.Value;
JsonResult result = (JsonResult)actionResult;
ProjectObject createdProjectObject = (ProjectObject)result.Value;
ProjectObject newSubProjectObject = new ProjectObject(Guid.NewGuid(), "NewSubProject", "NewDisplayNameSub", DateTime.Now, DateTime.Now.AddYears(1), "test2;test3", "abc", "investigator", "grandId",
new List<DisciplineObject>() { new DisciplineObject(Discipline.Id, Discipline.Url, Discipline.DisplayNameDe, Discipline.DisplayNameEn) },
......@@ -238,8 +231,8 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], subStream);
var subActionResult = Controller.Store();
OkObjectResult okSubObjectResult = (OkObjectResult)subActionResult;
ProjectObject createdSubProjectObject = (ProjectObject)okSubObjectResult.Value;
JsonResult resultSubProject = (JsonResult)subActionResult;
ProjectObject createdSubProjectObject = (ProjectObject)resultSubProject.Value;
SubProjectModel subProjectModel = new SubProjectModel();
var subProjects = subProjectModel.GetAllWhere((x) => x.ProjectId == createdProjectObject.Id);
......
......@@ -23,19 +23,19 @@ namespace Coscine.Api.Project.Tests
public void TestControllerIndex()
{
var actionResult = Controller.Index();
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
}
[Test]
public void TestControllerGet()
{
var actionResult = Controller.Get(Resources[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
Assert.IsTrue(okObjectResult.Value.GetType() == typeof(ResourceObject));
JsonResult result = (JsonResult)actionResult;
Assert.IsTrue(result.Value.GetType() == typeof(ResourceObject));
ResourceObject resourceObject = (ResourceObject)okObjectResult.Value;
ResourceObject resourceObject = (ResourceObject)result.Value;
Assert.IsTrue(resourceObject.Id == Resources[0].Id);
Assert.IsTrue(resourceObject.DisplayName == Resources[0].DisplayName);
......@@ -49,8 +49,8 @@ namespace Coscine.Api.Project.Tests
public void TestControllerUpdate()
{
var actionResult = Controller.Get(Resources[0].Id.ToString());
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
ResourceObject resourceObject = (ResourceObject)okObjectResult.Value;
JsonResult result = (JsonResult)actionResult;
ResourceObject resourceObject = (ResourceObject)result.Value;
resourceObject.DisplayName = "OtherName";
resourceObject.ResourceTypeOption = JObject.FromObject(new RDSResourceTypeObject(Guid.NewGuid(), "PITLABTTEST", 0));
......@@ -60,7 +60,7 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
actionResult = Controller.Update(Resources[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
// Cleanup
stream.Close();
......@@ -69,15 +69,8 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
try
{
Controller.Update(Resources[1].Id.ToString());
Assert.Fail();
}
catch (Exception e)
{
Assert.IsTrue(e.GetType() == typeof(NotAuthorizedException));
}
actionResult = Controller.Update(Resources[1].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(UnauthorizedObjectResult));
// Cleanup
stream.Close();
......@@ -107,9 +100,9 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
var actionResult = Controller.StoreToProject(Projects[0].Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
resourceObject = (ResourceObject)okObjectResult.Value;
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
JsonResult result = (JsonResult)actionResult;
resourceObject = (ResourceObject)result.Value;
// Cleanup
stream.Close();
......@@ -119,7 +112,7 @@ namespace Coscine.Api.Project.Tests
FakeControllerContext(Users[0], stream);
actionResult = Controller.Delete(resourceObject.Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
stream.Close();
}
......
......@@ -20,10 +20,10 @@ namespace Coscine.Api.Project.Tests
public void TestGettingFields()
{
var actionResult = Controller.Fields(Resources[0].Type.Id.ToString());
Assert.IsTrue(actionResult.GetType() == typeof(OkObjectResult));
Assert.IsTrue(actionResult.GetType() == typeof(JsonResult));
OkObjectResult okObjectResult = (OkObjectResult)actionResult;
List<string> fields = (List<string>) okObjectResult.Value;
JsonResult result = (JsonResult)actionResult;
List<string> fields = (List<string>) result.Value;
if(fields.Count() == 2)
{
Assert.IsTrue(fields[0] == "BucketName");
......
......@@ -88,7 +88,7 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Coscine.Database" publicKeyToken="767d77427707b70a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.12.1.0" newVersion="1.12.1.0" />
<bindingRedirect oldVersion="0.0.0.0-1.13.0.0" newVersion="1.13.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
......@@ -142,6 +142,10 @@
<assemblyIdentity name="Coscine.Logging" publicKeyToken="e1ed402bc3f6525e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.1.0" newVersion="1.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.IdentityModel.Logging" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
......
......@@ -4,10 +4,10 @@
<package id="AutoMapper.Extensions.Microsoft.DependencyInjection" version="6.0.0" targetFramework="net472" />
<package id="Castle.Core" version="4.4.0" targetFramework="net472" />
<package id="Consul" version="0.7.2.6" targetFramework="net472" />
<package id="Coscine.Action" version="1.7.0" targetFramework="net472" />
<package id="Coscine.ApiCommons" version="1.3.1" targetFramework="net472" />
<package id="Coscine.Action" version="1.7.1" targetFramework="net472" />
<package id="Coscine.ApiCommons" version="1.4.0" targetFramework="net472" />
<package id="Coscine.Configuration" version="1.4.0" targetFramework="net472" />
<package id="Coscine.Database" version="1.12.1" targetFramework="net472" />
<package id="Coscine.Database" version="1.13.0" targetFramework="net472" />
<package id="Coscine.Logging" version="1.0.1" targetFramework="net472" />
<package id="Coscine.ProxyApi" version="1.2.0" targetFramework="net472" />
<package id="Coscine.SharePoint.Webparts.Vue" version="1.4.0" targetFramework="net472" />
......@@ -22,8 +22,10 @@
<package id="Metadata" version="1.0.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Antiforgery" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication.Abstractions" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication.Core" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authentication.JwtBearer" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authorization" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Authorization.Policy" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.AspNetCore.Connections.Abstractions" version="2.2.0" targetFramework="net472" />
......@@ -115,6 +117,8 @@
<package id="Microsoft.IdentityModel" version="7.0.0" targetFramework="net472" />
<package id="Microsoft.IdentityModel.JsonWebTokens" version="5.6.0" targetFramework="net472" />
<package id="Microsoft.IdentityModel.Logging" version="5.6.0" targetFramework="net472" />
<package id="Microsoft.IdentityModel.Protocols" version="5.3.0" targetFramework="net472" />
<package id="Microsoft.IdentityModel.Protocols.OpenIdConnect" version="5.3.0" targetFramework="net472" />
<package id="Microsoft.IdentityModel.Tokens" version="5.6.0" targetFramework="net472" />
<package id="Microsoft.Net.Http.Headers" version="2.2.0" targetFramework="net472" />
<package id="Microsoft.Win32.Registry" version="4.5.0" targetFramework="net472" />
......
......@@ -91,7 +91,7 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Coscine.Database" publicKeyToken="767d77427707b70a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.12.1.0" newVersion="1.12.1.0" />
<bindingRedirect oldVersion="0.0.0.0-1.13.0.0" newVersion="1.13.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
......@@ -145,6 +145,10 @@
<assemblyIdentity name="Coscine.Logging" publicKeyToken="e1ed402bc3f6525e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.1.0" newVersion="1.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.IdentityModel.Logging" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
......
......@@ -5,6 +5,7 @@ using Coscine.ApiCommons.Factories;
using Coscine.ApiCommons.Utils;
using Coscine.Configuration;
using Coscine.Database.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
......@@ -22,6 +23,7 @@ using System.Web;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class DataSourceController : Controller
{
private readonly IConfiguration _configuration;
......@@ -30,6 +32,7 @@ namespace Coscine.Api.Project.Controllers
private static readonly HttpClient Client;
private readonly Authenticator _authenticator;
private readonly ResourceModel _resourceModel;
private readonly ProjectModel _projectModel;
static DataSourceController()
{
......@@ -45,6 +48,7 @@ namespace Coscine.Api.Project.Controllers
_jwtHandler = new JWTHandler(_configuration);
_authenticator = new Authenticator(this, _configuration);
_resourceModel = new ResourceModel();
_projectModel = new ProjectModel();
}
// inferring a ../ (urlencoded) can manipulate the url.
......@@ -53,6 +57,8 @@ namespace Coscine.Api.Project.Controllers
[HttpGet("[controller]/{resourceId}/{path}")]
public async Task<IActionResult> GetWaterButlerFolder(string resourceId, string path)
{
var user = _authenticator.GetUser();
if (!string.IsNullOrWhiteSpace(path))
{
path = HttpUtility.UrlDecode(path);
......@@ -64,6 +70,11 @@ namespace Coscine.Api.Project.Controllers
return check;
}
if (!_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
return BadRequest("User does not have permission to the resource.");
}
var authHeader = BuildAuthHeader(resource);
if (authHeader == null)
......@@ -107,6 +118,9 @@ namespace Coscine.Api.Project.Controllers
[DisableRequestSizeLimit]
public async Task<IActionResult> PutUploadFile(string resourceId, string path)
{
var user = _authenticator.GetUser();
if (!string.IsNullOrWhiteSpace(path))
{
path = HttpUtility.UrlDecode(path);
......@@ -118,6 +132,11 @@ namespace Coscine.Api.Project.Controllers
return check;
}
if(!_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
return BadRequest("User does not have permission to the resource.");
}
var authHeader = BuildAuthHeader(resource, new string[] { "gitlab" });
if (authHeader == null)
......@@ -156,6 +175,8 @@ namespace Coscine.Api.Project.Controllers
[DisableRequestSizeLimit]
public async Task<IActionResult> PutUpdateFile(string resourceId, string path)
{
var user = _authenticator.GetUser();
if (!string.IsNullOrWhiteSpace(path))
{
path = HttpUtility.UrlDecode(path);
......@@ -167,6 +188,11 @@ namespace Coscine.Api.Project.Controllers
return check;
}
if (!_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
return BadRequest("User does not have permission to the resource.");
}
var authHeader = BuildAuthHeader(resource, new string[] { "gitlab" });
if (authHeader == null)
......@@ -233,6 +259,8 @@ namespace Coscine.Api.Project.Controllers
[HttpDelete("[controller]/{resourceId}/{path}")]
public async Task<IActionResult> Delete(string resourceId, string path)
{
var user = _authenticator.GetUser();
if (!string.IsNullOrWhiteSpace(path))
{
path = HttpUtility.UrlDecode(path);
......@@ -244,6 +272,11 @@ namespace Coscine.Api.Project.Controllers
return check;
}
if (!_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
return BadRequest("User does not have permission to the resource.");
}
var authHeader = BuildAuthHeader(resource, new string[] { "gitlab" });
if (authHeader == null)
......@@ -286,7 +319,6 @@ namespace Coscine.Api.Project.Controllers
JToken resource = ObjectFactory<JToken>.DeserializeFromStream(Request.Body);
string authHeader = null;
if (resource["type"]["displayName"].ToString().ToLower() == "s3")
{
......@@ -298,10 +330,12 @@ namespace Coscine.Api.Project.Controllers
}
else if (resource["type"]["displayName"].ToString().ToLower() == "gitlab")
{
GitlabResourceType gitlabResourceType = new GitlabResourceType();
gitlabResourceType.RepositoryNumber = (int)resource["resourceTypeOption"]["RepositoryNumber"];
gitlabResourceType.RepositoryUrl = resource["resourceTypeOption"]["RepositoryUrl"].ToString();
gitlabResourceType.Token = resource["resourceTypeOption"]["Token"].ToString();
GitlabResourceType gitlabResourceType = new GitlabResourceType
{
RepositoryNumber = (int)resource["resourceTypeOption"]["RepositoryNumber"],
RepositoryUrl = resource["resourceTypeOption"]["RepositoryUrl"].ToString(),
Token = resource["resourceTypeOption"]["Token"].ToString()
};
authHeader = BuildGitlabAuthHeader(gitlabResourceType);
}
......@@ -382,11 +416,6 @@ namespace Coscine.Api.Project.Controllers
{
return NotFound($"Could not find resource with id: {resourceId}");
}
var user = _authenticator.GetUserFromToken();
if (!_resourceModel.OwnsResource(user, resource))
{
return Forbid($"The user does not own the resource {resourceId}");
}
}
catch (Exception)
{
......
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class DisciplineController : Controller
{
private readonly Authenticator _authenticator;
private readonly DisciplineModel _disciplineModel;
public DisciplineController()
{
_authenticator = new Authenticator(this, Program.Configuration);
_disciplineModel = new DisciplineModel();
}
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return _disciplineModel.GetAll().OrderBy(discipline => discipline.DisplayNameDe.Substring(discipline.DisplayNameDe.Length - 3)).Select((discipline) => new DisciplineObject(discipline.Id, discipline.Url, discipline.DisplayNameDe, discipline.DisplayNameEn));
}));
return Json(_disciplineModel.GetAll()
.OrderBy(discipline => discipline.DisplayNameDe.Substring(discipline.DisplayNameDe.Length - 3))
.Select((discipline) => new DisciplineObject(discipline.Id, discipline.Url, discipline.DisplayNameDe, discipline.DisplayNameEn)));
}
}
}
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class InstituteController : Controller
{
private readonly Authenticator _authenticator;
private readonly InstituteModel _instituteModel;
public InstituteController()
{
_authenticator = new Authenticator(this, Program.Configuration);
_instituteModel = new InstituteModel();
}
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return _instituteModel.GetAll().Select((institute) => new InstituteObject(institute.Id, institute.IKZ, institute.DisplayName));
}));
return Json(_instituteModel.GetAll()
.Select((institute) => new InstituteObject(institute.Id, institute.IKZ, institute.DisplayName)));
}
}
}
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class LicenseController : Controller
{
private readonly Authenticator _authenticator;
private readonly LicenseModel _licenseModel;
public LicenseController()
{
_authenticator = new Authenticator(this, Program.Configuration);
_licenseModel = new LicenseModel();
}
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return _licenseModel.GetAll().Select((license) => new LicenseObject(license.Id, license.DisplayName));
}));
return Json(_licenseModel.GetAll()
.Select((license) => new LicenseObject(license.Id, license.DisplayName)));
}
}
}
......@@ -11,15 +11,18 @@ using VDS.RDF.Parsing;
using VDS.RDF;
using Metadata;
using System.Web;
using System.IO;
using Microsoft.AspNetCore.Authorization;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class MetadataController : Controller
{
private readonly Authenticator _authenticator;
private readonly MetadataModel _metadataModel;
private readonly ResourceModel _resourceModel;
private readonly ProjectModel _projectModel;
private readonly Util _util;
public MetadataController()
......@@ -27,31 +30,29 @@ namespace Coscine.Api.Project.Controllers
_authenticator = new Authenticator(this, Program.Configuration);
_metadataModel = new MetadataModel();
_resourceModel = new ResourceModel();
_projectModel = new ProjectModel();
_util = new Util();
}
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return NoContent();
}));
}
// returns the basic application profile
[HttpGet("[controller]/resource/{projectId}/ap/{applicationProfileId}")]
public IActionResult GetApplicationProfile(Guid projectId, string applicationProfileId)
{
var user = _authenticator.GetUserFromToken();
var user = _authenticator.GetUser();
if (_metadataModel.IsProjectMember(user, projectId))
if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
{
var graph = _util.GetGraph(HttpUtility.UrlDecode(applicationProfileId));
var json = JToken.Parse(VDS.RDF.Writing.StringWriter.Write(graph, new RdfJsonWriter()));
return Ok(json);
return Json(json);
}
else
{
......@@ -64,10 +65,10 @@ namespace Coscine.Api.Project.Controllers
[HttpGet("[controller]/resource/{resourceId}/apc/{applicationProfileId}")]
public IActionResult GetApplicationProfileComplete(string resourceId, string applicationProfileId)
{
var user = _authenticator.GetUserFromToken();
var user = _authenticator.GetUser();
var resource = _resourceModel.GetById(Guid.Parse(resourceId));
if (_metadataModel.IsProjectMember(user, resource) && applicationProfileId != null)
if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member) && applicationProfileId != null)
{
var graph = _util.GetGraph(HttpUtility.UrlDecode(applicationProfileId));
var fixedValuesGraph = new Graph();
......@@ -90,44 +91,38 @@ namespace Coscine.Api.Project.Controllers
[HttpGet("[controller]/project/{projectId}/aplist/")]
public IActionResult ListAllApplicationProfiles(Guid projectId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
if (_metadataModel.IsProjectMember(user, projectId))
var user = _authenticator.GetUser();
if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
{
var graphUris = _util.ListGraphs();
return new JArray(graphUris.Select(x => x.ToString()).Where(x => x.StartsWith("https://purl.org/coscine/ap/")));
return Json(new JArray(graphUris.Select(x => x.ToString()).Where(x => x.StartsWith("https://purl.org/coscine/ap/"))));
}
else
{
throw new NotAuthorizedException("User is no project member!");
}
}));
}
[HttpGet("[controller]/resource/{resourceId}/filename/{filename}/ver/{version}")]
public IActionResult GetMetadataForFile(string resourceId, string filename, string version)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var user = _authenticator.GetUser();
var resource = _resourceModel.GetById(Guid.Parse(resourceId));
if (_metadataModel.IsProjectMember(user, resource))
if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
var id = _metadataModel.GenerateId(resourceId, filename, version);
var graph = _util.GetGraph(id);
return JToken.Parse(VDS.RDF.Writing.StringWriter.Write(graph, new RdfJsonWriter()));
return Json(JToken.Parse(VDS.RDF.Writing.StringWriter.Write(graph, new RdfJsonWriter())).ToString());
}
else
{
throw new NotAuthorizedException("User is no project member!");
}
}));
}
[HttpPut("[controller]/resource/{resourceId}/filename/{filename}/ver/{version}")]
public IActionResult StoreMetadataForFile(string resourceId, string filename, string version)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var innerBlock = ObjectFactory<JToken>.DeserializeFromStream(Request.Body);
var graphName = _metadataModel.GenerateId(resourceId, filename, version);
......@@ -137,9 +132,30 @@ namespace Coscine.Api.Project.Controllers
[graphName] = innerBlock
};
var user = _authenticator.GetUser();
var resource = _resourceModel.GetById(Guid.Parse(resourceId));
if (_metadataModel.IsProjectMember(user, resource))
if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
json[graphName]["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"] = new JArray
{
new JObject
{
["value"] = resource.ApplicationProfile.Substring(0, resource.ApplicationProfile.Length-1),
["type"] = "uri"
}
};
// throw bad request if empty node value is detected
JToken root = json.First.First;
foreach (var node in root)
{
string nodeValue = node.First.First["value"].ToString().ToLower();
if (String.IsNullOrEmpty(nodeValue))
{
throw new ArgumentException("Empty values in application profile are not accepted.");
}
}
var graph = new Graph();
graph.LoadFromString(json.ToString(), new RdfJsonParser());
......@@ -187,19 +203,17 @@ namespace Coscine.Api.Project.Controllers
{
throw new NotAuthorizedException("User is no project member!");
}
}));
}
[HttpGet("[controller]/vocabulary/{projectId}/{path}")]
public IActionResult GetVocabulary(Guid projectId, string path)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
if (_metadataModel.IsProjectMember(user, projectId))
var user = _authenticator.GetUser();
if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
{
var graph = _util.GetGraph(HttpUtility.UrlDecode(path));
JArray de = new JArray();
var de = new JArray();
foreach (var kv in _util.GetVocabularyLabels(graph, "de"))
{
JObject obj = new JObject
......@@ -210,7 +224,7 @@ namespace Coscine.Api.Project.Controllers
de.Add(obj);
}
JArray en = new JArray();
var en = new JArray();
foreach(var kv in _util.GetVocabularyLabels(graph, "en"))
{
JObject obj = new JObject
......@@ -227,13 +241,12 @@ namespace Coscine.Api.Project.Controllers
["en"] = en
};
return json;
return Json(json);
}
else
{
throw new NotAuthorizedException("User is no project member!");
}
}));
}
}
......
using Coscine.Action;
using Coscine.Action.EventArgs;
using Coscine.Action.Implementations.Project;
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Coscine.ApiCommons.Exceptions;
using Coscine.ApiCommons.Factories;
using Coscine.Database.Model;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using Coscine.Configuration;
using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class ProjectController : Controller
{
private readonly Authenticator _authenticator;
......@@ -27,105 +26,96 @@ namespace Coscine.Api.Project.Controllers
_authenticator = new Authenticator(this, Program.Configuration);
_configuration = Program.Configuration;
_projectModel = new ProjectModel();
_emitter = new Emitter(this._configuration);
_emitter = new Emitter(_configuration);
}
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return _projectModel.GetAllWhere((project) =>
(from projectRole in project.ProjectRolesProjectIdIds
where projectRole.User == user
&& projectRole.Role.DisplayName == "Owner"
select projectRole).Any()
).Select((project) => _projectModel.CreateReturnObjectFromDatabaseObject(project));
}));
var user = _authenticator.GetUser();
return Ok(_projectModel.GetWithAccess(user, UserRoles.Member, UserRoles.Owner).ToList()
.Select((project) => _projectModel.CreateReturnObjectFromDatabaseObject(project))
.OrderBy(element => element.DisplayName)
);
}
[HttpGet("[controller]/{id}")]
public IActionResult Get(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var user = _authenticator.GetUser();
var project = _projectModel.GetById(Guid.Parse(id));
if (_projectModel.CanSeeProject(user, project))
if (_projectModel.HasAccess(user, project, UserRoles.Member, UserRoles.Owner))
{
return _projectModel.CreateReturnObjectFromDatabaseObject(project);
return Ok(_projectModel.CreateReturnObjectFromDatabaseObject(project));
}
else
{
throw new UnauthorizedAccessException("User is not allowed to see given project Id!");
return Unauthorized($"User is not allowed to see given the project {id}");
}
}));
}
[HttpGet("[controller]/{id}/resources")]
public IActionResult GetResources(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var project = _projectModel.GetById(Guid.Parse(id));
ResourceModel resourceModel = new ResourceModel();
ResourceTypeModel resourceTypeModel = new ResourceTypeModel();
if (_projectModel.CanSeeProject(user, project))
var user = _authenticator.GetUser();
var resourceModel = new ResourceModel();
var resourceTypeModel = new ResourceTypeModel();
if (_projectModel.HasAccess(user, project, UserRoles.Member, UserRoles.Owner))
{
return resourceModel.GetAllWhere((resource) =>
return Json(resourceModel.GetAllWhere((resource) =>
(from projectResource in resource.ProjectResourceResourceIdIds
where projectResource.ProjectId == project.Id
select projectResource).Any())
.Select((resource) =>
{
return resourceModel.CreateReturnObjectFromDatabaseObject(resource);
});
}).OrderBy(element => element.DisplayName));
}
else
{
throw new UnauthorizedAccessException("User cannot see resources of given project!");
return Unauthorized($"User is not allowed to see given the project {id}");
}
}));
}
[HttpPost("[controller]/{id}")]
public IActionResult Update(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
ProjectObject projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
var user = _authenticator.GetUser();
var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
var project = _projectModel.GetById(Guid.Parse(id));
if(_projectModel.OwnsProject(user, project))
if(_projectModel.HasAccess(user, project, UserRoles.Owner))
{
return _projectModel.UpdateByObject(project, projectObject);
return Ok(_projectModel.UpdateByObject(project, projectObject));
}
else
{
throw new NotAuthorizedException("The user is not authorized to perform an update on the selected project!");
return Unauthorized("The user is not authorized to perform an update on the selected project!");
}
}));
}
[HttpDelete("[controller]/{id}")]
public IActionResult Delete(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var user = _authenticator.GetUser();
var project = _projectModel.GetById(Guid.Parse(id));
if (_projectModel.OwnsProject(user, project))
if (_projectModel.HasAccess(user, project, UserRoles.Owner))
{
DeleteProject(project);
return _projectModel.CreateReturnObjectFromDatabaseObject(project);
return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
}
else
{
throw new NotAuthorizedException("The user is not authorized to perform an update on the selected project!");
return Unauthorized("The user is not authorized to perform an update on the selected project!");
}
}));
}
public void DeleteProject(Coscine.Database.Model.Project project)
public void DeleteProject(Database.Model.Project project)
{
SubProjectModel subProjectModel = new SubProjectModel();
var subProjectModel = new SubProjectModel();
foreach(var subProject in subProjectModel.GetAllWhere((subProject) => subProject.ProjectId == project.Id))
{
subProjectModel.Delete(subProject);
......@@ -137,7 +127,7 @@ namespace Coscine.Api.Project.Controllers
subProjectModel.Delete(subProject);
}
ProjectResourceModel projectResourceModel = new ProjectResourceModel();
var projectResourceModel = new ProjectResourceModel();
ResourceModel resourceModel = new ResourceModel();
foreach (var projectResource in projectResourceModel.GetAllWhere((projectResource) => projectResource.ProjectId == project.Id))
{
......@@ -145,19 +135,19 @@ namespace Coscine.Api.Project.Controllers
resourceModel.Delete(resourceModel.GetById(projectResource.ResourceId));
}
ProjectRoleModel projectRoleModel = new ProjectRoleModel();
var projectRoleModel = new ProjectRoleModel();
foreach (var projectRole in projectRoleModel.GetAllWhere((projectRole) => projectRole.ProjectId == project.Id))
{
projectRoleModel.Delete(projectRole);
}
ProjectDisciplineModel projectDisciplineModel = new ProjectDisciplineModel();
var projectDisciplineModel = new ProjectDisciplineModel();
foreach (var projectDiscipline in projectDisciplineModel.GetAllWhere((projectDiscipline) => projectDiscipline.ProjectId == project.Id))
{
projectDisciplineModel.Delete(projectDiscipline);
}
ProjectInstituteModel projectInstituteModel = new ProjectInstituteModel();
var projectInstituteModel = new ProjectInstituteModel();
foreach (var projectInstitute in projectInstituteModel.GetAllWhere((projectInstitute) => projectInstitute.ProjectId == project.Id))
{
projectInstituteModel.Delete(projectInstitute);
......@@ -174,16 +164,24 @@ namespace Coscine.Api.Project.Controllers
[HttpPost("[controller]")]
public IActionResult Store()
{
return base.Ok(_authenticator.ValidateAndExecute((user) =>
var user = _authenticator.GetUser();
var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
if (projectObject.ParentId != null
&& projectObject.ParentId != new Guid()
&& !_projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
{
ProjectObject projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
return Unauthorized("User is not allowed to create SubProjects.");
}
var project = _projectModel.StoreFromObject(projectObject, user);
if (projectObject.ParentId != null
&& projectObject.ParentId != new Guid()
&& _projectModel.IsMemberOrHigher(user, _projectModel.GetById(projectObject.ParentId))) // for now, only an owner can add subprojects to projects
// for now, only an owner can add subprojects to projects
&& _projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
{
SubProjectModel subProjectModel = new SubProjectModel();
var subProjectModel = new SubProjectModel();
subProjectModel.LinkSubProject(projectObject.ParentId, project.Id);
}
......@@ -193,8 +191,7 @@ namespace Coscine.Api.Project.Controllers
ProjectOwner = user
});
return _projectModel.CreateReturnObjectFromDatabaseObject(project);
}));
return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
}
}
}
using Coscine.Action;
using Coscine.Action.EventArgs;
using Coscine.Action.Implementations.User;
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Coscine.ApiCommons.Exceptions;
using Coscine.ApiCommons.Factories;
using Coscine.Database.Model;
using Coscine.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class ProjectRoleController : Controller
{
private readonly Authenticator _authenticator;
private readonly ProjectRoleModel _projectRoleModel;
private readonly Emitter _emitter;
private readonly Coscine.Configuration.IConfiguration _configuration;
private readonly IConfiguration _configuration;
public ProjectRoleController()
{
......@@ -34,49 +31,47 @@ namespace Coscine.Api.Project.Controllers
[Route("[controller]/{projectId}")]
public IActionResult Index(string projectId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
UserModel userModel = new UserModel();
RoleModel roleModel = new RoleModel();
ProjectModel projectModel = new ProjectModel();
var userModel = new UserModel();
var roleModel = new RoleModel();
var projectModel = new ProjectModel();
Guid.TryParse(projectId, out Guid projectIdGuid);
if (projectModel.OwnsProject(user, projectModel.GetById(projectIdGuid)))
var user = _authenticator.GetUser();
if (projectModel.HasAccess(user, projectModel.GetById(projectIdGuid), UserRoles.Owner, UserRoles.Member))
{
return _projectRoleModel.GetAllWhere((projectRole) =>
return Json(_projectRoleModel.GetAllWhere((projectRole) =>
(projectRole.ProjectId == projectIdGuid)
).Select((projectRole) =>
{
User userInst = projectRole.User;
var userInst = projectRole.User;
if (userInst == null)
{
userInst = userModel.GetById(projectRole.UserId);
}
Role role = projectRole.Role;
var role = projectRole.Role;
if (role == null)
{
role = roleModel.GetById(projectRole.RoleId);
}
return new ProjectRoleObject(projectRole.ProjectId, new UserObject(userInst.Id, userInst.DisplayName, userInst.Givenname, userInst.Surname, userInst.EmailAddress), new RoleObject(role.Id, role.DisplayName));
});
}));
}
else
{
throw new UnauthorizedAccessException("User is not allowed to list all users to the given project!");
return Unauthorized("User is not allowed to list all users to the given project!");
}
}));
}
//Get all roles for current user and given project
[HttpGet("[controller]/project/{projectId}")]
public IActionResult Get(string projectId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
RoleModel roleModel = new RoleModel();
var roleModel = new RoleModel();
Guid.TryParse(projectId, out Guid projectIdGuid);
UserObject userObject = new UserObject(user.Id, user.DisplayName, user.Givenname, user.Surname, user.EmailAddress);
var user = _authenticator.GetUser();
var userObject = new UserObject(user.Id, user.DisplayName, user.Givenname, user.Surname, user.EmailAddress);
return _projectRoleModel.GetAllWhere((projectRole) =>
return Json(_projectRoleModel.GetAllWhere((projectRole) =>
(projectRole.UserId == user.Id &&
projectRole.ProjectId == projectIdGuid)
).Select((projectRole) => {
......@@ -85,51 +80,49 @@ namespace Coscine.Api.Project.Controllers
projectRole.Role = roleModel.GetById(projectRole.RoleId);
}
return new ProjectRoleObject(projectRole.RelationId, userObject, new RoleObject(projectRole.Role.Id, projectRole.Role.DisplayName));
});
}));
}
[HttpPost("[controller]")]
public IActionResult Set()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
ProjectRoleObject projectRoleObject = ObjectFactory<ProjectRoleObject>.DeserializeFromStream(Request.Body);
ProjectModel projectModel = new ProjectModel();
var projectRoleObject = ObjectFactory<ProjectRoleObject>.DeserializeFromStream(Request.Body);
var projectModel = new ProjectModel();
var project = projectModel.GetById(projectRoleObject.ProjectId);
RoleModel roleModel = new RoleModel();
var roleModel = new RoleModel();
var role = roleModel.GetById(projectRoleObject.Role.Id);
UserModel userModel = new UserModel();
var userModel = new UserModel();
var userToAdd = userModel.GetById(projectRoleObject.User.Id);
if (projectModel.OwnsProject(user, project))
var user = _authenticator.GetUser();
if (projectModel.HasAccess(user, project, UserRoles.Owner))
{
_emitter.EmitUserAdd(new UserEventArgs(this._configuration)
_emitter.EmitUserAdd(new UserEventArgs(_configuration)
{
Project = project,
Role = role,
User = userToAdd
});
return _projectRoleModel.SetFromObject(projectRoleObject);
return Json(_projectRoleModel.SetFromObject(projectRoleObject));
}
else
{
throw new NotAuthorizedException("The user is not authorized to store a project role to the given project!");
return Unauthorized("The user is not authorized to store a project role to the given project!");
}
}));
}
[HttpDelete("[controller]/project/{projectId}/user/{userId}/role/{roleId}")]
public IActionResult Delete(Guid projectId, Guid userId, Guid roleId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
ProjectModel projectModel = new ProjectModel();
if (projectModel.OwnsProject(user, projectModel.GetById(projectId)))
var projectModel = new ProjectModel();
var user = _authenticator.GetUser();
if (projectModel.HasAccess(user, projectModel.GetById(projectId), UserRoles.Owner))
{
_projectRoleModel.CheckIfLastOwnerWillBeRemoved(roleId, projectId);
var project = projectModel.GetById(projectId);
UserModel userModel = new UserModel();
var userModel = new UserModel();
var userToRemove = userModel.GetById(userId);
_emitter.EmitUserRemove(new UserEventArgs(this._configuration)
......@@ -138,16 +131,15 @@ namespace Coscine.Api.Project.Controllers
User = userToRemove
});
return _projectRoleModel.Delete(_projectRoleModel.GetWhere((projectRole) =>
return Json(_projectRoleModel.Delete(_projectRoleModel.GetWhere((projectRole) =>
projectRole.ProjectId == projectId
&& projectRole.UserId == userId
&& projectRole.RoleId == roleId));
&& projectRole.RoleId == roleId)));
}
else
{
throw new NotAuthorizedException("The user is not authorized to delete a project role for the given project!");
return Unauthorized("The user is not authorized to delete a project role for the given project!");
}
}));
}
}
}
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Coscine.ApiCommons.Exceptions;
using Coscine.ApiCommons.Factories;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using Newtonsoft.Json.Linq;
using Coscine.Action;
using Coscine.Configuration;
using Coscine.Action.EventArgs;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json.Linq;
using Coscine.Database.Model;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class ResourceController : Controller
{
private readonly Authenticator _authenticator;
......@@ -31,63 +33,71 @@ namespace Coscine.Api.Project.Controllers
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return _resourceModel.GetAllWhere((resource) =>
var user = _authenticator.GetUser();
return Json(_resourceModel.GetAllWhere((resource) =>
(from projectResource in resource.ProjectResourceResourceIdIds
where (from projectRole in projectResource.Project.ProjectRolesProjectIdIds
where projectRole.User == user
&& projectRole.Role.DisplayName == "Owner"
&& (projectRole.Role.DisplayName == "Owner" || projectRole.Role.DisplayName == "Member")
select projectRole).Any()
select projectResource).Any()
).Select((resource) => _resourceModel.CreateReturnObjectFromDatabaseObject(resource));
}));
).Select((resource) => _resourceModel.CreateReturnObjectFromDatabaseObject(resource)));
}
[HttpGet("[controller]/{id}")]
public IActionResult Get(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var resource = _resourceModel.GetById(Guid.Parse(id));
if (_resourceModel.OwnsResource(user, resource))
var user = _authenticator.GetUser();
if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
_resourceModel.SetType(resource);
return _resourceModel.CreateReturnObjectFromDatabaseObject(resource);
return Json(_resourceModel.CreateReturnObjectFromDatabaseObject(resource));
}
else
{
throw new NotAuthorizedException("User does not own resource!");
return Unauthorized("User does not own resource!");
}
}));
}
[HttpGet("[controller]/resource/{id}/isCreator")]
public IActionResult IsUserResourceCreator(string id)
{
Resource resource = _resourceModel.GetById(Guid.Parse(id));
var user = _authenticator.GetUser();
var json = new JObject
{
["isResourceCreator"] = resource.Creator.Equals(user.Id)
};
return Json(json);
}
[HttpPost("[controller]/{id}")]
public IActionResult Update(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
ResourceObject resourceObject = ObjectFactory<ResourceObject>.DeserializeFromStream(Request.Body);
var resourceObject = ObjectFactory<ResourceObject>.DeserializeFromStream(Request.Body);
var resource = _resourceModel.GetById(Guid.Parse(id));
if (_resourceModel.OwnsResource(user, resource))
var user = _authenticator.GetUser();
if (_resourceModel.HasAccess(user, resource, UserRoles.Owner) ||
(_resourceModel.HasAccess(user, resource, UserRoles.Member) && resource.Creator.Equals(user.Id)))
{
return _resourceModel.UpdateByObject(resource, resourceObject);
return Json(_resourceModel.UpdateByObject(resource, resourceObject));
}
else
{
throw new NotAuthorizedException("The user is not authorized to perform an update on the selected resource!");
return Unauthorized("The user is not authorized to perform an update on the selected resource!");
}
}));
}
[HttpDelete("[controller]/{id}")]
public IActionResult Delete(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var resource = _resourceModel.GetById(Guid.Parse(id));
if (_resourceModel.OwnsResource(user, resource))
var user = _authenticator.GetUser();
if (_resourceModel.HasAccess(user, resource, UserRoles.Owner) ||
(_resourceModel.HasAccess(user, resource, UserRoles.Member) && resource.Creator.Equals(user.Id)))
{
var returnObject = _resourceModel.CreateReturnObjectFromDatabaseObject(resource);
_emitter.EmitResourceDelete(new ResourceEventArgs(_configuration)
......@@ -95,28 +105,26 @@ namespace Coscine.Api.Project.Controllers
Resource = resource
});
_resourceModel.DeleteResource(resource);
return returnObject;
return Json(returnObject);
}
else
{
throw new NotAuthorizedException("The user is not authorized to perform an update on the selected resource!");
return Unauthorized("The user is not authorized to perform an update on the selected resource!");
}
}));
}
[HttpPost("[controller]/project/{projectId}")]
public IActionResult StoreToProject(string projectId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
ResourceObject resourceObject = ObjectFactory<ResourceObject>.DeserializeFromStream(Request.Body);
ProjectModel projectModel = new ProjectModel();
var resourceObject = ObjectFactory<ResourceObject>.DeserializeFromStream(Request.Body);
var projectModel = new ProjectModel();
var project = projectModel.GetById(Guid.Parse(projectId));
if (projectModel.OwnsProject(user, project))
var user = _authenticator.GetUser();
if (projectModel.HasAccess(user, project, UserRoles.Owner, UserRoles.Member))
{
resourceObject.Creator = user.Id;
var resource = _resourceModel.StoreFromObject(resourceObject);
projectModel.AddResource(project, resource);
_emitter.EmitResourceCreate(new ResourceEventArgs(_configuration)
......@@ -124,13 +132,12 @@ namespace Coscine.Api.Project.Controllers
Resource = resource
});
return _resourceModel.CreateReturnObjectFromDatabaseObject(resource);
return Json(_resourceModel.CreateReturnObjectFromDatabaseObject(resource));
}
else
{
throw new NotAuthorizedException("The user is not authorized to add a new resource to the selected project!");
return Unauthorized("The user is not authorized to add a new resource to the selected project!");
}
}));
}
}
}
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class ResourceTypeController : Controller
{
private readonly Authenticator _authenticator;
......@@ -25,46 +24,40 @@ namespace Coscine.Api.Project.Controllers
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return _resourceTypeModel.GetAll().Select((resourceType) => new ResourceTypeObject(resourceType.Id, resourceType.DisplayName));
}));
return Json(_resourceTypeModel.GetAll()
.Select((resourceType) => new ResourceTypeObject(resourceType.Id, resourceType.DisplayName)));
}
[Route("[controller]/{id}/fields")]
public IActionResult Fields(string id)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
var resourceType = _resourceTypeModel.GetById(Guid.Parse(id));
if (resourceType.DisplayName == "s3")
{
return Type.GetType("Coscine.Api.Project.ReturnObjects.S3ResourceTypeObject").GetProperties()
return Json(Type.GetType("Coscine.Api.Project.ReturnObjects.S3ResourceTypeObject").GetProperties()
.Where((property) => property.Name != "Id")
.Select((property) => property.Name)
.ToList();
.ToList());
}
else if (resourceType.DisplayName == "rds")
{
return Type.GetType("Coscine.Api.Project.ReturnObjects.RDSResourceTypeObject").GetProperties()
return Json(Type.GetType("Coscine.Api.Project.ReturnObjects.RDSResourceTypeObject").GetProperties()
.Where((property) => property.Name != "Id")
.Select((property) => property.Name)
.ToList();
.ToList());
}
else if(resourceType.DisplayName == "gitlab")
{
return Type.GetType("Coscine.Api.Project.ReturnObjects.GitlabResourceTypeObject").GetProperties()
return Json(Type.GetType("Coscine.Api.Project.ReturnObjects.GitlabResourceTypeObject").GetProperties()
.Where((property) => property.Name != "Id")
.Select((property) => property.Name)
.ToList();
.ToList());
}
else
{
throw new ArgumentException("Invalid Resource Type!");
}
}));
}
}
}
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class RoleController : Controller
{
private readonly Authenticator _authenticator;
private readonly RoleModel _roleModel;
public RoleController()
{
_authenticator = new Authenticator(this, Program.Configuration);
_roleModel = new RoleModel();
}
[Route("[controller]")]
public IActionResult Index()
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
return _roleModel.GetAll().Select((role) => new RoleObject(role.Id, role.DisplayName));
}));
return Json(_roleModel.GetAll()
.Select((role) => new RoleObject(role.Id, role.DisplayName)));
}
}
}
using System.Linq;
using Coscine.Api.Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Coscine.ApiCommons;
using Coscine.ApiCommons.Utils;
using LinqToDB.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using VDS.RDF.Query.Expressions.Functions.Sparql.String;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Authorization;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class SearchController : Controller
{
private readonly Authenticator _authenticator;
private DatabaseConnection _databaseConnection;
private readonly ProjectModel _projectModel;
private readonly DatabaseConnection _databaseConnection;
public SearchController()
{
_authenticator = new Authenticator(this, Program.Configuration);
_projectModel = new ProjectModel();
_databaseConnection = new DatabaseConnection(Program.Configuration);
}
[HttpGet("[controller]/allNoFilter/")]
public IActionResult SearchNoFilter()
{
var user = _authenticator.GetUser();
return Ok(GetSearchResults(user.Id, "", ""));
}
[HttpGet("[controller]/all/{encodedSearchWord}")]
public IActionResult Search(string encodedSearchWord)
{
var user = _authenticator.GetUser();
return Ok(GetSearchResults(user.Id, encodedSearchWord, ""));
}
[HttpGet("[controller]/projectNoFilter/{projectId}")]
public IActionResult SearchProjectNoFilter(string projectId)
{
var user = _authenticator.GetUser();
return Ok(GetSearchResults(user.Id, "", projectId));
}
[HttpGet("[controller]/project/{projectId}/{encodedSearchWord}")]
public IActionResult SearchProject(string projectId, string encodedSearchWord)
{
var user = _authenticator.GetUser();
return Ok(GetSearchResults(user.Id, encodedSearchWord, projectId));
}
private JToken GetSearchResults(Guid userId, string encodedSearchWord, string projectId)
{
string searchQuery;
if (!string.IsNullOrWhiteSpace(encodedSearchWord))
{
searchQuery = HttpUtility.UrlDecode(encodedSearchWord);
}
else
{
searchQuery = "";
}
List<Guid> list;
if (projectId.Equals(""))
{
list = new List<Guid>();
}
else
{
list = GetAllSubProjects(projectId);
}
[Route("[controller]")]
public IActionResult Index()
// create return object
var json = new JObject();
// search and add results for resources
json["Resources"] = SearchForResources(userId, searchQuery, projectId, list);
// search and add results for projects
if (projectId.Equals(""))
{
return Ok(_authenticator.ValidateAndExecute((user) =>
json["Projects"] = SearchForProjects(userId, searchQuery, projectId, list, false);
}
else
{
json["Projects"] = new JArray();
}
// remove the id of the root project since it cann not be a subproject of it self
if (list.Count >= 1)
{
list.RemoveAt(0);
}
// search and ad results for sub-projects
json["SubProjects"] = SearchForProjects(userId, searchQuery, projectId, list, true);
return json;
}
private List<Guid> GetAllSubProjects(string projectId)
{
var list = new List<Guid>();
if (!projectId.Equals(""))
{
list.Add(new Guid(projectId));
var counter = 0;
_databaseConnection.ConnectToDatabase((db) =>
{
while (counter != list.Count)
{
var innerResults = (from sp in db.SubProjects
where sp.ProjectId.Equals(list[counter])
select sp.SubProjectId);
list.AddRange(innerResults.ToList());
counter++;
}
});
}
return list;
}
private JToken SearchForProjects(Guid userId, string searchQuery, string projectId, List<Guid> listOfSubprojects, bool showSubProjects)
{
string searchQuery = "";
return _databaseConnection.ConnectToDatabase((db) =>
{
return
var allSubProjects = (from sp in db.SubProjects select sp.SubProjectId).ToList();
var allSubProjectsList = new List<Guid>();
allSubProjectsList.AddRange(allSubProjects);
var results =
(from p in db.Projects
join v in db.Visibilities on p.VisibilityId equals v.Id
join pd in db.ProjectDisciplines on p.Id equals pd.ProjectId
join d in db.Disciplines on pd.DisciplineId equals d.Id
join pi in db.ProjectInstitutes on p.Id equals pi.ProjectId
join i in db.Institutes on pi.InstituteId equals i.Id
join pr in db.ProjectRoles on p.Id equals pr.ProjectId into joinedPr
from jpr in joinedPr.DefaultIfEmpty()
join v in db.Visibilities on p.VisibilityId equals v.Id into joinedV
from jv in joinedV.DefaultIfEmpty()
join pd in db.ProjectDisciplines on p.Id equals pd.ProjectId into joinedPd
from jpd in joinedPd.DefaultIfEmpty()
join d in db.Disciplines on jpd.DisciplineId equals d.Id into joinedD
from jd in joinedD.DefaultIfEmpty()
join pi in db.ProjectInstitutes on p.Id equals pi.ProjectId into joinedPi
from jpi in joinedPi.DefaultIfEmpty()
join i in db.Institutes on jpi.InstituteId equals i.Id into joinedI
from ji in joinedI.DefaultIfEmpty()
where p.ProjectName.Contains(searchQuery) ||
where ((!showSubProjects && p.Id.NotIn(allSubProjectsList)) ||
(showSubProjects && p.Id.In(allSubProjectsList))) &&
(jpr.UserId.Equals(userId) || jv.DisplayName.Equals("Public")) &&
(projectId.Equals("") || p.Id.In(listOfSubprojects)) &&
(searchQuery.Equals("") ||
p.ProjectName.Contains(searchQuery) ||
p.Description.Contains(searchQuery) ||
p.StartDate.ToString().Contains(searchQuery) ||
p.EndDate.ToString().Contains(searchQuery) ||
p.Keywords.Contains(searchQuery) ||
p.DisplayName.Contains(searchQuery) ||
p.PrincipleInvestigators.Contains(searchQuery) ||
p.GrantId.Contains(searchQuery) ||
v.DisplayName.Contains(searchQuery) ||
d.Url.Contains(searchQuery) ||
d.DisplayNameDe.Contains(searchQuery) ||
d.DisplayNameEn.Contains(searchQuery) ||
i.DisplayName.Contains(searchQuery) ||
i.IKZ.Contains(searchQuery)
select new {p.Id, p.DisplayName});
jv.DisplayName.Contains(searchQuery) ||
jd.Url.Contains(searchQuery) ||
jd.DisplayNameDe.Contains(searchQuery) ||
jd.DisplayNameEn.Contains(searchQuery) ||
ji.DisplayName.Contains(searchQuery) ||
ji.IKZ.Contains(searchQuery))
select new { p.Id, p.DisplayName }).OrderBy(element => element.DisplayName).Distinct();
return JToken.Parse(JsonConvert.SerializeObject(results));
});
}
private JToken SearchForResources(Guid userId, string searchQuery, string projectId, List<Guid> listOfSubprojects)
{
return _databaseConnection.ConnectToDatabase((db) =>
{
var results = (from r in db.Resources
join pres in db.ProjectResources on r.Id equals pres.ResourceId into joinedPres
from jpres in joinedPres.DefaultIfEmpty()
join p in db.Projects on jpres.ProjectId equals p.Id into joinedP
from jp in joinedP.DefaultIfEmpty()
join pr in db.ProjectRoles on jp.Id equals pr.ProjectId into joinedPr
from jpr in joinedPr.DefaultIfEmpty()
join v in db.Visibilities on r.VisibilityId equals v.Id into joinedV
from jv in joinedV.DefaultIfEmpty()
join rd in db.ResourceDisciplines on r.Id equals rd.ResourceId into joinedRd
from jrd in joinedRd.DefaultIfEmpty()
join d in db.Disciplines on jrd.DisciplineId equals d.Id into joinedD
from jd in joinedD.DefaultIfEmpty()
join l in db.Licenses on r.LicenseId equals l.Id into joinedL
from jl in joinedL.DefaultIfEmpty()
join rt in db.ResourceTypes on r.TypeId equals rt.Id into joinedRt
from jrt in joinedRt.DefaultIfEmpty()
where (jpr.UserId.Equals(userId) || jv.DisplayName.Equals("Public")) &&
(projectId.Equals("") || jp.Id.In(listOfSubprojects)) &&
(searchQuery.Equals("") ||
r.ResourceName.Contains(searchQuery) ||
r.DisplayName.Contains(searchQuery) ||
r.ResourceName.Contains(searchQuery) ||
r.Keywords.Contains(searchQuery) ||
r.UsageRights.Contains(searchQuery) ||
r.Description.Contains(searchQuery) ||
r.ApplicationProfile.Contains(searchQuery) ||
jrt.DisplayName.Contains(searchQuery) ||
jl.DisplayName.Contains(searchQuery) ||
jd.DisplayNameDe.Contains(searchQuery) ||
jd.DisplayNameEn.Contains(searchQuery))
select new { r.Id, r.DisplayName, jpr.ProjectId }).OrderBy(element => element.DisplayName).Distinct();
return JToken.Parse(JsonConvert.SerializeObject(results));
});
}));
/*
return DatabaseConnection.ConnectToDatabase((db) => (from relation in db.ProjectRoles
where relation.Project == project
&& relation.User == user
&& (relation.Role.DisplayName == "Owner"
|| relation.Role.DisplayName == "Member")
select relation).Any());*/
}
}
}
\ No newline at end of file
using Coscine.Api.Project.Models;
using Coscine.Api.Project.ReturnObjects;
using Coscine.ApiCommons;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
namespace Coscine.Api.Project.Controllers
{
[Authorize]
public class SubProjectController : Controller
{
private readonly Authenticator _authenticator;
......@@ -21,22 +22,21 @@ namespace Coscine.Api.Project.Controllers
[HttpGet("[controller]/{parentId}")]
public IActionResult Get(string parentId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
{
Guid parentGuid = new Guid(parentId);
ProjectModel projectModel = new ProjectModel();
if (projectModel.CanSeeProject(user, projectModel.GetById(parentGuid)))
var parentGuid = new Guid(parentId);
var projectModel = new ProjectModel();
var user = _authenticator.GetUser();
if (projectModel.HasAccess(user, projectModel.GetById(parentGuid), UserRoles.Owner, UserRoles.Member))
{
var subProjects = _subProjectModel.GetAllWhere((subProjectM) => (subProjectM.ProjectId == parentGuid))
.Select((subProject) => projectModel.GetById(subProject.SubProjectId))
.Select((project) => projectModel.CreateReturnObjectFromDatabaseObject(project, parentGuid));
return subProjects;
.Select((project) => projectModel.CreateReturnObjectFromDatabaseObject(project, parentGuid))
.OrderBy(element => element.DisplayName);
return Json(subProjects);
}
else
{
throw new UnauthorizedAccessException("User is not allowed to create a subproject for the given project id!");
return Unauthorized("User is not allowed to create a subproject for the given project id!");
}
}));
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment