import type {
AdminInitiateAuthCommandInput,
AdminInitiateAuthCommandOutput
} from "@aws-sdk/client-cognito-identity-provider";
import {
AdminInitiateAuthCommand, CognitoIdentityProviderClient, NotAuthorizedException
} from "@aws-sdk/client-cognito-identity-provider";
import crypto from "crypto";
import invariant from "tiny-invariant";
const clientId = process.env.USER_POOL_CLIENT_ID || "";
const userPoolId = process.env.USER_POOL_ID || "";
const clientSecret = process.env.USER_POOL_CLIENT_SECRET || "";
invariant(process.env.REGION, "REGION must be set");
invariant(process.env.USER_POOL_ID, "USER_POOL_ID must be set");
invariant(clientId, "USER_POOL_CLIENT_ID must be set");
invariant(clientSecret, "USER_POOL_CLIENT_SECRET must be set");
const client = new CognitoIdentityProviderClient({
region: process.env.REGION,
});
export async function signIn({
email,
password,
}: {
email: string;
password: string;
}): Promise<AdminInitiateAuthCommandOutput | Error | undefined> {
const input: AdminInitiateAuthCommandInput = {
ClientId: clientId,
AuthFlow: "ADMIN_USER_PASSWORD_AUTH",
AuthParameters: {
USERNAME: email,
PASSWORD: password,
SECRET_HASH: hashSecret({
clientSecret,
email,
clientId,
}),
},
UserPoolId: userPoolId,
};
const command = new AdminInitiateAuthCommand(input);
try {
const data = await client.send(command);
console.log("Sign In successfully");
return data;
} catch (error) {
console.log("Sign In failed");
if (error instanceof NotAuthorizedException) {
return error;
}
return error as Error;
}
}
export function hashSecret({
clientSecret,
email,
clientId,
}: {
clientSecret: string;
email: string;
clientId: string;
}) {
return crypto
.createHmac("SHA256", clientSecret)
.update(email + clientId)
.digest("base64");
}