Skip to content

Commit

Permalink
Notp (#429)
Browse files Browse the repository at this point in the history
  • Loading branch information
asafshen authored Apr 18, 2024
1 parent 6360633 commit b0b6bd2
Show file tree
Hide file tree
Showing 11 changed files with 626 additions and 12 deletions.
72 changes: 64 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,15 @@ These sections show how to use the SDK to perform various authentication/authori
2. [Magic Link](#magic-link)
3. [Enchanted Link](#enchanted-link)
4. [OAuth](#oauth)
5. [SSO (SAML / OIDC)](#sso-saml--oidc)
6. [TOTP Authentication](#totp-authentication)
7. [Passwords](#passwords)
8. [Session Validation](#session-validation)
9. [Roles & Permission Validation](#roles--permission-validation)
10. [Tenant selection](#tenant-selection)
11. [Logging Out](#logging-out)
12. [History](#history)
5. [NOTP (WhatsApp)] (#notp-whatsapp)
6. [SSO (SAML / OIDC)](#sso-saml--oidc)
7. [TOTP Authentication](#totp-authentication)
8. [Passwords](#passwords)
9. [Session Validation](#session-validation)
10. [Roles & Permission Validation](#roles--permission-validation)
11. [Tenant selection](#tenant-selection)
12. [Logging Out](#logging-out)
13. [History](#history)

## Management Functions

Expand Down Expand Up @@ -259,6 +260,61 @@ if err != nil {

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)

### NOTP (WhatsApp)

Using the NOTP (WhatsApp) APIs enables users to log in using their WhatsApp account, according to the following process:
a. The user will be redirected to WhatsApp (with a QR Code or link) with a pre-filled message containing a 16-character alphanumeric code.
b. The user will send the message to the WhatsApp Application associated with the Descope project.
c. Descope will receive the message, validate the code, and send an approval message back to the user.
d. The user will be logged in after receiving the approval message.

Note: The NOTP (WhatsApp) authentication method should be configured in the Descope Console before using it

The user can either `sign up`, `sign in`, or `sign up or in`:

```go
loginID := "" // OR phone number
res, err := descopeClient.Auth.NOTP().SignUpOrIn(context.Background(), loginID, nil, nil)
if err != nil {
// handle error
}

// The URL to redirect the user to initiate a conversation in the WhatsApp Web Application with the pre-filled message containing the code
res.RedirectURL
// A QR code image that can be displayed to the user to scan using their mobile device camera app to start the WhatsApp conversation
res.Image
// Used to poll for a valid session
res.PendingRef
```

After sending the link, you must poll to receive a valid session using the `PendingRef` from the previous step. A valid session will be returned only after the user sends the message to the WhatsApp Application associated with the Project with the code

```go
// Poll for a certain number of tries / time frame
for i := retriesCount; i > 0; i-- {
authInfo, err := descopeClient.Auth.NOTP().GetSession(context.Background(), res.PendingRef, w)
if err == nil {
// The user successfully authenticated
// The optional `w http.ResponseWriter` adds the session and refresh cookies to the response automatically.
// Otherwise they're available via authInfo
break
}
if errors.Is(err, descope.ErrNOTPUnauthorized) && i > 1 {
// poll again after X seconds
time.Sleep(time.Second * time.Duration(retryInterval))
continue
}
if err != nil {
// handle error
break
}
}
```

The verification process is conducted using the WhatsApp application by the user sending a message with the token included in the link. After sending the message, the user will receive an approval message back, and the session polling will then receive a valid response

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)

### SSO (SAML / OIDC)

Users can authenticate to a specific tenant using SAML or OIDC. Configure your SSO (SAML / OIDC) settings on the [Descope console](https://app.descope.com/settings/authentication/sso). To start a flow call:
Expand Down
24 changes: 24 additions & 0 deletions descope/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ var (
signUpTOTP: "auth/totp/signup",
updateTOTP: "auth/totp/update",
verifyTOTPCode: "auth/totp/verify",
signUpNOTP: "auth/notp/whatsapp/signup",
signInNOTP: "auth/notp/whatsapp/signin",
signUpOrInNOTP: "auth/notp/whatsapp/signup-in",
getNOTPSession: "auth/notp/pending-session",
verifyCode: "auth/otp/verify",
signUpPassword: "auth/password/signup",
signInPassword: "auth/password/signin",
Expand Down Expand Up @@ -222,6 +226,10 @@ type authEndpoints struct {
signUpTOTP string
updateTOTP string
verifyTOTPCode string
signUpNOTP string
signInNOTP string
signUpOrInNOTP string
getNOTPSession string
verifyCode string
signUpPassword string
signInPassword string
Expand Down Expand Up @@ -411,6 +419,22 @@ func (e *endpoints) UpdateTOTP() string {
return path.Join(e.version, e.auth.updateTOTP)
}

func (e *endpoints) SignUpNOTP() string {
return path.Join(e.version, e.auth.signUpNOTP)
}

func (e *endpoints) SignInNOTP() string {
return path.Join(e.version, e.auth.signInNOTP)
}

func (e *endpoints) SignUpOrInNOTP() string {
return path.Join(e.version, e.auth.signUpOrInNOTP)
}

func (e *endpoints) GetNOTPSession() string {
return path.Join(e.version, e.auth.getNOTPSession)
}

func (e *endpoints) VerifyCode() string {
return path.Join(e.version, e.auth.verifyCode)
}
Expand Down
1 change: 1 addition & 0 deletions descope/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var (
ErrEnchantedLinkUnauthorized = newServerError("E062503")
ErrPasswordExpired = newServerError("E062909")
ErrTokenExpiredByLoggedOut = newServerError("E064001")
ErrNOTPUnauthorized = newServerError("E066103")

// server management
ErrManagementUserNotFound = newServerError("E112102")
Expand Down
31 changes: 31 additions & 0 deletions descope/internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ type authenticationService struct {
magicLink sdk.MagicLink
enchantedLink sdk.EnchantedLink
totp sdk.TOTP
notp sdk.NOTP
password sdk.Password
webAuthn sdk.WebAuthn
oauth sdk.OAuth
Expand All @@ -59,6 +60,7 @@ func NewAuth(conf AuthParams, c *api.Client) (*authenticationService, error) {
authenticationService.sso = &sso{authenticationsBase: base}
authenticationService.webAuthn = &webAuthn{authenticationsBase: base}
authenticationService.totp = &totp{authenticationsBase: base}
authenticationService.notp = &notp{authenticationsBase: base}
authenticationService.password = &password{authenticationsBase: base}
return authenticationService, nil
}
Expand All @@ -79,6 +81,10 @@ func (auth *authenticationService) TOTP() sdk.TOTP {
return auth.totp
}

func (auth *authenticationService) NOTP() sdk.NOTP {
return auth.notp
}

func (auth *authenticationService) Password() sdk.Password {
return auth.password
}
Expand Down Expand Up @@ -830,6 +836,15 @@ func getPendingRefFromResponse(httpResponse *api.HTTPResponse) (*descope.Enchant
return response, nil
}

func getNOTPResponse(httpResponse *api.HTTPResponse) (*descope.NOTPResponse, error) {
var response *descope.NOTPResponse
if err := utils.Unmarshal([]byte(httpResponse.BodyStr), &response); err != nil {
logger.LogError("Failed to load NOTP response from http response", err)
return response, descope.ErrUnexpectedResponse.WithMessage("Failed to load NOTP response")
}
return response, nil
}

func composeURLMethod(base string, method descope.DeliveryMethod) string {
return path.Join(base, string(method))
}
Expand All @@ -854,6 +869,22 @@ func composeUpdateTOTPURL() string {
return api.Routes.UpdateTOTP()
}

func composeNOTPSignInURL() string {
return api.Routes.SignInNOTP()
}

func composeNOTPSignUpURL() string {
return api.Routes.SignUpNOTP()
}

func composeNOTPSignUpOrInURL() string {
return api.Routes.SignUpOrInNOTP()
}

func composeNOTPGetSession() string {
return api.Routes.GetNOTPSession()
}

func composeVerifyCodeURL(method descope.DeliveryMethod) string {
return composeURLMethod(api.Routes.VerifyCode(), method)
}
Expand Down
2 changes: 1 addition & 1 deletion descope/internal/auth/enchantedlink.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (auth *enchantedLink) SignUpOrIn(ctx context.Context, loginID, URI string,

func (auth *enchantedLink) GetSession(ctx context.Context, pendingRef string, w http.ResponseWriter) (*descope.AuthenticationInfo, error) {
var err error
httpResponse, err := auth.client.DoPostRequest(ctx, composeGetSession(), newAuthenticationGetMagicLinkSessionBody(pendingRef), nil, "")
httpResponse, err := auth.client.DoPostRequest(ctx, composeGetSession(), newAuthenticationGetSessionBody(pendingRef), nil, "")
if err != nil {
return nil, err
}
Expand Down
66 changes: 66 additions & 0 deletions descope/internal/auth/notp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package auth

import (
"context"
"net/http"

"github.com/descope/go-sdk/descope"
)

type notp struct {
authenticationsBase
}

func (auth *notp) SignIn(ctx context.Context, loginID string, r *http.Request, loginOptions *descope.LoginOptions) (*descope.NOTPResponse, error) {
var pswd string
var err error
if loginOptions.IsJWTRequired() {
pswd, err = getValidRefreshToken(r)
if err != nil {
return nil, descope.ErrInvalidStepUpJWT
}
}
httpResponse, err := auth.client.DoPostRequest(ctx, composeNOTPSignInURL(), newNOTPAuthenticationRequestBody(loginID, loginOptions), nil, pswd)
if err != nil {
return nil, err
}
return getNOTPResponse(httpResponse)
}

func (auth *notp) SignUp(ctx context.Context, loginID string, user *descope.User, signUpOptions *descope.SignUpOptions) (*descope.NOTPResponse, error) {
if user == nil {
user = &descope.User{}
}
if len(user.Phone) == 0 {
user.Phone = loginID
}

httpResponse, err := auth.client.DoPostRequest(ctx, composeNOTPSignUpURL(), newNOTPAuthenticationSignUpRequestBody(loginID, user, signUpOptions), nil, "")
if err != nil {
return nil, err
}
return getNOTPResponse(httpResponse)
}

func (auth *notp) SignUpOrIn(ctx context.Context, loginID string, signUpOptions *descope.SignUpOptions) (*descope.NOTPResponse, error) {
if signUpOptions == nil {
signUpOptions = &descope.SignUpOptions{}
}
httpResponse, err := auth.client.DoPostRequest(ctx, composeNOTPSignUpOrInURL(), newNOTPAuthenticationRequestBody(loginID, &descope.LoginOptions{
CustomClaims: signUpOptions.CustomClaims,
TemplateOptions: signUpOptions.TemplateOptions,
}), nil, "")
if err != nil {
return nil, err
}
return getNOTPResponse(httpResponse)
}

func (auth *notp) GetSession(ctx context.Context, pendingRef string, w http.ResponseWriter) (*descope.AuthenticationInfo, error) {
var err error
httpResponse, err := auth.client.DoPostRequest(ctx, composeNOTPGetSession(), newAuthenticationGetSessionBody(pendingRef), nil, "")
if err != nil {
return nil, err
}
return auth.generateAuthenticationInfo(httpResponse, w)
}
Loading

0 comments on commit b0b6bd2

Please sign in to comment.