Skip to content
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

New auth endpoint #68

Merged
merged 9 commits into from
Mar 21, 2024
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
Binary file modified examples/bun/bun.lockb
Binary file not shown.
13 changes: 8 additions & 5 deletions examples/bun/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { core } from '@commercelayer/js-auth'
import { authenticate, AuthenticateOptions, GrantType } from '@commercelayer/js-auth'

const auth = await core.authentication('client_credentials', {
const grantType: GrantType = 'client_credentials'

const options: AuthenticateOptions<'client_credentials'> = {
clientId: 'BISG8bb3GWpC8_D7Nt1SuWWdieS5bJq831A50LgB_Ig',
slug: 'demo-store',
scope: 'market:11279'
})
scope: 'market:id:KoaJYhMVVj'
}

const auth = await authenticate(grantType, options)

console.log(auth)
5 changes: 4 additions & 1 deletion examples/bun/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
"scripts": {
"start": "bun run index.ts"
},
"workspaces": [
"../../packages/*"
],
"dependencies": {
"@commercelayer/js-auth": "^5.2.0"
"@commercelayer/js-auth": "workspace:^5.0.0"
}
}
9 changes: 5 additions & 4 deletions examples/cjs/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const { core } = require('@commercelayer/js-auth')
// @ts-check

const { authenticate } = require('@commercelayer/js-auth')

async function run() {
const auth = await core.authentication('client_credentials', {
const auth = await authenticate('client_credentials', {
clientId: 'BISG8bb3GWpC8_D7Nt1SuWWdieS5bJq831A50LgB_Ig',
slug: 'demo-store',
scope: 'market:11279'
scope: 'market:id:KoaJYhMVVj'
})

console.log(auth)
Expand Down
7 changes: 3 additions & 4 deletions examples/cloudflare-workers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* Learn more at https://developers.cloudflare.com/workers/
*/

import { core } from '@commercelayer/js-auth'
import { authenticate } from '@commercelayer/js-auth'

export interface Env {
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
Expand All @@ -29,10 +29,9 @@ export interface Env {

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const auth = await core.authentication('client_credentials', {
const auth = await authenticate('client_credentials', {
clientId: 'BISG8bb3GWpC8_D7Nt1SuWWdieS5bJq831A50LgB_Ig',
slug: 'demo-store',
scope: 'market:11279'
scope: 'market:id:KoaJYhMVVj'
})

return new Response(`Hello World!\n\nThis is your token: ${auth.accessToken}`);
Expand Down
7 changes: 3 additions & 4 deletions examples/deno/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { core } from 'https://esm.sh/@commercelayer/js-auth'
import { authenticate } from 'https://esm.sh/@commercelayer/js-auth'

const auth = await core.authentication('client_credentials', {
const auth = await authenticate('client_credentials', {
clientId: 'BISG8bb3GWpC8_D7Nt1SuWWdieS5bJq831A50LgB_Ig',
slug: 'demo-store',
scope: 'market:11279'
scope: 'market:id:KoaJYhMVVj'
})

console.log(auth)
9 changes: 5 additions & 4 deletions examples/esm/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { core } from '@commercelayer/js-auth'
// @ts-check

import { authenticate } from '@commercelayer/js-auth'

async function run() {
const auth = await core.authentication('client_credentials', {
const auth = await authenticate('client_credentials', {
clientId: 'BISG8bb3GWpC8_D7Nt1SuWWdieS5bJq831A50LgB_Ig',
slug: 'demo-store',
scope: 'market:11279'
scope: 'market:id:KoaJYhMVVj'
})

console.log(auth)
Expand Down
1 change: 0 additions & 1 deletion packages/js-auth/.env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Unit tests
VITE_TEST_CLIENT_ID=
VITE_TEST_SLUG=
VITE_TEST_DOMAIN=
VITE_TEST_SCOPE=
VITE_TEST_USERNAME=
Expand Down
41 changes: 16 additions & 25 deletions packages/js-auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,10 @@ Sales channel applications use the [client credentials](https://docs.commercelay
2. Use this code to get your access token:

```ts
import { core } from '@commercelayer/js-auth'
import { authenticate } from '@commercelayer/js-auth'

const token = await core.authentication('client_credentials', {
clientId: 'your-client-id',
slug: 'your-organization-slug',
scope: 'market:{id}'
const token = await authenticate('client_credentials', {
clientId: 'your-client-id'
})

console.log('My access token: ', token.accessToken)
Expand All @@ -101,12 +99,10 @@ Sales channel applications can use the [password](https://docs.commercelayer.io/
2. Use this code (changing user name and password with the customer credentials) to get the access token:

```ts
import { core } from '@commercelayer/js-auth'
import { authenticate } from '@commercelayer/js-auth'

const token = await core.authentication('password', {
const token = await authenticate('password', {
clientId: 'your-client-id',
slug: 'your-organization-slug',
scope: 'market:{id}',
username: 'john@example.com',
password: 'secret'
})
Expand All @@ -119,12 +115,10 @@ console.log('My refresh token: ', token.refreshToken)
Sales channel applications can use the [refresh token](https://docs.commercelayer.io/developers/authentication/refresh-token) grant type to refresh a customer access token with a "remember me" option:

```ts
import { core } from '@commercelayer/js-auth'
import { authenticate } from '@commercelayer/js-auth'

const newToken = await core.authentication('refresh_token', {
const newToken = await authenticate('refresh_token', {
clientId: 'your-client-id',
slug: 'your-organization-slug',
scope: 'market:{id}',
refreshToken: 'your-refresh-token'
})
```
Expand All @@ -140,12 +134,11 @@ Integration applications use the [client credentials](https://docs.commercelayer
2. Use this codes to get the access token:

```ts
import { core } from '@commercelayer/js-auth'
import { authenticate } from '@commercelayer/js-auth'

const token = await core.authentication('client_credentials', {
const token = await authenticate('client_credentials', {
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
slug: 'your-organization-slug',
})

console.log('My access token: ', token.accessToken)
Expand All @@ -168,15 +161,15 @@ In this case, first, you need to get an authorization code, then you can exchang

```bash
curl -g -X GET \
'https://dashboard.commercelayer.io/oauth/authorize?client_id=your-client-id&redirect_uri=https://yourdomain.com/redirect&scope=market:1234&response_type=code' \
'https://dashboard.commercelayer.io/oauth/authorize?client_id=your-client-id&redirect_uri=https://yourdomain.com/redirect&scope=market:id:1234&response_type=code' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json'
```

or copy and paste this URL in your browser:

```bash
https://dashboard.commercelayer.io/oauth/authorize?client_id=your-client-id&redirect_uri=https://yourdomain.com/redirect&scope=market:1234&response_type=code
https://dashboard.commercelayer.io/oauth/authorize?client_id=your-client-id&redirect_uri=https://yourdomain.com/redirect&scope=market:id:1234&response_type=code
```

3. Once you've authorized the application, you will be redirected to the callback URL:
Expand All @@ -186,14 +179,12 @@ In this case, first, you need to get an authorization code, then you can exchang
Use this code to get the access token:

```ts
import { core } from '@commercelayer/js-auth'
import { authenticate } from '@commercelayer/js-auth'

const token = await core.authentication('authorization_code', {
const token = await authenticate('authorization_code', {
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
callbackUrl: '<https://yourdomain.com/callback>',
slug: 'your-organization-slug',
scope: 'market:{id}',
code: 'your-auth-code'
})

Expand All @@ -203,7 +194,7 @@ In this case, first, you need to get an authorization code, then you can exchang

### Provisioning

Provisioning applications use a specific authentication function which implicitly uses the [client credentials](https://docs.commercelayer.io/developers/authentication/client-credentials) grant type to get an access token.
Provisioning applications use the [client credentials](https://docs.commercelayer.io/developers/authentication/client-credentials) grant type to get an access token.

#### Steps

Expand All @@ -212,9 +203,9 @@ Provisioning applications use a specific authentication function which implicitl
2. Use this codes to get the access token:

```ts
import { provisioning } from '@commercelayer/js-auth'
import { authenticate } from '@commercelayer/js-auth'

const token = await provisioning.authentication({
const token = await authenticate('client_credentials', {
clientId: 'your-client-id',
clientSecret: 'your-client-secret'
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { core } from '../src/index.js'
import { authenticate } from '../src/index.js'

const slug = process.env.VITE_TEST_SLUG
const clientId = process.env.VITE_TEST_CLIENT_ID
const integrationClientId = process.env.VITE_TEST_INTEGRATION_CLIENT_ID
const clientSecret = process.env.VITE_TEST_CLIENT_SECRET
Expand All @@ -11,8 +10,7 @@ const password = process.env.VITE_TEST_PASSWORD

describe('Authentication', () => {
it('Get a sales channel token', async () => {
const res = await core.authentication('client_credentials', {
slug,
const res = await authenticate('client_credentials', {
clientId,
domain
})
Expand All @@ -26,23 +24,28 @@ describe('Authentication', () => {
expect(res.expires.getTime()).toBeGreaterThan(Date.now())
})
it('Get an error requesting a sales channel token', async () => {
const res = await core.authentication('client_credentials', {
slug,
const res = await authenticate('client_credentials', {
clientId: 'wrong-client-id',
domain,
scope
})
expect(res).toHaveProperty('error')
expect(res).toHaveProperty('errorDescription')
expect(res).toHaveProperty('errors')
expect(res.errors).toBeInstanceOf(Array)
expect(res.errors?.[0]).toMatchObject({
code: 'UNAUTHORIZED',
detail:
'Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.',
status: 401,
title: 'invalid_client'
})
expect(res).not.toHaveProperty('accessToken')
expect(res).not.toHaveProperty('tokenType')
expect(res).not.toHaveProperty('expiresIn')
expect(res).not.toHaveProperty('scope')
expect(res).not.toHaveProperty('createdAt')
})
it('Get a integration token', async () => {
const res = await core.authentication('client_credentials', {
slug,
const res = await authenticate('client_credentials', {
clientId: integrationClientId,
clientSecret,
domain
Expand All @@ -54,8 +57,7 @@ describe('Authentication', () => {
expect(res).toHaveProperty('createdAt')
})
it('Get a customer token', async () => {
const res = await core.authentication('password', {
slug,
const res = await authenticate('password', {
clientId,
domain,
username,
Expand All @@ -72,8 +74,7 @@ describe('Authentication', () => {
expect(res).toHaveProperty('refreshToken')
})
it('Refresh a customer token', async () => {
const res = await core.authentication('password', {
slug,
const res = await authenticate('password', {
clientId,
domain,
username,
Expand All @@ -88,11 +89,11 @@ describe('Authentication', () => {
expect(res).toHaveProperty('ownerId')
expect(res).toHaveProperty('ownerType')
expect(res).toHaveProperty('refreshToken')
const res2 = await core.authentication('refresh_token', {
slug,
const res2 = await authenticate('refresh_token', {
clientId,
domain,
refreshToken: res.refreshToken
refreshToken: res.refreshToken,
scope
})
expect(res2).toHaveProperty('accessToken')
expect(res2).toHaveProperty('tokenType')
Expand All @@ -104,8 +105,7 @@ describe('Authentication', () => {
expect(res2).toHaveProperty('refreshToken')
})
it('Set a custom header', async () => {
const res = await core.authentication('password', {
slug,
const res = await authenticate('password', {
clientId,
domain,
username,
Expand Down
4 changes: 2 additions & 2 deletions packages/js-auth/specs/provisioning.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { provisioning } from '../src/index.js'
import { authenticate } from '../src/index.js'

const clientId = process.env.VITE_TEST_PROVISIONING_CLIENT_ID
const clientSecret = process.env.VITE_TEST_PROVISIONING_CLIENT_SECRET
const domain = process.env.VITE_TEST_PROVISIONING_DOMAIN

describe('Provisioning', () => {
it('Get a provisioning token', async () => {
const res = await provisioning.authentication({
const res = await authenticate('client_credentials', {
domain,
clientId,
clientSecret
Expand Down
1 change: 0 additions & 1 deletion packages/js-auth/specs/types/global.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
declare namespace NodeJS {
interface ProcessEnv {
NODE_ENV: 'development' | 'production' | 'test'
VITE_TEST_SLUG: string
VITE_TEST_CLIENT_ID: string
VITE_TEST_DOMAIN: string
VITE_TEST_SCOPE: string
Expand Down
43 changes: 43 additions & 0 deletions packages/js-auth/src/authenticate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type {
GrantType,
AuthenticateOptions,
AuthenticateReturn
} from '#types/index.js'

import { camelCaseToSnakeCase } from '#utils/camelCaseToSnakeCase.js'
import { mapKeys } from '#utils/mapKeys.js'
import { snakeCaseToCamelCase } from '#utils/snakeCaseToCamelCase.js'

interface TokenJson {
expires: Date
expires_in: number
[key: string]: string | number | Date
}

export async function authenticate<G extends GrantType>(
grantType: G,
{ domain = 'commercelayer.io', headers, ...options }: AuthenticateOptions<G>
): Promise<AuthenticateReturn<G>> {
const body = mapKeys(
{
grant_type: grantType,
...options
},
camelCaseToSnakeCase
)

const response = await fetch(`https://auth.${domain}/oauth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
...headers
},
body: JSON.stringify(body)
})

const json: TokenJson = await response.json()
json.expires = new Date(Date.now() + json.expires_in * 1000)

return mapKeys(json, snakeCaseToCamelCase) as unknown as AuthenticateReturn<G>
}
Loading