5. Google認証
Google認証を実装します。
Google Cloud Platform Console
プロジェクト設定
- Consoleからプロジェクト作成
- API & Services > OAuth consent screen > User Type: External (外部アプリケーション)
- Application name:
Slack Clone
, Authorized domains: ConvexのHTTP Actions URL
とする
クレデンシャル作成
- API & Services > Credentials > Create Credentials > OAuth client ID
- Application type:
Web application
, Name:Slack Clone
, Authorized Javascript origins:http://localhost:3000
, Authorized redirect URIs: ConvexのHTTP Actions URL
+/api/auth/callback/google
とする - 作成されたClient IDとClient Secretをメモ
Convex
環境変数設定
terminal
$ bunx convex env set AUTH_GOOGLE_ID 作成したClient ID
$ bunx convex env set AUTH_GOOGLE_SECRET 作成したClient Secret
認証機能の修正
convex/auth.ts
import GitHub from "@auth/core/providers/github";
import Google from "@auth/core/providers/google";
import { convexAuth } from "@convex-dev/auth/server";
export const { auth, signIn, signOut, store } = convexAuth({
providers: [GitHub, Google],
});
あとはボタンにGithubと同様の機能追加で認証ができる。
Tips
ダブルクリックした場合の動作制御
本来1度のAuth処理でいいところで2度実施されてしまうので、制御を加える
src/features/auth/components/sign-in-card.tsx
export const SignInCard = ({ setState }: SignInCardProps) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [pending, setPending] = useState(false);
const { signIn } = useAuthActions();
const onProviderSignIn = (value: "github" | "google") => {
setPending(true);
signIn(value).finally(() => setPending(false));
};