Skip to content

Commit

Permalink
Merge pull request #115 from PinguApps/84-feat-account-create-jwt
Browse files Browse the repository at this point in the history
Implemented account - create jwt
  • Loading branch information
pingu2k4 authored Aug 4, 2024
2 parents b299594 + 865f8b3 commit 03d34de
Show file tree
Hide file tree
Showing 10 changed files with 138 additions and 14 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,11 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(

## ⌛ Progress
### Server & Client
![16 / 288](https://progress-bar.dev/16/?scale=288&suffix=%20/%20288&width=500)
![17 / 288](https://progress-bar.dev/17/?scale=288&suffix=%20/%20288&width=500)
### Server Only
![2 / 195](https://progress-bar.dev/2/?scale=195&suffix=%20/%20195&width=300)
### Client Only
![14 / 93](https://progress-bar.dev/14/?scale=93&suffix=%20/%2093&width=300)
![15 / 93](https://progress-bar.dev/15/?scale=93&suffix=%20/%2093&width=300)

### 🔑 Key
| Icon | Definition |
Expand All @@ -153,7 +153,7 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(
|| There is currently no intention to implement the endpoint for the given SDK type (client or server) |

### Account
![16 / 52](https://progress-bar.dev/16/?scale=52&suffix=%20/%2052&width=120)
![17 / 52](https://progress-bar.dev/17/?scale=52&suffix=%20/%2052&width=120)

| Endpoint | Client | Server |
|:-:|:-:|:-:|
Expand All @@ -162,7 +162,7 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(
| [Update Email](https://appwrite.io/docs/references/1.5.x/client-rest/account#updateEmail) |||
| [List Identities](https://appwrite.io/docs/references/1.5.x/client-rest/account#listIdentities) |||
| [Delete Identity](https://appwrite.io/docs/references/1.5.x/client-rest/account#deleteIdentity) |||
| [Create JWT](https://appwrite.io/docs/references/1.5.x/client-rest/account#createJWT) | ||
| [Create JWT](https://appwrite.io/docs/references/1.5.x/client-rest/account#createJWT) | ||
| [List Logs](https://appwrite.io/docs/references/1.5.x/client-rest/account#listLogs) |||
| [Update MFA](https://appwrite.io/docs/references/1.5.x/client-rest/account#updateMFA) |||
| [Add Authenticator](https://appwrite.io/docs/references/1.5.x/client-rest/account#createMfaAuthenticator) |||
Expand Down
15 changes: 15 additions & 0 deletions src/PinguApps.Appwrite.Client/Clients/AccountClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,19 @@ public async Task<AppwriteResult<Token>> CreateEmailVerificationConfirmation(Cre
return e.GetExceptionResponse<Token>();
}
}

/// <inheritdoc/>
public async Task<AppwriteResult<Jwt>> CreateJwt()
{
try
{
var result = await _accountApi.CreateJwt(Session);

return result.GetApiResponse();
}
catch (Exception e)
{
return e.GetExceptionResponse<Jwt>();
}
}
}
7 changes: 7 additions & 0 deletions src/PinguApps.Appwrite.Client/Clients/IAccountClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,11 @@ public interface IAccountClient
/// <param name="request">The request content</param>
/// <returns>The token</returns>
Task<AppwriteResult<Token>> CreateEmailVerificationConfirmation(CreateEmailVerificationConfirmationRequest request);

/// <summary>
/// Use this endpoint to create a JSON Web Token. You can use the resulting JWT to authenticate on behalf of the current user when working with the Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes from its creation and will be invalid if the user will logout in that time frame.
/// <para><see href="https://appwrite.io/docs/references/1.5.x/client-rest/account#createJWT">Appwrite Docs</see></para>
/// </summary>
/// <returns>The JWT</returns>
Task<AppwriteResult<Jwt>> CreateJwt();
}
3 changes: 3 additions & 0 deletions src/PinguApps.Appwrite.Client/Internals/IAccountApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,7 @@ internal interface IAccountApi : IBaseApi

[Put("/account/verification")]
Task<IApiResponse<Token>> CreateEmailVerificationConfirmation(CreateEmailVerificationConfirmationRequest request);

[Post("/account/jwt")]
Task<IApiResponse<Jwt>> CreateJwt([Header("x-appwrite-session")] string? session);
}
10 changes: 1 addition & 9 deletions src/PinguApps.Appwrite.Playground/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,7 @@ public async Task Run(string[] args)
Url = "https://localhost:5001/abc123"
};

var response = await _client.Account.CreateEmailVerification(request);

//var request = new CreateEmailVerificationConfirmationRequest
//{
// Secret = "secret",
// UserId = "userId"
//};

//var response = await _client.Account.CreateEmailVerificationConfirmation(request);
var response = await _client.Account.CreateJwt();

Console.WriteLine(response.Result.Match(
account => account.ToString(),
Expand Down
11 changes: 11 additions & 0 deletions src/PinguApps.Appwrite.Shared/Responses/Jwt.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Text.Json.Serialization;

namespace PinguApps.Appwrite.Shared.Responses;

/// <summary>
/// A JWT response object
/// </summary>
/// <param name="token">JWT encoded string</param>
public record Jwt(
[property: JsonPropertyName("jwt")] string Token
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System.Net;
using PinguApps.Appwrite.Shared.Tests;
using RichardSzalay.MockHttp;

namespace PinguApps.Appwrite.Client.Tests.Clients.Account;
public partial class AccountClientTests
{
[Fact]
public async Task CreateJwt_ShouldReturnSuccess_WhenApiCallSucceeds()
{
// Arrange
_mockHttp.Expect(HttpMethod.Post, $"{Constants.Endpoint}/account/jwt")
.ExpectedHeaders(true)
.Respond(Constants.AppJson, Constants.JwtResponse);

_appwriteClient.SetSession(Constants.Session);

// Act
var result = await _appwriteClient.Account.CreateJwt();

// Assert
Assert.True(result.Success);
}

[Fact]
public async Task CreateJwt_ShouldHandleException_WhenApiCallFails()
{
// Arrange
_mockHttp.Expect(HttpMethod.Post, $"{Constants.Endpoint}/account/jwt")
.ExpectedHeaders(true)
.Respond(HttpStatusCode.BadRequest, Constants.AppJson, Constants.AppwriteError);

_appwriteClient.SetSession(Constants.Session);

// Act
var result = await _appwriteClient.Account.CreateJwt();

// Assert
Assert.True(result.IsError);
Assert.True(result.IsAppwriteError);
}

[Fact]
public async Task CreateJwt_ShouldReturnErrorResponse_WhenExceptionOccurs()
{
// Arrange
_mockHttp.Expect(HttpMethod.Post, $"{Constants.Endpoint}/account/jwt")
.ExpectedHeaders(true)
.Throw(new HttpRequestException("An error occurred"));

_appwriteClient.SetSession(Constants.Session);

// Act
var result = await _appwriteClient.Account.CreateJwt();

// Assert
Assert.False(result.Success);
Assert.True(result.IsInternalError);
Assert.Equal("An error occurred", result.Result.AsT2.Message);
}
}
6 changes: 6 additions & 0 deletions tests/PinguApps.Appwrite.Shared.Tests/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,10 @@ public static class Constants
"mfaUpdatedAt": "2020-10-15T06:38:00.000+00:00"
}
""";

public const string JwtResponse = """
{
"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}
""";
}
30 changes: 30 additions & 0 deletions tests/PinguApps.Appwrite.Shared.Tests/Responses/JwtTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Text.Json;
using PinguApps.Appwrite.Shared.Responses;

namespace PinguApps.Appwrite.Shared.Tests.Responses;
public class JwtTests
{
[Fact]
public void Token_Constructor_AssignsPropertiesCorrectly()
{
// Arrange
var token = "testToken";

// Act
var jwt = new Jwt(token);

// Assert
Assert.Equal(token, jwt.Token);
}

[Fact]
public void Token_CanBeDeserialized_FromJson()
{
// Act
var jwt = JsonSerializer.Deserialize<Jwt>(Constants.JwtResponse, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

// Assert
Assert.NotNull(jwt);
Assert.Equal("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", jwt.Token);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ public void Token_Constructor_AssignsPropertiesCorrectly()
var expiresAt = DateTime.UtcNow;
var phrase = "phrase";


// Act
var token = new Token(id, createdAt, userId, secret, expiresAt, phrase);

Expand Down

0 comments on commit 03d34de

Please sign in to comment.