Updating a User (not the logged in User) in Appcelerator - appcelerator

I want to enable an admin. user to update User info (e.g. First Name, Last Name, etc.) I have a List View of Users...when admin User selects one of the Users to update, details are shown, but actual update is applied to Admin User. Not the User I'm trying to Update.
function updateUser() {
Cloud.Users.update({
// Id of User to Update
id : userId,
first_name : firstNameValue.value,
last_name : lastNameValue.value,
}, function(e) {
if (e.success) {
var user = e.users[0];
//alert('Success:\n' + 'id: ' + user.id + '\n' + 'first name: ' + user.first_name + '\n' + 'last name: ' + user.last_name);
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
};

As stated in the docs, Cloud.User.update
Update the current user.
This should explain why your code is updating the admin user.
But I also found in the documentation for Users: Update Current User the following parameter
su_id : String [ADMIN-ONLY]
User ID to update this user on behalf of.
The current login user must be an application admin to update a user
on behalf of another user.
I would try with it. (BTW I never used it, but still I hope it could help you)

Related

How do I delete only the selected data?

When I select a user and an item that a user is using and press the button, I want only that item to disappear. However, the code I created now removes all items the User has.
When adding selected data, I inserted and saved using .add and .save. But I don't know how to delete and save it.
-- spring boot (controller)
#PutMapping(value = {"/users/{id}", "/profileModi/{id}", "/users/productSetting/{id}"})
public ResponseEntity<User> updateUser(#PathVariable("id") long id, #RequestBody User user) {
Optional<User> userData = userRepository.findById(id);
if (userData.isPresent()) {
User _user = userData.get();
_user.setProductInfo(user.getProductInfo());
_user.setRoles(user.getRoles());
_user.setUsername(user.getUsername());
_user.setEmail(user.getEmail());
_user.setPassword(user.getPassword());
_user.setDelYn(user.isDelYn());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
-- vue.js
<b-button variant="danger" class="btn btn-fw"
#click="updateProductUser()"
>
cancle
</b-button>
--vue.js (script)
updateProductUser() {
var data = {
id:this.currentUser.id,
email:this.currentUser.email,
delYn:this.currentUser.delYn,
password:this.currentUser.password,
username:this.currentUser.username,
roles:this.currentUser.roles
};
ProductSettingUserDataService.update(this.currentUser.id, data)
.then(response => {
this.currentUser = response.data;
console.log(this.currentUser);
})
.catch(e => {
console.log(e);
});
},
Originally, there was a productInfo table in the User table, and I used a simple method of deleting data by not writing this table. But now I only want to delete one of the data of the productInfo I have selected.
Can you tell which code should be inserted in the controller to be deleted and saved?
I also tried with #DeleteMapping. But it failed...
Relationship table between user and product
As you can see in the picture, User and productInfo have a 1:n relationship. For example, I want to delete only product_id = 12 out of 3 products with user_id = 1.
++ users Table
users
++ productInfo Table
productInfo
The productInfo table exists in the users table.
++ console window
console
Your controller is replacing all the data from the user and your vue.jsscript is not sending product data:
// Data sent by the front
var data = {
id:this.currentUser.id,
email:this.currentUser.email,
delYn:this.currentUser.delYn,
password:this.currentUser.password,
username:this.currentUser.username,
roles:this.currentUser.roles
};
// Controller PUT
User _user = userData.get();
// The front is not sending any productInfo
_user.setProductInfo(user.getProductInfo());
_user.setRoles(user.getRoles());
_user.setUsername(user.getUsername());
_user.setEmail(user.getEmail());
_user.setPassword(user.getPassword());
_user.setDelYn(user.isDelYn());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
Since you are not sending product info, the previous product info is deleted. Your front need to send the product info data that you want to preserve.
let me see user table's data. i guess that your userInfo and your productInfo share one table; If you have a productinfo table, you shoud transfer a productId from vue page instead of userId

Need to create a controller that deactivates a user.

The following code is the deactivate method:
#RequestMapping(method=RequestMethod.POST, value = "/deactivate")
public boolean deactivateAccount(#RequestBody SomeReqBean someReqBean) {
//code already finished
}
I am looking to see how I can go about creating a controller that will allow me to deactivate a user upon request from a submit button.
For what I understood from your question is that you want to deactivate a user after clicking on submit button.
There're several ways to do that.
The simpler way is that :--
1.) Create a column in your user table by the name 'status' (or anything you want)
2.) When you're creating a user save the value of that 'status' column to 1 for that userID (status = 1 means, this user is currently in active state)
3.) Now, when you want to deactivate that user, simply update that 'status' value to 0
So, your code will be something like this :---
#RequestMapping(method=RequestMethod.POST, value = "/deactivate")
public boolean deactivateAccount(#RequestBody String user_id) {
boolean statusFlag = your further query to update user's status field in DB to 0
if(statusFlag){
//means status is successfully updated in DB
return true;
}else{
return false;
}
}

How to refresh variables in react-apollo

Here is the scenario :
USER 1
1) Goes to login page
2) Writes email and password which are sent to the server by a mutation
3) Authentication OK -> the server returns a token and user informations (id, firstName, lastName)
4)The token and each user information are stored in a separate key in local storage
5) The user is redirected to the HomePage
6) The user goes to Profile Page
7) A query is sent to the server to retrieve all the informations about that user (thanks to the user id stored in local storage)
Here is the query :
const PROFILE_QUERY = gql`
query profileQuery($id: ID!) {
getUser(id: $id) {
firstName
lastName
email
}
}
`;
export default graphql(PROFILE_QUERY, {
options: {
variables: {
id: localStorage.getItem("id")
},
errorPolicy: "all"
}
})(ProfilePage);
8) The server returns the informations and the user can see them in the Profile Page
9) The user decides to logout
So everything is working for the first user, now a second user arrives at the same computer and the same browser.
USER 2
Same steps than the previous user from 1 to 7
The query sent to the server to retrieve user informations is not working because the id sent by the query is the id of the previous user (and a user is not allowed to retrieve informations about an other user)
If I do a browser refresh the query is sent with the good user id...
So why the id variable is not refreshed (seems like the id value in local storage is not read) at the first attempt ? How can I resolve this ?
Thank you for your help.
That happens because your options field is static and is evaluated when the file containing the query is first loaded. (I'm assuming somewhere, perhaps steps 3 or 4, the id in local storage is updated correctly for the second user.)
config.options can be an object like the one you are passing now or a function that is evaluated when needed by the query.
So to load the id from the localStorage each time instead of just once, you can do something like this:
options: () => ({
variables: {
id: localStorage.getItem("id")
},
errorPolicy: "all"
})
Then first user logged out, you need to reset Apollo store and clear local storage.

Send 2 different types of mails using mailchimp

I have a set of internal users for my project. Admin can activate/deactivate them. I want to send them a mail saying "your account has been deactivated" when their account is deactivated by admin. Similarly they should receive a mail saying "your account has been activated" when admin activates their account. How can I do this?
I am trying by creating 2 separate lists in mailchimp and two separate campaigns. but when I'm writing mailchimps credentials in my development.js with 2 separate list ids and then trying to get it in my javascript file,it is getting undefined (checked by console.log)..
Is there a way to do it by just single campaign/list?
Here's my development.js code of mailchimp credentials:
mailchimp: {
api_key: "***************-***",
list_id1: "*********", //internal users
list_id2: "*********" //internal deactivated users
},
my user.helper.js
const config = require('../../config/environment');
const Mailchimp = require('mailchimp-api-3');
const mailchimp = new Mailchimp(config.mailchimp.api_key);
exports.addToDeactivatedList = function (email, name) {
console.log(mailchimp.list_id1);
mailchimp.members.create(config.mailchimp.list_id1, {
email_address: email,
merge_fields: {
FNAME: name
},
status: 'subscribed'
}).then(user => { }).catch(e => {
console.log("deactivate list me add ho gya");
})
}
exports.addToActivatedList = function (email, name) {
console.log(mailchimp.list_id2);
mailchimp.members.create(config.mailchimp.list_id2, {
email_address: email,
merge_fields: {
FNAME: name
},
status: 'subscribed'
}).then(user => { }).catch(e => {
console.log("activate list me add ho gya");
})
}
and my user.controller.js (selective part only)
var helper = require('./user.helper');
.
.
if(req.body.status != user.status){
(req.body.status == "active") ? helper.addToActivatedList(user.email, user.name) : helper.addToDeactivatedList(user.email, user.name);
}
All the help will be appreciated. THANKS
I'd try to put everyone in the same list, and then create segments based on that list. After that, create a campaign based on that segment.
You could for instance create a custom list attribute that records wether or not an account is activated and create a segment based on that attribute. The campaign should then be based on that segment.
Perhaps also record the date an account has been activated or deactivated by the admin in another custom attribute and use that to check if a user already had an activation/deactivation mail.
MailChimp offers a feature for situations like this called automations. Automations allow you to send individual emails to subscribers when an event is triggered. So instead of creating separate campaigns every time a user is activated or deactivated, you can use just two automations and a single list.
Whether a user is active or not can be tracked with list merge fields. To do this, you'll need to add a new text merge field to your list. Let's name the field label 'Active'. Uncheck the 'Visible' checkbox so the user can't see it, and name your merge field something like 'ACTIVE'. You can use values like yes/no or true/false to identify the users by their active status.
Next, create your automations, one for activated users and one for deactivated users. You can set a trigger to send the email when a list field value is changed. So just make each of your two automations send the emails when the 'Active' list field values change to either 'yes' or 'no'.
Then all you need to do with the API is subscribe users to a single list whenever their accounts are activated or deactivated. Just make sure the new 'ACTIVE' merge field is set to 'yes' or 'no' when you do this, and any addresses already subscribed will be updated with the new value. So your mailchimp.members.create() would look something like this, based on the example from here:
mailchimp.members.create(<list_id>, {
email_address: <user_email>,
merge_fields: {
FNAME: name,
ACTIVE: 'yes' //Or 'no' if being used for deactivated users
},
status: 'subscribed'
})

ACL works in playground?

Could you please let us know if ACL works in playground ??
I want to create a rules, where owner of the asset can only modify the rules. I tried in playground by,which is not working
I created file as an asset and supplier as the owner of the asset. Then, created asset called file1 attached the supplier1 as the owner. When i am performing the submit transactions, Supplier2 can also modify the transactions. IS my rule are not valid ?? Do i need to some more ruless ??
/**
* New model file
*/
namespace org.acme.model
enum TransactionState {
o CREATED
o VERIFIED
}
asset File identified by fileId {
o String fileId
o String data
--> Supplier owner
o TransactionState state
}
participant Supplier identified by supplierId {
o String supplierId
o String emailId
o String details
}
transaction DataValidate {
--> File asset
o TransactionState state
--> Supplier supplier
}
/**
* Data Validation by Supplier
* #param {org.acme.model.DataValidate} dataValidate - the DataValidate transaction
* #transaction
*/
function DataValidate(dataValidate) {
dataValidate.asset.state = dataValidate.state;
return getAssetRegistry('org.acme.model.File')
.then(function (assetRegistry) {
return assetRegistry.update(dataValidate.asset);
});
}
rule Rule1 {
description: "can perform ALL operations , IF the participant is owner of the asset"
participant(m): "org.acme.model.Supplier"
operation: ALL
resource(v): "org.acme.model.File"
condition: (v.owner.getIdentifier() == m.getIdentifier())
action: ALLOW
}
rule Member {
description: "Allow the member read access"
participant: "org.acme.model.Supplier"
operation: READ
resource: "org.acme.model.*"
action: ALLOW
}
My criteria, data validation should be done only by the owner of the file, not others. how to handle it
To answer your main question - Yes the ACL file does work in the Online Playground, I have it working for one of my applications. If you are not referring to the online playground I'm not sure if the rest of my answer helps.
If you are using the online Playground presume that you've gone to the top right where it says 'admin' and created new identities and issued those to participants? If not you can do so by:
Clicking 'admin' in the top right of the playground
'+ Issue New ID'
Supply a User ID (whatever you like) and participant (will be one you created earlier) and then press 'Create New'
Select Option 2: '+ Add to my Wallet' (This will allow you to then use the identity and you will 'be' that participant
The reason I ask is that even with your ACL file working, if you remain as the 'admin' identity you can still view/do everything you want.
Another thing, could you try '===' instead of '==' in your Rule1? The two rules make sense, and from looking at it, all users can view, but an error would be raised if anyone except the owner tries to validate that asset because it requires UPDATE permissions which are not granted.
Hope this helps.

Resources