Commits (3)
......@@ -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);
......
......@@ -9,8 +9,8 @@ using System.Reflection;
[assembly: AssemblyDescription("Project.Tests is a part of the CoScInE group.")]
[assembly: AssemblyCompany("IT Center, RWTH Aachen University")]
[assembly: AssemblyProduct("Project.Tests")]
[assembly: AssemblyVersion("1.11.1.0")]
[assembly: AssemblyFileVersion("1.11.1.0")]
[assembly: AssemblyInformationalVersion("1.11.1.0")]
[assembly: AssemblyVersion("1.12.0.0")]
[assembly: AssemblyFileVersion("1.12.0.0")]
[assembly: AssemblyInformationalVersion("1.12.0.0")]
[assembly: AssemblyCopyright("2020 IT Center, RWTH Aachen University")]
......@@ -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)
......@@ -220,7 +246,7 @@ namespace Coscine.Api.Project.Controllers
return resource["type"]["displayName"].ToString().ToLower();
}
}
public async Task<HttpResponseMessage> UploadFile(string url, string authHeader, Stream stream)
{
......@@ -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);
}
......@@ -374,7 +408,7 @@ namespace Coscine.Api.Project.Controllers
{
return BadRequest($"{resourceId} is not a guid.");
}
try
{
resource = _resourceModel.GetById(resourceGuid);
......@@ -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();
}));
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,150 +91,162 @@ namespace Coscine.Api.Project.Controllers
[HttpGet("[controller]/project/{projectId}/aplist/")]
public IActionResult ListAllApplicationProfiles(Guid projectId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
var user = _authenticator.GetUser();
if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
{
if (_metadataModel.IsProjectMember(user, projectId))
{
var graphUris = _util.ListGraphs();
var graphUris = _util.ListGraphs();
return 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!");
}
}));
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 (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
var resource = _resourceModel.GetById(Guid.Parse(resourceId));
if (_metadataModel.IsProjectMember(user, resource))
{
var id = _metadataModel.GenerateId(resourceId, filename, version);
var graph = _util.GetGraph(id);
return JToken.Parse(VDS.RDF.Writing.StringWriter.Write(graph, new RdfJsonWriter()));
}
else
{
throw new NotAuthorizedException("User is no project member!");
}
}));
var id = _metadataModel.GenerateId(resourceId, filename, version);
var graph = _util.GetGraph(id);
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);
var graphNameUri = new Uri(graphName);
var json = new JObject
{
var innerBlock = ObjectFactory<JToken>.DeserializeFromStream(Request.Body);
var graphName = _metadataModel.GenerateId(resourceId, filename, version);
var graphNameUri = new Uri(graphName);
var json = new JObject
[graphName] = innerBlock
};
var user = _authenticator.GetUser();
var resource = _resourceModel.GetById(Guid.Parse(resourceId));
if (_resourceModel.HasAccess(user, resource, UserRoles.Owner, UserRoles.Member))
{
json[graphName]["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"] = new JArray
{
[graphName] = innerBlock
new JObject
{
["value"] = resource.ApplicationProfile.Substring(0, resource.ApplicationProfile.Length-1),
["type"] = "uri"
}
};
var resource = _resourceModel.GetById(Guid.Parse(resourceId));
if (_metadataModel.IsProjectMember(user, resource))
// throw bad request if empty node value is detected
JToken root = json.First.First;
foreach (var node in root)
{
var graph = new Graph();
graph.LoadFromString(json.ToString(), new RdfJsonParser());
string nodeValue = node.First.First["value"].ToString().ToLower();
if (String.IsNullOrEmpty(nodeValue))
{
throw new ArgumentException("Empty values in application profile are not accepted.");
}
}
var fixedValuesGraph = new Graph();
fixedValuesGraph.LoadFromString(resource.FixedValues, new RdfJsonParser());
var graph = new Graph();
graph.LoadFromString(json.ToString(), new RdfJsonParser());
foreach(var triple in fixedValuesGraph.Triples.Where(x => x.Predicate.ToString() == "https://purl.org/coscine/fixedValue"))
var fixedValuesGraph = new Graph();
fixedValuesGraph.LoadFromString(resource.FixedValues, new RdfJsonParser());
foreach(var triple in fixedValuesGraph.Triples.Where(x => x.Predicate.ToString() == "https://purl.org/coscine/fixedValue"))
{
// Remove any existing triples
foreach (var triple2 in graph.GetTriplesWithSubjectPredicate(graph.CreateUriNode(graphNameUri), triple.Subject).ToList())
{
// Remove any existing triples
foreach (var triple2 in graph.GetTriplesWithSubjectPredicate(graph.CreateUriNode(graphNameUri), triple.Subject).ToList())
{
graph.Retract(triple2);
}
graph.Assert(graph.CreateUriNode(graphNameUri), triple.Subject, triple.Object);
graph.Retract(triple2);
}
graph.Assert(graph.CreateUriNode(graphNameUri), triple.Subject, triple.Object);
}
// Default values is not checked or added
// Default values is not checked or added
// validate the data
if (_util.ValidateShacl(graph, graphNameUri))
// validate the data
if (_util.ValidateShacl(graph, graphNameUri))
{
// store the data
if (_util.HasGraph(graphNameUri))
{
// store the data
if (_util.HasGraph(graphNameUri))
{
_util.ClearGraph(graphNameUri);
}
else
{
_util.CreateNamedGraph(graphNameUri);
}
// BaseUri must be set for the sparql query
graph.BaseUri = graphNameUri;
_util.AddGraph(graph);
return NoContent();
_util.ClearGraph(graphNameUri);
}
else
{
throw new NotAuthorizedException("Data has the wrong format!");
_util.CreateNamedGraph(graphNameUri);
}
// BaseUri must be set for the sparql query
graph.BaseUri = graphNameUri;
_util.AddGraph(graph);
return NoContent();
}
else
{
throw new NotAuthorizedException("User is no project member!");
throw new NotAuthorizedException("Data has the wrong format!");
}
}));
}
else
{
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) =>
var user = _authenticator.GetUser();
if (_projectModel.HasAccess(user, _projectModel.GetById(projectId), UserRoles.Owner, UserRoles.Member))
{
if (_metadataModel.IsProjectMember(user, projectId))
{
var graph = _util.GetGraph(HttpUtility.UrlDecode(path));
JArray de = new JArray();
foreach (var kv in _util.GetVocabularyLabels(graph, "de"))
{
JObject obj = new JObject
{
["value"] = kv.Key,
["name"] = kv.Value
};
de.Add(obj);
}
var graph = _util.GetGraph(HttpUtility.UrlDecode(path));
JArray en = new JArray();
foreach(var kv in _util.GetVocabularyLabels(graph, "en"))
var de = new JArray();
foreach (var kv in _util.GetVocabularyLabels(graph, "de"))
{
JObject obj = new JObject
{
JObject obj = new JObject
{
["value"] = kv.Key,
["name"] = kv.Value
};
en.Add(obj);
}
["value"] = kv.Key,
["name"] = kv.Value
};
de.Add(obj);
}
JObject json = new JObject
var en = new JArray();
foreach(var kv in _util.GetVocabularyLabels(graph, "en"))
{
JObject obj = new JObject
{
["de"] = de,
["en"] = en
["value"] = kv.Key,
["name"] = kv.Value
};
return json;
en.Add(obj);
}
else
JObject json = new JObject
{
throw new NotAuthorizedException("User is no project member!");
}
}));
["de"] = de,
["en"] = en
};
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 project = _projectModel.GetById(Guid.Parse(id));
if (_projectModel.CanSeeProject(user, project))
{
return _projectModel.CreateReturnObjectFromDatabaseObject(project);
}
else
{
throw new UnauthorizedAccessException("User is not allowed to see given project Id!");
}
}));
var user = _authenticator.GetUser();
var project = _projectModel.GetById(Guid.Parse(id));
if (_projectModel.HasAccess(user, project, UserRoles.Member, UserRoles.Owner))
{
return Ok(_projectModel.CreateReturnObjectFromDatabaseObject(project));
}
else
{
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))
{
return resourceModel.GetAllWhere((resource) =>
(from projectResource in resource.ProjectResourceResourceIdIds
where projectResource.ProjectId == project.Id
select projectResource).Any())
.Select((resource) =>
{
return resourceModel.CreateReturnObjectFromDatabaseObject(resource);
});
}
else
{
throw new UnauthorizedAccessException("User cannot see resources of given project!");
}
}));
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))
{
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
{
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 project = _projectModel.GetById(Guid.Parse(id));
if(_projectModel.OwnsProject(user, project))
{
return _projectModel.UpdateByObject(project, projectObject);
}
else
{
throw new NotAuthorizedException("The user is not authorized to perform an update on the selected project!");
}
}));
var user = _authenticator.GetUser();
var projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
var project = _projectModel.GetById(Guid.Parse(id));
if(_projectModel.HasAccess(user, project, UserRoles.Owner))
{
return Ok(_projectModel.UpdateByObject(project, projectObject));
}
else
{
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 project = _projectModel.GetById(Guid.Parse(id));
if (_projectModel.OwnsProject(user, project))
{
DeleteProject(project);
return _projectModel.CreateReturnObjectFromDatabaseObject(project);
}
else
{
throw new NotAuthorizedException("The user is not authorized to perform an update on the selected project!");
}
}));
var user = _authenticator.GetUser();
var project = _projectModel.GetById(Guid.Parse(id));
if (_projectModel.HasAccess(user, project, UserRoles.Owner))
{
DeleteProject(project);
return Json(_projectModel.CreateReturnObjectFromDatabaseObject(project));
}
else
{
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,27 +164,34 @@ namespace Coscine.Api.Project.Controllers
[HttpPost("[controller]")]
public IActionResult Store()
{
return base.Ok(_authenticator.ValidateAndExecute((user) =>
{
ProjectObject projectObject = ObjectFactory<ProjectObject>.DeserializeFromStream(Request.Body);
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
{
SubProjectModel subProjectModel = new SubProjectModel();
subProjectModel.LinkSubProject(projectObject.ParentId, project.Id);
}
_emitter.EmitProjectCreate(new ProjectEventArgs(_configuration)
{
Project = project,
ProjectOwner = user
});
return _projectModel.CreateReturnObjectFromDatabaseObject(project);
}));
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))
{
return Unauthorized("User is not allowed to create SubProjects.");
}
var project = _projectModel.StoreFromObject(projectObject, user);
if (projectObject.ParentId != null
&& projectObject.ParentId != new Guid()
// for now, only an owner can add subprojects to projects
&& _projectModel.HasAccess(user, _projectModel.GetById(projectObject.ParentId), UserRoles.Owner))
{
var subProjectModel = new SubProjectModel();
subProjectModel.LinkSubProject(projectObject.ParentId, project.Id);
}
_emitter.EmitProjectCreate(new ProjectEventArgs(_configuration)
{
Project = project,
ProjectOwner = user
});
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,120 +31,115 @@ namespace Coscine.Api.Project.Controllers
[Route("[controller]/{projectId}")]
public IActionResult Index(string projectId)
{
return Ok(_authenticator.ValidateAndExecute((user) =>
var userModel = new UserModel();
var roleModel = new RoleModel();
var projectModel = new ProjectModel();
Guid.TryParse(projectId, out Guid projectIdGuid);
var user = _authenticator.GetUser();
if (projectModel.HasAccess(user, projectModel.GetById(projectIdGuid), UserRoles.Owner, UserRoles.Member))
{
UserModel userModel = new UserModel();
RoleModel roleModel = new RoleModel();
ProjectModel projectModel = new ProjectModel();
Guid.TryParse(projectId, out Guid projectIdGuid);
if (projectModel.OwnsProject(user, projectModel.GetById(projectIdGuid)))
return Json(_projectRoleModel.GetAllWhere((projectRole) =>
(projectRole.ProjectId == projectIdGuid)
).Select((projectRole) =>
{
return _projectRoleModel.GetAllWhere((projectRole) =>
(projectRole.ProjectId == projectIdGuid)
).Select((projectRole) =>
var userInst = projectRole.User;
if (userInst == null)
{
User userInst = projectRole.User;
if (userInst == null)
{
userInst = userModel.GetById(projectRole.UserId);
}
Role 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!");
}
}));
userInst = userModel.GetById(projectRole.UserId);
}
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
{
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();
Guid.TryParse(projectId, out Guid projectIdGuid);
UserObject userObject = new UserObject(user.Id, user.DisplayName, user.Givenname, user.Surname, user.EmailAddress);
var roleModel = new RoleModel();
</