LoginSignup
1
1

More than 3 years have passed since last update.

オレオレ短縮URLアプリ

Last updated at Posted at 2020-12-14

この記事は、上智大学エレクトロニクス研究部Advent Calendar第15日目の記事です。

背景

短縮URLアプリといえば、bit.ly が有名ですね。当初はこのアプリの無料プランで十分だと思っていたのですが、何度も繰り返し短縮URLを生成するに連れて満足できなくなってきました。特にVS Codeのliveshareのリンクをbit.lyで短縮する際に、毎回別のリンクを生成されてしまうのが不満でした。同じ目的ならば同じリンクになるべきだと考え、固定リンクを使ってみたいと思ったのですが、月額29ドルもかかってしまいます。個人として使うのには(そしてこの目的だけのために使うのには)高すぎると思い、自分で短縮リンクアプリを作ってみることにしました。

使った技術スタック

  • AWS Lambda(API Gateway)
  • AWS DyanmoDB
  • TypeSciprt
  • GitHub Actions

実装

GitHubに載せました。この記事ではその中で一番重要なリダイレクトの部分だけ解説します。

リダイレクト処理の実装について

関数定義(GitHub)

if (result.Item.public || (await verifySession(sessionId))) {
  const location = result.Item.originalUrl.toString();

  if (xhr) {
    return {
      statusCode: 200,
      body: JSON.stringify({location}),
      headers: httpUtils.toKebabCase({contentType})
    };
  } else {
    return {
      statusCode: 302,
      body: null,
      headers: httpUtils.toKebabCase({location, contentType})
    };
  }
} else {
  if (xhr) {
    const session = await checkSessionId(dynamodb, sessionId, linkId);
    const setCookie = `session=${session}; Path=/; Max-Age=${maxAge}; HttpOnly${isDev(event) ? "" : "; Secure"}`
    return {
      statusCode: 403,
      body: null,
      headers: httpUtils.toKebabCase({contentType, setCookie})
    };
  } else {
    const location = `/link?id=${event.pathParameters.id}`;
    return {
      statusCode: 302,
      body: null,
      headers: httpUtils.toKebabCase({location, contentType})
    };
  }
}

色々書いてありますが、やっていることは、公開リンクならそのままリダイレクトを行う、非公開リンクなら管理者の許可があるまでリダイレクトを行わないということです。
非公開リンクのときに誰に許可を行うのかという判断をするために、 Set-Cookie を行っています。Cookieの値はDyanmoDBで管理され、 approvedtrue になると管理者の許可が得られたと判断されます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1