FosUser, Create a user manually - ajax

For a special case in my application, i need to register a user manually from an ajax request.
So, first i send with ajax all my datas : firstname, lastname, mail, password etc... to my controller.
For now, after that, i just do in my controller :
$firstname = $request->get('firstname');
$lastname = $request->get('lastname');
$mail = $request->get('mail');
$password = $request->get('password');
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->createUser();
$user->setUsername($firstname.$lastname);
$user->setPlainPassword($password);
$user->setEmail($mail);
$user->setFirstname($firstname);
$user->setLastname($lastname);
$userManager->updateUser($user);
But my problem, how can i validate the user before updateUser() ? I need to check manually if this email/username already exist ?
How can i do that with a better way ?

You can check if the email arealdy exists with the findUserByEmail method just before the updateUser :
$user = $this->get('fos_user.user_manager')->findUserByEmail($mail);

Related

how to session()->forget('cart') for another user in laravel?

my session driver is set to database,
.env => SESSION_DRIVER=database
I have made a model for session and I access to a session of another user by user_id like this :
use App\Models\Session;
$payload = Session::where('user_id', $request->user_id)->pluck('payload');
$payload = unserialize(base64_decode($payload));
if (!isset($payload['cart'])) {
dd($payload['cart']);
}
now I want to session()->forget('cart') of that specific user not the current user, but the payload field is decode by base64 and serialized.
how to do that?
thanks
I tried a few things and by changing the id it works :
// Get the store from laravel (encrypted or not)
$store = session()->getDrivers()['database'];
// Change the id
$store->setId($id);
// Start the session
$store->start();
// Remove the item
$store->pull('cart');
// Save the session in database
$store->save();
i don't think it's something that laravel support, so this might break in the future
Yes I found it.
the problem is to displacement of serialize() and base64_encode() after unset($payload['cart']) like this:
use App\Models\Session;
$session = Session::where('user_id', $request->user_id)->first();
$payload = unserialize(base64_decode($session->payload));
if (!isset($payload['cart'])){
unset($payload['cart']);
}
$session->payload = base64_encode(serialize($payload));
$session->save();

How to access variables from database in Email class?

I need to set SMTPUser, Pass and Host in Email Class as variables taken from MySQL database. I can set them in Controllers like this:
$configModel = new ConfigModel();
$config = $configModel->where('id', 1)->find();
$user = $config[0]['mail_user'];
$pass = $config[0]['mail_pass'];
$server = $config[0]['mail_server'];
but how to use them in Email Class? Should I set them as some session variables and access them in Email class? Is it safe?
Additionaly, I've also tried doing email initialization in my Controller like this:
$emailConfig['SMTPUser'] = $user;
$emailConfig['SMTPPass'] = $pass;
$emailConfig['SMTPHost'] = $server;
$emailConfig['SMTPPort'] = 465;
$emailConfig['SMTPCrypto'] = 'ssl';
$emailConfig['protocol'] = 'smtp';
$email->initialize($emailConfig)
but it gives me error:
Sender address rejected: need fully-qualified address
So logging to email is successful, but it cannot sent mails for some reason. Is this option missing some configuration?
I'd rather use default Email Class provided by CI4 with database variables.

How to make login as other user in API using laravel passport?

I am using laravel passport for API authentication. and I want to log in as different users with different roles from superadmin. So how can I achieve this? Please give your suggestions.
public function masqueradeNotary($profileId)
{
$userId = decodeC($profileId);
$notaryUser = $this->adminService->getUser($userId);
if($userId){
//logout from current login user
$user = auth()->user()->token();
$user->revoke();
//login as notary user
$userRoles = $notaryUser->roles()->get();
// $scopes = [];
// if ($userRoles) {
// $scopes = Arr::pluck($userRoles,'code');
// }
if(Auth::login($notaryUser)){
\Log::info("auth user");
\Log::info(auth()->user());
// $token = $user->createToken($user->email . '-' . now(), $scopes);
}
}
}
Welcome to stackoverflow.
Well, you should look at spatie's package, it might make your life easier.
You can apply roles on the registration if you create two different registration functions. In the front-end, you have to somehow make the user decide and pass that value (a checkbox would be ideal).
I got the solution. there is no need to check auth login just log out the current user and revoke the access token and create a token for the user directly.
$token = $user->createToken($user->email . '-' . now(), $scopes);

login a user and granting core permissions in Joomla

I am working on a project which requires some manager level access to perform tasks, so when I receive a call I forcefully logging in the request as a superuser so that it will have all permissions to complete that task. For login I am using this code:
function forceLogin($superuserId)
{
$user = JFactory::getUser($superuserId);
//Will authorize you as this user.
JPluginHelper::importPlugin('user');
$options = array();
$options['action'] = 'core.login.site';
$response = new stdClass();
$response->username = $user->username;
$response->language = '';
$response->email = $user->email;
$response->password_clear = '';
$response->fullname = '';
$result = $app->triggerEvent('onUserLogin', array((array)$response, $options));
return true;
}
By this my current login user will be superuser. Now the concern is when any extension is searching for permissions, it is still getting that current session doesn't have them and so it returns false.
One of the solutions I came around is to redirect internally after login and then proceed to other tasks, in that way the system recognizes session to be availed with all permissions. For example -
I received something in getNotification()
function getNotification()
{
//from here I log in the user
$this->forceLogin($speruserId);
//and now redirect
$app = JFactory::getApplication();
$app->redirect('index.php?option=com_mycomponent&task=setNotification');
}
Now I proceed further request from setNotification()
function getNotification()
{
// do my work here
}
To be specific, the issue is arising in VirtueMart (e-commerce extension) in which I am creating a product from my call and while creating a product it checks vmAccess::manager('product.create') which is actually same as core.create of Joomla.
I think by redirecting session is being reset with current user and so it gets all permission. Can it be done without redirection? If yes, how?

Magento: How to get user role from user id

I am building a custom admin extension, I need to find a user's role having it's ID, any way to do this, I've been trying to find where does magento store the info on what users are what role with no luck so far. Any help would be very appreciated.
Assuming you're talking about the users who log into the admin console, this should get you what you want.
//By ID
$id = 2;
$role_data = Mage::getModel('admin/user')->load($id)->getRole()->getData();
var_dump($role_data);
//By Username
$username = 'admin';
$role_data = Mage::getModel('admin/user')->getCollection()->addFieldToFilter('username',$username)->getFirstItem()->getRole()->getData();
var_dump($role_data);
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'];
By using this code you will get the detail of the user and also it's role data
$user = Mage::getSingleton('admin/session');
$username = $user->getUser()->getUsername();
$role_data = Mage::getModel('admin/user')->
getCollection()-addFieldToFilter('username',$username)->
getFirstItem()->getRole()->getData();
$role_name = $role_data['role_name'];

Resources