Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API for editing and removing levels #222

Merged
merged 5 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Refresh.GameServer/Database/GameDatabaseContext.Levels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using JetBrains.Annotations;
using Realms;
using Refresh.GameServer.Authentication;
using Refresh.GameServer.Endpoints.ApiV3.DataTypes.Request;
using Refresh.GameServer.Extensions;
using Refresh.GameServer.Services;
using Refresh.GameServer.Types;
Expand Down Expand Up @@ -86,6 +87,30 @@ public GameLevel GetStoryLevelById(int id)
return oldSlot;
}

public GameLevel UpdateLevel(ApiEditLevelRequest body, GameLevel level)
{
this._realm.Write(() =>
{
PropertyInfo[] userProps = typeof(ApiEditLevelRequest).GetProperties();
foreach (PropertyInfo prop in userProps)
{
if (!prop.CanWrite || !prop.CanRead) continue;

object? propValue = prop.GetValue(body);
if(propValue == null) continue;

PropertyInfo? gameLevelProp = level.GetType().GetProperty(prop.Name);
Debug.Assert(gameLevelProp != null, $"Invalid property {prop.Name} on {nameof(ApiEditLevelRequest)}");

gameLevelProp.SetValue(level, prop.GetValue(body));
}

level.UpdateDate = this._time.TimestampMilliseconds;
});

return level;
}

public void DeleteLevel(GameLevel level)
{
this._realm.Write(() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ namespace Refresh.GameServer.Endpoints.ApiV3.ApiTypes.Errors;
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class ApiAuthenticationError : ApiError
{
public const string NoPermissionsForObjectWhen = "You do not lack the permissions to manage or view this resource.";
public static readonly ApiAuthenticationError NoPermissionsForObject = new(NoPermissionsForObjectWhen);

public bool Warning { get; init; }

public ApiAuthenticationError(string message, bool warning = false) : base(message, Forbidden)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Refresh.GameServer.Endpoints.ApiV3.DataTypes.Request;

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class ApiEditLevelRequest
{
public string? Title { get; set; }
public string? Description { get; set; }
public string? IconHash { get; set; }
}
38 changes: 38 additions & 0 deletions Refresh.GameServer/Endpoints/ApiV3/LevelApiEndpoints.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using AttribDoc.Attributes;
using Bunkum.Core;
using Bunkum.Core.Endpoints;
using Bunkum.Protocols.Http;
using Refresh.GameServer.Authentication;
using Refresh.GameServer.Database;
using Refresh.GameServer.Documentation.Attributes;
using Refresh.GameServer.Endpoints.ApiV3.ApiTypes;
using Refresh.GameServer.Endpoints.ApiV3.ApiTypes.Errors;
using Refresh.GameServer.Endpoints.ApiV3.DataTypes.Request;
using Refresh.GameServer.Endpoints.ApiV3.DataTypes.Response;
using Refresh.GameServer.Extensions;
using Refresh.GameServer.Services;
Expand Down Expand Up @@ -66,4 +68,40 @@ public ApiResponse<ApiGameLevelResponse> GetLevelById(RequestContext context, Ga

return ApiGameLevelResponse.FromOld(level);
}

[ApiV3Endpoint("levels/id/{id}", HttpMethods.Patch)]
[DocSummary("Edits a level by the level's numerical ID")]
[DocError(typeof(ApiNotFoundError), ApiNotFoundError.LevelMissingErrorWhen)]
[DocError(typeof(ApiAuthenticationError), ApiAuthenticationError.NoPermissionsForObjectWhen)]
public ApiResponse<ApiGameLevelResponse> EditLevelById(RequestContext context, GameDatabaseContext database, GameUser user,
[DocSummary("The ID of the level")] int id, ApiEditLevelRequest body)
{
GameLevel? level = database.GetLevelById(id);
if (level == null) return ApiNotFoundError.LevelMissingError;

if (level.Publisher?.UserId != user.UserId)
return ApiAuthenticationError.NoPermissionsForObject;

database.UpdateLevel(body, level);

return ApiGameLevelResponse.FromOld(level);
}

[ApiV3Endpoint("levels/id/{id}", HttpMethods.Delete)]
[DocSummary("Deletes a level by the level's numerical ID")]
[DocError(typeof(ApiNotFoundError), ApiNotFoundError.LevelMissingErrorWhen)]
[DocError(typeof(ApiAuthenticationError), ApiAuthenticationError.NoPermissionsForObjectWhen)]
public ApiOkResponse DeleteLevelById(RequestContext context, GameDatabaseContext database, GameUser user,
[DocSummary("The ID of the level")] int id)
{
GameLevel? level = database.GetLevelById(id);
if (level == null) return ApiNotFoundError.LevelMissingError;

if (level.Publisher?.UserId != user.UserId)
return ApiAuthenticationError.NoPermissionsForObject;

database.DeleteLevel(level);

return new ApiOkResponse();
}
Beyley marked this conversation as resolved.
Show resolved Hide resolved
}
5 changes: 5 additions & 0 deletions Refresh.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RPCS/@EntryIndexedValue">RPCS</s:String>
<s:Boolean x:Key="/Default/Environment/Editor/UseCamelHumps/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/Environment/Hierarchy/Build/SolBuilderDuo/UseMsbuildSolutionBuilder/@EntryValue">No</s:String>





<s:Boolean x:Key="/Default/UserDictionary/Words/=Asdf/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Autodiscover/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=BCAS/@EntryIndexedValue">True</s:Boolean>
Expand Down
86 changes: 86 additions & 0 deletions RefreshTests.GameServer/Tests/ApiV3/EditApiTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
using System.Net.Http.Json;
using Refresh.GameServer.Authentication;
using Refresh.GameServer.Endpoints.ApiV3.DataTypes.Request;
using Refresh.GameServer.Types.Levels;
using Refresh.GameServer.Types.UserData;

namespace RefreshTests.GameServer.Tests.ApiV3;

public class EditApiTests : GameServerTest
{
[Test]
public void CanUpdateLevel()
{
using TestContext context = this.GetServer();
GameUser user = context.CreateUser();
GameLevel level = context.CreateLevel(user, "Not updated");

long oldUpdate = level.UpdateDate;

ApiEditLevelRequest payload = new()
{
Title = "Updated",
};

context.Time.TimestampMilliseconds = 1;

using HttpClient client = context.GetAuthenticatedClient(TokenType.Api, user);
HttpResponseMessage response = client.PatchAsync($"/api/v3/levels/id/{level.LevelId}", JsonContent.Create(payload)).Result;
Assert.That(response.StatusCode, Is.EqualTo(OK));

context.Database.Refresh();
Assert.Multiple(() =>
{
Assert.That(level.Title, Is.EqualTo("Updated"));
Assert.That(level.UpdateDate, Is.Not.EqualTo(oldUpdate));
Assert.That(level.UpdateDate, Is.EqualTo(context.Time.TimestampMilliseconds));
});
}

[Test]
public void OtherUserCantUpdateLevel()
{
using TestContext context = this.GetServer();
GameUser user = context.CreateUser();
GameUser user2 = context.CreateUser();
GameLevel level = context.CreateLevel(user, "Not updated");

ApiEditLevelRequest payload = new()
{
Title = "Updated",
};

using HttpClient client = context.GetAuthenticatedClient(TokenType.Api, user2);
HttpResponseMessage response = client.PatchAsync($"/api/v3/levels/id/{level.LevelId}", JsonContent.Create(payload)).Result;
Assert.That(response.StatusCode, Is.EqualTo(Forbidden));

context.Database.Refresh();
Assert.Multiple(() =>
{
Assert.That(level.Title, Is.EqualTo("Not updated"));
});
}

[Test]
public void CantUpdateMissingLevel()
{
using TestContext context = this.GetServer();
GameUser user = context.CreateUser();
GameLevel level = context.CreateLevel(user, "Not updated");

ApiEditLevelRequest payload = new()
{
Title = "Updated",
};

using HttpClient client = context.GetAuthenticatedClient(TokenType.Api, user);
HttpResponseMessage response = client.PatchAsync($"/api/v3/levels/id/{int.MaxValue}", JsonContent.Create(payload)).Result;
Assert.That(response.StatusCode, Is.EqualTo(NotFound));

context.Database.Refresh();
Assert.Multiple(() =>
{
Assert.That(level.Title, Is.EqualTo("Not updated"));
});
}
}
38 changes: 38 additions & 0 deletions RefreshTests.GameServer/Tests/ApiV3/LevelApiTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Refresh.GameServer.Authentication;
using Refresh.GameServer.Endpoints.ApiV3.ApiTypes;
using Refresh.GameServer.Endpoints.ApiV3.ApiTypes.Errors;
using Refresh.GameServer.Endpoints.ApiV3.DataTypes.Response;
Expand Down Expand Up @@ -92,4 +93,41 @@ public void DoesntGetLevelByInvalidId()
Assert.That(levelResponse, Is.Not.Null);
levelResponse!.AssertErrorIsEqual(ApiNotFoundError.LevelMissingError);
}

[Test]
public void CanDeleteLevel()
{
using TestContext context = this.GetServer();
GameUser author = context.CreateUser();
GameLevel level = context.CreateLevel(author);

using HttpClient client = context.GetAuthenticatedClient(TokenType.Api, author);
client.DeleteAsync($"/api/v3/levels/id/{level.LevelId}").Wait();
Assert.That(level.IsValid, Is.False);
}

[Test]
public void CantDeleteLevelIfNotAuthor()
{
using TestContext context = this.GetServer();
GameUser author = context.CreateUser();
GameUser moron = context.CreateUser();
GameLevel level = context.CreateLevel(author);

using HttpClient client = context.GetAuthenticatedClient(TokenType.Api, moron);
client.DeleteAsync($"/api/v3/levels/id/{level.LevelId}").Wait();
Assert.That(level.IsValid, Is.True);
}

[Test]
public void CantDeleteLevelIfLevelInvalid()
{
using TestContext context = this.GetServer();
GameUser author = context.CreateUser();
GameLevel level = context.CreateLevel(author);

using HttpClient client = context.GetAuthenticatedClient(TokenType.Api, author);
client.DeleteAsync($"/api/v3/levels/id/{int.MaxValue}").Wait();
Assert.That(level.IsValid, Is.True);
}
}
Loading