Changing Cognito-User-Pool/AWS-Amplify; leading to SignUp issue - ios

I am, handling some SignUp/SignIn process within an iOS app, using AWS-Amplify (and Cognito).
It was working fine, but then I decided to require a few more information when signing up.
Namely: name, given_name, family_name.
Here is the function called to authenticate:
func showSignIn() {
AWSAuthUIViewController
.presentViewController(with: self.navigationController!,
configuration: nil,
completionHandler: {
(provider: AWSSignInProvider, error: Error?) in
if error != nil {
print("Error occurred: \(String(describing: error))")
} else {
print("Identity provider: \(provider.identityProviderName)")
}
})
}
After I did the necessary manipulations (using amplify-cli) to remove the old user pool and make a new one. I recompiled my iOS app and launched it.
This was OK, but now when I want to sign up a user I get this message:
The message content is not surprising, since now I require the indicated fields.
But the problem is that I don't see any space in the UI where to input those new fields.
Did I forget to do something so that the UI could be updated adequately?
Or am I suppose to do something (to update the UI by hand) by modifying the function above? If YES, what is the way to make the change?
These are my first steps with amplify, I may well be making some basic mistakes.

I'm only using AWS Amplify with JavaScript, but in JS you do need to update the UI manually.
Here is the JS code and how I have to call it manually, maybe this helps.
handleSignUpPressed = async ({
emailAddress = '',
firstName = '',
lastName = '',
password = '',
phoneNumber = '',
wantsToImproveApp = true,
} = {}) => {
if (emailAddress && firstName && lastName && password && phoneNumber) {
try {
const res = await Auth.signUp({
username: emailAddress,
password,
attributes: {
email: emailAddress,
name: firstName,
family_name: lastName,
phone_number: phoneNumber,
},
});
console.log('success', res);
this.props.navigation.push('VerificationScreen', {
username: res.username,
});
} catch (err) {
console.log(err);
}
}
};

You can use AWSMobileClient to show the drop-in Auth https://aws-amplify.github.io/docs/ios/authentication#user-attributes which is using AWSAuthUIViewController underneath the covers.
I didn't see a way to customize it with SignInUIOptions for your use case. There is also an existing RFC to improve the usability of AWSMobileClient and the drop-in UI: https://github.com/aws-amplify/aws-sdk-ios/issues/1158
If you roll your own sign-up/sign-in flow, you can then pass in user attributes to AWSMobileClient.signUp: https://aws-amplify.github.io/docs/ios/authentication#user-attributes

Related

Parse - Delete another user as super admin from iOS app

I use back4app for my app, I would like to delete another user (not authorised user on this device).
The app throws this:
[Error]: User cannot be deleted unless they have been authenticated. (Code: 206, Version: 1.19.1)
which make sense to me if I am not a super admin of the product. But in case I have super admin rights I would like to remove a user from the system completely.
Is there any solution for this purpose? I've tried to find some function from Parse.Cloud code.
The idea was to create cloud code and execute it form the iOS device by calling smth like this:
PFCloud.callFunctionInBackground("deleteUserAsSuperAdmin",
withParameters: user id param here)
{ success, error) -> Void in
}
I have not found such a solution and for me it's a bit difficult to write such code in a right way using cloud code, for sure if this is an option.
You will have to create a cloud code function for that, and use useMasterKey option to delete the user. Something like:
Parse.Cloud.define('deleteUser', async ({ user, params: { userIdToDelete } }) => {
if (user) {
const query = new Parse.Query(Parse.Role);
query.equalTo('name', 'admin');
query.equalTo('users', user);
const count = await query.count({ useMasterKey: true });
if (count === 1) {
const userToDelete = new Parse.User();
userToDelete = userIdToDelete;
return userToDelete.destroy({ useMasterKey: true });
}
}
throw new Error('Not an admin');
});

How can I send a POST request to start a password reset flow using axios

I'm implementing the Forgot password feature using truevault API. Now, I've been testing the requests following the flow with Postman, and it works, but, when I started coding using axios, it keeps throwing issues about authentication. I've tried several combinations (logical ones, not just random craziness).
Also, worth mentioning that I was able to list my truevault users from UI (not only postman), and tried to mimic the same principle to the post request, but it didn't work
Here is the postman request that worked for me:
for the url request, method is: POST
url: https://api.truevault.com/v1/password_reset_flows
For the Authorization tab, I filled the "username" field with the truevault user API Key, and left the "password" field empty
And the "Body" tab, I filled it with a Json text, and for radio button options, I selected raw, and picked json as the format. (these are the only tabs being used)
The json body is as follow
{
"name":"XXXXX password reset",
"sg_template_id":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXcf42",
"sg_api_key":"XX.XXXXXXXXXXXXXXXXXXXXXX.XXXXXX_XXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXZftJo",
"user_email_value_spec":{
"system_field":"username"
},
"from_email_value_spec":{
"literal_value":"do-not-reply#XXXXXX.com"
},
"substitutions":{
"{{FIRST_NAME}}":{
"user_attribute":"first_name"
}
}
}
And the result was successful,
Now, when I tried with axios, I kept getting the auth error. Code is as follows:
createPasswordResetFlow()
{
axios.defaults.headers.common["Authorization"] = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27"; //tv user API KEY
axios.defaults.headers.post["Content-Type"] = "application/json";
var request = axios.post("https://api.truevault.com/v1/password_reset_flows",
{
auth:
{
username: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27',
password: ""
},
data:
{
"name": "XXXXX password reset",
"sg_template_id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXcf42",
"sg_api_key": "XX.XXXXXXXXXXXXXXXXXXXXXX.XXXXXX_XXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXZftJo",
"user_email_value_spec":
{
"system_field": "username"
},
"from_email_value_spec":
{
"literal_value": "do-not-reply#XXXXXX.com"
},
"substitutions":
{
"{{FIRST_NAME}}":
{
"user_attribute": "first_name"
}
}
}
})
.then((res) =>
{
console.log(res);
return res.data.users;
})
.catch(error =>
{
console.log('error', error);
return error;
});
}
As mentioned also earlier, I've been researching and trying, but to no avail, if someone could help me please.
There are two issues with the JS code you shared which are causing the problem:
The line where you set the default Auth header looks like this: axios.defaults.headers.common["Authorization"] = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27"; //tv user API KEY. Note that the Authorization header is being set to the API key, not an HTTP Basic Auth header value. If you want to set the default auth header this way, you need to set it to base64(API_KEY:) rather than just API_KEY.
According to the axios docs the post method has the signature .post(url, data, config). As a result, your code is POSTing a JSON object that looks like {auth: ..., data: ...}.
Try removing the line where you set the authorization header, and changing the post call to look something like this:
axios.post("https://api.truevault.com/v1/password_reset_flows",
{
"name": "XXXXX password reset",
"sg_template_id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXcf42",
"sg_api_key": "XX.XXXXXXXXXXXXXXXXXXXXXX.XXXXXX_XXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXZftJo",
"user_email_value_spec":
{
"system_field": "username"
},
"from_email_value_spec":
{
"literal_value": "do-not-reply#XXXXXX.com"
},
"substitutions":
{
"{{FIRST_NAME}}":
{
"user_attribute": "first_name"
}
}
}
}, {
username: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX27',
password: ""
})

Custom authentication integration with parse-server and auth0

I would like to use auth0.com in conjunction with the open source-parse server.
My current approach is to obtain the token from auth0 by using their standard login through the Lock library for iOS. With that token I would like to call a custom authentication method on my parse-server, that checks whether the token is valid and if it is will log in the user.
My problem is that there is almost no documentation on writing custom oauth for parse-server.
So far, I have this code for my custom auth.
var Parse = require('parse/node').Parse;
function validateAuthData(authData, options) {
console.log('validateAuthData()');
return new Promise((resolve, reject) => {
try {
var decoded = jwt.verify(authData.access_token, opions.sharedSecret);
if (authData.id === decoded.sub) {
resolve({});
}
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Unauthorized');
} catch(e) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, e.message);
}
});
}
function validateAppId(appIds, authData) {
console.log('validateAppId()');
return Promise.resolve();
}
module.exports = {
validateAppId: validateAppId,
validateAuthData: validateAuthData
};
However, it doesn't work and also I don't understand how this code can be used to authenticate a specific user. Does the parse-server do database look-ups to match the specific auth data to a specific user? Also, how can I register a new user with custom auth. What happens when a user tries to log in but he doesn't exist yet in my parse database?
An alternative seems to be this, using a rule an auth0.com. What are the differences and how would the rule work? I have very little experience with authentication and oauth and jwt's.
Lastly, I am using this to call my custom auth from my iOS client. However this doesn't work either, but I am not sure whether it is due to the iOS part or because my custom auth isn't working yet.
In conclusion, I am having trouble with something that seems rather easy. I want to use auth0 as my authentication provider and I want to integrate it was the parse-server, since I really appreciate the convenience around parse and the client sdk's. I am fairly certain that more people have a similar problem, however I have not found any definitive resource on how to properly do this.
Further Links
Parse user authenticated using Auth0
https://auth0.com/blog/2016/03/07/hapijs-authentication-secure-your-api-with-json-web-tokens/
https://github.com/ParsePlatform/parse-server/wiki/OAuth
https://jwt.io/introduction/
late answer but I was solving the same problem and came across this post:
Auth0 has rules you can apply that run when the login occurs. I've modified their example one from https://github.com/auth0/rules/blob/master/src/rules/parse.js, extracting the API endpoint into a constant.
function(user, context, callback) {
// run this only for the Parse application
// if (context.clientID !== 'PARSE CLIENT ID IN AUTH0') return callback(null, user, context);
const request = require('request');
const MY_API = 'https://subdomian.back4app.io';
const PARSE_APP_ID = '*********';
const PARSE_API_KEY = '**********';
const PARSE_USER_PASSWORD = 'REPLACE_WITH_RANDOM_STRING'; // you can use this to generate one http://www.random.org/strings/
const username = user.email || user.name || user.user_id; // this is the Auth0 user prop that will be mapped to the username in the db
request.get({
url: `${MY_API}/login`,
qs: {
username: username,
password: PARSE_USER_PASSWORD
},
headers: {
'X-Parse-Application-Id': PARSE_APP_ID,
'X-Parse-REST-API-Key': PARSE_API_KEY
}
},
function(err, response, body) {
if (err) return callback(err);
// user was found, add sessionToken to user profile
if (response.statusCode === 200) {
context.idToken[`${MY_API}/parse_session_token`] = JSON.parse(body).sessionToken;
return callback(null, user, context);
}
// Not found. Likely the user doesn't exist, we provision one
if (response.statusCode === 404) {
request.post({
url: `${MY_API}/users`,
json: {
username: username,
password: PARSE_USER_PASSWORD
},
headers: {
'X-Parse-Application-Id': PARSE_APP_ID,
'X-Parse-REST-API-Key': PARSE_API_KEY,
'Content-Type': 'application/json'
}
},
function(err, response, body) {
if (err) return callback(new Error('user already exists'));
// user created, add sessionToken to user profile
if (response.statusCode === 201) {
context.idToken[`${MY_API}/parse_session_token`] = body.sessionToken;
return callback(null, user, context);
}
return callback(new Error(username + ' The user provisioning returned an unknown error. Body: ' + JSON.stringify(body)));
});
} else {
return callback(new Error('The login returned an unknown error. Status: ' + response.statusCode + ' Body: ' + body));
}
});
}
I'm writing a SPA in JS, so I have some client side code that handles the Auth0 login, (replace 'https://subdomian.back4app.io' with your own parse server's API address - the same value as used in the above Auth0 rule). Note the Parse.User.become function, which assigns the session id created in the Auth0 rule to the current parse User:
handleAuthentication() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
Parse.User.become(authResult.idTokenPayload['https://subdomian.back4app.io/parse_session_token']);
history.replace('/');
} else if (err) {
history.replace('/home');
console.log(err);
}
});
}

parse swift add new user to existing role

Can some one just confirm that in order to add a user to a existing role the role needs to have public read & write access ?
as this seems to be the only way i can get it to work?
Code to create the Role (Working Fine)
let roleACL = PFACL()
roleACL.setPublicReadAccess(true)
//roleACL.setPublicWriteAccess(true)
let role = PFRole(name: "ClubName", acl:roleACL)
role.saveInBackground()
Code to add user to said Role (Works If write access set to public)
let QueryRole = PFRole.query()
QueryRole!.whereKey("name", equalTo: "ClubName")
QueryRole!.getFirstObjectInBackgroundWithBlock({ (roleObject: PFObject?, error: NSError?) -> Void in
if error == nil
{
let roleToAddUser = roleObject as! PFRole
roleToAddUser.users.addObject(user)
roleToAddUser.saveInBackground()
//print(roleObject)
}
else
{
print(error)
//print(roleObject)
}
})
the above code works but as i said only when the public write access to the role has been set true.
this is driving me crazy now
also IF the role is meant to have the public write access doesn't that make it vulnerable to someone changing the role?
if the role shouldn't have public write access then can someone point me in the right direction to get the above code working without setting the role with public write access.
the error i get if there is no public write access on the role is: object not found for update (Code: 101, Version: 1.8.1)
Why not perform all the work in cloud code instead, that will get you around the issue of read/write issue. Here is what I am doing.
Important to note: The code below would not work when the cloud code JDK was set to 'latest', I had to set it to JDK 1.5 and then redepled my cloud code.
Parse.Cloud.afterSave(Parse.User, function(request) {
Parse.Cloud.useMasterKey();
var user = request.object;
if (user.existed()) {
//console.log('object exits');
response.success();
// console.log('********return after save');
return;
}
// set ACL so that it is not public anymore
var acl = new Parse.ACL(user);
acl.setPublicReadAccess(false);
acl.setPublicWriteAccess(false);
user.setACL(acl);
user.save();
//add user to role
var query = new Parse.Query(Parse.Role);
query.equalTo("name", "signedmember");
query.first().then(function(object) {
if (object) {
object.relation("users").add(request.user);
object.save(null, {
success: function(saveObject) {
object.relation("users").add(request.user);
object.save(null, {
success: function(saveObject) {
// The object was saved successfully.
console.log('assigned user to role');
},
error: function(saveObject, error) {
// The save failed.
console.error("Failed creating role with error: " + error.code + ":"+ error.message);
}
});
},
});
}
});
});

full email validation on Meteor using Mandrill

I have read several SO posts about using Mandrill with Meteor.js for email validation, yet I've found a problem no others seem to face.
Ultimately, I want the verified property of a user to be set to true after clicking the email validation url. I am using Mandrill to send customized email templates containing a verification_url. I have the accounts-password and accounts-ui packages added. My code looks like this:
if (Meteor.isServer) {
Meteor.startup(function () {
Mandrill.config({
username: process.env.MANDRILL_API_USER,
key: process.env.MANDRILL_API_KEY
// port: 587, // defaults to 465 for SMTP over TLS
// host: 'smtp.mandrillapp.com', // the SMTP host
// baseUrl: 'https://mandrillapp.com/api/1.0/' // update this in case Mandrill changes its API endpoint URL or version
});
Accounts.config({
sendVerificationEmail: true
});
Accounts.emailTemplates.verifyEmail.html = function (user, url) {
var referralCode = Random.id();
var result;
try {
result = Mandrill.templates.render({
template_name: 'email-verification',
template_content: [],
merge_vars: [
{
name: 'SUBJECT',
content: 'my fancy subject'
},
{ name: 'EMAIL',
content: 'my fancy email'
},
{
name: 'VERIFICATION_URL',
content: 'http://localhost:3000/?ref=' + referralCode
}
]
});
} catch (error) {
console.error('Error while rendering Mandrill template', error);
}
return result.data.html;
};
});
When I create a user the verification email is correctly sent, however when I click the verification link within the email, nothing is done on the server, i.e. I look at my app's MongoDB and see on the user document still have the property verified: false. I've tried to work with onEmailVerificationLink (http://docs.meteor.com/#/full/Accounts-onEmailVerificationLink) but I get an error in the console saying onEmailVerificationLink has already been called, which happens because accounts-ui is apparently calling it for me. How do I do proper email verification in Meteor.js using Mandrill?
Finally figured it out. Instead of the line
content: 'http://localhost:3000/?ref=' + referralCode
I should replace it with
content: url
since Meteor is already creating the validation url for me, and passing it in through the "url" argument of the function. Clearly I didn't need referralCode either

Resources