I am able to singup user but cannot set role on the user signup.
here is json data I am using to singup.
let data = JSON.stringify({
firstName: "first",
lastName: "last",
role : 'User',
email: "first.last#gmail.com",
password: "password",
confirmPassword: "password",
parameters:{
phone: "0000000"
}
});
Thanx
This is already answered , please look here
How to use Backand Security Action Parameters
Related
I hard coded the users in my seed file
I can view the the users in the database
But when i try to test the details in the database i get an error "invalid credentials"
I don't know why it says that when the user is already in the database
This is the seeds file
const noPassword = "$2a$12$ZQwXBTq7UMgmugpy5zz9SOdG4JvEa3Bj5MofQl9fIMFb1wTSGU9.C"; exports.seed = function (knex) { // Deletes ALL existing entries return knex("users") .truncate() .then(function () { // Inserts seed entries return knex("users").insert([ { email: "danielAsuquo15#gmail.com", first_name: "Daniel", last_name: "Asuquo", password:noPassword, }, { email: "josiahdamiwilliams#gmail.com", first_name: "josiah", last_name: "williams", password:noPassword, }, ]); }); };
I have an Apollo GraphQL client running in react native. It connects to a lambda instance running graphQL. My problem is that I am trying to send a mutate request to the server (have not setup queries yet), and the server is getting the following and declaring a syntax error(Expected Name, found String \"operationName\").
When I was testing the graphQL server, the requests looked like the ones specified below. Is Apollo Client not formatting the requests properly (if so why not) or is it functioning as intended?
Body sent from Apollo client to graphQL lambda:
{
"operationName": "createUser",
"variables": {
"firstName": "Jane",
"lastName": "Doe",
"email": "jane#doe.com",
"username": "jane_doe.com",
"provider": "none"
"jwt": "none"
},
"query": "mutation createUser($firstName: String!, $lastName: String!, $email: String!, $username: String!, $provider: String, $jwt: String!) {
createUser(firstName: $firstName, lastName: $lastName, email: $email, username: $username, provider: $provider, jwt: $jwt) {
createdAt
__typename
}
}"}
A Normal request that works from Postman.
mutation {
createUser(firstName: "Jane", lastName: "Doe", email: "jane#doe.com", username: "jane_doe.com", jwt: "none", provider: "none") {
firstName
}
}
Code from react-native app
// The mutation in the render function
<Mutation mutation={createUserMutation}>
{(createUser, error) => {
console.log('error-----------', error);
// If there is an error throw the error
if (error) {
console.log('error----------', error);
}
if (createUser) {
// If the response has data load the response data via the createPlayer property.
return (
<LoginButton
onPress={() => {
this.signIn(createUser);
}}
/>
);
}
// By default it is loading the result so just return loading...
return <Text>Loading...</Text>;
}}
</Mutation>
// The signin function called when the user presses the login button
async signIn(createUser) {
...
try {
Auth.signIn(un, password)
.then(data => {
...
this.createUserFunc(
createUser,
'Jane',
'Doe',
'jane#doe.com',
'jane_doe.com',
'none',
'none'
);
}
...
}
// The create user function called from the signin function
createUserFunc = (func, firstName, lastName, email, username, provider, jwt) => {
const newUser = {
firstName,
lastName,
email,
username,
provider,
jwt,
};
func({variables: newUser});
};
// The gql syntax mutation
const createUserMutation = gql`
mutation createUser(
$firstName: String!
$lastName: String!
$email: String!
$username: String!
$provider: String
$jwt: String!
) {
createUser(
firstName: $firstName
lastName: $lastName
email: $email
username: $username
provider: $provider
jwt: $jwt
) {
createdAt
}
}
`;
Most GraphQL servers that accept requests over HTTP are listening to two different types of content (indicated with the Content-Type header): application/graphql and application/json. You server seems to only listen to requests with a application/graphql body.
The problem with Content-Type: application/graphql is that GraphQL execution consist out of up to three parameters that can be supplied by the client:
The query (required)
The variable values of the query
The operation name
This enables query documents to be entirely static. But if the content of the request is only the GraphQL query, the other parameters need to go somewhere else. In theory they could be supplied as GET parameters but usually all clients use the JSON format to supply all three as outlined here.
As Daniel has pointed out you can use a GraphQL server implementation for your framework/technology of choice to handle that for you.
Alternatively you would have to react to the header of the request yourself (which could be a good exercise but you are probably going to miss an edge case that the library authors have thought of).
I'm doing an http request with "Vue.http", but the data is not sent.
On the server side, the controller method is hit, but the request is empty.
console.log(email, username, password) // NOT EMPTY
Vue.http({
url: 'auth/signup',
method: 'POST',
data: {
email: email,
username: username,
password: password
}
})
Is there something wrong with "data:" ?
This works :
Vue.http.post('auth/signup', {
email: email,
username: username,
password: password
})
I must have used an older "Vue.http" syntax.
How do I go about email verifying a user who is CONFIRMED yet email_verified is false?
The scenario is roughly an agent signs up user on their behalf, and I confirm the user through the admin call adminConfirmSignUp. At that point, the user cannot change their password because of the email_verified flag being false.
I can't call resendConfirmationCode because the user is already confirmed.
I can't call forgotPassword because the email_verified flag is false.
The best I can think of is deleting the user account and calling signUp (prompting them to re-enter their password or a new password), hence recreating their account.
Using the AWS CLI you can update the email_verified attribute:
aws cognito-idp admin-update-user-attributes
--user-pool-id eu-west-xxxxxx
--username xxxxyyyy#example.com
--user-attributes Name=email_verified,Value=true
Here is the official documentation: https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-update-user-attributes.html
You can change email_verified, phone_number_verified and other attributes by calling adminUpdateUserAttributes without any lambdas and triggers:
'use strict'
var AWS = require('aws-sdk')
AWS.config.update({
accessKeyId: 'YOUR_ACCESS_KEY_HERE',
secretAccessKey: 'YOUR_SECRET_ACCESS_KEY_HERE',
region: 'us-east-1' // change region if required
});
var CognitoIdentityServiceProvider = AWS.CognitoIdentityServiceProvider
var client = new CognitoIdentityServiceProvider({
apiVersion: '2016-04-19',
region: 'us-east-1' // change region if required
})
client.adminUpdateUserAttributes({
UserAttributes: [{
Name: 'phone_number_verified',
Value: 'true'
}, {
Name: 'email_verified',
Value: 'true'
}
// other user attributes like phone_number or email themselves, etc
],
UserPoolId: 'COGNITO_USER_POOL_ID_HERE',
Username: 'USERNAME'
}, function(err) {
if (err) {
console.log(err, err.stack)
} else {
console.log('Success!')
}
})
Currently, Cognito does not allow an external agent to update the email_verified and phone_verified attributes on behalf of the user. The only way these can be marked as true is through a code verification process which can be done by the end user. The exception to this is with admin level APIs, as answers below describe, but those shouldn't be done from client side.
The process is this: user signs-in and gets an access token. They then call GetUserAttrbuteVerificationCode API with the attribute they want to verify. This will deliver a code to the user, which can be used by calling VerifyUserAttribute which will flip the attribute as verified.
You can now programmatically set email_verified to true using the Pre-Signup lambda trigger and modifying the returned event with event.response.autoVerifyEmail = true;
It's not in the docs yet but referenced on this github issue. Also read working with cognito lambda triggers.
Here is the Another Approach you can use to create users by Agents.
You can Use AdminCreateUser on the Behalf of user. By calling this API user will be created with a temp Password which will be sent to the user Email Address. (i.e. User will be in Force_Change_Password state). Now use RespondToAuthChallenge API to change the Password.
Note: You need to set "email_verified" attribute in attribute List. to make sure user email will be verified.
Here is the Code Example in NodeJS:
var params = {
UserPoolId: process.env.userPoolId, /* required */
Username: email,//'STRING_VALUE', /* required */
DesiredDeliveryMediums: [
"EMAIL",
/* more items */
],
ForceAliasCreation: false,
UserAttributes: [{
Name: 'email_verified',
Value: 'True'
},/* any other Attributes*/],
};
cognitoidentityserviceprovider.adminCreateUser(params, function (err, data) {
if (err) {
console.log(err, err.stack);
reject(err); // an error occurred
}
else {
console.log(data);
resolve(data);
}// successful response
});
});
It was giving an error message: 'No email provided but email_verified was true', code: 'InvalidParameterException'.
So I added also email attribute into attributes list.
const params = {
UserPoolId: this.userPoolId /* required */,
Username: username /* required */,
TemporaryPassword: password,
DesiredDeliveryMediums: ['EMAIL'],
ForceAliasCreation: false,
UserAttributes: [
{
Name: 'email_verified' /* required */,
Value: 'true',
},
{
Name: 'email' /* required */,
Value: email,
},
],
};
then create the user with these params
cognitoidentityserviceprovider.adminCreateUser(
params,
(err, data) => {
console.log(data);
if (err) {
console.log(err);
reject(err);
throw new BadRequestException(err);
}
// an error occurred
else resolve(data); // successful response
},
);
Trigger on pre-registration this lambda function (Node.js v6):
exports.handler = function(event, context) {
event.response.autoConfirmUser = true;
event.response.autoVerifyEmail = true;
event.response.autoVerifyPhone = true;
context.done(null, event);
};
Using the "Configure test event" you can test it first with this payload
{
"version": 1,
"triggerSource": "PreSignUp_SignUp",
"region": "<region>",
"userPoolId": "<userPoolId>",
"userName": "<userName>",
"callerContext": {
"awsSdk": "<calling aws sdk with version>",
"clientId": "<apps client id>"
},
"request": {
"userAttributes": {
"email": "usertestsns06#yopmail.com"
},
"validationData": {
"k1": "v1",
"k2": "v2"
}
},
"response": {
"autoConfirmUser": false,
"autoVerifyEmail": false,
"autoVerifyPhone": false
}
}
Now when you create the user from the API those verifications flags should be true.
verify user email on aws cognito with python using boto3
response =client.get_user_attribute_verification_code(AccessToken='eyJraWQiOiJtTEM4Vm......',AttributeName='email')
response = client.verify_user_attribute( AccessToken='eyJraWQiOiJtTEM......', AttributeName='email', Code='230433')
Here is the Official Documentation.
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html
I would like to add programmatically few users and login with one of them in my meteor app. I could not find any methods to add users at server side; so I added two buttons at client side to generate users and login with one of them. I can create users (I see them in mogodb) but I cannot login, getting Error: Incorrect password [403]. What I am missing?
This is client.js code
Template.hello.events({
'click #createUsers': function () {
console.log("Creating users...");
var users = [
{ email: "dgra#gmail.com", username: "gra", name: "gra", roles: ['admin'] }
];
_.each(users, function (user) {
Accounts.createUser({
email: user.email,
password: "admin",
profile: { username: user.username },
profile: { name: user.name },
roles: user.roles
});
});
},
'click #logIn': function () {
console.log("logIn gra...");
Meteor.loginWithPassword("dgra#gmail.com", "admin", function (err) {
if (err) {
console.log("loginError: " + err);
}
});
}
});
I could not find any methods to add users at server side
You can add users from the server. As the docs point out, Accounts.createUser runs anywhere. Here is a working example:
server/initialize.js
var insertUser = function() {
var user = {
email: 'dgra#gmail.com',
username: 'gra',
name: 'gra'
};
Accounts.createUser({
username: user.username,
email: user.email,
password: 'admin',
profile: {
name: user.name
}
});
};
Meteor.startup(function() {
if (Meteor.users.find().count() === 0) {
insertUser();
}
});
A few points:
You can add only one profile object.
Accounts.createUser only takes the arguments shown in the docs, so you can't add arbitrary objects.
If you are trying to use roles, the example there shows the roles being added after the account is created.
In the code above, I only add the user if there are no users in the database. This is convenient for testing since the user will automatically be inserted after a meteor reset (no button pushing requred).