Skip to content

Commit

Permalink
Merge pull request #172 from PinguApps/104-update-phone-session
Browse files Browse the repository at this point in the history
Implemented update phone session
  • Loading branch information
pingu2k4 authored Sep 24, 2024
2 parents 3872b55 + f4fb492 commit 28c10c8
Show file tree
Hide file tree
Showing 13 changed files with 376 additions and 13 deletions.
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,14 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(
```

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

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

<!-- ![41 / 93](https://progress-bar.dev/41/?scale=93&suffix=%20/%2093&width=300) -->
![Client - 41 / 90](https://img.shields.io/badge/Client-41%20%2F%2090-gold?style=for-the-badge)
<!-- ![42 / 93](https://progress-bar.dev/42/?scale=93&suffix=%20/%2093&width=300) -->
![Client - 42 / 90](https://img.shields.io/badge/Client-42%20%2F%2090-gold?style=for-the-badge)

### 🔑 Key
| Icon | Definition |
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
<!-- ![51 / 55](https://progress-bar.dev/51/?scale=55&suffix=%20/%2052&width=120) -->
![Account - 51 / 55](https://img.shields.io/badge/Account-51%20%2F%2055-forestgreen?style=for-the-badge)
<!-- ![53 / 55](https://progress-bar.dev/53/?scale=55&suffix=%20/%2052&width=120) -->
![Account - 53 / 55](https://img.shields.io/badge/Account-53%20%2F%2055-forestgreen?style=for-the-badge)

| Endpoint | Client | Server | Notes |
|:-:|:-:|:-:|:-:|
Expand Down Expand Up @@ -202,7 +202,7 @@ string emailAddressOrErrorMessage = userResponse.Result.Match(
| [Create Email Token (OTP)](https://appwrite.io/docs/references/1.6.x/client-rest/account#createEmailToken) ||| |
| [Create Magic URL Token](https://appwrite.io/docs/references/1.6.x/client-rest/account#createMagicURLToken) ||| |
| [Create OAuth2 Token](https://appwrite.io/docs/references/1.6.x/client-rest/account#createOAuth2Token) ||| |
| [Create Phone Token](https://appwrite.io/docs/references/1.6.x/client-rest/account#createPhoneToken) | | | |
| [Create Phone Token](https://appwrite.io/docs/references/1.6.x/client-rest/account#createPhoneToken) | | | |
| [Create Email Verification](https://appwrite.io/docs/references/1.6.x/client-rest/account#createVerification) ||| |
| [Create Email Verification (Confirmation)](https://appwrite.io/docs/references/1.6.x/client-rest/account#updateVerification) ||| |
| [Create Phone Verification](https://appwrite.io/docs/references/1.6.x/client-rest/account#createPhoneVerification) ||| |
Expand Down
17 changes: 17 additions & 0 deletions src/PinguApps.Appwrite.Client/Clients/AccountClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -714,4 +714,21 @@ public async Task<AppwriteResult<Token>> CreatePhoneToken(CreatePhoneTokenReques
return e.GetExceptionResponse<Token>();
}
}

/// <inheritdoc/>
public async Task<AppwriteResult<Session>> UpdatePhoneSession(UpdatePhoneSessionRequest request)
{
try
{
request.Validate(true);

var result = await _accountApi.UpdatePhoneSession(request);

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

/// <summary>
/// Use this endpoint to create a session from token. Provide the <c>userId</c> and <c>secret</c> parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login.
/// <para><see href="https://appwrite.io/docs/references/1.6.x/client-rest/account#updatePhoneSession">Appwrite Docs</see></para>
/// </summary>
/// <param name="request">The request content</param>
/// <returns>The session</returns>
Task<AppwriteResult<Session>> UpdatePhoneSession(UpdatePhoneSessionRequest request);
}
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 @@ -126,4 +126,7 @@ internal interface IAccountApi : IBaseApi

[Post("/account/tokens/phone")]
Task<IApiResponse<Token>> CreatePhoneToken(CreatePhoneTokenRequest request);

[Put("/account/sessions/phone")]
Task<IApiResponse<Session>> UpdatePhoneSession(UpdatePhoneSessionRequest request);
}
14 changes: 10 additions & 4 deletions src/PinguApps.Appwrite.Playground/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,23 @@ public App(IAppwriteClient client, IAppwriteServer server, IConfiguration config

public async Task Run(string[] args)
{
_client.SetSession(_session);
//_client.SetSession(_session);

var response = await _server.Account.CreatePhoneToken(new CreatePhoneTokenRequest
Console.WriteLine(_client.Session);

var response = await _server.Account.UpdatePhoneSession(new UpdatePhoneSessionRequest
{
UserId = "664aac1a00113f82e620",
PhoneNumber = "+447500112374"
//PhoneNumber = "+44123456",
Secret = "816076"
});

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


Console.WriteLine(_client.Session);
}
}
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 @@ -29,4 +29,7 @@ internal interface IAccountApi : IBaseApi

[Post("/account/tokens/phone")]
Task<IApiResponse<Token>> CreatePhoneToken(CreatePhoneTokenRequest request);

[Put("/account/sessions/phone")]
Task<IApiResponse<Session>> UpdatePhoneSession(UpdatePhoneSessionRequest request);
}
17 changes: 17 additions & 0 deletions src/PinguApps.Appwrite.Server/Servers/AccountServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,21 @@ public async Task<AppwriteResult<Token>> CreatePhoneToken(CreatePhoneTokenReques
return e.GetExceptionResponse<Token>();
}
}

/// <inheritdoc/>
public async Task<AppwriteResult<Session>> UpdatePhoneSession(UpdatePhoneSessionRequest request)
{
try
{
request.Validate(true);

var result = await _accountApi.UpdatePhoneSession(request);

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

/// <summary>
/// Use this endpoint to create a session from token. Provide the <c>userId</c> and <c>secret</c> parameters from the successful response of authentication flows initiated by token creation. For example, magic URL and phone login.
/// <para><see href="https://appwrite.io/docs/references/1.6.x/server-rest/account#updatePhoneSession">Appwrite Docs</see></para>
/// </summary>
/// <param name="request">The request content</param>
/// <returns>The session</returns>
Task<AppwriteResult<Session>> UpdatePhoneSession(UpdatePhoneSessionRequest request);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Text.Json.Serialization;
using PinguApps.Appwrite.Shared.Requests.Validators;

namespace PinguApps.Appwrite.Shared.Requests;

/// <summary>
/// The request for updating the phone session.
/// </summary>
public class UpdatePhoneSessionRequest : BaseRequest<UpdatePhoneSessionRequest, UpdatePhoneSessionRequestValidator>
{
/// <summary>
/// User ID. Choose a custom ID or generate a random ID with <see cref="Utils.IdUtils.GenerateUniqueId(int)"/>. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can't start with a special char. Max length is 36 chars.
/// </summary>
[JsonPropertyName("userId")]
public string UserId { get; set; } = string.Empty;

/// <summary>
/// Valid verification token.
/// </summary>
[JsonPropertyName("secret")]
public string Secret { get; set; } = string.Empty;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using FluentValidation;

namespace PinguApps.Appwrite.Shared.Requests.Validators;
public class UpdatePhoneSessionRequestValidator : AbstractValidator<UpdatePhoneSessionRequest>
{
public UpdatePhoneSessionRequestValidator()
{
RuleFor(x => x.UserId)
.NotEmpty().WithMessage("The user ID is required.")
.Matches("^[a-zA-Z0-9][a-zA-Z0-9._-]{0,35}$").WithMessage("The user ID must be between 1 and 36 characters long and can only contain a-z, A-Z, 0-9, period, hyphen, and underscore.");

RuleFor(x => x.Secret)
.NotEmpty().WithMessage("The secret is required.");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System.Net;
using PinguApps.Appwrite.Shared.Requests;
using PinguApps.Appwrite.Shared.Tests;
using RichardSzalay.MockHttp;

namespace PinguApps.Appwrite.Client.Tests.Clients.Account;
public partial class AccountClientTests
{
[Fact]
public async Task UpdatePhoneSession_ShouldReturnSuccess_WhenApiCallSucceeds()
{
// Arrange
var request = new UpdatePhoneSessionRequest()
{
UserId = "user123",
Secret = "validSecret"
};

_mockHttp.Expect(HttpMethod.Put, $"{Constants.Endpoint}/account/sessions/phone")
.ExpectedHeaders()
.WithJsonContent(request)
.Respond(Constants.AppJson, Constants.SessionResponse);

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

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

[Fact]
public async Task UpdatePhoneSession_ShouldHandleException_WhenApiCallFails()
{
// Arrange
var request = new UpdatePhoneSessionRequest()
{
UserId = "user123",
Secret = "validSecret"
};

_mockHttp.Expect(HttpMethod.Put, $"{Constants.Endpoint}/account/sessions/phone")
.ExpectedHeaders()
.WithJsonContent(request)
.Respond(HttpStatusCode.BadRequest, Constants.AppJson, Constants.AppwriteError);

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

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

[Fact]
public async Task UpdatePhoneSession_ShouldReturnErrorResponse_WhenExceptionOccurs()
{
// Arrange
var request = new UpdatePhoneSessionRequest()
{
UserId = "user123",
Secret = "validSecret"
};

_mockHttp.Expect(HttpMethod.Put, $"{Constants.Endpoint}/account/sessions/phone")
.ExpectedHeaders()
.WithJsonContent(request)
.Throw(new HttpRequestException("An error occurred"));

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

// 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
@@ -0,0 +1,77 @@
using System.Net;
using PinguApps.Appwrite.Shared.Requests;
using PinguApps.Appwrite.Shared.Tests;
using RichardSzalay.MockHttp;

namespace PinguApps.Appwrite.Server.Tests.Servers.Account;
public partial class AccountServerTests
{
[Fact]
public async Task UpdatePhoneSession_ShouldReturnSuccess_WhenApiCallSucceeds()
{
// Arrange
var request = new UpdatePhoneSessionRequest()
{
UserId = "user123",
Secret = "validSecret"
};

_mockHttp.Expect(HttpMethod.Put, $"{Constants.Endpoint}/account/sessions/phone")
.ExpectedHeaders()
.WithJsonContent(request)
.Respond(Constants.AppJson, Constants.SessionResponse);

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

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

[Fact]
public async Task UpdatePhoneSession_ShouldHandleException_WhenApiCallFails()
{
// Arrange
var request = new UpdatePhoneSessionRequest()
{
UserId = "user123",
Secret = "validSecret"
};

_mockHttp.Expect(HttpMethod.Put, $"{Constants.Endpoint}/account/sessions/phone")
.ExpectedHeaders()
.WithJsonContent(request)
.Respond(HttpStatusCode.BadRequest, Constants.AppJson, Constants.AppwriteError);

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

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

[Fact]
public async Task UpdatePhoneSession_ShouldReturnErrorResponse_WhenExceptionOccurs()
{
// Arrange
var request = new UpdatePhoneSessionRequest()
{
UserId = "user123",
Secret = "validSecret"
};

_mockHttp.Expect(HttpMethod.Put, $"{Constants.Endpoint}/account/sessions/phone")
.ExpectedHeaders()
.WithJsonContent(request)
.Throw(new HttpRequestException("An error occurred"));

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

// Assert
Assert.False(result.Success);
Assert.True(result.IsInternalError);
Assert.Equal("An error occurred", result.Result.AsT2.Message);
}
}
Loading

0 comments on commit 28c10c8

Please sign in to comment.