how to pass session variable into view using laravel4 - laravel-4

I want to pass logged in id into my view page.i got the id in the function of user_login_submits.
Actually i want to get the id in one more function in the same controller.
how to get the session id in controller..
Normally session put its enough i did like that.
Here is my code anyone can check and tel me what need to change here
Controller
public function user_login_submits()
{
$inputs = Input::all();
$uname = Input::get('username');
$password = Input::get('password');
$logincheck=Userlogin::login_checks($uname,$password);
if($logincheck == 1)
{
$id=Session::get('customer_id');
return Redirect::to('businessprio/create_news?p=1');
}
else if($logincheck == 0)
{
//echo "fail";
return Redirect::to('businessprio/create');
}
}
Model
public static function login_checks($uname,$password)
{
$check = DB::table('customer_login')
->where('username','=',$uname)
->where('password','=',$password)->get();
if($check)
{
//Session::put(['customer_id'=>'value']);
Session::put('customer_id', $check[0]->customer_id);
Session::put('username', $check[0]->username);
return 1;
}
else
{
return 0;
}
}

I won't pass it to model, instead i would do it in controller itself,
public function user_login_submits()
{
$uname = Input::get('username');
$password = Input::get('password');
$check = DB::table('customer_login')
->where('username','=',$uname)
->where('password','=',$password)->count();
if($check==1)
{
$id=Session::get('customer_id');
return Redirect::to('businessprio/create_news?p=1');
}
else
{
return Redirect::to('businessprio/create');
}
}
Recommendation :
But i would strongly recommend you to do it by Auth::attempt i.e., to follow the clean one
public function user_login_submits()
{
if (Auth::attempt(['email' => $userEmail, 'password' => $userPassword])) {
return Redirect::to('businessprio/create_news?p=1');
}
else
{
return Redirect::to('businessprio/create');
}
}
If you do so, then you can access the Default checking for authenticated user
Auth::check()
Get the Logged in user details by
Auth::user()->id
Auth::user()->username
Note : To use default Auth::attempt you should use the User Model too.

Related

Auth::user() Returns Null in API Controller

I'm using Laravel 7 and my problem is to get null from Auth::user();
auth()->user and Auth::id() return null as well.
BTW, in balde template Auth::user() works.
It returns null when I try to use it in controller.
What I'm trying to do is to create a comment page in backend (Vuejs) and I want to build up a filter logic. In order to do that, I want to add a new property named repliedBy into each comment in controller. If a comment isn't replied by the current user, repliedBy will be notByMe. So I don't event try to return user id to Vuejs. I can't get id even in the controller. BTW, login, registration etc work normal way.
Here is my CommentsController:
public function index()
{
$comments = Comment::join("site_languages", "language_id", "=", "site_languages.id")
->select("content_comments.*", "site_languages.shorthand as lang_shorthand")
->with(["replies", "post", "user"])
->orderBy('id', 'desc')
->get()
->groupBy("commentable_type");
$grouppedComments = [];
foreach ($comments as $type => $typeSet) {
$newType = strtolower(explode("\\", $type)[1]);
$grouppedByLanguage = $typeSet->groupBy("lang_shorthand");
$langSet = [];
foreach ($grouppedByLanguage as $lang => $commentSet) {
$grouppedBycontent = [];
foreach ($commentSet as $comments) {
$content = $newType . "_" . $comments->commentable_id;
if (array_key_exists($content, $grouppedBycontent)) {
array_push($grouppedBycontent[$content], $comments);
} else {
$grouppedBycontent[$content] = [$comments];
}
}
$groupAfterOrganized = [];
foreach ($grouppedBycontent as $content => $comments) {
$order = 1;
$commentAndReplies = [];
foreach ($comments as $comment) {
if ($comment->parent_id === null) {
if (isset($comment->order) === false || $comment->order > $order) {
$comment->order = $order;
}
array_push($commentAndReplies, $comment);
} else {
foreach ($comments as $parentComment) {
if ($parentComment->id === $comment->parent_id) {
$parent = $parentComment;
break;
}
}
foreach ($parent->replies as $replyInParent) {
if ($replyInParent->id === $comment->id) {
$reply = $replyInParent;
break;
}
}
if (isset($comment->order) === false) {
$comment->order = $order;
$order++;
}
if (isset($parent->order) === false || $parent->order > $comment->order) {
$parent->order = $comment->order;
}
$reply->order = $comment->order;
$reply->replies = $comment->replies;
$reply[$newType] = $comment[$newType];
$basePower = 6;
if ($comment->user_id !== null) {
if ($comment->user_id === Auth::id()) {
$reply->replyFrom = "me";
} else if ($comment->user->role->power >= $basePower) {
$reply->replyFrom = "staff";
} else {
$reply->replyFrom = "user";
}
} else {
$reply->replyFrom = "visitor";
}
$iReplied = false;
$staffReplied = false;
foreach ($reply->replies as $replyOfReply) {
if ($replyOfReply->user_id !== null) {
$power = $replyOfReply->user->role->power;
if ($power >= $basePower) {
$staffReplied = true;
}
}
if ($replyOfReply->user_id === Auth::id()) {
$iReplied = true;
}
}
if ($staffReplied === false) {
if ($reply->replyFrom === "user" && $reply->replyFrom === "visitor") {
$reply->replied = "notReplied";
} else {
$reply->replied = "lastWords";
}
} else if ($staffReplied && $iReplied === false) {
$reply->replied = "notByMe";
} else if ($staffReplied) {
$reply->replied = "replied";
}
}
}
$groupAfterOrganized[$content] = $commentAndReplies;
}
$langSet[$lang] = $groupAfterOrganized;
}
$grouppedComments[$newType] = $langSet;
}
return $grouppedComments;
}
api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResources([
'languages' => 'API\LanguagesController',
'users' => 'API\UsersController',
'roles' => 'API\RolesController',
'tags' => 'API\TagsController',
'categories' => 'API\CategoryController',
'pictures' => 'API\PicturesController',
'posts' => 'API\PostsController',
'comments' => 'API\CommentsController'
]);
EDIT
I'm using the code down below in RedirectIfAuthenticated.php and when I try with
dd(Auth::user());
it returns null as well. BTW obviosly, redirect to backend doesn't work.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if (Auth::user()->role->power > 5) {
return redirect('backend');
}
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
The solution to this problem is fairly simple . because you are using api request laravel default auth can not understand the user so here the passport comes :
https://laravel.com/docs/7.x/passport
as written in documenation you should go 3 steps :
composer require laravel/passport
php artisan migrate
php artisan passport:install
after that you can generate token for logged in users and use that token in api authentication to use for your api which is the only and more reliable way that laravel default auth .
this link can be helpful to you too :
https://laravel.io/forum/laravel-passport-vue-check-user-authentication
this way if you intent to use you api in mobile or any other application you can simply authenticate your user in that :)
hope this helps
EDIT
according To your comment now you must generate token for your vue api to use so this would be like below :
$token = $user->createToken(config('app.name'))->accessToken;
if ($this->isApiType()) {
$token = $user->createToken(config('app.name'))->accessToken;
} else {
Auth::login($user);
$redirect = $this->getRedirectTo($user);
}
this must be added in the end of your login method so if the request comes from api it generates a JWT token for you which can be used in vue for login
yes for getting the authencated user detail your API must under the auth:API middleware.
Route::group(['middleware' => 'auth:api'], function () {
}
As you are using Resource those are not under the Api middleware just put that into that and Auth::user will return the result set.
Route::group(['middleware' => 'auth:api'], function () {
Route::apiResources([
'comments' => 'API\CommentsController'
]);
}
will fix the issue.

Laravel route : any slug takes all the requests

I have a route something like this. The $slug is a variable that is matched to the slugs stored in the database to add the pages dynamically to the website.
#slug variable for different values of page slug....
Route::get('/{slug?}', array(
'as' => 'page',
'uses' => 'AbcController#renderPage'
));
However, now I wish to add an admin side of the website and want routes to be prefixed with media-manager.
My problem is, whenever I make a call to another route in the file, the above mentioned route takes the request call and calls the renderPage method every time, no matter wherever the request is coming from.
This is my middleware where I check for whether request is coming from a URL like 'media-manager/*', if so I don't want to check for the language of the website and redirect it to the media-manager's page.
private $openRoute = ['media-manager/login', 'media-manager/postLogin', 'media-manager/media'];
public function handle($request, Closure $next)
{
foreach ($this->openRoute as $route) {
if ($request->is($route)) {
return $next($request);
}
}
// Make sure current locale exists.
$lang = $request->segment(1);
if(!isValidLang($lang)) {
$lang = getDefaultLang();
$segments = $request->segments();
array_unshift($segments, $lang);
$newUrl = implode('/', $segments);
if (array_key_exists('QUERY_STRING', $_SERVER))
$newUrl .= '?'.$_SERVER['QUERY_STRING'];
return $this->redirector->to($newUrl);
}
setLang($lang);
return $next($request);
}
This is the renderPage method where every time the request is being redirected, no matter what.
public function renderPage($slug = '')
{
if ($slug == 'login') {
return view ('site.login');
}
$page = Page::getBySlug($slug);
if(empty($page)){
return URL::to ('/');
}
if($slug == ''){//home page
$testimonial = DB::table('testimonial')->where('lang','=',$this->lang)->get();
$client_logo = DB::table('client_logo')->get();
return View::make('index', compact('data','page', 'testimonial', 'client_logo'));
}elseif($slug == 'services'){
return View::make('services', compact('page'));
}elseif($slug == 'portfolio'){
$categories = PortfolioCategory::getAll();
$portfolio = Portfolio::getAll();
return View::make('portfolio', compact('page', 'categories', 'portfolio'));
}elseif($slug == 'oshara'){
return View::make('oshara', compact('page'));
}elseif($slug == 'blog'){
$limit = 8;
$pageNum = 1;
$offset = ($pageNum-1)*$limit;
$totalPosts = BlogPost::totalPosts();
$totalPages = ceil($totalPosts/$limit);
$posts = BlogPost::getAll($offset, $limit);
$blog_posts = View::make('partials.blog_posts', compact('posts','pageNum','totalPages'));
return View::make('blog', compact('page', 'blog_posts', 'pageNum', 'totalPages'));
}elseif($slug == 'contact'){
$budgets = Budget::getAll();
return View::make('contact', compact('page', 'budgets'));
}
}
This is postLogin method in the controller that I want to call after user clicks on Login button on login page.
public function postLogin($request) {
# code...
//$request = $this->request;
$this->validate($request, [
'email1' => 'required|email',
'password' => 'required|string'
]);
if($user = User::whereEmail($request->email1)->first() ) {
if(Hash::check($request['password'], $user->getAttributes()['password'])) {
if(!$user->getAttributes()['is_active']) {
return redirect('/media-manager/login')->withErrors('Your Account is not Activated Yet!');
} else if($user->getAttributes()['is_deleted']) {
return redirect('/media-manager/login')->withErrors('Your Account is Banned!');
} else {
# Success
$cookie = Cookie::make('user_id', $user->getAttributes()['id'], 864000);
//echo "hello";
return view('site.media')->with('message', 'You have Successfully Logged In!')->withCookie($cookie);
}
} else {
return redirect('/media-manager/login')->withErrors('Your Login Information is Wrong!');
}
} else {
return redirect('/media-manager/login')->withErrors('Your Login Information is Wrong!');
}
}
Can any one please suggest me some way so that I can disable renderPage method on every call and have my normal routing perform perfectly.
In Laravel the first matching route is used. So I would guess you have your slug route defined above the others (at least above the media-manager ones), right?
So a simple solution would be to just put the slug route definition at the end of your routing file.
Another approach would be utilize conditions for the route. For more information you can read this or leave a comment!
Hope that helps!

Access information from session in website with two different sessions

My website has two restrict areas, in the public website and admin area. I've tried to follow some instructions to make multiple sessions throughout the website, but I'm facing some problems about accessing and retrieving their information.
Below are the login methods from both pages. First from the administration area:
public function login()
{
if ($this->Admin_model->find_credentials()) {
$data['user_email'] = $this->input->post('email');
$this->session->set_userdata('auto', $data);
redirect('/admin/dashboard', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/admin/entrar');
}
}
And then, the admin area in the public website:
public function login()
{
if ($this->Usuarios_model->find_credentials()) {
$email = $this->input->post('email');
if ($this->Usuarios_model->is_active($email)) {
$data = array();
$data['nome'] = $this->Usuarios_model->find_col_by_email('nome_razao_social', $email);
$data['email'] = $email;
$data['tipo_usuario'] = $this->Usuarios_model->find_col_by_email('tipo_usuario', $email);
$data['id_usuario'] = $this->Usuarios_model->find_col_by_email('id', $email);
$this->session->set_userdata('auto', $data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/usuario/painel');
} else {
$this->session->set_flashdata('message', 'Por favor, ative o seu cadastro');
redirect('/');
}
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
}
For each new session, I am settling a name for it. Now, every point I call the session value, I must specify the name of which session I want, but I am having an error message after I try to log-in:
Message: Array to string conversion
This error points at line 161 of my model, which has the following code:
public function find_details($email = null, $id = null, $id_carro = null)
{
$this->db
->select(
'usuario.*,' .
'estado.nome_estado AS uf,' .
'cidade.nome_cidade AS cidade'
)
->join('cidade', 'cidade.id = usuario.id_cidade')
->join('estado', 'estado.id = usuario.id_estado');
if ($email) {$this->db->where('usuario.email', $email);} // 161
...
}
What do I need to do to make multiple sessions work correctly?
Alright. The solution for me was a different way to echo the value of a certain session:
$this->session->userdata('foo')['bar'].
Where foo is the session name, specified when creating a new session. In my case, a good example can be $this->session->userdata('auto')['email'];

laravel auth and session not persisting

The laravel session and auth I use have some problem in server, but working really fine in localhost . I will show.
Route
Route::get('/signin', 'PageController#signin');
Route::get('/signup', 'PageController#signup');
Route::get('/terms', 'PageController#terms');
Route::resource('/', 'PageController');
Route::controller('user', 'UserController');
PageController
public function index() {
if (Auth::check()) {
return View::make('user.index');
} else {
return View::make('landing');
}
}
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Redirect::to('/');
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
Auth::check() fails in pagecontoller even after login succeds. But if I change the code to
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
I get the index page and if I click the link of the home I get the landing page not the index page.
I guess I clarify my problem, I have gone through may solution replied earlier in same manner question nothing working.
I don't think its the server problem because another laravel application is working fine in same server.
Please help.
Your query seems to be incomplete, from what i understand you are able to get the index page after passing the authentication check only once, and that is by using this method:
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
}
else {
$data['success'] = false;
}
}
else {
$data['success'] = false;
}
return $data;
}
try using a different browser to make sure there is no cookie storage restrictions in the client side and check the app/config/session.php file and see if you have configured the HTTPS Only Cookies according to your needs.
and just on an additional note this line "return Return View::make(user.index);" looks vague.

CodeIgniter Session Userdate seems not to exists

I'm coding my first CI project and try to write a loginscript. Everything works almost fine, except that the session userdata is not available (even not if i check my cookies / sessions in Firefox).
I don't understand why the session userdata only are available after login, but if i load the same page again (not a refresh, but a new load) i would expect i still will be logged in, but i'm logged out ? Even if i try to read the session userdata it doesn't exists.
I simplified my script to an example version for stackoverflow. Who can tell me how this session issue can be solved?
Regards,
Guido
<?php
class Test extends CI_Controller
{
function index()
{
$logged_in = $this->is_logged_in();
if($logged_in) {
echo "You are logged in. <a href='test/logout'>Logout</a> | <a href='../'>Return to index</a>";
}
else {
echo "You are logged out";
echo form_open('test/check_login');
echo "Email: ".form_input('email', set_value('email'));
echo "Password: ".form_password('password', set_value('password'));
echo form_submit('submit','Login');
echo form_close();
}
}
function is_logged_in() // check if user has logged in
{
// AUTOLOAD SESSIONS HAS SET in autoload.php-config >> $autoload['libraries'] = arra y('database', 'session', 'email');
$is_logged_in = $this->session->userdata('is_logged_in');
if($is_logged_in) {
return TRUE;
}
else {
return FALSE;
}
}
function check_login()
{
$client_id = $this->validate();
if(is_numeric($client_id)) // if the user's credentials validated then user exists
{
$data = array(
'client_id' => $client_id,
'is_logged_in' => true
);
$this->session->set_userdata($data);
}
$this->index();
}
// normally we put this function in a model, but for this example we put it here.
function validate() // check if user exists in database
{
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('client_users'); // this is our user table
if($query->num_rows == 1) // user exists
{
$row = $query->row();
return $row->id_client;
}
else
{
return false;
}
}
function logout()
{
$this->session->sess_destroy(); // kill session, so user will be logged out.
redirect('/test');
}
}
?>
Your validate function's if statement should read:
if($query->num_rows() == 1) // user exists
You left out the () after num_rows.
Edit: After further review, that shouldn't matter. The only other thing I can tell is maybe your result is not equal to 1. Either the user isn't found or you're getting more than one result, both resulting in !== 1.

Resources