url#URLSearchParams TypeScript Examples

The following examples show how to use url#URLSearchParams. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From server with Apache License 2.0 7 votes vote down vote up
public async processItemAction(actionIdentifier: string, event: string, item: Item, newParent: string, newName: string, newValues: any, newChannels:any, isImport: boolean) {
        const mng = ModelsManager.getInstance().getModelManager(this.#context.getCurrentUser()!.tenantId)

        let action  = mng.getActions().find(act => act.identifier === actionIdentifier)
        if (!action) {
            throw new Error('Failed to find action by identifier: ' + actionIdentifier + ', tenant: ' + mng.getTenantId())
        }

        const context = this.#context
        return await processActions(mng, [action], { Op: Op,
            event: event,
            user: context.getCurrentUser()?.login,
            roles: context.getUser()?.getRoles(),
            utils: new ActionUtils(context),
            system: { AdmZip, fs, exec, awaitExec, fetch, URLSearchParams, mailer, http, https, http2 },
            isImport: isImport, 
            item: makeItemProxy(item), values: newValues, channels: newChannels, name: newName, parent: newParent,
            models: { 
                item: makeModelProxy(Item.applyScope(context), makeItemProxy),  
                itemRelation: makeModelProxy(ItemRelation.applyScope(context), makeItemRelationProxy),  
                lov: makeModelProxy(LOV.applyScope(context), makeLOVProxy),
                Item,
                ItemRelation
            } 
        })
    }
Example #2
Source File: format.ts    From format-imports-vscode with MIT License 6 votes vote down vote up
export async function formatDocument(document: TextDocument, from: TriggeredFrom) {
  const log = logger('vscode.formatDocument');
  if (!isSupported(document)) return undefined;
  const { uri: fileUri, languageId, eol } = document;
  const { fsPath: fileName } = fileUri;
  log.debug('Triggered from:', from);
  try {
    const config = resolveConfig(fileUri, languageId, eol, from === 'onCommand');
    if (from === 'onSave' && config.autoFormat !== 'onSave') {
      log.info('Auto format is', config.autoFormat);
      return undefined;
    }
    if (isFileExcludedByConfig(fileName, config)) {
      const { exclude, excludeGlob } = config;
      log.info('Excluded fileName:', fileName, 'via config:', { exclude, excludeGlob });
      return undefined;
    }
    const sourceText = document.getText();
    const newText = await formatSourceFromFile(sourceText, fileName, config);
    log.info('Finished', newText === undefined ? 'format with no-op' : 'format');
    return newText;
  } catch (e: unknown) {
    log.error('Found exception:', e);
    void window
      .showErrorMessage(
        'Something is wrong. Please open the logs and report an issue.',
        'Open logs & report an issue',
      )
      .then(v => {
        if (!v) return;
        vscChannel.show();
        const p = new URLSearchParams({
          title: `Exception: ${e instanceof Error ? e.message : e}`,
        });
        void commands.executeCommand('vscode.open', Uri.parse(ISSUE_URL + p.toString()));
      });
  }
  return undefined;
}
Example #3
Source File: index.ts    From swiss-maker with MIT License 6 votes vote down vote up
async function createTournament(tour: any): Promise<any> {
  const body = new URLSearchParams();
  for (const k of Object.keys(tour)) body.append(k, tour[k]);
  const response = await fetch(`${config.server}/api/swiss/new/${config.team}`, {
    method: 'POST',
    body,
    headers: { Authorization: `Bearer ${config.oauthToken}` },
  });
  if (response.status != 200) {
    const error = await response.text();
    console.error(response.status, error);
  }
  await new Promise(r => setTimeout(r, 1500));
}
Example #4
Source File: spotify.ts    From natemoo-re with MIT License 6 votes vote down vote up
export async function topTrack({ index, timeRange = 'short_term' }: { index: number, timeRange?: 'long_term'|'medium_term'|'short_term' }): Promise<SpotifyApi.TrackObjectFull> {
  const Authorization = await getAuthorizationToken();
  const params = new URLSearchParams();
  params.set('limit', '1');
  params.set('offset', `${index}`);
  params.set('time_range', `${timeRange}`);
  const response = await fetch(`${BASE_URL}${TOP_TRACKS_ENDPOINT}?${params}`, {
    headers: {
      Authorization
    },
  });
  const { status } = response;
  if (status === 204) {
    return null;
  } else if (status === 200) {
    const data = await response.json() as SpotifyApi.UsersTopTracksResponse;
    return data.items[0];
  }
}
Example #5
Source File: Mybot.ts    From js-sdk with MIT License 6 votes vote down vote up
/**
     * 해당 유저가 내 봇에 하트를 눌렀는지 체크합니다. (cache TTL: 10초)
     * @param id 
     * @returns 
     * @example
     * ```js
     * koreanbots.mybot.checkVote("12345678901234567")
     *     .then(voted => {
     *         if (voted) return message.channel.send(`${message.author} 님, 하트를 눌러주셔서 감사합니다!`)
     * 
     *         return message.channel.send(`${message.author} 님, 하트를 아직 누르지 않으셨습니다.`)
     *     })
     * ```
     */
    async checkVote(id: string): Promise<Vote> {
        const cache = this.votes.get(id)
        if (cache) return cache

        const query = new URLSearchParams()
        query.append("userID", id)

        const res = await this.koreanbots.api().bots(this.clientID).vote.get({
            [KoreanbotsInternal]: {
                query
            }
        })

        if (!res.data) throw new Error(res.message)

        return res.data
    }
Example #6
Source File: check.ts    From merkle-stellar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
async fetchPathAndSigsForUsername(groveHash: Sha256Hash, username: string): Promise<PathAndSigsJSON> {
    const params = new URLSearchParams({username: username})
    params.append('start_hash256', groveHash)
    const reporter = this.reporter.step(`fetch ${chalk.bold('keybase')} path from root for ${chalk.italic(username)}`)
    const url = keybaseAPIServerURI + 'merkle/path.json?' + params.toString()
    reporter.start(`contact ${chalk.grey(url)}`)
    const response = await axios.get(url)
    const ret = response.data as PathAndSigsJSON
    if (ret.status.code != 0) {
      throw new Error(`error fetching user: ${ret.status.desc}`)
    }
    reporter.success(`got back seqno #${ret.root.seqno}`)
    return ret
  }
Example #7
Source File: _getDS.ts    From genshin-kit-node with Apache License 2.0 6 votes vote down vote up
function getCnDS({
  query,
  body,
}: {
  query: Record<string, any>
  body: Record<string, any>
}) {
  const salt = 'xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs'
  const time = Math.floor(Date.now() / 1000)
  // Integer between 100000 - 200000
  const random = Math.floor(Math.random() * (200000 - 100000 + 1)) + 100000

  const b = body ? JSON.stringify(sortKeys(body)) : ''
  const q = query ? new URLSearchParams(sortKeys(query)) : ''

  const check = crypto
    .createHash('md5')
    .update(`salt=${salt}&t=${time}&r=${random}&b=${b}&q=${q}`)
    .digest('hex')

  const dynamic = `${time},${random},${check}`

  return dynamic
}
Example #8
Source File: oauthClientServer.ts    From cli with Apache License 2.0 6 votes vote down vote up
private getTokenQueryString(code: string) {
    const {redirect_uri} = this.clientConfig;
    const params = {
      grant_type: 'authorization_code',
      redirect_uri,
      code,
    };

    return new URLSearchParams(params);
  }
Example #9
Source File: authentication-provider.ts    From malagu with MIT License 6 votes vote down vote up
protected async getAccessTokenByCode(code: string) {
        const { id, secret, redirectUri } = this.ssoOptions;
        const { data } = await axios.post('https://sso.authing.cn/oauth/oidc/token',
            new URLSearchParams({
                code,
                client_id: id,
                client_secret: secret,
                grant_type: 'authorization_code',
                redirect_uri: redirectUri
            }).toString(),
            {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }
        );
        return data.access_token;
    }
Example #10
Source File: renderer.ts    From Adachi-BOT with MIT License 6 votes vote down vote up
private getURL( route: string, params?: Record<string, any> ): string {
		const paramStr: string = new URLSearchParams( params ).toString();
		
		try {
			new URL( route );
			return `${ route }?${ paramStr }`;
		} catch ( e ) {
			const url: string = this.httpBase + route;
			return `${ url }?${ paramStr }`;
		}
	}
Example #11
Source File: DJSCommand.ts    From Mandroc with GNU General Public License v3.0 6 votes vote down vote up
public async exec(message: Message, { query, type }: args) {
    if (query === "djs") {
      return message.util?.send(
        new MessageEmbed()
          .setColor(Color.Primary)
          .setImage("https://i.redd.it/1gxyc19z70s51.jpg")
      );
    }

    const qs = new URLSearchParams({
      src: type.toLowerCase(),
      q: query.replace(/#/g, "."),
      force: "false"
    });

    const res = await fetch(`${API_URL}?${qs}`).then(r => r.json());
    if (!res) {
      const embed = new MessageEmbed()
        .setDescription(`Sorry, I couldn't find anything for \`${query}\``)
        .setColor(Color.Warning);

      return message.util?.send(embed);
    }

    const embed = new MessageEmbed(res).setColor(Color.Primary);

    return message.util?.send(embed);
  }
Example #12
Source File: serializers.ts    From stellar-anchor-tests with Apache License 2.0 6 votes vote down vote up
function getParamsFromSearchString(
  searchString: string,
): Record<string, string | string[]> {
  let params: Record<string, string | string[]> = {};
  const searchParams = new URLSearchParams(searchString);
  for (const key of Object.keys(searchParams)) {
    const values = searchParams.getAll(key);
    if (values.length === 1) {
      params[key] = values[0];
    } else {
      params[key] = values;
    }
  }
  return params;
}
Example #13
Source File: getLinkFromName.ts    From ytdl with MIT License 6 votes vote down vote up
/**
 * Get first link from list of videos obtained by searching `name` on YouTube.
 * @param name Stores name of video
 */
export default async function getLinkFromName(name: string) {
    const searchParams = new URLSearchParams();
    searchParams.set('search_query', name);
    const searchURL = `https://www.youtube.com/results?${searchParams.toString()}`;

    const searchPage = await axios.get(searchURL);

    const firstWatchLink = searchPage.data.split('/watch?v=')[1].split('"')[0];

    return `https://youtube.com/watch?v=${firstWatchLink}`;
}
Example #14
Source File: price.ts    From stellar-anchor-tests with Apache License 2.0 5 votes vote down vote up
acceptsBuyAmounts: Test = {
  assertion: "accepts the 'buy_amount' parameter",
  sep: 38,
  group: "GET /price",
  dependencies: [returnsValidResponse],
  context: {
    expects: {
      token: undefined,
      quoteServerUrl: undefined,
      sep38StellarAsset: undefined,
      sep38OffChainAsset: undefined,
      sep38OffChainAssetBuyDeliveryMethod: undefined,
    },
    provides: {},
  },
  failureModes: {
    ...genericFailures,
  },
  async run(_config: Config): Promise<Result> {
    const result: Result = { networkCalls: [] };
    const requestBody: any = {
      sell_asset: this.context.expects.sep38StellarAsset,
      buy_asset: this.context.expects.sep38OffChainAsset,
      buy_amount: "100",
      context: "sep31",
    };
    if (this.context.expects.sep38OffChainAssetBuyDeliveryMethod !== undefined)
      requestBody.buy_delivery_method =
        this.context.expects.sep38OffChainAssetBuyDeliveryMethod;
    const networkCall: NetworkCall = {
      request: new Request(
        this.context.expects.quoteServerUrl +
          "/price?" +
          new URLSearchParams(requestBody),
        {
          headers: {
            Authorization: `Bearer ${this.context.expects.token}`,
          },
        },
      ),
    };
    result.networkCalls.push(networkCall);
    const priceResponse = await makeRequest(
      networkCall,
      200,
      result,
      "application/json",
    );
    if (!priceResponse) return result;
    const validationResult = validate(priceResponse, priceSchema);
    if (validationResult.errors.length !== 0) {
      result.failure = makeFailure(this.failureModes.INVALID_SCHEMA, {
        errors: validationResult.errors.join("\n"),
      });
      return result;
    }
    return result;
  },
}
Example #15
Source File: google-login.controller.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
@authenticate(
    STRATEGY.GOOGLE_OAUTH2,
    {
      accessType: 'offline',
      scope: ['profile', 'email'],
      authorizationURL: process.env.GOOGLE_AUTH_URL,
      callbackURL: process.env.GOOGLE_AUTH_CALLBACK_URL,
      clientID: process.env.GOOGLE_AUTH_CLIENT_ID,
      clientSecret: process.env.GOOGLE_AUTH_CLIENT_SECRET,
      tokenURL: process.env.GOOGLE_AUTH_TOKEN_URL,
    },
    queryGen('query'),
  )
  @authorize({permissions: ['*']})
  @get('/auth/google-auth-redirect', {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'Google Redirect Token Response',
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: {[X_TS_TYPE]: TokenResponse},
          },
        },
      },
    },
  })
  async googleCallback(
    @param.query.string('code') code: string,
    @param.query.string('state') state: string,
    @inject(RestBindings.Http.RESPONSE) response: Response,
    @inject(AuthCodeBindings.CODEWRITER_PROVIDER)
    googleCodeWriter: CodeWriterFn,
    @inject(AuthenticationBindings.CURRENT_USER)
    user: AuthUser | undefined,
  ): Promise<void> {
    const clientId = new URLSearchParams(state).get('client_id');
    if (!clientId || !user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    const client = await this.authClientRepository.findOne({
      where: {
        clientId,
      },
    });
    if (!client || !client.redirectUrl) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    try {
      const codePayload: ClientAuthCode<User, typeof User.prototype.id> = {
        clientId,
        user: user,
      };
      const token = await googleCodeWriter(
        jwt.sign(codePayload, client.secret, {
          expiresIn: client.authCodeExpiration,
          audience: clientId,
          issuer: process.env.JWT_ISSUER,
          algorithm: 'HS256',
        }),
      );
      response.redirect(`${client.redirectUrl}?code=${token}`);
    } catch (error) {
      this.logger.error(error);
      throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
    }
  }
Example #16
Source File: deposit.ts    From stellar-anchor-tests with Apache License 2.0 5 votes vote down vote up
depositRequiresAssetCode: Test = {
  assertion: "requires 'asset_code' parameter",
  sep: 6,
  group: depositTestsGroup,
  dependencies: [
    hasWebAuthEndpoint,
    returnsValidJwt,
    hasTransferServerUrl,
    assetCodeEnabledForDeposit,
  ],
  context: {
    expects: {
      tomlObj: undefined,
      authRequired: undefined,
      webAuthEndpoint: undefined,
      token: undefined,
      clientKeypair: undefined,
      sep6TransferServerUrl: undefined,
    },
    provides: {},
  },
  failureModes: {
    NO_ERROR_RESPONSE_ATTRIBUTE: {
      name: "no 'error' attribute in response",
      text(_args: any): string {
        return (
          "400 Bad Request response bodies should include a " +
          "human-readable 'error' message"
        );
      },
      links: {
        "Error Schema":
          "https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0006.md#6-error",
      },
    },
    ...genericFailures,
  },
  async run(_config: Config): Promise<Result> {
    const result: Result = { networkCalls: [] };
    const callParams = new URLSearchParams({
      account: this.context.expects.clientKeypair.publicKey(),
    });
    const headers = this.context.expects.authRequired
      ? {
          headers: {
            Authorization: `Bearer ${this.context.expects.token}`,
          },
        }
      : {};
    const getDepositCall: NetworkCall = {
      request: new Request(
        this.context.expects.sep6TransferServerUrl +
          depositEndpoint +
          `?${callParams.toString()}`,
        { ...headers },
      ),
    };
    result.networkCalls.push(getDepositCall);
    const errorResponse = await makeRequest(
      getDepositCall,
      400,
      result,
      "application/json",
    );
    if (result.failure || !errorResponse) return result;
    if (!errorResponse.error) {
      result.failure = makeFailure(
        this.failureModes.NO_ERROR_RESPONSE_ATTRIBUTE,
      );
    }
    return result;
  },
}
Example #17
Source File: videoData.ts    From ytdl with MIT License 5 votes vote down vote up
/**
     * Returns a promise which resolves with a `videoInfo` object.
     * @param videoId Stores the video id
     */
    private static async getVideoInfo(videoId: string): Promise<VideoInfo> {
        const videoIdRegex = /^[\w_-]+$/;
        if (!videoIdRegex.test(videoId)) {
            throw new Error('Invalid videoId.');
        }

        const body = await axios.get(
            `https://www.youtube.com/watch?v=${videoId}&hl=en&bpctr=${Math.ceil(Date.now() / 1000)}`, {
                headers: {
                    'User-Agent': '',
                },
            },
        );

        const jsonStr = between(body.data, 'ytplayer.config = ', '</script>');
        let config;

        try {
            config = JSON.parse(jsonStr.slice(0, jsonStr.lastIndexOf(';ytplayer.load')));
        } catch (err) {
            if (err.name === 'SyntaxError') {
                return this.getVideoInfo(videoId);
            }
            throw err;
        }

        let playerResponse = JSON.parse(config.args.player_response);

        if (!config.args.player_response) {
            const eurl = `https://youtube.googleapis.com/v/${videoId}`;
            const response = await axios.get(
                `https://www.youtube.com/get_video_info?video_id=${videoId}&el=embedded&eurl=${eurl}&sts=18333`,
            );
            playerResponse = JSON.parse(
                Object.fromEntries(new URLSearchParams(response.data)).player_response,
            );
        }

        const { playabilityStatus, videoDetails, streamingData } = playerResponse;

        const html5playerfileResponse = await axios.get(`https://www.youtube.com${config.assets.js}`);

        const tokens = extractActions(html5playerfileResponse.data);

        const videoInfo = <VideoInfo>{
            playabilityStatus,
            videoDetails,
            streamingData,
            tokens,
        };

        return videoInfo;
    }
Example #18
Source File: facebook-login.controller.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
@authenticate(
    STRATEGY.FACEBOOK_OAUTH2,
    {
      accessType: 'offline',
      authorizationURL: process.env.FACEBOOK_AUTH_URL,
      callbackURL: process.env.FACEBOOK_AUTH_CALLBACK_URL,
      clientID: process.env.FACEBOOK_AUTH_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_AUTH_CLIENT_SECRET,
      tokenURL: process.env.FACEBOOK_AUTH_TOKEN_URL,
    },
    queryGen('query'),
  )
  @authorize({permissions: ['*']})
  @get('/auth/facebook-auth-redirect', {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'Facebook Redirect Token Response',
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: {[X_TS_TYPE]: TokenResponse},
          },
        },
      },
    },
  })
  async facebookCallback(
    @param.query.string('code') code: string,
    @param.query.string('state') state: string,
    @inject(RestBindings.Http.RESPONSE) response: Response,
    @inject(AuthCodeBindings.CODEWRITER_PROVIDER)
    facebookCodeWriter: CodeWriterFn,
    @inject(AuthenticationBindings.CURRENT_USER)
    user: AuthUser | undefined,
  ): Promise<void> {
    const clientId = new URLSearchParams(state).get('client_id');
    if (!clientId || !user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    const client = await this.authClientRepository.findOne({
      where: {
        clientId,
      },
    });
    if (!client || !client.redirectUrl) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    try {
      const codePayload: ClientAuthCode<User, typeof User.prototype.id> = {
        clientId,
        user: user,
      };
      const token = await facebookCodeWriter(
        jwt.sign(codePayload, client.secret, {
          expiresIn: client.authCodeExpiration,
          audience: clientId,
          issuer: process.env.JWT_ISSUER,
          algorithm: 'HS256',
        }),
      );
      response.redirect(`${client.redirectUrl}?code=${token}`);
    } catch (error) {
      this.logger.error(error);
      throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
    }
  }
Example #19
Source File: HTTP.ts    From fnbr.js with MIT License 5 votes vote down vote up
/**
   * Sends a HTTP request
   * @param method The HTTP method
   * @param url The uri
   * @param headers The headers
   * @param body The body
   * @param form The form
   * @param responseType The axios response type
   * @param retries How many times this request has been retried
   */
  public async send(method: Method, url: string, headers: KeyValuePair = {}, body?: any, form?: KeyValuePair, responseType?: ResponseType, retries = 0): Promise<HTTPResponse> {
    let data;

    if (body) data = body;
    else if (form) {
      const urlSearchParams = new URLSearchParams();
      for (const key of Object.keys(form)) {
        urlSearchParams.append(key, form[key]);
      }

      data = urlSearchParams;
    }

    const finalHeaders = headers;

    if (!finalHeaders['Accept-Language']) finalHeaders['Accept-Language'] = this.client.config.language;

    const reqStartTime = Date.now();
    try {
      const response = await this.axios.request({
        method,
        url,
        headers: finalHeaders,
        data,
        responseType,
      });
      this.client.debug(`${method} ${url} (${((Date.now() - reqStartTime) / 1000).toFixed(2)}s): `
        + `${response.status} ${response.statusText || '???'}`, 'http');
      return { response };
    } catch (err: any) {
      this.client.debug(`${method} ${url} (${((Date.now() - reqStartTime) / 1000).toFixed(2)}s): `
        + `${err.response?.status || '???'} ${err.response?.statusText || '???'}`, 'http');

      const errResponse = (err as AxiosError).response;

      if (errResponse?.status.toString().startsWith('5') && retries < this.client.config.restRetryLimit) {
        return this.send(method, url, headers, body, form, responseType, retries + 1);
      }

      if (errResponse && (errResponse.status === 429 || (errResponse?.data as any)?.errorCode === 'errors.com.epicgames.common.throttled')) {
        const retryAfter = parseInt(errResponse.headers['Retry-After'] || (errResponse.data as any).messageVars[0], 10);
        if (!Number.isNaN(retryAfter)) {
          const sleepTimeout = (retryAfter * 1000) + 500;
          await new Promise((res) => {
            setTimeout(res, sleepTimeout);
          });

          return this.send(method, url, headers, body, form, responseType);
        }
      }

      return { error: err as AxiosError };
    }
  }
Example #20
Source File: keycloak-login.controller.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
@authenticate(
    STRATEGY.KEYCLOAK,
    {
      host: process.env.KEYCLOAK_HOST,
      realm: process.env.KEYCLOAK_REALM, //'Tenant1',
      clientID: process.env.KEYCLOAK_CLIENT_ID, //'onboarding',
      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET, //'e607fd75-adc8-4af7-9f03-c9e79a4b8b72',
      callbackURL: process.env.KEYCLOAK_CALLBACK_URL, //'http://localhost:3001/auth/keycloak-auth-redirect',
      authorizationURL: `${process.env.KEYCLOAK_HOST}/auth/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/auth`,
      tokenURL: `${process.env.KEYCLOAK_HOST}/auth/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
      userInfoURL: `${process.env.KEYCLOAK_HOST}/auth/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/userinfo`,
    },
    queryGen('query'),
  )
  @authorize({permissions: ['*']})
  @get('/auth/keycloak-auth-redirect', {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'Keycloak Redirect Token Response',
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: {[X_TS_TYPE]: TokenResponse},
          },
        },
      },
    },
  })
  async keycloakCallback(
    @param.query.string('code') code: string,
    @param.query.string('state') state: string,
    @inject(RestBindings.Http.RESPONSE) response: Response,
    @inject(AuthCodeBindings.CODEWRITER_PROVIDER)
    keycloackCodeWriter: CodeWriterFn,
    @inject(AuthenticationBindings.CURRENT_USER)
    user: AuthUser | undefined,
  ): Promise<void> {
    const clientId = new URLSearchParams(state).get('client_id');
    if (!clientId || !user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    const client = await this.authClientRepository.findOne({
      where: {
        clientId,
      },
    });
    if (!client || !client.redirectUrl) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    try {
      const codePayload: ClientAuthCode<User, typeof User.prototype.id> = {
        clientId,
        user: user,
      };
      const token = await keycloackCodeWriter(
        jwt.sign(codePayload, client.secret, {
          expiresIn: client.authCodeExpiration,
          audience: clientId,
          issuer: process.env.JWT_ISSUER,
          algorithm: 'HS256',
        }),
      );
      response.redirect(`${client.redirectUrl}?code=${token}`);
    } catch (error) {
      this.logger.error(error);
      throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
    }
  }
Example #21
Source File: http.ts    From amazon-mws-api-sdk with MIT License 5 votes vote down vote up
canonicalizeParameters = (parameters: CleanParameters): string => {
  const sp = new URLSearchParams(parameters)
  sp.sort()
  return sp.toString().replace(/\+/g, '%20')
}
Example #22
Source File: proxy-middleware.ts    From kfp-tekton-backend with Apache License 2.0 5 votes vote down vote up
export function _rewritePath(proxyPrefix: string, path: string, query: string): string {
  // Trim the proxy prefix if exists. It won't exist for any requests made
  // to absolute paths by the proxied resource.
  const querystring = new URLSearchParams(query).toString();
  const decodedPath = decodeURIComponent(path);
  return _trimProxyPrefix(proxyPrefix, decodedPath) + (querystring && '?' + querystring);
}
Example #23
Source File: TokensApi.ts    From hubspot-api-nodejs with Apache License 2.0 5 votes vote down vote up
/**
     * @param grantType 
     * @param code 
     * @param redirectUri 
     * @param clientId 
     * @param clientSecret 
     * @param refreshToken 
     */
    public async createToken(grantType?: string, code?: string, redirectUri?: string, clientId?: string, clientSecret?: string, refreshToken?: string, _options?: Configuration): Promise<RequestContext> {
        let _config = _options || this.configuration;







        // Path Params
        const localVarPath = '/oauth/v1/token';

        // Make Request Context
        const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
        requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8")

        // Form Params
        const useForm = canConsumeForm([
            'application/x-www-form-urlencoded',
        ]);

        let localVarFormParams
        if (useForm) {
            localVarFormParams = new FormData();
        } else {
            localVarFormParams = new URLSearchParams();
        }

        if (grantType !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('grant_type', grantType as any);
        }
        if (code !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('code', code as any);
        }
        if (redirectUri !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('redirect_uri', redirectUri as any);
        }
        if (clientId !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('client_id', clientId as any);
        }
        if (clientSecret !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('client_secret', clientSecret as any);
        }
        if (refreshToken !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('refresh_token', refreshToken as any);
        }

        requestContext.setBody(localVarFormParams);

        if(!useForm) {
            const contentType = ObjectSerializer.getPreferredMediaType([
                "application/x-www-form-urlencoded"
            ]);
            requestContext.setHeaderParam("Content-Type", contentType);
        }


        return requestContext;
    }
Example #24
Source File: apple-login.controller.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
@authenticate(
    STRATEGY.APPLE_OAUTH2,
    {
      accessType: 'offline',
      scope: ['name', 'email'],
      callbackURL: process.env.APPLE_AUTH_CALLBACK_URL,
      clientID: process.env.APPLE_AUTH_CLIENT_ID,
      teamID: process.env.APPLE_AUTH_TEAM_ID,
      keyID: process.env.APPLE_AUTH_KEY_ID,
      privateKeyLocation: process.env.APPLE_AUTH_PRIVATE_KEY_LOCATION,
    },
    queryGen('query'),
  )
  @authorize({permissions: ['*']})
  @get('/auth/apple-oauth-redirect', {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'Apple Redirect Token Response',
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: {[X_TS_TYPE]: TokenResponse},
          },
        },
      },
    },
  })
  async appleCallback(
    @param.query.string('code') code: string,
    @param.query.string('state') state: string,
    @inject(RestBindings.Http.RESPONSE) response: Response,
    @inject(AuthCodeBindings.CODEWRITER_PROVIDER)
    appleCodeWriter: CodeWriterFn,
    @inject(AuthenticationBindings.CURRENT_USER)
    user: AuthUser | undefined,
  ): Promise<void> {
    const clientId = new URLSearchParams(state).get('client_id');

    if (!clientId || !user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    const client = await this.authClientRepository.findOne({
      where: {
        clientId,
      },
    });
    if (!client || !client.redirectUrl) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    try {
      const codePayload: ClientAuthCode<User, typeof User.prototype.id> = {
        clientId,
        user: user,
      };
      const token = await appleCodeWriter(
        jwt.sign(codePayload, client.secret, {
          expiresIn: client.authCodeExpiration,
          audience: clientId,
          issuer: process.env.JWT_ISSUER,
          algorithm: 'HS256',
        }),
      );
      const role = user.role;
      response.redirect(
        `${process.env.WEBAPP_URL ?? ''}${
          client.redirectUrl
        }?code=${token}&role=${role}`,
      );
    } catch (error) {
      this.logger.error(error);
      throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
    }
  }
Example #25
Source File: TablesApi.ts    From hubspot-api-nodejs with Apache License 2.0 5 votes vote down vote up
/**
     * Import the contents of a CSV file into an existing HubDB table. The data will always be imported into the `draft` version of the table. Use `/publish` endpoint to push these changes to `published` version. This endpoint takes a multi-part POST request. The first part will be a set of JSON-formatted options for the import and you can specify this with the name as `config`.  The second part will be the CSV file you want to import and you can specify this with the name as `file`. Refer the [overview section](https://developers.hubspot.com/docs/api/cms/hubdb#importing-tables) to check the details and format of the JSON-formatted options for the import.
     * Import data into draft table
     * @param tableIdOrName The ID of the destination table where data will be imported.
     * @param config Configuration for the import in JSON format as described above.
     * @param file The source CSV file to be imported.
     */
    public async importDraftTable(tableIdOrName: string, config?: string, file?: HttpFile, _options?: Configuration): Promise<RequestContext> {
        let _config = _options || this.configuration;

        // verify required parameter 'tableIdOrName' is not null or undefined
        if (tableIdOrName === null || tableIdOrName === undefined) {
            throw new RequiredError("TablesApi", "importDraftTable", "tableIdOrName");
        }




        // Path Params
        const localVarPath = '/cms/v3/hubdb/tables/{tableIdOrName}/draft/import'
            .replace('{' + 'tableIdOrName' + '}', encodeURIComponent(String(tableIdOrName)));

        // Make Request Context
        const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
        requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8")

        // Form Params
        const useForm = canConsumeForm([
            'multipart/form-data',
        ]);

        let localVarFormParams
        if (useForm) {
            localVarFormParams = new FormData();
        } else {
            localVarFormParams = new URLSearchParams();
        }

        if (config !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('config', config as any);
        }
        if (file !== undefined) {
             // TODO: replace .append with .set
             if (localVarFormParams instanceof FormData) {
                 localVarFormParams.append('file', file.data, file.name);
             }
        }

        requestContext.setBody(localVarFormParams);

        if(!useForm) {
            const contentType = ObjectSerializer.getPreferredMediaType([
                "multipart/form-data"
            ]);
            requestContext.setHeaderParam("Content-Type", contentType);
        }

        let authMethod = null;
        // Apply auth methods
        authMethod = _config.authMethods["hapikey"]
        if (authMethod) {
            await authMethod.applySecurityAuthentication(requestContext);
        }
        // Apply auth methods
        authMethod = _config.authMethods["oauth2"]
        if (authMethod) {
            await authMethod.applySecurityAuthentication(requestContext);
        }

        return requestContext;
    }
Example #26
Source File: instagram-login.controller.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
@authenticate(
    STRATEGY.INSTAGRAM_OAUTH2,
    {
      accessType: 'offline',
      authorizationURL: process.env.INSTAGRAM_AUTH_URL,
      callbackURL: process.env.INSTAGRAM_AUTH_CALLBACK_URL,
      clientID: process.env.INSTAGRAM_AUTH_CLIENT_ID,
      clientSecret: process.env.INSTAGRAM_AUTH_CLIENT_SECRET,
      tokenURL: process.env.INSTAGRAM_AUTH_TOKEN_URL,
    },
    queryGen('query'),
  )
  @authorize({permissions: ['*']})
  @get('/auth/instagram-auth-redirect', {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'Instagram Redirect Token Response',
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: {[X_TS_TYPE]: TokenResponse},
          },
        },
      },
    },
  })
  async instagramCallback(
    @param.query.string('code') code: string,
    @param.query.string('state') state: string,
    @inject(RestBindings.Http.RESPONSE) response: Response,
    @inject(AuthCodeBindings.CODEWRITER_PROVIDER)
    instgaramCodeWriter: CodeWriterFn,
    @inject(AuthenticationBindings.CURRENT_USER)
    user: AuthUser | undefined,
  ): Promise<void> {
    const clientId = new URLSearchParams(state).get('client_id');
    if (!clientId || !user) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    const client = await this.authClientRepository.findOne({
      where: {
        clientId,
      },
    });
    if (!client || !client.redirectUrl) {
      throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
    }
    try {
      const codePayload: ClientAuthCode<User, typeof User.prototype.id> = {
        clientId,
        user: user,
      };
      const token = await instgaramCodeWriter(
        jwt.sign(codePayload, client.secret, {
          expiresIn: client.authCodeExpiration,
          audience: clientId,
          issuer: process.env.JWT_ISSUER,
          algorithm: 'HS256',
        }),
      );
      response.redirect(`${client.redirectUrl}?code=${token}`);
    } catch (error) {
      this.logger.error(error);
      throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
    }
  }
Example #27
Source File: CoreApi.ts    From hubspot-api-nodejs with Apache License 2.0 5 votes vote down vote up
/**
     * Begins importing data from the specified file resources. This uploads the corresponding file and uses the import request object to convert rows in the files to objects.
     * Start a new import
     * @param files A list of files containing the data to import
     * @param importRequest JSON formatted metadata about the import. This includes a name for the import and the column mappings for each file. See the overview tab for more on the required format.
     */
    public async create(files?: HttpFile, importRequest?: string, _options?: Configuration): Promise<RequestContext> {
        let _config = _options || this.configuration;



        // Path Params
        const localVarPath = '/crm/v3/imports/';

        // Make Request Context
        const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
        requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8")

        // Form Params
        const useForm = canConsumeForm([
            'multipart/form-data',
        ]);

        let localVarFormParams
        if (useForm) {
            localVarFormParams = new FormData();
        } else {
            localVarFormParams = new URLSearchParams();
        }

        if (files !== undefined) {
             // TODO: replace .append with .set
             if (localVarFormParams instanceof FormData) {
                 localVarFormParams.append('files', files.data, files.name);
             }
        }
        if (importRequest !== undefined) {
             // TODO: replace .append with .set
             localVarFormParams.append('importRequest', importRequest as any);
        }

        requestContext.setBody(localVarFormParams);

        if(!useForm) {
            const contentType = ObjectSerializer.getPreferredMediaType([
                "multipart/form-data"
            ]);
            requestContext.setHeaderParam("Content-Type", contentType);
        }

        let authMethod = null;
        // Apply auth methods
        authMethod = _config.authMethods["hapikey"]
        if (authMethod) {
            await authMethod.applySecurityAuthentication(requestContext);
        }
        // Apply auth methods
        authMethod = _config.authMethods["oauth2"]
        if (authMethod) {
            await authMethod.applySecurityAuthentication(requestContext);
        }

        return requestContext;
    }
Example #28
Source File: withdraw.ts    From stellar-anchor-tests with Apache License 2.0 4 votes vote down vote up
returnsProperSchemaForKnownAccounts: Test = {
  assertion:
    "returns a success or customer info status response for valid requests from KYC'ed accounts",
  sep: 6,
  group: withdrawTestsGroup,
  dependencies: [canCreateCustomer].concat(
    withdrawRequiresAssetCode.dependencies || [],
  ),
  context: {
    expects: withdrawRequiresAssetCode.context.expects,
    provides: {
      sep6WithdrawTransactionId: undefined,
    },
  },
  failureModes: {
    INVALID_SCHEMA: {
      name: "invalid schema",
      text(args: any): string {
        return (
          "The response body returned does not comply with the schema defined for the /withdraw endpoint. " +
          "The errors returned from the schema validation:\n\n" +
          `${args.errors}`
        );
      },
      links: {
        "Withdraw Deposit Info Needed Response":
          "https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0006.md#2-customer-information-needed-non-interactive",
        "Withdraw Customer Status Response":
          "https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0006.md#2-customer-information-needed-non-interactive",
      },
    },
    ...genericFailures,
  },
  async run(config: Config): Promise<Result> {
    if (
      !config.sepConfig ||
      !config.sepConfig["6"] ||
      !config.assetCode ||
      !config.sepConfig["6"].withdraw.types
    )
      throw { message: "improperly configured" };
    const result: Result = { networkCalls: [] };
    const headers = this.context.expects.authRequired
      ? {
          headers: {
            Authorization: `Bearer ${this.context.expects.token}`,
          },
        }
      : {};
    const withdrawInfo =
      this.context.expects.sep6InfoObj.withdraw[config.assetCode];
    const withdrawType = Object.keys(withdrawInfo.types)[0];
    const withdrawTypeFields =
      config.sepConfig["6"].withdraw.types[withdrawType].transactionFields ||
      {};
    const callParams = new URLSearchParams({
      asset_code: config.assetCode,
      account: this.context.expects.clientKeypair.publicKey(),
      type: withdrawType,
      ...withdrawTypeFields,
    });
    const getWithdrawCall: NetworkCall = {
      request: new Request(
        this.context.expects.sep6TransferServerUrl +
          withdrawEndpoint +
          `?${callParams.toString()}`,
        { ...headers },
      ),
    };
    result.networkCalls.push(getWithdrawCall);
    const responseBody = await makeRequest(
      getWithdrawCall,
      200,
      result,
      "application/json",
    );
    if (!responseBody || !getWithdrawCall.response) return result;
    let schema;
    if (getWithdrawCall.response.status == 200) {
      schema = withdrawSuccessResponseSchema;
    } else {
      schema = customerInfoStatusSchema;
    }
    const validatorResult = validate(responseBody, schema);
    if (validatorResult.errors.length !== 0) {
      result.failure = makeFailure(this.failureModes.INVALID_SCHEMA, {
        errors: validatorResult.errors.join("\n"),
      });
      return result;
    }
    this.context.provides.sep6WithdrawTransactionId = responseBody.id || null;
    if (getWithdrawCall.response.status === 200) {
      try {
        Keypair.fromPublicKey(responseBody.account_id);
      } catch {
        result.failure = makeFailure(this.failureModes.INVALID_SCHEMA, {
          errors: "invalid Stellar public key",
        });
        return result;
      }
      let memoValue = responseBody.memo;
      if (responseBody.memo_type === "hash") {
        memoValue = Buffer.from(responseBody.memo, "base64");
      }
      try {
        new Memo(responseBody.memo_type, memoValue);
      } catch {
        result.failure = makeFailure(this.failureModes.INVALID_SCHEMA, {
          errors: "invalid 'memo' for 'memo_type'",
        });
        return result;
      }
    }
    return result;
  },
}
Example #29
Source File: WidgetManager.ts    From js-sdk with MIT License 4 votes vote down vote up
/**
     * 직접적인 사용이 권장되지 않습니다.
     */
    async _fetch(options: WidgetMakeOptions, fetchOptions: FetchOptions = { cache: true, force: false }): Promise<Widget> {
        const query = new URLSearchParams()
        const queryOptions: (keyof WidgetOptions)[] = ["icon", "scale", "style"]

        const cacheKey = {
            id: options.id,
            style: options.style,
            scale: options.scale,
            icon: options.icon,
            target: options.target,
            type: options.type
        }

        const key = createHash("sha256").update(JSON.stringify(cacheKey)).digest("hex")
        const cache = this.cache.get(key)

        if (!fetchOptions?.force && cache)
            return cache

        for (const queryOption of queryOptions) {
            const value = options[queryOption]?.toString?.() || options[queryOption] as string
            if (options[queryOption] || typeof options[queryOption] === "boolean") query.append(queryOption, value)
        }

        const [res, sharp] = await Promise.allSettled([
            this.koreanbots.api({ global: true }).widget(options.target)(options.type)(`${options.id}.svg`).get({
                [KoreanbotsInternal]: {
                    query,
                    bodyResolver: async <T>(res: Dispatcher.ResponseData) => Buffer.from(await res.body.arrayBuffer()) as unknown as T
                }
            }),
            import("sharp").catch(() => {
                throw new Error(`"${options.format}" 파일 형식으로 변환하기 위한 모듈 "sharp"를 찾을 수 없습니다.`)
            })
        ])

        if (sharp.status === "rejected") throw new Error(sharp.reason)

        if (res.status === "fulfilled" && options?.format !== "svg") {
            const sh = sharp.value.default
            const buffer = res.value.data

            if (!buffer) throw new Error("위젯에서 Buffer 데이터를 읽을 수 없습니다.")

            let converted
            switch (options?.format) {
            case "jpeg":
            case "jpg":
                converted = sh(buffer).jpeg(options.convertOptions).toBuffer()
                break
            case "png":
                converted = sh(buffer).png(options.convertOptions).toBuffer()
                break
            case "webp":
                converted = sh(buffer).webp(options.convertOptions).toBuffer()
                break
            case "avif":
                converted = sh(buffer).avif(options.convertOptions).toBuffer()
                break
            case "heif":
                converted = sh(buffer).heif(options.convertOptions).toBuffer()
                break
            default:
                converted = buffer
                break
            }

            res.value.data = await converted
        }

        const instance = res.status === "fulfilled" &&
            new Widget(this.koreanbots, res.value.data ?? Buffer.alloc(0), options)

        if (!instance) throw new Error((res as PromiseRejectedResult).reason)

        if (fetchOptions.cache) this.cache.set(
            key,
            instance
        )

        return instance
    }