I have been changing user roles name on wordpress how ever
If i call
implode(', ', $user->roles)
I still get the original role names, Administrator, Subscriber, etc.
So, i figured something like this would be the correct way.
if(implode(', ', $user->roles) = "administrator"){
$role = "Site owner";
}
else{
$role = "User";
}
echo $role;
I am running this for each user,how ever this does not work.
What should i be doing to change the names? the backend presents the name correctly. how ever i wish to have the names on the front end for the users accounts.
More specifically, a user's role can be set by creating an instance of the WP_user class, and calling the add_role() or remove_role() methods.
Example
Change a subscribers role to editor
// NOTE: Of course change 3 to the appropriate user ID
$u = new WP_User( 3 );
// Remove role
$u->remove_role( 'subscriber' );
// Add role
$u->add_role( 'editor' );
Hopefully that's more helpful than my initial response, which wasn't necessarily as helpful.
Related
I'm creating an application in Symfony 3, that has the following structure:
class Account {
private $id;
private $name;
}
class User {
private $id;
private $email;
private $password;
}
class UserAccount {
private $id;
private $userId;
private $roles;
}
As we can see an user can belong to several accounts with different roles for each account, let's say that for Account 1 it has the role ROLE_ADMIN, and for the Account 2 it has the role ROLE_EDITOR.
The problem is that the user will have a select box where he can change the account, this means that the role needs to be loaded from the database based on a value on session ( since the account ID ) will be set on session.
This also means that when an user logins into the site, there will be no role, since the role is determined by the account selected.
I have tough about using events, but that doesn't seem to work from what I've read.
Does anyone has any thoughts/insights into this?
I have my own custom Authenticator, since I need to support both MD5 and bcrypt passwords.
This means that I have a class that extends SimpleFormAuthenticatorInterface of Symfony, this allows me to have the users login with MD5 and automatically upgrade them to bcrypt.
My User model ( which is an normal one ), and Custom Authenticator: Gist
To sumarize: I need a way in which I can change the roles of the user after he has logged in, without forcing the re login of the user.
So after two days of struggle, here is the solution.
Looking at the question, when the user logins it needs to take a role determined by what is in the UserAccount table, since an user can have several accounts associated to him, the only way to solve this was to first create a post login listener:
/**
* On login
*
* #param InteractiveLoginEvent $event The login event
*
* #return void
*/
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {
$user = $this->tokenStorage->getToken()->getUser();
// get the user accounts of the current from the database
$accountsOfUser = $this->em->getRepository('AppBundle\Entity\AccountHasUser')->getAccountsOfUser($user->getId());
foreach ( $accountsOfUser as $accountOfUser ) {
$this->session->set('accountid', $accountOfUser['account_id']);
$user->resetAndAddRole('ROLE_' . $accountOfUser['const']);
break;
}
// We just need to set the new security token
$token = new UsernamePasswordToken(
$user,
null,
'main',
$user->getRoles()
);
// Update the current token to set the new role
$this->tokenStorage->setToken($token);
}
I known that I can only get one record from the database, but this was just for show ( don't blindly copy/paste this to your code ).
So basically I get the first account of the user, get it's role, put the account id on the session ( still got to read a bit more about bags on Symfony sessions ), and procede to generate a new UsernamePasswordToken and adding it to the tokenStorage.
The $user->resetAndAddRole, is a function in my User Model, that has only the following:
/**
* Resets current user roles and add's the new one
*
* #param string $role The role to add
*
* #return AppBundle\Entity\User
*/
public function resetAndAddRole($role) {
$this->roles = array($role);
return $this;
}
Now I also need to allow the user to change between accounts when is logged in, so in a controller:
public function changeAccountAction(Request $request, $id) {
$user = $this->get('security.token_storage')->getToken()->getUser();
$em = $this->getDoctrine()->getManager();
$newAccountRole = $em->getRepository('AppBundle\Entity\AccountHasUser')->getAccountModelByAccountIdANdUserId($id, $user->getId());
$user->resetAndAddRole('ROLE_' . $newAccountRole['const']);
$token = new UsernamePasswordToken(
$user,
null,
'main',
$user->getRoles()
);
// Update the current token to set the new role
$this->get('security.token_storage')->setToken($token);
$this->get('session')->set('accountid', $id);
// $em = $this->getDoctrine()->getManager();
// $accountsList = $em->getRepository('AppBundle\Entity\AccountHasUser')->getAccountsOfUser($user->getId());
// We need to change the users roles right here and how to we do it?
// We simply change the
return new RedirectResponse($this->generateUrl('dashboard'));
}
Basically, get the account that is passed by parameter, change the session value, so we can use this in our queries and every other code that requires the account id, and then create a new UsernamePasswordToken and voilá everything starts to work perfectly.
Later on I'm going to move the code on the controller to a service, which will also be passed to the post login listener, so that way I only have one play to make the changes to.
I really don't know if this is the right way to do this, but for now it seems to work.
In my web application using codeigniter, I stored role data that I have query from database before in session.
$role = $this->session->userdata('role');
And in every model or controller, i always use this variabel ($role) to manage user behaviour in my web.
Such as
if($role==1)
{
//Behaviour for admin.
}
else if($role==2)
{
//Behaviour for general user
}
else
{
//Do something
}
My problem : If many users login to my system, the session data always lost without click logout before. Thanks.
FOR YOUR INFORMATION :
I have store the role in database, but for easy way the value of role that i've get before, I stored it in session. FOr the easy solution. Thanks.
Store the role in the database in a users table. I have 4 roles in my application student, staff, admin, president.
You then would query the database on the username that was entered,
if the role = 1 then send to the appropriate page.
Sort of like this :
$sql = "SELECT * FROM users WHERE username = :username AND role = 1";
$role = $this->db->conn_id->prepare($sql);
$role->bindParam(':username', $username);
$role->execute();
if ($role) {
if ($role->rowCount() == 1) {
return TRUE;
}
}
then in the controller do
if ($this->yourmodel->yourfunction($yourvariable)) { // Checks if the query above returns TRUE!
redirect(to what ever page you want)
}
I'm trying to get a logged in users type (eg super admin, registered). I've tried this code:
$user =& JFactory::getUser();
$curref = $user->usertype();
Which gives a function not found error. What is the correct way to get the user type name, without a db query if possible.
You just need to treat usertype as a member, not a method.
$type = $user->usertype;
Documentation: http://docs.joomla.org/Accessing_the_current_user_object
You can take a look at the $user object structure by doing a var_dump. Try this, and inspect the output:
var_dump( $user );
So if you want to iterate over the groups array, you could do the following:
$groupIDs = array();
foreach( $user->groups as $groupID ){
$groupIDs[] = $groupID;
}
var_dump( $groupIDs );
You can also use some joomla methods to return the groups in different ways. You may want to check out this forum thread: http://forum.joomla.org/viewtopic.php?t=530721
When my users log into the website their first name, last name and ID are missing from the session data because my session data is coded to take post data and submit into the session table in my database.
Because user logs in with email and password in my session data only email appears and nothing else does.
How can I make first name, last name and id appear in my session table in my db? I want to some how grab these details from the database when user is logging in and provide it in my $u_data array so it get's posted upload login success.
Here is my code:
<?php
class Login_Model extends CI_Model {
public function checkLogin() {
$this->db->where('email', $this->input->post('email')); //compare db email to email entered in form
$this->db->where('password', $this->hashed()); //compare db password to hashed user password
$query = $this->db->get('users'); //get the above info from 'user' table
if ($query->num_rows() == 1) { //if number of rows returned is 1
$u_data = array( //new variable with session data
'user_id' => $this->db->insert_id(),
'email' => $this->input->post('email'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'logged_in' => TRUE
);
$this->session->set_userdata($u_data); //send data from variable to db session
return TRUE;
} else {
return FALSE;
}
}
public function hashed() { //hashing method
// sha1 and salt password
$password = $this->encrypt->sha1($this->input->post('password')); //encrypt user password
$salt = $this->config->item('encryption_key'); //grab static salt from config file
$start_hash = sha1($salt . $password);
$end_hash = sha1($password . $salt);
$hashed = sha1($start_hash . $password . $end_hash);
return $hashed;
}
}
If you're tracking sessions in your DB, two solutions come to mind.
First, you could select the first/last from the user table and insert it into the session table. This requires changes to your application.
Second, you could set up a view for your application, in which the session table is automatically joined with the appropriate user, but that assumes you already have some unique identifier for which user it is in the session (was that the email address?*). This solution would not require any changes to the application code, but would require changes to the DB, which may be the preferred method depending upon your deployment requirements (or it may not :) ).
* as a side note, if you're using email addresses for unique identifiers, be aware that some people share email addresses as you decide if this is the right solution for you.
It'd be as simple as doing something like:
session_start();
$_SESSION['userdata'] = $u_data;
within your CheckLogin method. The session is just a regular PHP array that happens to be automatically preserved for you. You can put anything you want into it, but you do have do put things into it yourself - PHP won't do it for you.
comment followup:
gotcha. So, you simply modify you class to fetch that information from the DB once the login's authenticated. I don't know how your DB class works, but instead of merely checking if there's a matching row, fetch the first/last name, using a query something like this:
select firstname, lastname
from users
where email=$email and password=$password
If you get a result row, you know it's a valid login, and then you just retrieve the name data. I have no idea how your db class works, but it shouldn't be too hard to get it to do that.
When I'm working with Auth systems in CodeIgniter I have made it a practice to include the "user" object globally in views, and also globally in my controllers, by fetching the userdata in the constructor, like so...
<?php
class My_Controller extends Controller {
private $the_user; //global var to store current user data
function My_Controller() {
parent::Controller();
$data->the_user = $this->ion_auth->get_user(); //get user data
$this->load->vars($data); //load into all views as $the_user "$the_user"
$this->the_user=$data->the_user; //load into private class variable "$this->the_user"
}
At that point $the_user variable object is available in all views by default AND $this->the_user is always available to controller functions. It always represents the user currently logged in.
I am using Ion_auth for authentication and fetching the user, so that piece you would have to fill in.
I actually just constructed a "How-to" to implement extended Controller classes so all the Auth logic is automatically inherited to all "protected" Controllers.
The following solved this issue for me. I looked at one of my old questions on here and used my common sense.
I made this edit to my code.
if ($query->num_rows() == 1) { //if number of rows returned is 1
$user = $query->result();
$u_data = array( //new variable with session data
'user_id' => $user[0]->id,
'email' => $this->input->post('email'),
'first_name' => $user[0]->first_name,
'last_name' => $user[0]->last_name,
'logged_in' => TRUE
);
I am trying to get the name of the role of the currently logged in admin. I can get the admin user, but I can't figure out how to query their role name. The Magento docs are weak =/
$usr = Mage::getSingleton('admin/session')->getUser();
Ideas anyone?
Spoke too soon... I got the role name as follows:
$roleId = implode('', Mage::getSingleton('admin/session')->getUser()->getRoles());
$roleName = Mage::getModel('admin/roles')->load($roleId)->getRoleName();
Using this code you will get the role of current user
$admin_user_session = Mage::getSingleton('admin/session');
$adminuserId = $admin_user_session->getUser()->getUserId();
$role_data = Mage::getModel('admin/user')->load($adminuserId)->getRole()->getData();
$role_name = $role_data['role_name'];
Mage::getSingleton('admin/session')->getUser()->getRole()->getRoleName();
M.
Here's another one that may be a little friendlier:
$acl = Mage::getResourceModel('admin/acl')->loadAcl();
$acl->isAllowed($user->getAclRole(), 'admin/foo/bar'));
That will return a boolean. $user is an admin/user object.