Skip to content

Commit

Permalink
✨ add info function (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
Odonno committed Nov 21, 2023
1 parent 0a59740 commit efd6cbf
Show file tree
Hide file tree
Showing 7 changed files with 134 additions and 1 deletion.
100 changes: 100 additions & 0 deletions SurrealDb.Net.Tests/InfoTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System.Text;

namespace SurrealDb.Net.Tests;

public class User : SurrealDbRecord
{
public string Username { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string Avatar { get; set; } = string.Empty;
public DateTime RegisteredAt { get; set; }
}

public class InfoTests
{
[Theory]
[InlineData("http://localhost:8000")]
[InlineData("ws://localhost:8000/rpc")]
public async Task ShouldNotRetrieveInfoForRootUser(string url)
{
User? currentUser = null;

Func<Task> func = async () =>
{
await using var surrealDbClientGenerator = new SurrealDbClientGenerator();
var dbInfo = surrealDbClientGenerator.GenerateDatabaseInfo();
using var client = surrealDbClientGenerator.Create(url);
await client.SignIn(new RootAuth { Username = "root", Password = "root" });
await client.Use(dbInfo.Namespace, dbInfo.Database);
currentUser = await client.Info<User>();
};

await func.Should().NotThrowAsync();

currentUser.Should().BeNull();
}

[Theory]
[InlineData("http://localhost:8000")]
[InlineData("ws://localhost:8000/rpc")]
public async Task ShouldRetrieveInfoForScopedUser(string url)
{
User? currentUser = null;

Func<Task> func = async () =>
{
await using var surrealDbClientGenerator = new SurrealDbClientGenerator();
var dbInfo = surrealDbClientGenerator.GenerateDatabaseInfo();
using var client = surrealDbClientGenerator.Create(url);
await client.SignIn(new RootAuth { Username = "root", Password = "root" });
await client.Use(dbInfo.Namespace, dbInfo.Database);
{
string filePath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Schemas/user.surql"
);
string fileContent = File.ReadAllText(filePath, Encoding.UTF8);
string query = fileContent;
await client.Query(query);
}
{
var authParams = new AuthParams
{
Namespace = dbInfo.Namespace,
Database = dbInfo.Database,
Scope = "user_scope",
Username = "johndoe",
Email = "john.doe@example.com",
Password = "password123"
};
var jwt = await client.SignUp(authParams);
await client.Authenticate(jwt);
}
currentUser = await client.Info<User>();
};

await func.Should().NotThrowAsync();

var expected = new User
{
Id = currentUser?.Id,
Username = "johndoe",
Email = "john.doe@example.com",
Password = string.Empty, // 💡 Forbid password retrieval
Avatar = "https://www.gravatar.com/avatar/8eb1b522f60d11fa897de1dc6351b7e8",
RegisteredAt = currentUser?.RegisteredAt ?? default
};

currentUser.Should().BeEquivalentTo(expected);
currentUser?.Id.Should().NotBeNull();
}
}
2 changes: 1 addition & 1 deletion SurrealDb.Net.Tests/Schemas/user.surql
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ DEFINE TABLE user SCHEMAFULL

DEFINE FIELD username ON user TYPE string;
DEFINE FIELD email ON user TYPE string ASSERT string::is::email($value);
DEFINE FIELD password ON user TYPE string;
DEFINE FIELD password ON user TYPE string PERMISSIONS FOR SELECT NONE;
DEFINE FIELD registered_at ON user TYPE datetime DEFAULT time::now();
DEFINE FIELD avatar ON user TYPE string;

Expand Down
13 changes: 13 additions & 0 deletions SurrealDb.Net/Internals/SurrealDbEngine.Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,19 @@ public async Task<bool> Health(CancellationToken cancellationToken)
}
}

public async Task<T> Info<T>(CancellationToken cancellationToken)
{
const string query = "SELECT * FROM $auth;";

var dbResponse = await Query(query, new Dictionary<string, object>(), cancellationToken)
.ConfigureAwait(false);

EnsuresFirstResultOk(dbResponse);

var results = dbResponse.GetValue<List<T>>(0)!;
return results.First();
}

public Task Invalidate(CancellationToken _)
{
_config.ResetAuth();
Expand Down
1 change: 1 addition & 0 deletions SurrealDb.Net/Internals/SurrealDbEngine.Interface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Task<T> Create<T>(T data, CancellationToken cancellationToken)
Task Delete(string table, CancellationToken cancellationToken);
Task<bool> Delete(Thing thing, CancellationToken cancellationToken);
Task<bool> Health(CancellationToken cancellationToken);
Task<T> Info<T>(CancellationToken cancellationToken);
Task Invalidate(CancellationToken cancellationToken);
Task Kill(
Guid queryUuid,
Expand Down
6 changes: 6 additions & 0 deletions SurrealDb.Net/Internals/SurrealDbEngine.Ws.cs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,12 @@ public async Task<bool> Health(CancellationToken cancellationToken)
}
}

public async Task<T> Info<T>(CancellationToken cancellationToken)
{
var dbResponse = await SendRequest("info", null, cancellationToken).ConfigureAwait(false);
return dbResponse.GetValue<T>()!;
}

public async Task Invalidate(CancellationToken cancellationToken)
{
await SendRequest("invalidate", null, cancellationToken).ConfigureAwait(false);
Expand Down
8 changes: 8 additions & 0 deletions SurrealDb.Net/SurrealDbClient.Interface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,14 @@ Task<T> Create<T>(T data, CancellationToken cancellationToken = default)
/// <exception cref="SurrealDbException"></exception>
Task<bool> Health(CancellationToken cancellationToken = default);

/// <summary>
/// Retrieves information about the authenticated scope user.
/// </summary>
/// <typeparam name="T">The scope user type.</typeparam>
/// <param name="cancellationToken">The cancellationToken enables graceful cancellation of asynchronous operations</param>
/// <returns>Returns the record of an authenticated scope user.</returns>
Task<T> Info<T>(CancellationToken cancellationToken = default);

/// <summary>
/// Invalidates the authentication for the current connection.
/// </summary>
Expand Down
5 changes: 5 additions & 0 deletions SurrealDb.Net/SurrealDbClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ public Task<bool> Health(CancellationToken cancellationToken = default)
return _engine.Health(cancellationToken);
}

public Task<T> Info<T>(CancellationToken cancellationToken = default)
{
return _engine.Info<T>(cancellationToken);
}

public Task Invalidate(CancellationToken cancellationToken = default)
{
return _engine.Invalidate(cancellationToken);
Expand Down

0 comments on commit efd6cbf

Please sign in to comment.