Developing an API where at the start of every request, the provided API key is used to obtain the Account object which is associated with the request.
$account = $em->getRepository(Entity\Account\Account::class)
->findOneBy(['mainKey'=>$request->getHeaderLine('X-API-Key')]);
This Account entity contains a User's ArrayCollection where each of the User entities contains an username property which is unique for a given Account.
Given the username, how can I obtain the User entity? I can do something like the following, however, feel I should be doing differently.
$user = $em->getRepository(Entity\Account\User::class)
->findOneBy(['accountId'=>$account->getId(), 'username'=>'John.Doe']);
Thanks,
PS. I assume that findOneBy() is using a prepared statement behind the scenes and isn't subject to SQL injection, right?
PSS. I just assumed that an ArrayCollection holds a group of objects, but looking at some of the docs, am now not certain.
If Account is related to User (I suppose it is one-to-one), then Account should have $user property defined. And you can access it kinda:
$user = $account->getUser();
Where getUser is:
public function getUser()
{
return $this->user;
}
Both of these approaches seem to work:
$criteria = \Doctrine\Common\Collections\Criteria::create()
->where(\Doctrine\Common\Collections\Criteria::expr()->eq("username", $username));
$user = $users->matching($criteria)->current();
$expr = new \Doctrine\Common\Collections\Expr\Comparison('username', '=', $username);
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($expr);
$user = $users->matching($criteria)->current();
Related
I am getting various error messages depending on various attempted implementations to achieve the mentioned issue. Here is what I tried to do:
Assign group on user creation
//Get group object
$group = $graph->createRequest('GET', "/groups/xxxxx-xxxxx-xxxx-xxxx-xxxxx")
->setReturnType(Model\Group::class)
->execute();
$newUser = new Model\User();
$newUser->setGivenName($firstName);
$newUser->setSurname($surname);
$newUser->setUserPrincipalName($userPrincipalName.'#xxxxxx.com');
// $newUser->setUserType($userType);
// $newUser->setMySite($website);
$newUser->setPasswordProfile(["forceChangePasswordNextSignIn" => false,'password' => $pwd]);
$newUser->setDisplayName($firstName.' '.$surname);
$newUser->setMailNickname($firstName.$surname);
$newUser->setMemberOf([$group]);
$newUser->setAccountEnabled(true);
$user = $graph->createRequest($action, "/users")
->attachBody($newUser)
->setReturnType(Model\User::class)
->execute();
Assign membership through group object
//we get $user object from the last line above
$grp = $graph->createRequest('POST', "/groups/xxxxx-xxx-xxxx-xxxx-xxxxxxx/members/\$ref")
->attachBody(["#odata.id" => $graph->$_baseUrl.'/'.$graph->$_apiVersion.'/users/'.$user->id])
->setReturnType(Model\Group::class)
->execute();
None of the above strategies work. I'd really appreciate pointers to where I am going wrong. Thank you in advance.
I'm not sure if your first approach (referencing the group as part of memberOf when creating the user) is supported.
You second approach has a couple issues:
By using $graph->$_baseUrl and $graph->$_apiVersion, you are attempting to reference private properties of $graph, which you cannot do (because they're private). See the PHP documentation for more information on visibility.
You are attempting to reference the user's id attribute with $user->id. This would work only if $user had a public property named id (which it doesn't). Instead, you need to use the getter for the id: $user->getId().
An approach that works is the following (which is a slight variation of your second attempt):
// Add $user as a member of $group
$newMemberRef = 'https://graph.microsoft.com/v1.0/users/' . $user->getId();
$groupMembersRef = '/groups/' . $group->getId() . '/members/$ref';
$response = $graph->createRequest('POST', $groupMembersRef)
->attachBody(['#odata.id' => $newMemberRef])
->execute();
(Note how in this case we're referencing a user object, though you could also reference a group object, or (more generically) a directoryObject object.)
I'm trying to find a user form a database with 'email' = $email and send them an email. When I try to echo the $user, I receive an error that it's not a string.
public function sendEmail($user)
{
Mail::to($user['email'])->Send(new VerifyEmail($user));
}
public function verifyEmail($email)
{
$user = User::where('email',$email);
$this->sendEmail($user ); //mail won't send
return view('auth.email.verifyemail')->with('email', $email);
}
Please help, thank you!
Your code has a few more issues than not being able to find the user, but let's address this first.
Explanation
Calling the where() method on the User::class is returning an instance of Illuminate\Database\Query\Builder and not the record that you are looking for.
To get a collection of records you can call fluently the get() method or in your case you can just get the first result by calling first().
More on the topic: Retrieving Single Models / Aggregates
Solution
$user = User::where('email', '=', $email)->first();
if(!$user) {
// handle the case if no user is found
}
echo $user->email // access the user's email address
Then you can call your sendmail method or whatever you need and pass the $user instance like this $this->sendmail($user)
$thisUser has only a query. You need to execute it to get the user. Try to get the first record:
$thisUser = User::where('email',$email)->first();
I'm trying save user IP adress after login on website. I'm using laravel 5.2 framework. I got user table and login_ip row. My code looks like that:
$user = User::where('login_ip', Request::getClientIp());
$user->save();
But it does not saving. What i'm doing wrong? Sorry for my bad english :)
If you want to save IP for current user, you can do this:
auth()->user()->update(['login_ip' => Request::getClientIp()]);
This will not create additional query as code in shoieb0101, Amit and Ronald answers.
Don't forget to add login_ip to the $fillable array in User model:
protected $fillable = ['login_ip'];
If you want to save IP for only logged in users and ignore guests, you can do a check:
!auth()->check() ? : auth()->user()->update(['login_ip' => Request::getClientIp()]);
Try
$user = User::find(auth()->user()->id);
$user->login_ip = Request::getClientIp();
$user->save();
//assuming $userid is also requested
$user = User::where('id', $userid);
$user->login_ip = Request::getClientIp();
$user->save();
You can try it as:
auth()->user()->login_ip = Request::getClientIp();
auth()->user()->save();
OR
auth()->user()->save(['login_ip' => Request::getClientIp()]);
Note - It will update the user's login_ip in single query.
You dont have to get logged user form db, all info about your user you have in Auth::user() so:
Auth::user()->login_ip = Request::getClientIp();
Auth::user()->save();
or
Auth::user()->login_ip = $request->ip();
Auth::user()->save();
but you need to have Request $request as parameter of your method.
I am probably stating the obvious, but your first line...
$user = User::where('login_ip', Request::getClientIp());
... returns an Eloquent query builder, right?
So, a save() on this will never work?
$user = User::where('login_ip', Request::getClientIp())->first();
... will return an actual User (if in the DB), which makes save() also possible.
Or did you make a typo in your OP?
I am writing a Symfony3 appusing Doctrine ORM.
SO what i am trying to do is to find if a given email address exists in a table (every email is unique). so i have a user repository with some attributes I can easily persist data to the db but failing to retrive data.
/**
* #param $email
*/
public function findUserByEmail($email)
{
$user = $this->getDoctrine()
->getRepository('TestBundle:TestUser')
->find($email);
if (!$user) {
echo 'Error';die();
}
}
I know the var passed to the function contains a email string, but what i get in return is error and when i var_dump $user before the if statment i get null.
I followed the Symfony docs
Your User probably has a separate primary key field. the find() method on a repo only retrieves by primary key.
Repositories use __call to dynamically process findBy* and findOneBy* methods, so you could call it like this:
$repo = $this->getDoctrine()->getRepository('TestBundle:TestUser');
// magic find method
$user = $repo->findOneByEmail($email);
// explicit find method
$user = $repo->findOneBy(['email' => $email]);
// custom QueryBuilder
$user = $repo->createQueryBuilder('user')
->where('user.email = :email')
->setParameter('email', $email)
->getQuery()
->getSingleResult();
BTW: If you are validating this for a submitted form, there is a contraint that does this check for you: UniqueEntity
I think the problem is because you forgot to call getManager().
So the code would be:
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('TestBundle:TestUser')->findOneBy(['email' => $email]);
Hope it would help you!
How do I get the email address of the current user ?
To retrieved the Username or user id is easy , but i didn't found any example that explain how to get the email address of the current use.
$entity = new Post();
$userManager = $this->container->get('fos_user.user_manager');
$usr = $userManager->findUserByUsername($this->container->get('security.context')
->getToken()
->getUser());
$entity->setUsername($usr);
In controller (that extends symfony controller)
$this->getUser();
For services you need to inject security.token_storage service and use
$this->tokenStorage()->getToken()->getUser()
TokenStorage::getToken() can return null, consider it!