Skip to content

Commit

Permalink
Merge pull request #148 from PinguApps/145-create-anonymous-session
Browse files Browse the repository at this point in the history
Added server implementation of create anonymous session
  • Loading branch information
pingu2k4 authored Sep 3, 2024
2 parents 4f96f48 + 7fcd217 commit 36c62eb
Show file tree
Hide file tree
Showing 9 changed files with 124 additions and 33 deletions.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,11 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(
```

## ⌛ Progress
<!-- ![35 / 293](https://progress-bar.dev/35/?scale=293&suffix=%20/%20288&width=500) -->
![Server & Client - 35 / 293](https://img.shields.io/badge/Server_&_Client-35%20%2F%20293-red?style=for-the-badge)
<!-- ![36 / 293](https://progress-bar.dev/36 /?scale=293&suffix=%20/%20288&width=500) -->
![Server & Client - 36 / 293](https://img.shields.io/badge/Server_&_Client-36%20%2F%20293-red?style=for-the-badge)

<!-- ![2 / 200](https://progress-bar.dev/2/?scale=195&suffix=%20/%20200&width=300) -->
![Server - 2 / 200](https://img.shields.io/badge/Server-2%20%2F%20200-red?style=for-the-badge)
<!-- ![3 / 200](https://progress-bar.dev/3/?scale=195&suffix=%20/%20200&width=300) -->
![Server - 3 / 200](https://img.shields.io/badge/Server-3%20%2F%20200-red?style=for-the-badge)

<!-- ![33 / 93](https://progress-bar.dev/33/?scale=93&suffix=%20/%2093&width=300) -->
![Client - 33 / 93](https://img.shields.io/badge/Client-33%20%2F%2093-red?style=for-the-badge)
Expand All @@ -155,8 +155,8 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(
|| There is currently no intention to implement the endpoint for the given SDK type (client or server) |

### Account
<!-- ![35 / 57](https://progress-bar.dev/35/?scale=57&suffix=%20/%2052&width=120) -->
![Account - 35 / 57](https://img.shields.io/badge/Account-35%20%2F%2057-0af0?style=for-the-badge)
<!-- ![36 / 57](https://progress-bar.dev/36/?scale=57&suffix=%20/%2052&width=120) -->
![Account - 36 / 57](https://img.shields.io/badge/Account-36%20%2F%2057-gold?style=for-the-badge)

| Endpoint | Client | Server |
|:-:|:-:|:-:|
Expand Down Expand Up @@ -186,7 +186,7 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(
| [Create Password Recovery (Confirmation)](https://appwrite.io/docs/references/1.6.x/client-rest/account#updateRecovery) |||
| [List Sessions](https://appwrite.io/docs/references/1.6.x/client-rest/account#listSessions) |||
| [Delete Sessions](https://appwrite.io/docs/references/1.6.x/client-rest/account#deleteSessions) |||
| [Create Anonymous Session](https://appwrite.io/docs/references/1.6.x/client-rest/account#createAnonymousSession) || |
| [Create Anonymous Session](https://appwrite.io/docs/references/1.6.x/client-rest/account#createAnonymousSession) || |
| [Create Email Password Session](https://appwrite.io/docs/references/1.6.x/client-rest/account#createEmailPasswordSession) |||
| [Update Magic URL Session](https://appwrite.io/docs/references/1.6.x/client-rest/account#updateMagicURLSession) |||
| [Create OAuth2 Session](https://appwrite.io/docs/references/1.6.x/client-rest/account#createOAuth2Session) |||
Expand Down
19 changes: 9 additions & 10 deletions src/PinguApps.Appwrite.Playground/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,20 @@ public async Task Run(string[] args)
{
//_client.SetSession(_session);

Console.WriteLine(_client.Session);

var response = _client.Account.CreateOauth2Session(new Shared.Requests.CreateOauth2SessionRequest
{
Provider = "google",
SuccessUri = "https://localhost:5001/success",
FailureUri = "https://localhost:5001/fail",
Scopes = ["scope1", "scope2"]
});
var response = await _server.Account.CreateAnonymousSession();

Console.WriteLine(response.Result.Match(
account => account.ToString(),
appwriteError => appwriteError.Message,
internalERror => internalERror.Message));

Console.WriteLine(_client.Session);
await Task.Delay(5000);

var response2 = await _server.Account.CreateAnonymousSession();

Console.WriteLine(response2.Result.Match(
account => account.ToString(),
appwriteError => appwriteError.Message,
internalERror => internalERror.Message));
}
}
3 changes: 3 additions & 0 deletions src/PinguApps.Appwrite.Server/Internals/IAccountApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ internal interface IAccountApi : IBaseApi

[Post("/account/tokens/email")]
Task<IApiResponse<Token>> CreateEmailToken(CreateEmailTokenRequest request);

[Post("/account/sessions/anonymous")]
Task<IApiResponse<Session>> CreateAnonymousSession();
}
15 changes: 15 additions & 0 deletions src/PinguApps.Appwrite.Server/Servers/AccountServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,19 @@ public async Task<AppwriteResult<Token>> CreateEmailToken(CreateEmailTokenReques
return e.GetExceptionResponse<Token>();
}
}

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

return result.GetApiResponse();
}
catch (Exception e)
{
return e.GetExceptionResponse<Session>();
}
}
}
7 changes: 7 additions & 0 deletions src/PinguApps.Appwrite.Server/Servers/IAccountServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,11 @@ public interface IAccountServer
/// <param name="request">The request content</param>
/// <returns>The token</returns>
Task<AppwriteResult<Token>> CreateEmailToken(CreateEmailTokenRequest request);

/// <summary>
/// Use this endpoint to allow a new user to register an anonymous account in your project. This route will also create a new session for the user. To allow the new user to convert an anonymous account to a normal account, you need to call <see cref="UpdateEmail(UpdateEmailRequest)"/> or create an OAuth2 session
/// <para><see href="https://appwrite.io/docs/references/1.6.x/server-rest/account#createAnonymousSession">Appwrite Docs</see></para>
/// </summary>
/// <returns>The Session</returns>
Task<AppwriteResult<Session>> CreateAnonymousSession();
}
10 changes: 9 additions & 1 deletion src/PinguApps.Appwrite.Server/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
using PinguApps.Appwrite.Server.Handlers;
using PinguApps.Appwrite.Server.Internals;
Expand Down Expand Up @@ -27,7 +28,14 @@ public static IServiceCollection AddAppwriteServer(this IServiceCollection servi

services.AddRefitClient<IAccountApi>(refitSettings)
.ConfigureHttpClient(x => x.BaseAddress = new Uri(endpoint))
.AddHttpMessageHandler<HeaderHandler>();
.AddHttpMessageHandler<HeaderHandler>()
.ConfigurePrimaryHttpMessageHandler((handler, sp) =>
{
if (handler is HttpClientHandler clientHandler)
{
clientHandler.UseCookies = false;
}
});

services.AddSingleton<IAccountServer, AccountServer>();
services.AddSingleton<IAppwriteServer, AppwriteServer>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System.Net;
using PinguApps.Appwrite.Shared.Tests;
using RichardSzalay.MockHttp;

namespace PinguApps.Appwrite.Server.Tests.Servers.Account;
public partial class AccountServerTests
{
[Fact]
public async Task CreateAnonymousSession_ShouldReturnSuccess_WhenApiCallSucceeds()
{
// Arrange
_mockHttp.Expect(HttpMethod.Post, $"{Constants.Endpoint}/account/sessions/anonymous")
.ExpectedHeaders()
.Respond(Constants.AppJson, Constants.SessionResponse);

// Act
var result = await _appwriteServer.Account.CreateAnonymousSession();

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

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

// Act
var result = await _appwriteServer.Account.CreateAnonymousSession();

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

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

// Act
var result = await _appwriteServer.Account.CreateAnonymousSession();

// Assert
Assert.False(result.Success);
Assert.True(result.IsInternalError);
Assert.Equal("An error occurred", result.Result.AsT2.Message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,3 @@ public AccountServerTests()
_appwriteServer = serviceProvider.GetRequiredService<IAppwriteServer>();
}
}

public static class AccountTestsExtensions
{
public static MockedRequest ExpectedHeaders(this MockedRequest request)
{
return request
.WithHeaders("x-appwrite-project", Constants.ProjectId)
.WithHeaders("x-appwrite-key", Constants.ApiKey)
.WithHeaders("x-sdk-name", Constants.SdkName)
.WithHeaders("x-sdk-platform", "server")
.WithHeaders("x-sdk-language", Constants.SdkLanguage)
.WithHeaders("x-sdk-version", Constants.SdkVersion)
.WithHeaders("x-appwrite-response-format", Constants.AppwriteResponseFormat);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using PinguApps.Appwrite.Shared.Tests;
using RichardSzalay.MockHttp;

namespace PinguApps.Appwrite.Server.Tests.Servers.Account;

public static class AccountTestsExtensions
{
public static MockedRequest ExpectedHeaders(this MockedRequest request)
{
return request
.WithHeaders("x-appwrite-project", Constants.ProjectId)
.WithHeaders("x-appwrite-key", Constants.ApiKey)
.WithHeaders("x-sdk-name", Constants.SdkName)
.WithHeaders("x-sdk-platform", "server")
.WithHeaders("x-sdk-language", Constants.SdkLanguage)
.WithHeaders("x-sdk-version", Constants.SdkVersion)
.WithHeaders("x-appwrite-response-format", Constants.AppwriteResponseFormat);
}
}

0 comments on commit 36c62eb

Please sign in to comment.