|
import yargs from 'https://deno.land/x/yargs/deno.ts' |
|
import Ask from "https://deno.land/x/[email protected]/mod.ts" |
|
import { CognitoIdentityProvider } from "https://deno.land/x/[email protected]/client-cognito-identity-provider/mod.ts" |
|
import { hmac } from "https://denopkg.com/chiefbiiko/hmac/mod.ts"; |
|
|
|
const args = yargs(Deno.args) |
|
.usage( |
|
"$0 <region> <cognito_client_id> [cognito_client_secret]", |
|
'Authenticates against your AWS Cognito user pool and returns an access token.', |
|
(yargs: any) => { |
|
yargs |
|
.positional("cognito_client_id", { |
|
default: Deno.env.get("AWS_COGNITO_CLIENT_ID"), |
|
describe: 'Cognito client ID (required)', |
|
}) |
|
.positional("region", { |
|
default: Deno.env.get("AWS_REGION"), |
|
describe: 'AWS region ID (required)', |
|
}) |
|
.option("cognit_client_secret", { |
|
describe: "Cognito client secret", |
|
}) |
|
} |
|
) |
|
.help() |
|
.parse() |
|
|
|
const ask = new Ask(); |
|
|
|
const loginQuestions = [ |
|
{ |
|
name: 'username', |
|
message: 'Username:', |
|
}, |
|
{ |
|
name: 'password', |
|
message: 'Password:', |
|
}, |
|
] |
|
|
|
const answers = await ask.prompt(loginQuestions) |
|
const { username, password } = answers |
|
const { |
|
cognito_client_id: cognitoClientId, |
|
cognito_client_secret: cognitoClientSecret, |
|
region |
|
} = args |
|
|
|
const cognitoClient = new CognitoIdentityProvider({ |
|
region, |
|
}) |
|
|
|
type AuthOptions = { |
|
AuthFlow: string, |
|
ClientId: string, |
|
AuthParameters: {[key: string]: string}, |
|
} |
|
|
|
const authOpts: AuthOptions = { |
|
AuthFlow: "USER_PASSWORD_AUTH", |
|
ClientId: cognitoClientId, |
|
AuthParameters: { |
|
'USERNAME': username as string, |
|
'PASSWORD': password as string, |
|
}, |
|
} |
|
|
|
if (cognitoClientSecret) { |
|
authOpts.AuthParameters.SECRET_HASH = hmac("sha256", cognitoClientSecret, username as string + cognitoClientId, "utf8", "base64") as string |
|
} |
|
|
|
const response = await cognitoClient.initiateAuth(authOpts!) |
|
|
|
console.log(response!.AuthenticationResult!.IdToken) |