jeudi 1 février 2018

Laravel view @include auto logout when refresh

I am using Laravel 5.5 with mysql database, session storing in database.

@Problem : Whenever I refresh or go into another page, it will log me out and redirect me back to the login page.

@Cause : After debugging, I found out whenever I @include a view top.blade.php inside my view template named master.blade.php, when I refresh the page, it will auto log me out and killing off the session.

The codes inside top.blade.php :

<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">

  <!-- Mobile Menu -->
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>

  <!-- Header Icon -->
    <a  href="">
      <img class="navbar-brand" src="" alt="Little Project">
    </a>

    <!-- Message Of The Day -->
    <div class="navbar-text visible-xs"><p>Little Project</p></div>
     <!-- to check the user info if it retains -->
</div>



<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

<!--Right side of the NavBar -->
  <ul class="nav navbar-nav navbar-right">
      @guest
        <li><a href="">Login</a></li>
        <li><a href="">Register</a></li>
      @else
        <li><a href="">Demo</a></li>
        <li><a href="">Logout</a></li>
      @endguest
  </ul>

</div><!-- /.navbar-collapse -->

While the master.blade.php file is

<!DOCTYPE html>
<html lang="">
<head>

<!--meta header-->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="">

    <!-- Styles -->
    <link href="" rel="stylesheet">

    <!-- Title -->
    <title>Little Project</title>
</head>
<body>
    @include('constants.top')
    <div class="container">
      <!-- Contents -->
      @yield('content')

    </div>


    <!-- Scripts -->
    <script src=""></script>
</body>

</html>

Upon login, successful display of information at both top.blade.php and master.blade.php to check the User's login information

However when refresh, it will destroy all sessions as long as I @include top.blade.php



via Chebli Mohamed

LARAVEL 5 - Dynamic Menu from Arrays in Model. How to make it ? [suggestions]

I'm quite new in Laravel, so please be forgiving for me and give me some suggestions as i am not at all need proper solution. Just wants to learn something new, but it's hard to find it.

It'll be progressive topic, so let's start :

My idea is to create dynamic menu based on Arrays in Model on the left side of the page. It has to be build by user's choice. For example :

  • If user choose 'Products' from "nav bar" at the top then the menu should shown at the left panel which is called "nav menu" with proper Products' category and also the content in the proper content div in the middle of the page. I hope it clears what i mean.

Basically, i need to create a Model, let's call it "Menu" so :

php artisan make:model Menu

Then Controller for that Model "MenuController" :

php artisan make:controller MenuController --model=Menu

Ok, now i created Arrays in Model like this :

namespace App;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{



        protected $Data1 = [

                        'Category' => 'someCategory',
                        'SubCategory' => [
                                            1 => 'subcategory 1',
                                            2 => 'subcategory 2',
                                            3 => 'subcategory 3',
                                            4 => 'subcategory 4'
                                        ],
        ];

        protected $Data2 = [

                        'Category' => 'someCategory',
                        'SubCategory' => [
                                            1 => 'subcategory 1',
                                            2 => 'subcategory 2',
                                            3 => 'subcategory 3',
                                            4 => 'subcategory 4'
                                        ],
         ];



}

For now my question is, is that good way "i'm walking through" ? as i have doubts. What should i do next ?



via Chebli Mohamed

Laravel Controller 2FA PGP dont generate key, find the error?

I have coded an Laravel 2FA PGP login using GPGME. I am sure I have installed GPGME correct!

After a User signs in, he gets a Message generated with PGP from his Public Key that he saved before.

But I just get always an empty field with no generated Key.

My Controller:

public function showDecryptionForm()
    {
      if(session()->has('user_name'))
      {
        $user_name = session()->get('user_name');
        $user_password = session()->get('user_password');
      }
      else
      {
        return redirect()->route('login');
      }
      $user_details = User::where('username',$user_name)->first();

      $secret = $this->generateSecretKey();

      $secret_hash = password_hash($secret, PASSWORD_BCRYPT);

      $this->secret_code = $secret_hash;

      //echo $user_details->pgp;

      putenv("GNUPGHOME =/home/.gnupg");
      $gpg = new gnupg();
      $key = $gpg->import($user_details->pgp);
      $gpg->addencryptkey($key['fingerprint']);
      $enc = $gpg->encrypt($secret);
      $gpg->clearencryptkeys();
      //echo '<textarea rows="30" class="form-control" name="pgp-msg">'.$enc.'</textarea>';

      session()->flash('secret_hash',$secret_hash);

      return view('auth.decryptionform',compact('enc','user_name','user_password'));
    }


    public function postDecryptionForm(Request $request)
    {
      if (Hash::check($request->decrypt_code,session()->get('secret_hash'))) 
      {
        if (Auth::attempt(['username' => $request->user_name, 'password' => $request->user_password]))
        { 
          $user = Auth::user();
          $user->last_seen = date('Y-m-d H:i:s', time());
          $user->save();
          return redirect()->route('home');
        }
      }
      else
      { 
        session()->flash('errormessage','Your PGP Decryption Code is Wrong!!!');
        return redirect('login');
      }  
    }
    public function generateSecretKey($length = 15)
    {
      $secret = '';
      for($i = 0; $length > $i; $i++)
      {
        $secret = $secret.rand(0,9);
      }
      return $secret;
    }
}

Blade:

   <label for="message">Public Key:</label>
   <textarea name="message" id="message" class="form-control" rows="15" cols="40" readonly></textarea>
</div>
<div class="form-group">
  <label for="decrypt_code">Please Enter the Message:</label>
  <input type="text" name="decrypt_code" id="decrypt_code" class="form-control">

Have I forgotten something to print the code in my script?



via Chebli Mohamed

Transfer html tags to specific characters

I'm trying to transfer the following HTML to a little bit tricky form using php, as shown below:

<dd>abc<br />def<br />ghi</dd>

↓

abc
def
ghi

Say <dd>abc<br />def<br />ghi</dd> is defined at $strRet. How can I use some combinations of str_replace and/or preg_replace functions to modify to the specific format?

Thanks in advance,



via Chebli Mohamed

Laravel store form file in alternative folder and access in request

At the moment, my application is stored on a Linux server (I do not have control of the server, so server adjustments are out of the question).

In my application there is a form where users can upload excel and csv files, the request is then being passed into a laravel validation request as shown below.

Whenever I try to upload the file, it claims the file is not there.

Laravel Request

public function rules()
{
    return [
        'user-file' => 'required|mimes:csv,xslx',
    ];
}

I've already figured out my problem, its that the default tmp folder stores and then instantly deletes the file so that the request cant find the file, so that by the time the above code runs, the file is no longer there and just returns an error.

How would I change the folder where the files are stored and point to there instead inside a request?

Something like

public function rules()
{
 $name = 'user-file' .'.'. $this->file('user-file')->getClientOriginalExtension();
 $move = $this->file('user-file')->storeAs('/newdirectory',$name);
 return [
    //Point to the new file inside 'newdirectory' for the below request validation
    'user_file' => 'required|mimes:csv,xslx',
 ];
}



via Chebli Mohamed

Laravel "function name must be a string" error on saving a model when code is executing second pass in a scheduled loop

I am running a daily schedule in Laravel 5.5 which selects matching Posts and runs a foreach loop that calls a static function in PostController, editing the Post model and saving it afterwards.

When the code is executed, everything works fine on the first loop with the first post, but on the second pass, I get the function name must be a string error on when the function attempts saving the model.

Here is the schedule in kernel.php

$schedule->call(function () {
    $posts = DB::table('post')
        ->where('finish_time', '<', Carbon::now()->toDateTimeString())
        ->where('status', '=', '1')
        ->where('expiry_processed_at', '=', null)
        ->get()->all();

    if(count($posts) > 0){
        foreach ($posts as $post){
            PostController::processExpiry($post->post_id);
        }
    }
})->everyMinute();

And here is the function it calls in PostController:

public static function processExpiry($post_id){
    $post = Study::find($post_id);
    $latestLicense = $post->licenses->last();

    $email = $post->user->email;
    $param = ['post' => $post];

    \Mail::send(['html' => 'emails.post_expiry', 'text' => 'emails.txt.post_expiry'], $param, function ($message) use ($email) {
        $message->to($email)
            ->subject(trans('email_subject.post_expiry'));
    });

    // Identify post as processed
    $post->expiry_processed_at = Carbon::now()->toDateTimeString();

    $validator = \Validator::make(
        $post->toArray(),
        $post->rules
    );
    try {
        $post->saveOrFail(); // This is the line where error occurs on second pass
    } catch (\Exception $e) {
        // catch is never triggered
        $messages = $e->getMessage();
        return (Object) array('status' => false, 'error_message' => 'Error saving post to database');
    }
    // return because same function can be called manually by user
    return (Object) array('status' => true);
}

Thank you for your help!



via Chebli Mohamed

The WHERE clause error in Laravel 5.4

I am creating a DB raw query, to return a record between two dates, but giving an error, my MYSQL look like this 2018-01-25 using the format Y-m-d

This is my query

public function index() {
        date_default_timezone_set('UTC');
        $format = 'Y/m/d';
        $now = date($format);
        $to = date($format);
        $data = [
            'from' => $now,
            'to' => $to
        ];

        $em = $this->getEm($data);
        return view('report.index', ['em' => $em, 'search' => $data]);
    }


private function getData($data) {
        return DB::table('A')     
        ->select('A.firstname', 'A.middlename', 'A.lastname')
        ->where('date_hired', '>=', $data['from'])
        ->where('date_hired', '<=', $data['to'])
        ->get()
        ->map(function ($item, $key) {
        return (array) $item;
        })
        ->all();
    }
}

The following error occurs when I run the query

 (1/1) InvalidArgumentException
Illegal operator and value combination.

The question is how to remove the error to return results, who can assist me



via Chebli Mohamed