Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions packages/Gotrue/Gotrue.Tests/Authentication/SignInContractTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#region

using System.Threading.Tasks;
using FluentAssertions;
using Gotrue.Tests.Support;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Gotrue;
using Supabase.Gotrue.Exceptions;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using static Gotrue.Tests.TestUtils;
using static Supabase.Gotrue.Constants;
using static Supabase.Gotrue.Exceptions.FailureHint.Reason;
using static Supabase.Gotrue.StatelessClient;

#endregion

namespace Gotrue.Tests.Authentication;

/// <summary>
/// Password sign-in sends the captcha token in <c>gotrue_meta_security</c>, and <c>SignInWithPassword</c> rejects an
/// empty password without a request.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class SignInContractTests
{
private MockGotrueServer server = null!;

[TestInitialize]
public void TestInitialize()
{
this.server = new MockGotrueServer();
this.server.Given(Request.Create().WithPath("/token").UsingPost())
.RespondWith(Response.Create().WithStatusCode(200).WithHeader("Content-Type", "application/json").WithBody("{}"));
}

[TestCleanup]
public void TestCleanup() => this.server.Dispose();

[TestMethod]
[DataRow(SignInType.Email, "captcha@example.com")]
[DataRow(SignInType.Phone, "+15555550123")]
public async Task SignInWithPassword_ShouldSendTheCaptchaToken(SignInType type, string identifier)
{
await TestClients.Against(this.server).SignInWithPassword(type, identifier, Password, new SignInWithPasswordOptions { CaptchaToken = "the-captcha" });
this.server.VerifySingleReceivedRequest().WithNestedJsonBody("gotrue_meta_security", "captcha_token", "the-captcha");
}

[TestMethod]
[DataRow(SignInType.Email, "captcha@example.com")]
[DataRow(SignInType.Phone, "+15555550123")]
public async Task SignInWithPassword_ShouldThrowUserBadLogin_GivenEmptyPassword(SignInType type, string identifier)
{
var signIn = () => TestClients.Against(this.server).SignInWithPassword(type, identifier, "", new SignInWithPasswordOptions());
(await signIn.Should().ThrowAsync<GotrueException>()).Which.Reason.Should().Be(UserBadLogin);
this.server.CountReceivedRequests().Should().Be(0, "an empty password must not fall back to an OTP");
}

[TestMethod]
[DataRow(SignInType.Email, "captcha@example.com")]
[DataRow(SignInType.Phone, "+15555550123")]
public async Task StatelessSignIn_ShouldSendTheCaptchaToken(SignInType type, string identifier)
{
var options = new StatelessClientOptions { Url = this.server.Url };
await new StatelessClient().SignIn(type, identifier, Password, options, new SignInWithPasswordOptions { CaptchaToken = "the-captcha" });
this.server.VerifySingleReceivedRequest().WithNestedJsonBody("gotrue_meta_security", "captcha_token", "the-captcha");
}
}
24 changes: 22 additions & 2 deletions packages/Gotrue/Gotrue/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,19 @@ private Task<BaseResponse> MakeRequestAsync(HttpMethod method, string url, objec
/// <param name="email"></param>
/// <param name="password"></param>
/// <returns></returns>
public Task<Session?> SignInWithEmail(string email, string password)
public Task<Session?> SignInWithEmail(string email, string password) => this.SignInWithEmail(email, password, new SignInWithPasswordOptions());

/// <summary>
/// Logs in an existing user using their email address.
/// </summary>
public Task<Session?> SignInWithEmail(string email, string password, SignInWithPasswordOptions options)
{
var body = new Dictionary<string, object> { { "email", email }, { "password", password } };
if (!string.IsNullOrEmpty(options.CaptchaToken))
{
body.Add("gotrue_meta_security", new Dictionary<string, string> { { "captcha_token", options.CaptchaToken! } });
}

return this.MakeRequestAsync<Session>(HttpMethod.Post, $"{this.Url}/token?grant_type=password", body, this.Headers);
}

Expand Down Expand Up @@ -420,13 +430,23 @@ public Task<BaseResponse> InviteUserByEmail(string email, string jwt, InviteUser
/// <param name="phone">The phone number of the user.</param>
/// <param name="password">The password of the user.</param>
/// <returns></returns>
public Task<Session?> SignInWithPhone(string phone, string password)
public Task<Session?> SignInWithPhone(string phone, string password) => this.SignInWithPhone(phone, password, new SignInWithPasswordOptions());

/// <summary>
/// Logs in an existing user using their phone number and password.
/// </summary>
public Task<Session?> SignInWithPhone(string phone, string password, SignInWithPasswordOptions options)
{
var data = new Dictionary<string, object>
{
{ "phone", phone },
{ "password", password }
};
if (!string.IsNullOrEmpty(options.CaptchaToken))
{
data.Add("gotrue_meta_security", new Dictionary<string, string> { { "captcha_token", options.CaptchaToken! } });
}

return this.MakeRequestAsync<Session>(HttpMethod.Post, $"{this.Url}/token?grant_type=password", data, this.Headers);
}

Expand Down
24 changes: 20 additions & 4 deletions packages/Gotrue/Gotrue/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,24 @@ public async Task<PasswordlessSignInState> SignInWithOtp(SignInWithPasswordlessP
public Task<Session?> SignInWithPassword(string email, string password) => this.SignIn(email, password);

/// <inheritdoc />
public async Task<Session?> SignIn(SignInType type, string identifierOrToken, string? password = null,
string? scopes = null)
public Task<Session?> SignInWithPassword(SignInType type, string identifier, string password, SignInWithPasswordOptions options)
{
if (type == SignInType.RefreshToken)
{
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
if (string.IsNullOrEmpty(password))
{
throw new GotrueException("Password not provided.", UserBadLogin);
}
return this.SignIn(type, identifier, password, options);
}

/// <inheritdoc />
public Task<Session?> SignIn(SignInType type, string identifierOrToken, string? password = null,
string? scopes = null) => this.SignIn(type, identifierOrToken, password, new SignInWithPasswordOptions());

private async Task<Session?> SignIn(SignInType type, string identifierOrToken, string? password, SignInWithPasswordOptions options)
{
using var activity = GotrueInstrumentation.Source.StartActivity(GotrueInstrumentation.Spans.SignIn);
activity?.SetTag(GotrueInstrumentation.Tags.SignInType, type.ToString());
Expand All @@ -316,7 +332,7 @@ public async Task<PasswordlessSignInState> SignInWithOtp(SignInWithPasswordlessP
switch (type)
{
case SignInType.Email:
newSession = await this.api.SignInWithEmail(identifierOrToken, password!);
newSession = await this.api.SignInWithEmail(identifierOrToken, password!, options).ConfigureAwait(false);
await this.UpdateSessionAsync(newSession).ConfigureAwait(false);
break;
case SignInType.Phone:
Expand All @@ -325,7 +341,7 @@ public async Task<PasswordlessSignInState> SignInWithOtp(SignInWithPasswordlessP
await this.api.SendMobileOTP(identifierOrToken);
return null;
}
newSession = await this.api.SignInWithPhone(identifierOrToken, password!);
newSession = await this.api.SignInWithPhone(identifierOrToken, password!, options).ConfigureAwait(false);
await this.UpdateSessionAsync(newSession).ConfigureAwait(false);
break;
case SignInType.RefreshToken:
Expand Down
2 changes: 2 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public interface IGotrueApi<TUser, TSession> : IGettableHeaders
Task<TSession?> SignInWithIdToken(Provider provider, string idToken, string? accessToken = null, string? nonce = null, string? captchaToken = null);
Task<TSession?> SignInWithEmail(string email, string password);
Task<TSession?> SignInWithPhone(string phone, string password);
Task<TSession?> SignInWithEmail(string email, string password, SignInWithPasswordOptions options);
Task<TSession?> SignInWithPhone(string phone, string password, SignInWithPasswordOptions options);
Task<PasswordlessSignInState> SignInWithOtp(SignInWithPasswordlessEmailOptions options);
Task<PasswordlessSignInState> SignInWithOtp(SignInWithPasswordlessPhoneOptions options);
Task<TSession?> SignInAnonymously(SignInAnonymouslyOptions? options = null);
Expand Down
5 changes: 5 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,11 @@ public interface IGotrueClient<TUser, TSession> : IGettableHeaders
/// <returns></returns>
Task<TSession?> SignInWithPassword(string email, string password);

/// <summary>
/// Log in an existing user with an email or phone and password.
/// </summary>
Task<TSession?> SignInWithPassword(SignInType type, string identifier, string password, SignInWithPasswordOptions options);

/// <summary>
/// Retrieves a <see cref="ProviderAuthState" /> to redirect to for signing in with a <see cref="Provider" />.
/// This will likely be paired with a PKCE flow (set in SignInOptions) - after redirecting the
Expand Down
5 changes: 5 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueStatelessClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,11 @@ public interface IGotrueStatelessClient<TUser, TSession>
/// <returns></returns>
Task<TSession?> SignIn(SignInType type, string identifierOrToken, string? password = null, StatelessClientOptions? options = null);

/// <summary>
/// Log in an existing user with an email or phone and password.
/// </summary>
Task<TSession?> SignIn(SignInType type, string identifierOrToken, string? password, StatelessClientOptions options, SignInWithPasswordOptions signInOptions);

/// <summary>
/// Sends a Magic email login link to the specified email.
/// </summary>
Expand Down
12 changes: 12 additions & 0 deletions packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,17 @@ Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.GetUserAsync(string! jwt,
Supabase.Gotrue.Interfaces.IGotrueClient<TUser, TSession>.GetClaimsAsync(string? jwt = null, Supabase.Gotrue.Claims.GetClaimsOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Claims.GetClaimsResponse!>!
Supabase.Gotrue.SignUpOptions.CaptchaToken.get -> string?
Supabase.Gotrue.SignUpOptions.CaptchaToken.set -> void
Supabase.Gotrue.Api.SignInWithEmail(string! email, string! password, Supabase.Gotrue.SignInWithPasswordOptions! options) -> System.Threading.Tasks.Task<Supabase.Gotrue.Session?>!
Supabase.Gotrue.Api.SignInWithPhone(string! phone, string! password, Supabase.Gotrue.SignInWithPasswordOptions! options) -> System.Threading.Tasks.Task<Supabase.Gotrue.Session?>!
Supabase.Gotrue.Client.SignInWithPassword(Supabase.Gotrue.Constants.SignInType type, string! identifier, string! password, Supabase.Gotrue.SignInWithPasswordOptions! options) -> System.Threading.Tasks.Task<Supabase.Gotrue.Session?>!
Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.SignInWithEmail(string! email, string! password, Supabase.Gotrue.SignInWithPasswordOptions! options) -> System.Threading.Tasks.Task<TSession?>!
Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.SignInWithPhone(string! phone, string! password, Supabase.Gotrue.SignInWithPasswordOptions! options) -> System.Threading.Tasks.Task<TSession?>!
Supabase.Gotrue.Interfaces.IGotrueClient<TUser, TSession>.SignInWithPassword(Supabase.Gotrue.Constants.SignInType type, string! identifier, string! password, Supabase.Gotrue.SignInWithPasswordOptions! options) -> System.Threading.Tasks.Task<TSession?>!
Supabase.Gotrue.Interfaces.IGotrueStatelessClient<TUser, TSession>.SignIn(Supabase.Gotrue.Constants.SignInType type, string! identifierOrToken, string? password, Supabase.Gotrue.StatelessClient.StatelessClientOptions! options, Supabase.Gotrue.SignInWithPasswordOptions! signInOptions) -> System.Threading.Tasks.Task<TSession?>!
Supabase.Gotrue.Interfaces.IGotrueStatelessClient<TUser, TSession>.SignOut(string! accessToken, Supabase.Gotrue.StatelessClient.StatelessClientOptions! options, Supabase.Gotrue.Constants.SignOutScope scope) -> System.Threading.Tasks.Task!
Supabase.Gotrue.SignInWithPasswordOptions
Supabase.Gotrue.SignInWithPasswordOptions.CaptchaToken.get -> string?
Supabase.Gotrue.SignInWithPasswordOptions.CaptchaToken.init -> void
Supabase.Gotrue.SignInWithPasswordOptions.SignInWithPasswordOptions() -> void
Supabase.Gotrue.StatelessClient.SignIn(Supabase.Gotrue.Constants.SignInType type, string! identifierOrToken, string? password, Supabase.Gotrue.StatelessClient.StatelessClientOptions! options, Supabase.Gotrue.SignInWithPasswordOptions! signInOptions) -> System.Threading.Tasks.Task<Supabase.Gotrue.Session?>!
Supabase.Gotrue.StatelessClient.SignOut(string! accessToken, Supabase.Gotrue.StatelessClient.StatelessClientOptions! options, Supabase.Gotrue.Constants.SignOutScope scope) -> System.Threading.Tasks.Task!
12 changes: 12 additions & 0 deletions packages/Gotrue/Gotrue/SignInWithPasswordOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Supabase.Gotrue;

/// <summary>
/// Options for signing in with a password.
/// </summary>
public sealed class SignInWithPasswordOptions
{
/// <summary>
/// Verification token received when the user completes the captcha on the site.
/// </summary>
public string? CaptchaToken { get; init; }
}
11 changes: 7 additions & 4 deletions packages/Gotrue/Gotrue/StatelessClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,23 +145,26 @@ public async Task<bool> SignIn(string email, StatelessClientOptions options, Sig
public Task<Session?> SignIn(string email, string password, StatelessClientOptions options) => this.SignIn(SignInType.Email, email, password, options);

/// <inheritdoc />
public async Task<Session?> SignIn(SignInType type, string identifierOrToken, string? password = null, StatelessClientOptions? options = null)
public Task<Session?> SignIn(SignInType type, string identifierOrToken, string? password = null, StatelessClientOptions? options = null) =>
this.SignIn(type, identifierOrToken, password, options ?? new StatelessClientOptions(), new SignInWithPasswordOptions());

/// <inheritdoc />
public async Task<Session?> SignIn(SignInType type, string identifierOrToken, string? password, StatelessClientOptions options, SignInWithPasswordOptions signInOptions)
{
options ??= new StatelessClientOptions();
var api = this.GetApi(options);
Session? session;
switch (type)
{
case SignInType.Email:
session = await api.SignInWithEmail(identifierOrToken, password!);
session = await api.SignInWithEmail(identifierOrToken, password!, signInOptions).ConfigureAwait(false);
break;
case SignInType.Phone:
if (string.IsNullOrEmpty(password))
{
await api.SendMobileOTP(identifierOrToken);
return null;
}
session = await api.SignInWithPhone(identifierOrToken, password!);
session = await api.SignInWithPhone(identifierOrToken, password!, signInOptions).ConfigureAwait(false);
break;
default: throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
Expand Down