how should i fetch post of user who he follows and fetch all post of database with it and give some condition like follow user post should not be fetch in all post result it should be fetch first.....
my relation:
public function following()
{
return $this->belongsToMany('App\User', 'follower_following', 'follower_id', 'following_id')
->select('id', 'uname', 'name');
}
public function posts(){
return $this->hasMany(Post::class)
->orderBy('created_at');
}
public function user()
{
return $this->belongsTo('App\User','user_id','id');
}
i have tried this :
1.
$user = User::with('following.files')->get();
return response()->json(['data' => $user], 200,[],JSON_NUMERIC_CHECK);
2.
$follows = Auth::user()->following->pluck('id');
$post = Posts::whereIn('user_id',$follows)
->with('user')
->latest()
->limit(10)
->get();
just getting the auth user following post what to use to get all post with following user post
Related
I'm trying to make use of the new FormSchema class in Silverstripe 4 but I'm having a tough time with the workflow for submitting the form. I've been able to return the schema and state, but when submitting the form back to the controller is where I run in to issues. Here is some example code:
class TestController extends Controller {
private static $allowed_actions = [
'schema',
'TestForm'
];
public function schema(HTTPRequest $request) {
$schema = new FormSchema();
return json_encode($schema->getMultipartSchema(['schema', 'state', 'errors'], "FormID", $this->TestForm()));
}
public function TestForm() {
$fields = FieldList::create(
TextField::create('Name', 'Name'),
EmailField::create('Email', 'Email')
);
$actions = FieldList::create(
FormAction::create('doTestSubmit', 'Submit')
);
$required = RequiredFields::create(['Name', 'Email']);
return Form::create($this, 'TestForm', $fields, $actions, $required);
}
public function doTestSubmit($data, $form) {
return json_encode(array('response' => 'The form validated and was submitted.'));
}
}
So in this scenario hitting /schema returns TestForm schema in json then the front end renders the form. Submitting the form sends the data back to /TestForm where it is validated. If the submission is valid it'll continue to doTestSubmit and return the response. That's great! But, if the submission is not valid then TestForm attempts to return the form and not the schema with the validation messages.
I first though about using a condition in TestForm() like if($this->request->isPOST()) or if($form->validationResult()->isValid()) but it doesn't seem like the proper way to handle it.
Any input or a simple code sample would be great.
I think you cannot use the standard Form > Form Post > Form Action way, you have to create an own Form Handler that validates the form. Like this (untested code):
public function doTestSubmit($request) {
$form = $this->TestForm()
$form->loadDataFrom($request->postVars);
if(!$form->validationResult()->isValid()) {
$formSchema = new FormSchema();
$state = $formSchema->getState($form);
return json_encode($state);
}
//Valid, continue
}
I'm using SfGuardPlugin and on the backend of my site I have the full list of users and I want to be able to login on the frontend with the user that I choose from the list.
I've tried this method:
public function executeListLogin(sfWebRequest $request) {
// client that I've selected from list
$client = $this->getRoute()->getObject();
// create instance if doesn't exist
if(!sfContext::hasInstance('frontend')){
sfContext::createInstance(ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false));
}
// switch to frontend
sfContext::switchTo('frontend');
// also tried with: sfContext::getInstance('frontend')
sfContext::getInstance()->getUser()->signin($client->getSfGuardUser(), true);
// redirect to frontend homepage
$this->redirect('#homepage');
}
It redirects me to the frontend homepage, but I'm not logged in.
After more digging I've found out that I'm logged out from backend and now I'm logged in on frontend with admin instead of the user I choose. So the sfContext::switchTo doesn't work correctly.
I've found a workaround.
Create a new column(login_frontend_key) on the users table.
Create a new frontend route with a required parameter(named key)
Create the action in frontend controller witch is responsible for sign in the user, ex:
public function executeLoginClientKey(sfWebRequest $request){
// get the client by key
$this->forward404Unless($user = ClientPeer::getByLoginFrontendKey($request->getParameter("key")));
// if you already logged in with another user, signout
if($this->getUser()->isAuthenticated())
{
$this->getUser()->signOut();
}
// signin with the new user
$this->getUser()->signIn($user->getsfGuardUser(), false);
$user->setLoginFrontendKey(null); // delete the key from DB
$user->save();
$this->redirect('#homepage');
}
Use this to generate cross application links http://symfony.com/blog/cross-application-links
Create the object action on the backend users page:
public function executeListLogin(sfWebRequest $request)
{
// get the selected client
$client = $this->getRoute()->getObject();
$key = $client->generateLoginFrontendKey(); // generate a random key
$client->setLoginFrontendKey($key); // store the key in DB
$client->save();
// generate the frontend url for login
$url = $this->getContext()->getConfiguration()->generateFrontendUrl('login_frontend_key', array('key' => $key, 'sf_culture' => 'nb'));
$this->redirect($url);
}
I would like to pass the authenticated users list of roles to my front end apps, so I can use the same access control structure in the front and back end.
I was looking in the security / authentication classes as that is where the isGranted function are for me to do this
$this->container->get('security.context')->isGranted('ROLE_SUPER_ADMIN')
I can't find anything to get a list of roles though, is this not a supported feature?
nb: I don't want the entire role hierarchy, just the list of roles for the authenticated user
I ended up adding a new repository function and a service method to get this info.
MyProject/UserBundle/Entity/Repository/UserRepository
public function getRoles($userId)
{
$queryBuilder = $this->createQueryBuilder('u');
$queryBuilder
->select('u.id, u.roles AS user_roles, g.roles AS group_roles')
->leftJoin('u.groups', 'g')
->andWhere('u.id = :user_id')
->setParameter('user_id', $userId);
return $queryBuilder->getQuery()->getArrayResult();
}
MyProject/UserBundle/Service/UserService
public function getUserRoles($user)
{
$groupRoles = $this->repository->getRoles($user->getId());
$roles = array('user_roles' => array(), 'group_roles' => array());
foreach ($groupRoles as $groupRole) {
$roles['user_roles'] = array_merge($roles['user_roles'], $groupRole['user_roles']);
$roles['group_roles'] = array_merge($roles['group_roles'], $groupRole['group_roles']);
}
return $roles;
}
This gives me an array like this
"roles":{
"user_roles":[],
"group_roles":["ROLE_ADMIN","ROLE_ONE","ROLE_TWO","ROLE_BEST"]
}
Assuming you're using the Symfony security component, the user interface which your user class implements has this already included:
$user = $this->get('security.token_storage')->getToken()->getUser();
var_dump($user->getRoles());
http://api.symfony.com/3.1/Symfony/Component/Security/Core/User/UserInterface.html#method_getRoles
I'm trying to create a fosuserbundle for a quite strange use case, which is mandatory requirement, so no space to diplomacy.
Use case is as follow:
users in a mongo db table populated by jms messages -no registration form
users log in by ldap
user record not created by ldap, after a successful login username is checked against mongodb document
Considering that ldap could successfully log in people that exhist in ldap but cannot access site (but login is still successful), what could be the best way to perform such authentication chain?
I was thinking about some possible options:
listen on interactive login event, but imho there's no way to modify an onSuccess event
create a custom AuthenticationListener to do another check inside onSuccess method
chain authentication using scheb two-factor bundle
any hint?
I've used Fr3DLdapBundle which can be incorporate with FOSUserBundle quite easily (I'm using the 2.0.x version, I have no idea if the previous ones will do the same or be as easy to set up).
In the LdapManager (by default) it creates a new user if one is not already on the database which is not what I wanted (and doesn't seem to be what you want) so I have added my own manager that checks for the presence of the user in the database and then deals with the accordingly.
use FR3D\LdapBundle\Ldap\LdapManager as BaseLdapManager;
.. Other use stuff ..
class LdapManager extends BaseLdapManager
{
protected $userRepository;
protected $usernameCanonicalizer;
public function __construct(
LdapDriverInterface $driver,
$userManager,
array $params,
ObjectRepository $userRepository,
CanonicalizerInterface $usernameCanonicalizer
) {
parent::__construct($driver, $userManager, $params);
$this->userRepository = $userRepository;
$this->usernameCanonicalizer = $usernameCanonicalizer;
}
/**
* {#inheritDoc}
*/
public function findUserBy(array $criteria)
{
$filter = $this->buildFilter($criteria);
$entries = $this->driver->search(
$this->params['baseDn'], $filter, $this->ldapAttributes
);
if ($entries['count'] > 1) {
throw new \Exception('This search can only return a single user');
}
if ($entries['count'] == 0) {
return false;
}
$uid = $entries[0]['uid'][0];
$usernameCanonical = $this->usernameCanonicalizer->canonicalize($uid);
$user = $this->userRepository->findOneBy(
array('usernameCanonical' => $usernameCanonical)
);
if (null === $user) {
throw new \Exception('Your account has yet to be set up. See Admin.');
}
return $user;
}
I'm working on an ASP.NET MVC4 web app, and I have a controller method for handling a GET request with an id in the URL, like so ...
[PortalAuthorization]
public ActionResult View(int id)
{
// get the individual ftp log
PortalFTPLog log = PortalFTPLogs.Get(id);
if (log == null)
{
TempData["Error"] = "The provided ftp log id does not exist.";
return RedirectToAction("Index");
}
// get the available matters to tie uploads to
ViewBag.matters = PortalMatters.Get();
return View(log);
}
In my view for this controller method, I have a form so that they can update it, that I want to POST back to the same URL. A URL like foo.com\items\1. Thats what the function above handles.
How do I make a function that handles a POST request for a function that requires a parameter, though? IN previous POST handlers I create a FormsCollection param, but when I add it to the param list for this function, the id param is null.
[HttpPost]
[PortalAuthorization]
public ActionResult View(FormCollection collection, int id)
{
PortalFTPLog log = PortalFTPLogs.Get(id);
if (log == null)
{
TempData["Error"] = "The provided ftp log id does not exist.";
return RedirectToAction("Index");
}
// update the matter id and save to database
log.Matter = Convert.ToInt32(collection.Get("matter"));
log.Save();
TempData["Notice"] = "The FTP log meta data has been updated.";
return RedirectToAction("View", new { id = id });
}
You need to provide RouteValues in Html.BeginForm on your View:
#using (Html.BeginForm(new {id = someIntIdValue}))
{
// Your form code
}