Skip to content

Commit

Permalink
feat: add totp UI & recovery code (#429)
Browse files Browse the repository at this point in the history
  • Loading branch information
lakhansamani authored Dec 3, 2023
1 parent d7da81d commit cac67b7
Show file tree
Hide file tree
Showing 11 changed files with 87 additions and 62 deletions.
22 changes: 11 additions & 11 deletions app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"author": "Lakhan Samani",
"license": "ISC",
"dependencies": {
"@authorizerdev/authorizer-react": "^1.1.13",
"@authorizerdev/authorizer-react": "^1.1.15",
"@types/react": "^17.0.15",
"@types/react-dom": "^17.0.9",
"esbuild": "^0.12.17",
Expand Down
2 changes: 1 addition & 1 deletion app/src/pages/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export default function Login({ urlProps }: { urlProps: Record<string, any> }) {
{view === VIEW_TYPES.LOGIN && (
<Fragment>
<h1 style={{ textAlign: 'center' }}>Login</h1>
<br />
<AuthorizerSocialLogin urlProps={urlProps} />
<br />
{config.is_basic_authentication_enabled &&
!config.is_magic_link_login_enabled && (
<AuthorizerBasicAuthLogin urlProps={urlProps} />
Expand Down
24 changes: 12 additions & 12 deletions app/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@
# yarn lockfile v1


"@authorizerdev/authorizer-js@^1.2.6":
version "1.2.6"
resolved "https://registry.npmjs.org/@authorizerdev/authorizer-js/-/authorizer-js-1.2.6.tgz"
integrity sha512-9+9phHUMF+AeDM0y+XQvIRDoerOXnQ1vfTfYN6KxWN1apdrkAd9nzS1zUsA2uJSnX3fFZOErn83GjbYYCYF1BA==
"@authorizerdev/authorizer-js@^1.2.17":
version "1.2.17"
resolved "https://registry.npmjs.org/@authorizerdev/authorizer-js/-/authorizer-js-1.2.17.tgz"
integrity sha512-aF/lu9wZR7TBRaRMAes/hy1q8cZzz5Zo60QLU9Iu09sqnhliHJCp5wSkjsVH+V4ER9i7bmJ2HNABTmOdluxj3A==
dependencies:
cross-fetch "^3.1.5"

"@authorizerdev/authorizer-react@^1.1.13":
version "1.1.13"
resolved "https://registry.npmjs.org/@authorizerdev/authorizer-react/-/authorizer-react-1.1.13.tgz"
integrity sha512-LmpzyfR0+nEn+bjUrb/QU9b3kiVoYzMBIvcQ1nV4TNvrvVSqbLPKk+GmoIPkiBEtfy/QSM6XFLkiGNGD9BRP+g==
"@authorizerdev/authorizer-react@^1.1.15":
version "1.1.15"
resolved "https://registry.npmjs.org/@authorizerdev/authorizer-react/-/authorizer-react-1.1.15.tgz"
integrity sha512-Y71qC4GUAHL0QCNj5mVv0Jwv1cIg4Y0yXRiOeYV21C1NMleyLRXgw4qzJ/Vk8rmXsxqSHmr8SGrwOLcSKA2oMA==
dependencies:
"@authorizerdev/authorizer-js" "^1.2.6"
"@authorizerdev/authorizer-js" "^1.2.17"

"@babel/code-frame@^7.22.13":
version "7.22.13"
Expand Down Expand Up @@ -420,9 +420,9 @@ [email protected]:
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==

node-fetch@^2.6.12:
version "2.6.12"
resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.12.tgz"
integrity sha512-C/fGU2E8ToujUivIO0H+tpQ6HWo4eEmchoPIoXtxCrVghxdKq+QOHqEZW7tuP3KlV3bC8FRMO5nMCC7Zm1VP6g==
version "2.7.0"
resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz"
integrity sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==
dependencies:
whatwg-url "^5.0.0"

Expand Down
6 changes: 3 additions & 3 deletions server/authenticators/providers/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type Provider interface {
// Generate totp: to generate totp, store secret into db and returns base64 of QR code image
Generate(ctx context.Context, id string) (*AuthenticatorConfig, error)
// Validate totp: user passcode with secret stored in our db
Validate(ctx context.Context, passcode string, id string) (bool, error)
// RecoveryCode totp: gives a recovery code for first time user
RecoveryCode(ctx context.Context, id string) (*string, error)
Validate(ctx context.Context, passcode string, userID string) (bool, error)
// ValidateRecoveryCode totp: allows user to validate using recovery code incase if they lost their device
ValidateRecoveryCode(ctx context.Context, recoveryCode, userID string) (bool, error)
}
53 changes: 34 additions & 19 deletions server/authenticators/providers/totp/totp.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"image/png"
"time"

Expand Down Expand Up @@ -113,24 +114,38 @@ func (p *provider) Validate(ctx context.Context, passcode string, userID string)
return status, nil
}

// RecoveryCode generates a recovery code for a user's TOTP authentication, if not already verified.
func (p *provider) RecoveryCode(ctx context.Context, id string) (*string, error) {
// ValidateRecoveryCode validates a Time-Based One-Time Password (TOTP) recovery code against the stored TOTP recovery code for a user.
func (p *provider) ValidateRecoveryCode(ctx context.Context, recoveryCode, userID string) (bool, error) {
// get totp details
// totpModel, err := db.Provider.GetAuthenticatorDetailsByUserId(ctx, id, constants.EnvKeyTOTPAuthenticator)
// if err != nil {
// return nil, fmt.Errorf("error while getting totp details from authenticators")
// }
// //TODO *totpModel.RecoveryCode == "null" used to just verify couchbase recoveryCode value to be nil
// // have to find another way round
// if totpModel.RecoveryCode == nil || *totpModel.RecoveryCode == "null" {
// recoveryCode := utils.GenerateTOTPRecoveryCode()
// totpModel.RecoveryCode = &recoveryCode

// _, err = db.Provider.UpdateAuthenticator(ctx, totpModel)
// if err != nil {
// return nil, fmt.Errorf("error while updaing authenticator table for totp")
// }
// return &recoveryCode, nil
// }
return nil, nil
totpModel, err := db.Provider.GetAuthenticatorDetailsByUserId(ctx, userID, constants.EnvKeyTOTPAuthenticator)
if err != nil {
return false, err
}
// convert recoveryCodes to map
recoveryCodesMap := map[string]bool{}
err = json.Unmarshal([]byte(refs.StringValue(totpModel.RecoveryCodes)), &recoveryCodesMap)
if err != nil {
return false, err
}
// check if recovery code is valid
if val, ok := recoveryCodesMap[recoveryCode]; !ok {
return false, fmt.Errorf("invalid recovery code")
} else if val {
return false, fmt.Errorf("recovery code already used")
}
// update recovery code map
recoveryCodesMap[recoveryCode] = true
// convert recoveryCodesMap to string
jsonData, err := json.Marshal(recoveryCodesMap)
if err != nil {
return false, err
}
recoveryCodesString := string(jsonData)
totpModel.RecoveryCodes = refs.NewStringRef(recoveryCodesString)
// update recovery code map in db
_, err = db.Provider.UpdateAuthenticator(ctx, totpModel)
if err != nil {
return false, err
}
return true, nil
}
10 changes: 5 additions & 5 deletions server/graph/generated/generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion server/graph/model/models_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion server/graph/schema.graphqls
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ input VerifyOTPRequest {
email: String
phone_number: String
otp: String!
totp: Boolean
is_totp: Boolean
# state is used for authorization code grant flow
# it is used to get code for an on-going auth process during login
# and use that code for setting `c_hash` in id_token
Expand Down
14 changes: 12 additions & 2 deletions server/resolvers/verify_otp.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,25 @@ func VerifyOtpResolver(ctx context.Context, params model.VerifyOTPRequest) (*mod
return res, err
}
// Verify OTP based on TOPT or OTP
if refs.BoolValue(params.Totp) {
if refs.BoolValue(params.IsTotp) {
status, err := authenticators.Provider.Validate(ctx, params.Otp, user.ID)
if err != nil {
log.Debug("Failed to validate totp: ", err)
return nil, fmt.Errorf("error while validating passcode")
}
if !status {
log.Debug("Failed to verify otp request: Incorrect value")
return res, fmt.Errorf(`invalid otp`)
log.Info("Checking if otp is recovery code")
// Check if otp is recovery code
isValidRecoveryCode, err := authenticators.Provider.ValidateRecoveryCode(ctx, params.Otp, user.ID)
if err != nil {
log.Debug("Failed to validate recovery code: ", err)
return nil, fmt.Errorf("error while validating recovery code")
}
if !isValidRecoveryCode {
log.Debug("Failed to verify otp request: Incorrect value")
return res, fmt.Errorf(`invalid otp`)
}
}
} else {
var otp *models.OTP
Expand Down
12 changes: 6 additions & 6 deletions server/test/totp_login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ func totpLoginTest(t *testing.T, s TestSetup) {
cookie = strings.TrimSuffix(cookie, ";")
req.Header.Set("Cookie", cookie)
valid, err := resolvers.VerifyOtpResolver(ctx, model.VerifyOTPRequest{
Email: &email,
Totp: refs.NewBoolRef(true),
Otp: code,
Email: &email,
IsTotp: refs.NewBoolRef(true),
Otp: code,
})
accessToken := valid.AccessToken
assert.NoError(t, err)
Expand Down Expand Up @@ -147,9 +147,9 @@ func totpLoginTest(t *testing.T, s TestSetup) {
cookie = strings.TrimSuffix(cookie, ";")
req.Header.Set("Cookie", cookie)
valid, err = resolvers.VerifyOtpResolver(ctx, model.VerifyOTPRequest{
Otp: code,
Email: &email,
Totp: refs.NewBoolRef(true),
Otp: code,
Email: &email,
IsTotp: refs.NewBoolRef(true),
})
assert.NoError(t, err)
assert.NotNil(t, *valid.AccessToken)
Expand Down

0 comments on commit cac67b7

Please sign in to comment.