How to use @commercetools/sdk-middleware-auth - 10 common examples

To help you get started, we’ve selected a few @commercetools/sdk-middleware-auth examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github commercetools / nodejs / integration-tests / sdk / auth-middleware.it.js View on Github external
const anonymousId = `${Date.now()}-bar`
      const userConfig = {
        ...apiConfig,
        ...{ scopes: [`manage_project:${projectKey}`] },
        ...{
          credentials: {
            clientId: apiConfig.credentials.clientId,
            clientSecret: apiConfig.credentials.clientSecret,
            anonymousId,
          },
        },
        fetch,
      }
      const client = createClient({
        middlewares: [
          createAuthMiddlewareForAnonymousSessionFlow(userConfig),
          httpMiddleware,
        ],
      })
      const cartMock = {
        currency: 'EUR',
      }
      return client
        .execute({
          // creates a cart that is tied to the logged in anonymous token
          uri: `/${projectKey}/me/carts`,
          method: 'POST',
          body: cartMock,
        })
        .then(({ body: cart }) => {
          expect(cart).toHaveProperty('anonymousId', anonymousId)
          return client.execute({
github commercetools / nodejs / integration-tests / sdk / auth-middleware.it.js View on Github external
.then(({ body: cart }) => {
          expect(cart).toHaveProperty('anonymousId', anonymousId)

          // fetch another token with the refresh token flow
          const userConfig = {
            ...apiConfig,
            refreshToken: tokenObject.refresh_token,
            fetch,
          }
          const client = createClient({
            middlewares: [
              createAuthMiddlewareForRefreshTokenFlow(userConfig),
              httpMiddleware,
            ],
          })
          return client.execute({
            // fetch all carts tied to the anonymous token, if cart is present,
            // then the cart belongs to the same anonymousId
            uri: `/${projectKey}/me/carts`,
            method: 'GET',
          })
        })
        .then(
github commercetools / nodejs / integration-tests / ts-sdk / ts-sdk.it.js View on Github external
it('create an anonymous session and a cart tied to the session', () => {
      const authConfig = {
        ...apiConfig,
        ...{ scopes: [`manage_project:${projectKey}`] },
        ...{
          credentials: {
            clientId: apiConfig.credentials.clientId,
            clientSecret: apiConfig.credentials.clientSecret,
          },
        },
        fetch,
      }
      const client = createClient({
        middlewares: [
          createAuthMiddlewareForClientCredentialsFlow(authConfig),
          httpMiddleware,
        ],
      })

      const apiRoot = createApiBuilderFromCtpClient(client)

      return apiRoot
        .withProjectKey({
          projectKey,
        })
        .get()
        .execute()
        .then(res => {
          expect(res.body.key).toEqual(projectKey)
        })
    }, 7000)
github commercetools / nodejs / integration-tests / sdk / channels.it.js View on Github external
.then(credentials => {
        apiConfig = {
          host: 'https://auth.sphere.io',
          apiUrl: 'https://api.sphere.io',
          projectKey,
          credentials: {
            clientId: credentials.clientId,
            clientSecret: credentials.clientSecret,
          },
          fetch,
        }
        const authMiddleware = createAuthMiddlewareForClientCredentialsFlow(
          apiConfig
        )
        client = createClient({
          middlewares: [
            authMiddleware,
            queueMiddleware,
            userAgentMiddleware,
            httpMiddleware,
          ],
        })
      })
      .then(() => clearData(apiConfig, 'channels'))
github commercetools / nodejs / integration-tests / cli / helpers / utils.js View on Github external
export function createData(apiConfig, entityName, data, id) {
  const client = createClient({
    middlewares: [
      createAuthMiddlewareForClientCredentialsFlow({ ...apiConfig, fetch }),
      createHttpMiddleware({ host: apiConfig.apiUrl, fetch }),
    ],
  })
  const requestOption = { projectKey: apiConfig.projectKey }
  const service = createRequestBuilder(requestOption)[entityName]
  return Promise.all(
    data.map(_data => {
      if (id) service.byId(id)
      const request = {
        uri: service.build(),
        method: 'POST',
        body: _data,
      }
      return client.execute(request)
    })
  )
github commercetools / nodejs / integration-tests / sdk / auth.it.js View on Github external
function getApiClient(token) {
  return createClient({
    middlewares: [
      createAuthMiddlewareWithExistingToken(token),
      createHttpMiddleware({
        host: 'https://api.sphere.io',
        fetch,
      }),
    ],
  })
}
github commercetools / nodejs / integration-tests / sdk / auth-middleware.it.js View on Github external
...{ scopes: [`manage_project:${projectKey}`] },
        ...{
          credentials: {
            clientId: apiConfig.credentials.clientId,
            clientSecret: apiConfig.credentials.clientSecret,
            user: {
              username: userEmail,
              password: userPassword,
            },
          },
        },
        fetch,
      }
      const client = createClient({
        middlewares: [
          createAuthMiddlewareForPasswordFlow(userConfig),
          httpMiddleware,
        ],
      })
      return client
        .execute({
          uri: `/${projectKey}/me`,
          method: 'GET',
        })
        .then(response => {
          const user = response.body
          expect(user).toHaveProperty('email', userEmail)
        })
    })
  })
github commercetools / nodejs / packages / inventories-exporter / src / main.js View on Github external
format: CONS.standardOption.format,
      delimiter: CONS.standardOption.delimiter,
    },
    accessToken: string
  ) {
    this.logger = {
      error: () => {},
      info: () => {},
      warn: () => {},
      verbose: () => {},
      ...logger,
    }

    this.client = createClient({
      middlewares: [
        createAuthMiddlewareForClientCredentialsFlow({ ...apiConfig, fetch }),
        createUserAgentMiddleware({
          libraryName: name,
          libraryVersion: version,
        }),
        createHttpMiddleware({
          host: apiConfig.apiUrl,
          enableRetry: true,
          fetch,
        }),
      ],
    })
    this.exportConfig = exportConfig
    this.accessToken = accessToken
    this.reqBuilder = createRequestBuilder({
      projectKey: apiConfig.projectKey,
    })
github commercetools / nodejs / packages / discount-code-importer / src / main.js View on Github external
constructor(options: ConstructorOptions, logger: LoggerOptions) {
    if (!options.apiConfig)
      throw new DiscountCodeImportError(
        'The contructor must be passed an `apiConfig` object'
      )
    if (options.batchSize > 200)
      throw new DiscountCodeImportError(
        'The `batchSize` must not be more than 200'
      )
    this.apiConfig = options.apiConfig
    this.accessToken = options.accessToken
    this.batchSize = options.batchSize || 50
    this.continueOnProblems = options.continueOnProblems || false
    this.client = createClient({
      middlewares: [
        createAuthMiddlewareForClientCredentialsFlow({
          ...this.apiConfig,
          fetch,
        }),
        createUserAgentMiddleware({
          libraryName: pkg.name,
          libraryVersion: pkg.version,
        }),
        createHttpMiddleware({
          host: this.apiConfig.apiUrl,
          fetch,
        }),
      ],
    })

    this.syncDiscountCodes = createSyncDiscountCodes()
github commercetools / nodejs / packages / state-importer / src / main.js View on Github external
constructor(options: ConstructorOptions, logger: LoggerOptions) {
    if (!options.apiConfig)
      throw new StateImportError(
        'The constructor must be passed an `apiConfig` object'
      )

    this.apiConfig = options.apiConfig
    this.accessToken = options.accessToken
    this.continueOnProblems = options.continueOnProblems || false
    this.client = createClient({
      middlewares: [
        createAuthMiddlewareWithExistingToken(
          this.accessToken ? `Bearer ${this.accessToken}` : ''
        ),
        createAuthMiddlewareForClientCredentialsFlow({
          ...this.apiConfig,
          fetch,
        }),
        createUserAgentMiddleware({
          libraryName: pkg.name,
          libraryVersion: pkg.version,
        }),
        createHttpMiddleware({
          host: this.apiConfig.apiUrl,
          fetch,
        }),
      ],
    })

    this.syncStates = createSyncStates()