Skip to content

Add users.EnrollAuthFactor() method #254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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
88 changes: 69 additions & 19 deletions pkg/users/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/google/go-querystring/query"
"github.com/workos/workos-go/v2/internal/workos"
"github.com/workos/workos-go/v2/pkg/common"
"github.com/workos/workos-go/v2/pkg/mfa"
"github.com/workos/workos-go/v2/pkg/workos_errors"
"net/http"
"time"
Expand Down Expand Up @@ -160,7 +161,8 @@ type AuthenticateWithMagicAuthOpts struct {
}

type AuthenticationResponse struct {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In ruby I think this is called AuthenticationFactorAndChallenge (or was 6 days ago, we may want to discuss standardization on this)

User User `json:"user"`
Factor mfa.Factor `json:"authentication_factor"`
Challenge mfa.Challenge `json:"authentication_challenge"`
}

type SendVerificationEmailOpts struct {
Expand Down Expand Up @@ -210,6 +212,11 @@ type RemoveUserFromOrganizationOpts struct {
Organization string `json:"organization_id"`
}

type EnrollAuthFactorOpts struct {
User string
Type mfa.FactorType `json:"type"`
}

func NewClient(apiKey string) *Client {
return &Client{
APIKey: apiKey,
Expand Down Expand Up @@ -547,7 +554,7 @@ func (c *Client) RemoveUserFromOrganization(ctx context.Context, opts RemoveUser
}

// AuthenticateWithPassword authenticates a user with Email and Password
func (c *Client) AuthenticateWithPassword(ctx context.Context, opts AuthenticateWithPasswordOpts) (AuthenticationResponse, error) {
func (c *Client) AuthenticateWithPassword(ctx context.Context, opts AuthenticateWithPasswordOpts) (UserResponse, error) {
payload := struct {
AuthenticateWithPasswordOpts
ClientSecret string `json:"client_secret"`
Expand All @@ -560,7 +567,7 @@ func (c *Client) AuthenticateWithPassword(ctx context.Context, opts Authenticate

jsonData, err := json.Marshal(payload)
if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

req, err := http.NewRequest(
Expand All @@ -570,7 +577,7 @@ func (c *Client) AuthenticateWithPassword(ctx context.Context, opts Authenticate
)

if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

// Add headers and context to the request
Expand All @@ -581,24 +588,24 @@ func (c *Client) AuthenticateWithPassword(ctx context.Context, opts Authenticate
// Execute the request
res, err := c.HTTPClient.Do(req)
if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}
defer res.Body.Close()

if err = workos_errors.TryGetHTTPError(res); err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

// Parse the JSON response
var body AuthenticationResponse
var body UserResponse
dec := json.NewDecoder(res.Body)
err = dec.Decode(&body)

return body, err
}

// AuthenticateWithCode authenticates an OAuth user or a managed SSO user that is logging in through SSO
func (c *Client) AuthenticateWithCode(ctx context.Context, opts AuthenticateWithCodeOpts) (AuthenticationResponse, error) {
func (c *Client) AuthenticateWithCode(ctx context.Context, opts AuthenticateWithCodeOpts) (UserResponse, error) {
payload := struct {
AuthenticateWithCodeOpts
ClientSecret string `json:"client_secret"`
Expand All @@ -611,7 +618,7 @@ func (c *Client) AuthenticateWithCode(ctx context.Context, opts AuthenticateWith

jsonData, err := json.Marshal(payload)
if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

req, err := http.NewRequest(
Expand All @@ -621,7 +628,7 @@ func (c *Client) AuthenticateWithCode(ctx context.Context, opts AuthenticateWith
)

if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

// Add headers and context to the request
Expand All @@ -632,16 +639,16 @@ func (c *Client) AuthenticateWithCode(ctx context.Context, opts AuthenticateWith
// Execute the request
res, err := c.HTTPClient.Do(req)
if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}
defer res.Body.Close()

if err = workos_errors.TryGetHTTPError(res); err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

// Parse the JSON response
var body AuthenticationResponse
var body UserResponse
dec := json.NewDecoder(res.Body)
err = dec.Decode(&body)

Expand All @@ -650,7 +657,7 @@ func (c *Client) AuthenticateWithCode(ctx context.Context, opts AuthenticateWith

// AuthenticateWithMagicAuth authenticates a user by verifying a one-time code sent to the user's email address by
// the Magic Auth Send Code endpoint.
func (c *Client) AuthenticateWithMagicAuth(ctx context.Context, opts AuthenticateWithMagicAuthOpts) (AuthenticationResponse, error) {
func (c *Client) AuthenticateWithMagicAuth(ctx context.Context, opts AuthenticateWithMagicAuthOpts) (UserResponse, error) {
payload := struct {
AuthenticateWithMagicAuthOpts
ClientSecret string `json:"client_secret"`
Expand All @@ -663,7 +670,7 @@ func (c *Client) AuthenticateWithMagicAuth(ctx context.Context, opts Authenticat

jsonData, err := json.Marshal(payload)
if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

req, err := http.NewRequest(
Expand All @@ -673,7 +680,7 @@ func (c *Client) AuthenticateWithMagicAuth(ctx context.Context, opts Authenticat
)

if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

// Add headers and context to the request
Expand All @@ -684,16 +691,16 @@ func (c *Client) AuthenticateWithMagicAuth(ctx context.Context, opts Authenticat
// Execute the request
res, err := c.HTTPClient.Do(req)
if err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}
defer res.Body.Close()

if err = workos_errors.TryGetHTTPError(res); err != nil {
return AuthenticationResponse{}, err
return UserResponse{}, err
}

// Parse the JSON response
var body AuthenticationResponse
var body UserResponse
dec := json.NewDecoder(res.Body)
err = dec.Decode(&body)

Expand Down Expand Up @@ -906,3 +913,46 @@ func (c *Client) SendMagicAuthCode(ctx context.Context, opts SendMagicAuthCodeOp

return body, err
}

// EnrollAuthFactor enrolls an authentication factor for the user.
func (c *Client) EnrollAuthFactor(ctx context.Context, opts EnrollAuthFactorOpts) (AuthenticationResponse, error) {
endpoint := fmt.Sprintf(
"%s/users/%s/auth/factors",
c.Endpoint,
opts.User,
)

data, err := c.JSONEncode(opts)
if err != nil {
return AuthenticationResponse{}, err
}

req, err := http.NewRequest(
http.MethodPost,
endpoint,
bytes.NewBuffer(data),
)
if err != nil {
return AuthenticationResponse{}, err
}
req = req.WithContext(ctx)
req.Header.Set("User-Agent", "workos-go/"+workos.Version)
req.Header.Set("Authorization", "Bearer "+c.APIKey)
req.Header.Set("Content-Type", "application/json")

res, err := c.HTTPClient.Do(req)
if err != nil {
return AuthenticationResponse{}, err
}
defer res.Body.Close()

if err = workos_errors.TryGetHTTPError(res); err != nil {
return AuthenticationResponse{}, err
}

var body AuthenticationResponse
dec := json.NewDecoder(res.Body)
err = dec.Decode(&body)

return body, err
}
110 changes: 103 additions & 7 deletions pkg/users/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"github.com/stretchr/testify/require"
"github.com/workos/workos-go/v2/pkg/common"
"github.com/workos/workos-go/v2/pkg/mfa"
"net/http"
"net/http/httptest"
"strings"
Expand Down Expand Up @@ -699,7 +700,7 @@ func TestAuthenticateUserWithPassword(t *testing.T) {
scenario string
client *Client
options AuthenticateWithPasswordOpts
expected AuthenticationResponse
expected UserResponse
err bool
}{{
scenario: "Request without API Key returns an error",
Expand All @@ -714,7 +715,7 @@ func TestAuthenticateUserWithPassword(t *testing.T) {
Email: "[email protected]",
Password: "test_123",
},
expected: AuthenticationResponse{
expected: UserResponse{
User: User{
ID: "testUserID",
FirstName: "John",
Expand Down Expand Up @@ -749,7 +750,7 @@ func TestAuthenticateUserWithCode(t *testing.T) {
scenario string
client *Client
options AuthenticateWithCodeOpts
expected AuthenticationResponse
expected UserResponse
err bool
}{{
scenario: "Request without API Key returns an error",
Expand All @@ -763,7 +764,7 @@ func TestAuthenticateUserWithCode(t *testing.T) {
ClientID: "project_123",
Code: "test_123",
},
expected: AuthenticationResponse{
expected: UserResponse{
User: User{
ID: "testUserID",
FirstName: "John",
Expand Down Expand Up @@ -798,7 +799,7 @@ func TestAuthenticateUserWithMagicAuth(t *testing.T) {
scenario string
client *Client
options AuthenticateWithMagicAuthOpts
expected AuthenticationResponse
expected UserResponse
err bool
}{{
scenario: "Request without API Key returns an error",
Expand All @@ -813,7 +814,7 @@ func TestAuthenticateUserWithMagicAuth(t *testing.T) {
Code: "test_123",
User: "user_123",
},
expected: AuthenticationResponse{
expected: UserResponse{
User: User{
ID: "testUserID",
FirstName: "John",
Expand Down Expand Up @@ -851,7 +852,7 @@ func authenticationResponseTestHandler(w http.ResponseWriter, r *http.Request) {
return
}
if secret, exists := payload["client_secret"].(string); exists && secret != "" {
response := AuthenticationResponse{
response := UserResponse{
User: User{
ID: "testUserID",
FirstName: "John",
Expand Down Expand Up @@ -1282,3 +1283,98 @@ func sendMagicAuthCodeTestHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(body)
}

func TestEnrollAuthFactor(t *testing.T) {
tests := []struct {
scenario string
client *Client
options EnrollAuthFactorOpts
expected AuthenticationResponse
err bool
}{
{
scenario: "Request without API Key returns an error",
client: NewClient(""),
err: true,
},
{
scenario: "Request returns User",
client: NewClient("test"),
options: EnrollAuthFactorOpts{
User: "user_01E3JC5F5Z1YJNPGVYWV9SX6GH",
Type: mfa.TOTP,
},
expected: AuthenticationResponse{
Factor: mfa.Factor{
ID: "auth_factor_test123",
CreatedAt: "2022-02-17T22:39:26.616Z",
UpdatedAt: "2022-02-17T22:39:26.616Z",
Type: "generic_otp",
},
Challenge: mfa.Challenge{
ID: "auth_challenge_test123",
CreatedAt: "2022-02-17T22:39:26.616Z",
UpdatedAt: "2022-02-17T22:39:26.616Z",
FactorID: "auth_factor_test123",
ExpiresAt: "2022-02-17T22:39:26.616Z",
},
},
},
}

for _, test := range tests {
t.Run(test.scenario, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(enrollAuthFactorTestHandler))
defer server.Close()

client := test.client
client.Endpoint = server.URL
client.HTTPClient = server.Client()

user, err := client.EnrollAuthFactor(context.Background(), test.options)
if test.err {
require.Error(t, err)
return
}
require.NoError(t, err)
require.Equal(t, test.expected, user)
})
}
}

func enrollAuthFactorTestHandler(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth != "Bearer test" {
http.Error(w, "bad auth", http.StatusUnauthorized)
return
}

var body []byte
var err error

if r.URL.Path == "/users/user_01E3JC5F5Z1YJNPGVYWV9SX6GH/auth/factors" {
body, err = json.Marshal(AuthenticationResponse{
Factor: mfa.Factor{
ID: "auth_factor_test123",
CreatedAt: "2022-02-17T22:39:26.616Z",
UpdatedAt: "2022-02-17T22:39:26.616Z",
Type: "generic_otp",
},
Challenge: mfa.Challenge{
ID: "auth_challenge_test123",
CreatedAt: "2022-02-17T22:39:26.616Z",
UpdatedAt: "2022-02-17T22:39:26.616Z",
FactorID: "auth_factor_test123",
ExpiresAt: "2022-02-17T22:39:26.616Z",
},
})
}

if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}

w.WriteHeader(http.StatusOK)
w.Write(body)
}
Loading