ATUALIZAR:
Houve algumas atualizações e o cliente Amplify não é mais necessário. Depois de adminCreateUser (), você pode apenas usar
cisp.adminSetUserPassword({
UserPoolId: pool_id,
Username: login,
Password: password,
Permanent: true
})
[https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html]
isso definirá o usuário como "confirmado".
ATUALIZAR:
Agora estou usando isso, traduzido para amplificar, dentro de um Lambda NodeJS:
// enable node-fetch polyfill for Node.js
global.fetch = require("node-fetch").default;
global.navigator = {};
const AWS = require("aws-sdk");
const cisp = new AWS.CognitoIdentityServiceProvider();
const Amplify = require("@aws-amplify/core").default;
const Auth = require("@aws-amplify/auth").default;
...
/*
this_user: {
given_name: string,
password: string,
email: string,
cell: string
}
*/
const create_cognito = (this_user) => {
let this_defaults = {
password_temp: Math.random().toString(36).slice(-8),
password: this_user.password,
region: global._env === "prod" ? production_region : development_region,
UserPoolId:
global._env === "prod"
? production_user_pool
: development_user_pool,
ClientId:
global._env === "prod"
? production_client_id
: development_client_id,
given_name: this_user.given_name,
email: this_user.email,
cell: this_user.cell,
};
// configure Amplify
Amplify.configure({
Auth: {
region: this_defaults.region,
userPoolId: this_defaults.UserPoolId,
userPoolWebClientId: this_defaults.ClientId,
},
});
if (!Auth.configure())
return Promise.reject("could not configure amplify");
return new Promise((resolve, reject) => {
let _result = {};
let this_account = undefined;
let this_account_details = undefined;
// create cognito account
cisp
.adminCreateUser({
UserPoolId: this_defaults.UserPoolId,
Username: this_defaults.given_name,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
MessageAction: "SUPPRESS",
TemporaryPassword: this_defaults.password_temp,
UserAttributes: [
{ Name: "given_name", Value: this_defaults.given_name },
{ Name: "email", Value: this_defaults.email },
{ Name: "phone_number", Value: this_defaults.cell },
{ Name: "email_verified", Value: "true" },
],
})
.promise()
.then((user) => {
console.warn(".. create_cognito: create..");
_result.username = user.User.Username;
_result.temporaryPassword = this_defaults.password_temp;
_result.password = this_defaults.password;
// sign into cognito account
return Auth.signIn(_result.username, _result.temporaryPassword);
})
.then((user) => {
console.warn(".. create_cognito: signin..");
// complete challenge
return Auth.completeNewPassword(user, _result.password, {
email: this_defaults.email,
phone_number: this_defaults.cell,
});
})
.then((user) => {
console.warn(".. create_cognito: confirmed..");
this_account = user;
// get details
return Auth.currentAuthenticatedUser();
})
.then((this_details) => {
if (!(this_details && this_details.attributes))
throw "account creation failes";
this_account_details = Object.assign({}, this_details.attributes);
// signout
return this_account.signOut();
})
.then(() => {
console.warn(".. create_cognito: complete");
resolve(this_account_details);
})
.catch((err) => {
console.error(".. create_cognito: error");
console.error(err);
reject(err);
});
});
};
Estou definindo uma senha temporária e, em seguida, redefinindo-a com a senha solicitada pelo usuário.
ANTIGA POSTAGEM:
Você pode resolver isso usando o SDK amazon-cognito-identity-js autenticando com a senha temporária após a criação da conta com cognitoidentityserviceprovider.adminCreateUser()
e executando cognitoUser.completeNewPasswordChallenge()
dentro cognitoUser.authenticateUser( ,{newPasswordRequired})
- tudo dentro da função que cria seu usuário.
Estou usando o código abaixo dentro do AWS lambda para criar contas de usuário do Cognito habilitadas. Tenho certeza de que pode ser otimizado, seja paciente comigo. Este é meu primeiro post, e ainda sou muito novo em JavaScript.
var AWS = require("aws-sdk");
var AWSCognito = require("amazon-cognito-identity-js");
var params = {
UserPoolId: your_poolId,
Username: your_username,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
MessageAction: "SUPPRESS",
TemporaryPassword: your_temporaryPassword,
UserAttributes: [
{ Name: "given_name", Value: your_given_name },
{ Name: "email", Value: your_email },
{ Name: "phone_number", Value: your_phone_number },
{ Name: "email_verified", Value: "true" }
]
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
let promise = new Promise((resolve, reject) => {
cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
promise
.then(data => {
// login as new user and completeNewPasswordChallenge
var anotherPromise = new Promise((resolve, reject) => {
var authenticationDetails = new AWSCognito.AuthenticationDetails({
Username: your_username,
Password: your_temporaryPassword
});
var poolData = {
UserPoolId: your_poolId,
ClientId: your_clientId
};
var userPool = new AWSCognito.CognitoUserPool(poolData);
var userData = {
Username: your_username,
Pool: userPool
};
var cognitoUser = new AWSCognito.CognitoUser(userData);
let finalPromise = new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(authResult) {
cognitoUser.getSession(function(err) {
if (err) {
} else {
cognitoUser.getUserAttributes(function(
err,
attResult
) {
if (err) {
} else {
resolve(authResult);
}
});
}
});
},
onFailure: function(err) {
reject(err);
},
newPasswordRequired(userAttributes, []) {
delete userAttributes.email_verified;
cognitoUser.completeNewPasswordChallenge(
your_newPoassword,
userAttributes,
this
);
}
});
});
finalPromise
.then(finalResult => {
// signout
cognitoUser.signOut();
// further action, e.g. email to new user
resolve(finalResult);
})
.catch(err => {
reject(err);
});
});
return anotherPromise;
})
.then(() => {
resolve(finalResult);
})
.catch(err => {
reject({ statusCode: 406, error: err });
});