Resolve merge conflicts

This commit is contained in:
jvyden 2021-10-16 19:17:46 -04:00
commit c9421b6d23
No known key found for this signature in database
GPG key ID: 18BCF2BE0262B278
22 changed files with 287 additions and 93 deletions

View file

@ -0,0 +1,11 @@
using ProjectLighthouse.Types;
using Xunit;
namespace ProjectLighthouse.Tests {
public sealed class DatabaseFact : FactAttribute {
public DatabaseFact() {
ServerSettings.DbConnectionString = "server=127.0.0.1;uid=root;pwd=lighthouse;database=lighthouse";
if(!ServerSettings.DbConnected) Skip = "Database not available";
}
}
}

View file

@ -0,0 +1,51 @@
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using ProjectLighthouse.Serialization;
using ProjectLighthouse.Types;
namespace ProjectLighthouse.Tests {
public class LighthouseTest {
public readonly TestServer Server;
public readonly HttpClient Client;
public LighthouseTest() {
this.Server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>());
this.Client = this.Server.CreateClient();
}
public async Task<HttpResponseMessage> AuthenticateResponse(int number = 0) {
const char nullChar = (char)0x00;
const char sepChar = (char)0x20;
const string username = "unitTestUser";
string stringContent = $"{nullChar}{sepChar}{username}{number}{nullChar}";
HttpResponseMessage response = await this.Client.PostAsync("/LITTLEBIGPLANETPS3_XML/login", new StringContent(stringContent));
return response;
}
public async Task<LoginResult> Authenticate(int number = 0) {
HttpResponseMessage response = await this.AuthenticateResponse(number);
string responseContent = LbpSerializer.StringElement("loginResult", await response.Content.ReadAsStringAsync());
XmlSerializer serializer = new(typeof(LoginResult));
return (LoginResult)serializer.Deserialize(new StringReader(responseContent))!;
}
public Task<HttpResponseMessage> AuthenticatedRequest(string endpoint, string mmAuth) => AuthenticatedRequest(endpoint, mmAuth, HttpMethod.Get);
public Task<HttpResponseMessage> AuthenticatedRequest(string endpoint, string mmAuth, HttpMethod method) {
using var requestMessage = new HttpRequestMessage(method, endpoint);
requestMessage.Headers.Add("Cookie", mmAuth);
return this.Client.SendAsync(requestMessage);
}
}
}

View file

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.11" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProjectLighthouse\ProjectLighthouse.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=tests/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View file

@ -0,0 +1,59 @@
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using ProjectLighthouse.Types;
using Xunit;
namespace ProjectLighthouse.Tests {
public class AuthenticationTests : LighthouseTest {
[Fact]
public async Task ShouldReturnErrorOnNoPostData() {
HttpResponseMessage response = await this.Client.PostAsync("/LITTLEBIGPLANETPS3_XML/login", null!);
Assert.False(response.IsSuccessStatusCode);
#if NET6_0_OR_GREATER
Assert.True(response.StatusCode == HttpStatusCode.BadRequest);
#else
Assert.True(response.StatusCode == HttpStatusCode.NotAcceptable);
#endif
}
[DatabaseFact]
public async Task ShouldReturnWithValidData() {
HttpResponseMessage response = await this.AuthenticateResponse();
Assert.True(response.IsSuccessStatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.Contains("MM_AUTH=", responseContent);
Assert.Contains(ServerSettings.ServerName, responseContent);
}
[DatabaseFact]
public async Task CanSerializeBack() {
LoginResult loginResult = await this.Authenticate();
Assert.NotNull(loginResult);
Assert.NotNull(loginResult.AuthTicket);
Assert.NotNull(loginResult.LbpEnvVer);
Assert.Contains("MM_AUTH=", loginResult.AuthTicket);
Assert.Equal(ServerSettings.ServerName, loginResult.LbpEnvVer);
}
[DatabaseFact]
public async Task CanUseToken() {
LoginResult loginResult = await this.Authenticate();
HttpResponseMessage response = await AuthenticatedRequest("/LITTLEBIGPLANETPS3_XML/eula", loginResult.AuthTicket);
string responseContent = await response.Content.ReadAsStringAsync();
Assert.True(response.IsSuccessStatusCode);
Assert.Contains("You are logged in", responseContent);
}
[DatabaseFact]
public async Task ShouldReturnForbiddenWhenNotAuthenticated() {
HttpResponseMessage response = await this.Client.GetAsync("/LITTLEBIGPLANETPS3_XML/eula");
Assert.False(response.IsSuccessStatusCode);
Assert.True(response.StatusCode == HttpStatusCode.Forbidden);
}
}
}

View file

@ -0,0 +1,31 @@
using System.Collections.Generic;
using ProjectLighthouse.Serialization;
using Xunit;
namespace ProjectLighthouse.Tests {
public class SerializerTests : LighthouseTest {
[Fact]
public void BlankElementWorks() {
Assert.Equal("<test></test>", LbpSerializer.BlankElement("test"));
}
[Fact]
public void StringElementWorks() {
Assert.Equal("<test>asd</test>", LbpSerializer.StringElement("test", "asd"));
Assert.Equal("<test>asd</test>", LbpSerializer.StringElement(new KeyValuePair<string, object>("test", "asd")));
}
[Fact]
public void TaggedStringElementWorks() {
Assert.Equal("<test foo=\"bar\">asd</test>", LbpSerializer.TaggedStringElement("test", "asd", "foo", "bar"));
Assert.Equal("<test foo=\"bar\">asd</test>", LbpSerializer.TaggedStringElement(new KeyValuePair<string, object>("test", "asd"),
new KeyValuePair<string, object>("foo", "bar")));
}
[Fact]
public void ElementsWorks() {
Assert.Equal("<test>asd</test><foo>bar</foo>", LbpSerializer.Elements(new KeyValuePair<string, object>("test", "asd"),
new KeyValuePair<string, object>("foo", "bar")));
}
}
}

View file

@ -2,6 +2,8 @@
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectLighthouse", "ProjectLighthouse\ProjectLighthouse.csproj", "{C6CFD4AD-47ED-4C86-B0C4-A4216D82E0DC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectLighthouse.Tests", "ProjectLighthouse.Tests\ProjectLighthouse.Tests.csproj", "{AFC74569-B289-4ACC-B21C-313A3A62C017}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -12,5 +14,9 @@ Global
{C6CFD4AD-47ED-4C86-B0C4-A4216D82E0DC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6CFD4AD-47ED-4C86-B0C4-A4216D82E0DC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6CFD4AD-47ED-4C86-B0C4-A4216D82E0DC}.Release|Any CPU.Build.0 = Release|Any CPU
{AFC74569-B289-4ACC-B21C-313A3A62C017}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AFC74569-B289-4ACC-B21C-313A3A62C017}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AFC74569-B289-4ACC-B21C-313A3A62C017}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AFC74569-B289-4ACC-B21C-313A3A62C017}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View file

@ -13,11 +13,17 @@ namespace ProjectLighthouse.Controllers {
[Route("LITTLEBIGPLANETPS3_XML/")]
[Produces("text/xml")]
public class CommentController : ControllerBase {
private readonly Database database;
public CommentController(Database database) {
this.database = database;
}
[HttpGet("userComments/{username}")]
public async Task<IActionResult> GetComments(string username) {
// the following is downright retarded, but its 12:48am and i do not give a shit
// ↓ ok... ↓ why does this need to be wrapped ↓ again???? whyyyy
List<Comment> comments = (await new Database().Comments.ToListAsync()).Where(c => c.TargetUsername == username).ToList();
List<Comment> comments = await database.Comments
.Include(c => c.Target)
.Where(c => c.Target.Username == username)
.ToListAsync();
string outputXml = comments.Aggregate(string.Empty, (current, comment) => current + comment.Serialize());
return this.Ok(LbpSerializer.StringElement("comments", outputXml));
@ -31,7 +37,6 @@ namespace ProjectLighthouse.Controllers {
XmlSerializer serializer = new(typeof(Comment));
Comment comment = (Comment)serializer.Deserialize(new StringReader(bodyString));
await using Database database = new();
User poster = await database.UserFromRequest(Request);
if(poster == null) return this.StatusCode(403, "");

View file

@ -2,7 +2,6 @@
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using ProjectLighthouse.Types;
namespace ProjectLighthouse.Controllers {
@ -10,11 +9,14 @@ namespace ProjectLighthouse.Controllers {
[Route("LITTLEBIGPLANETPS3_XML/login")]
[Produces("text/xml")]
public class LoginController : ControllerBase {
private readonly Database database;
public LoginController(Database database) {
this.database = database;
}
[HttpPost]
public async Task<IActionResult> Login() {
if(!this.Request.Query.TryGetValue("titleID", out StringValues _))
return this.BadRequest("");
string body = await new StreamReader(Request.Body).ReadToEndAsync();
LoginData loginData;
@ -25,8 +27,6 @@ namespace ProjectLighthouse.Controllers {
return this.BadRequest();
}
await using Database database = new();
Token? token = await database.AuthenticateUser(loginData);
if(token == null) return this.StatusCode(403, "");

View file

@ -7,9 +7,14 @@ namespace ProjectLighthouse.Controllers {
[Route("LITTLEBIGPLANETPS3_XML/")]
[Produces("text/plain")]
public class MessageController : ControllerBase {
private readonly Database database;
public MessageController(Database database) {
this.database = database;
}
[HttpGet("eula")]
public async Task<IActionResult> Eula() {
User user = await new Database().UserFromRequest(Request);
User user = await this.database.UserFromRequest(Request);
return user == null ? this.StatusCode(403, "") : this.Ok($"You are logged in as user {user.Username} (id {user.UserId})");
}

View file

@ -11,6 +11,12 @@ namespace ProjectLighthouse.Controllers {
[Route("LITTLEBIGPLANETPS3_XML/")]
[Produces("text/xml")]
public class PublishController : ControllerBase {
private readonly Database database;
public PublishController(Database database) {
this.database = database;
}
/// <summary>
/// Endpoint the game uses to verify that the level is compatible (?)
/// </summary>
@ -27,8 +33,6 @@ namespace ProjectLighthouse.Controllers {
/// </summary>
[HttpPost("publish")]
public async Task<IActionResult> Publish() {
await using Database database = new();
User user = await database.UserFromRequest(Request);
if(user == null) return this.StatusCode(403, "");
@ -52,8 +56,6 @@ namespace ProjectLighthouse.Controllers {
[HttpPost("unpublish/{id:int}")]
public async Task<IActionResult> Unpublish(int id) {
await using Database database = new();
Slot slot = await database.Slots.FirstOrDefaultAsync(s => s.SlotId == id);
database.Locations.Remove(slot.Location);

View file

@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProjectLighthouse.Serialization;
using ProjectLighthouse.Types;
@ -9,22 +10,29 @@ namespace ProjectLighthouse.Controllers {
[Route("LITTLEBIGPLANETPS3_XML/")]
[Produces("text/xml")]
public class SlotsController : ControllerBase {
private readonly Database database;
public SlotsController(Database database) {
this.database = database;
}
[HttpGet("slots/by")]
public IActionResult SlotsBy() {
string response = Enumerable.Aggregate(new Database().Slots, string.Empty, (current, slot) => current + slot.Serialize());
string response = Enumerable.Aggregate(
database.Slots
.Include(s => s.Creator)
.Include(s => s.Location)
, string.Empty, (current, slot) => current + slot.Serialize());
return this.Ok(LbpSerializer.TaggedStringElement("slots", response, "total", 1));
}
[HttpGet("s/user/{id:int}")]
public IActionResult SUser(int id) {
IEnumerable<Slot> slots = new Database().Slots
.Where(s => s.CreatorId == id)
.AsEnumerable();
public async Task<IActionResult> SUser(int id) {
Slot slot = await this.database.Slots
.Include(s => s.Creator)
.Include(s => s.Location)
.FirstOrDefaultAsync(s => s.SlotId == id);
string response = slots.Aggregate(string.Empty, (current, s) => current + s.Serialize());
return this.Ok(LbpSerializer.TaggedStringElement("slots", response, "total", 1));
return this.Ok(slot.Serialize());
}
}
}

View file

@ -12,11 +12,16 @@ namespace ProjectLighthouse.Controllers {
[Route("LITTLEBIGPLANETPS3_XML/")]
[Produces("text/xml")]
public class UserController : ControllerBase {
private readonly Database database;
public UserController(Database database) {
this.database = database;
}
[HttpGet("user/{username}")]
public async Task<IActionResult> GetUser(string username) {
await using Database database = new();
User user = await database.Users.FirstOrDefaultAsync(u => u.Username == username);
User user = await database.Users
.Include(u => u.Location)
.FirstOrDefaultAsync(u => u.Username == username);
if(user == null) return this.NotFound();
return this.Ok(user.Serialize());
@ -30,7 +35,6 @@ namespace ProjectLighthouse.Controllers {
[HttpPost("updateUser")]
public async Task<IActionResult> UpdateUser() {
await using Database database = new();
User user = await database.UserFromRequest(Request);
if(user == null) return this.StatusCode(403, "");

View file

@ -1,5 +1,3 @@
//#nullable enable
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
@ -11,7 +9,6 @@ namespace ProjectLighthouse {
public DbSet<User> Users { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Slot> Slots { get; set; }
public DbSet<QueuedLevel> QueuedLevels { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Token> Tokens { get; set; }
@ -29,7 +26,7 @@ namespace ProjectLighthouse {
User user = new() {
Username = username,
LocationId = l.Id,
Biography = "No biography provided",
Biography = username + " hasn't introduced themselves yet.",
Pins = "",
PlanetHash = "",
};
@ -63,7 +60,9 @@ namespace ProjectLighthouse {
public async Task<User?> UserFromAuthToken(string authToken) {
Token? token = await Tokens.FirstOrDefaultAsync(t => t.UserToken == authToken);
if(token == null) return null;
return await Users.FirstOrDefaultAsync(u => u.UserId == token.UserId);
return await Users
.Include(u => u.Location)
.FirstOrDefaultAsync(u => u.UserId == token.UserId);
}
public async Task<User?> UserFromRequest(HttpRequest request) {

View file

@ -1,5 +1,7 @@
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ProjectLighthouse.Types;
@ -9,13 +11,13 @@ namespace ProjectLighthouse {
Console.WriteLine("Welcome to Project Lighthouse!");
Console.WriteLine(ServerSettings.DbConnected ? "Connected to the database." : "Database unavailable. Starting in stateless mode.");
CreateHostBuilder(args).Build().Run();
}
IHostBuilder builder = Host.CreateDefaultBuilder(args);
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
builder.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
builder.Build().Run();
}
}
}

View file

@ -7,7 +7,8 @@
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.11" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="5.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>

View file

@ -3,10 +3,12 @@ using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ProjectLighthouse.Serialization;
using ProjectLighthouse.Types;
namespace ProjectLighthouse {
public class Startup {
@ -18,10 +20,11 @@ namespace ProjectLighthouse {
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddMvc(options =>
options.OutputFormatters.Add(new XmlOutputFormatter()));
services.AddDbContext<Database>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

View file

@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Xml.Serialization;
using ProjectLighthouse.Serialization;
@ -14,25 +15,11 @@ namespace ProjectLighthouse.Types {
public int TargetUserId { get; set; }
private string posterUsername;
[ForeignKey(nameof(PosterUserId))]
public User Poster { get; set; }
// [XmlAttribute("username")]
public string PosterUsername {
get {
if(this.posterUsername != null) return this.posterUsername;
return this.posterUsername = new Database().Users.First(u => u.UserId == PosterUserId).Username;
}
}
private string targetUsername;
public string TargetUsername {
get {
if(this.targetUsername != null) return this.targetUsername;
return this.targetUsername = new Database().Users.First(u => u.UserId == TargetUserId).Username;
}
}
[ForeignKey(nameof(TargetUserId))]
public User Target { get; set; }
public long Timestamp { get; set; }
@ -43,7 +30,7 @@ namespace ProjectLighthouse.Types {
private string serialize() {
return LbpSerializer.StringElement("id", CommentId) +
LbpSerializer.StringElement("npHandle", this.PosterUsername) +
LbpSerializer.StringElement("npHandle", this.Poster.Username) +
LbpSerializer.StringElement("timestamp", Timestamp) +
LbpSerializer.StringElement("message", Message) +
LbpSerializer.StringElement("thumbsup", ThumbsUp) +

View file

@ -1,12 +1,17 @@
using System.Collections.Generic;
using System.Xml.Serialization;
using ProjectLighthouse.Serialization;
namespace ProjectLighthouse.Types {
/// <summary>
/// Response to POST /login
/// </summary>
[XmlRoot("loginResult"), XmlType("loginResult")]
public class LoginResult {
[XmlElement("authTicket")]
public string AuthTicket { get; set; }
[XmlElement("lbpEnvVer")]
public string LbpEnvVer { get; set; }
public string Serialize() {

View file

@ -16,10 +16,11 @@ namespace ProjectLighthouse.Types {
public static string DbConnectionString {
get {
if(dbConnectionString == null) {
return dbConnectionString = Environment.GetEnvironmentVariable("LIGHTHOUSE_DB_CONNECTION_STRING") ?? "";
return dbConnectionString = Environment.GetEnvironmentVariable("") ?? "";
}
return dbConnectionString;
}
set => dbConnectionString = value;
}
public static bool DbConnected {

View file

@ -2,6 +2,7 @@ using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Xml.Serialization;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using ProjectLighthouse.Serialization;
namespace ProjectLighthouse.Types {
@ -40,29 +41,15 @@ namespace ProjectLighthouse.Types {
[XmlIgnore]
public int CreatorId { get; set; }
private User creator;
public User Creator {
get {
if(this.creator != null) return this.creator;
return creator = new Database().Users.First(u => u.UserId == CreatorId);
}
}
private Location location;
[ForeignKey(nameof(CreatorId))]
public User Creator { get; set; }
/// <summary>
/// The location of the level on the creator's earth
/// </summary>
[XmlElement("location")]
public Location Location {
get {
if(location != null) return this.location;
return location = new Database().Locations.First(l => l.Id == LocationId);
}
}
[ForeignKey(nameof(LocationId))]
public Location Location { get; set; }
[XmlElement("initiallyLocked")]
public bool InitiallyLocked { get; set; }

View file

@ -1,3 +1,4 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using ProjectLighthouse.Serialization;
@ -24,16 +25,11 @@ namespace ProjectLighthouse.Types {
public int LocationId { get; set; }
private Location location;
/// <summary>
/// The location of the profile card on the user's earth
/// </summary>
public Location Location {
get {
if(location != null) return this.location;
return location = new Database().Locations.First(l => l.Id == LocationId);
}
}
[ForeignKey("LocationId")]
public Location Location { get; set; }
public int FavouriteSlotCount { get; set; }
public int FavouriteUserCount { get; set; }