Laravel show page only to signed in user - laravel

How do I show a page only to a specific person that's signed in. For example if I've localhost/public/article/4 that's only allowed for James, how do I make sure that Harry can't see this?

the correct way of do this is associate all users to a Role model. This way you could differenciate one user from others. But if you dont want this way you could use the ID of the user to validate this.
How validate this?
when you make a session in laravel you can access to the user data using
Auth::user()->id, Auth::user()->name, Auth::user()->last_login, etc...
in the controller's function the make the view you could do this (James ID's = 1)
if(Auth::user()->id == 1):
return View::make('path_to_view.show');
else:
return View::make('path_to_view.error');
endif;

Related

laravel: how to check the other user is logged in .. like your friend is online

laravel: i want to know the solution.. If i logged in my account in my browser and i try to open other browser like incognito... and open other account.. and my problem i want to check or detect the other user is open.... like friend....is online.....
You have multiple answers to this question, you can use redis to live check all your currently logged in usersn but I can show you a simpler way :
Add a last_activity column in your use table,
then add a middleware in your app doing this :
if(auth()->check()){
auth()->user()->update(['last_activity' => now()]);
}
then assuming you have a friends() many to many relation in your user model
you can do this :
$online_friends = auth()->user()->friends()->where('last_activity' , '>', now()->subMinutes(5))->get();

Laravel menu based on role?

i have codeigniter background. Now, i'm learning about laravel. So, i'm in this condition (Example), I'm trying to create a webapp, which has multiple users. The UsersType A , they can access menu a, menu b & menu c and UsersType B they only can access Menu a.
Now, i'm using https://github.com/lavary/laravel-menu . Well, if it's only have two types , i can write it manually. But, what if there are five types of user or more.
When i'm using codeigniter. I create 4 table Users , UsersType , Menu & MenuAccess. You must be understand how it's work. I just, play it with query then i show it.
UsersType (Users) -> TypeId (UsersType) -> MenuId (MenuAccess) -> MenuId (Menu)
I already use google and I found this https://github.com/Zizaco/entrust but what i can see from that package. It's only give the permission on the action (input,edit & delete)
So, Can i do my codeigniter way in my laravel ? Save my routes properties than show it in my rouotes/web.php (I don't know if it possible, haven't try it yet). sorry for my english.
What I would do is put a function in the User class which checks it's own permission and then returns a view which contains the menu that user has access to.
public function menu()
{
switch($this->role) {
case 'admin':
return view('menus.admin');
[etc]
}
}
Then in the view just check if the user is logged in and show the menu:
#if Auth::check()
{{ Auth::user->menu() }}
#endif
As mentioned in the comments,it sounds like what you want is the ability to conditionally display content based on whether a user has certain permissions.
There's a number of implementations of this. Essentially what they all do is store permissions that can be granted to users, and optionally store roles that allow permissions to be assigned to a role and then users can be given that role, automatically granting them the permissions associated with that role.
I've found spatie/laravel-permission which appears to be quite good. Then, if you pass your user model into the view, you can do something like this:
#if ($user->can('edit-posts'))
<a>Edit post</a>
#endif
That should be flexible enough that it can be reused for different permissions too. If that doesn't do the trick, then it's not hard to roll your own permission system using Laravel's authorization system and you should be able to use the can() method in the same way.

Allow CRUD only to Auth::user that owns the ressource

I currently work on a project where the User creates Models, that only he/she is allowed to see, edit or delete.
The Create Part done by Eloquent Relationships, but for the other operations I would like to combine it with Route Model binding and not manually in the controller. I tried solving it with middlewares, but I couldn't access the Ressource.
Can somebody point me to the right Direction, any best Practices are welcome!
Personally I use route model binding, but only allow the model to bind if the user owns the record.
This means that no matter what - people can never access someone elses record. So for example, in my route I can do
$router->get('property/{property}, ['uses' => PropertyController#show]);
Then in my RouteServiceProvider:
$router->bind('property', function($value) {
$property = \App\Property::findOrFail($value);
if ((int)$property->user_id !== (int)auth()->id()) {
abort (404);
}
return $property;
});
So in the example above - we have a property route, and it will try and find the property record given. It will then check that the user owns the record, otherwise it throws a 404 (but you could just redirect or something - up to you).

Prevent direct access to a page in Joomla

I have a payment gateway integrated on my website. When user is done with payment he/she is redirected to a particular page say www.example.com/redirect. I want to prevent users from directly entering this url (www.example.com/redirect) in address bar and access the page. I want it asap.
Actually the page is protected from guest users but if logged in user types that url then it will redirect him to that page and hence the payment option will be skipped. I want the user must pay the amount first and then redirected to this page.
Hard to answer precisely since you only give a non-joomla url as an example, but at the top of every Joomla script is the following line:
defined('_JEXEC') or die( 'Restricted access' );
You obviously can't prevent a user from typing in the url, so this will at least detect if a session is already in place. If the user isn't in an active Joomla session, this will fire and prevent access. You could easily adapt it to do whatever you want to happen for your requirement, depending on whatever you have to check with, i.e. if the referrer is your payment gateway, etc.
I had a similar desire. I wanted the page to only display if the users was logged in and if they had filled out the order entry page.
What I decided to do was check to see if there was data in the POST.
controller/place_order.php (snipet)
public function submitOrder()
{
$post = JRequest::get('post');
$model = $this->getModel();
if($post != null && $post != ''){
if($model->placeOrder()){
}
}
JRequest::setVar('layout', 'submitOrder');
parent::display();
}
This prevents the task from executing my placeOder function anything in the model. Then I just add something similar to the submit order page. In your case "redirect".
view/place_order/tmpl/submitOrder.php (snipet)
defined('_JEXEC') or die('Restricted access');
$user =& JFactory::getUser();
if ($user->guest) {
echo "<p>You must login to access this page.</p>";
}
else if($_POST == "" || $_POST == null){
echo "<p>You can not directly access this page.</p>";
}else {
//Your order was submitted successfully HTML (don't forget to close it at the bottom ;)
There are a lot of ways you could do it... you probably don't even need to check in the controller if you don't want to but I do to save on time. With out seeing your code it's hard to tailor the answer but if you grasp the concept here it should help (I hope...).
You might also want to check out this page from Joomla on authorization and privileges.
this should be done in your component's base controller (controller.php). if you look at this code snippet:
// Check for edit form.
if ($vName == 'form' && !$this->checkEditId('com_weblinks.edit.weblink', $id))
{
// Somehow the person just went to the form - we don't allow that.
return JError::raiseError(403,
JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id));
}
this block of code is present in most of core components intended to do exactly what you want. how ever how this actually dos what it does is explained through the $this->checkEditId() function. I hope you are familiar with the JControllerForm class and if you are not check out the API. because creating an edit id for a page and "authorizing user for access to a specific page based on his last page" is done by JControllerForm.

Extending ion auth to only allow registrations from certain email addresses/domains

I want to extend Ion Auth to only allow certain email addresses to register.
I'm fairly sure I could hack this together and get something working, but as a newbie to codeigniter and ion auth I wish to find out if there is a "proper way" to be doing what I need?
For instance can I "extend" ion auth (so I can update ion auth core files without writing over my changes?).
I noticed there are also hooks including this one (in the register function):
$this->ci->ion_auth_model->trigger_events('pre_account_creation');
Where do these resolve and can I use this one in order to intercept registrations from email addresses which don't match a list of those I wish to register?
If so, how would I do it? I would need access to the $email variable from the register() function.
Or is it just a case of altering the base code from ion auth and not updating it in the future?
Thanks for any help you can give me. Don't worry about the email bit, I'm capable of working out whether an email address matches the required email domains, I'm more interested in what is the best way to go about extending the library.
Tom
EDIT: Hi Ben, thanks for your answer, and thanks for taking the time to have a look at my issue. Unfortunately this hasn't helped.
I guess what you're trying to do there is add a little bit to the sql query a "where in" clause? I guess that the where in bit is incorrect as there isn't a column name.
Also, at this point I can't modify the sql query satisfactorily to produce the required output. e.g. I can add a hook to a function which is literally $this->db->where('1=1') and this outputs this sql in the next query:
SELECT COUNT(*) AS `numrows` FROM (`users`) WHERE `1=1` AND `email` = 'rawr#rawr.com'
The AND email = 'rawr#rawr.com' bit will always still return no rows. It should be OR email = 'rawr#rawr.com', but without editing the Ion Auth core code then I won't be able to change this.
I am starting to suspect (from the last couple of hours of tinkering) that I may have to edit the ion auth core in order to achieve this.
Check out this example: https://gist.github.com/2881995
In the end I just wrote a little form_verification callback function which I put in the auth controller of ion_auth which checked through a list of allowed domains. :)
When you validate your form in the auth controller you add a callback:
$this->form_validation->set_rules('email', 'Email Address', required|callback_validate_email');
You create a method in the controller called validate_email:
function validate_email() {
if (strpos($this->input->post('email'), '#mycompany.com') === false) {
$this->form_validation->set_message('validate_email', 'Not official company email address.');
return false;
} else return true;
}
This will cause the creation of the user to fail, since all rules must pass. You also provide an error message. Just make sure to have this line on the form view side:
echo validation_errors();

Resources