Thursday, 25 October 2018

How to add google captcha in laravel


First, install anhskohbo/no-captcha Package for Google reCaptcha code. Using this Package, we can generate reCaptcha code for our Application.

composer require anhskohbo/no-captcha

Type below command to Publish Config File
php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"


In Env file add these lines

NOCAPTCHA_SECRET=6LfAxnYUAAAAAMFIDoHDyukSi4yHcYZp8q5WdB2m
NOCAPTCHA_SITEKEY=6LfAxnYUAAAAAH5JZ5xlK_iTjjkbdupMuvKeszYZ

Add this lines to your register or login page.

<div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
          <label for="ReCaptcha">Recaptcha:</label>
          {!! NoCaptcha::renderJs() !!}
          {!! NoCaptcha::display() !!}
            </div>
        </div>
 
Add in LoginContorller.php 
protected function validateLogin(Request $request)
    {   
         $this->validate($request,[
            'email' => ['required''string''email'],
            'password' => ['required''string'],
            'g-recaptcha-response' => ['required','captcha'],
        ]);
    }





Friday, 19 October 2018

How To Protect The .ENV File In Laravel From Public Access

Put this code in .htaccess to hide from access

     <Files ~ "\.(git|env|json|config.js|md|gitignore|gitattributes|lock|example)$">
        Order allow,deny
        Deny from all
    </Files>
    <Files ~ "(artisan)$">
        Order allow,deny
        Deny from all
    </Files>

How to hide .env passwords in Laravel when error occurs

Add this below line in  config/app.php


$envKeys = [];
$serverKeys = [];
$cookieKeys = [];
foreach ( $_ENV as $key => $value ) { if(is_string($value)) $envKeys[] = $key; }
foreach ( $_SERVER as $key => $value ) { if(is_string($value)) $serverKeys[] = $key; }
foreach ( $_COOKIE as $key => $value ) { if(is_string($value)) $cookieKeys[] = $key; }

return [

    // ...

    'debug_blacklist' => [
        '_COOKIE'   => $cookieKeys,
        '_SERVER'   => $serverKeys,
        '_ENV'      => $envKeys,
    ],

Monday, 8 October 2018

Database and files system backup

Database and files system backup

https://docs.spatie.be/laravel-backup/v5/installation-and-setup

composer require spatie/laravel-backup

php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"
 
In your config/database.php file, edit the mysql database config and add:

  'dump' => [
               'dump_binary_path' => 'C:/xampp/mysql/bin/', // only the path, so without `mysqldump` or `pg_dump`
               'use_single_transaction',
               'timeout' => 60 * 5, // 5 minute timeout
            ],

Create a folder in storage\app  site-backup.
 
Open config/backup.php file, 
'name' => 'site-backup',//env('APP_NAME', 'laravel-backup'), 

php artisan backup:run

Server up and down (Maintenance) Mode

Create a route

Route::get('/maintenance_down', 'OptimizeController@maintenance_down');
Route::get('/maintenance_up', 'OptimizeController@maintenance_up');


public function maintenance_down()
    { 
        $ip = \Request::ip();
          Artisan::call('down',['--allow'=>$ip]);
        return back();
    }   
    public function maintenance_up()
    {         
          Artisan::call('up');
        return back();
    }   

Database optimize

Create a route

Route::get('/database-optimize/','OptimizeController@database_optimize');

Add in a controller
 
use DB
public function database_optimize()
    {
        $users = DB::select('OPTIMIZE TABLE `users`');
        $orders = DB::select('OPTIMIZE TABLE `orders`');
        $orders_details = DB::select('OPTIMIZE TABLE `orders_details`');       
        $products = DB::select('OPTIMIZE TABLE `products`');
        return back();
    }

Optimize site

Create a route

Route::get('/site-optimize/','OptimizeController@site_optimize');

Add in a controller

public function site_optimize()
    {        
        Artisan::call('config:clear');
        Artisan::call('cache:clear');
        Artisan::call('view:clear');
        Artisan::call('route:clear');
        Artisan::call('config:cache');
        return back();
    }

How to store IP address of user after login?

How to store IP address of user after login?

https://packalyst.com/packages/package/yadahan/laravel-authentication-log

Follow below url to store IP address of s a user.

composer require yadahan/laravel-authentication-log

php artisan vendor:publish --provider="Yadahan\AuthenticationLog\
AuthenticationLogServiceProvider"

php artisan migrate

App\user.php
Add below lines

use Illuminate\Notifications\Notifiable;
use Yadahan\AuthenticationLog\AuthenticationLogable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable, AuthenticationLogable;
}

 


CORS

To use CORS follow below url details;



https://packalyst.com/packages/package/barryvdh/laravel-cors

How to set Sweet Alert.

To use sweet alert follow below url details;


https://packalyst.com/packages/package/uxweb/sweet-alert


List of online users

Follow these Steps

1. In route file.

Route::get('/useronline', 'HomeController@useronline')->name('useronline');

2. In HomeController

<?php

namespace App\Http\Controllers;
use App\user;
use Illuminate\Http\Request;

class HomeController extends Controller
{
   public function __construct(){ $this->middleware('auth'); }
      
    public function useronline()
    {
        $users = User::all();
        return view('useronline',compact('users'));
    }

public function isOnline()
    {
        return Cache::has('user-is-online-'. $this->id);
    }
}

3. View: useronline.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-8">
      <div class="card">
        <div class="card-header">Online users</div>
        <div class="card-body">
          <table class="table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
           
            @foreach ($users as $user)
            <tr>
              <td>{{ $user->name }}</td>
              <td>{{ $user->email }}</td>
              <td> @if ($user->isOnline())
                <li class="text-success"> Online </li>
                @else
                <li class="text-muted"> Offline </li>
                @endif </td>
            </tr>
            @endforeach
            </tbody>
           
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

How to login with username, email and mobile no?


checkstatus is a helper
<?php
namespace App\Http\Middleware;

use Closure;
use Auth;
use Session;

class CheckStatus
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if(Auth::check() && Auth::user()->status != '1'){
            Auth::logout();
            $request->session()->flash('alert-danger', 'Your Account is deactivated.');
            return redirect('/login')->with('erro_login', 'Your error text');
        }
        return $response;
    }
}
**********************************************************************************
Add below lines in login controller.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\User;

class LoginController extends Controller


use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;


public function __construct()
    {
         $this->middleware(['guest','checkstatus'])->except('logout');
    }
   
public function login(Request $request)
   {     
         $email = $request->email;
         if(is_numeric($email))
         {
            $auth = Auth::guard('web')->attempt(['mobile'=>$email,'password'=>$request->password]);
         }
         elseif (filter_var($email, FILTER_VALIDATE_EMAIL))
         {
            $auth = Auth::guard('web')->attempt(['email'=>$email,'password'=>$request->password]);
          }
         else
         {
               $auth = Auth::guard('web')->attempt(['name'=>$email,'password'=>$request->password]);
          }

         if($auth)
         { 
           return redirect()->route('home');         
                  $request->session()->put('email', $email);
          } else {
              session()->flash('login', 'Either Email or Password is incorrect.');
              return redirect()->route('login');
          }

      }

public function getLogin()
    {
          if(Auth::guard('web')->check()) {       
           return redirect()->route('login');
          }
          return view('auth.login');
    }
}

Note: active field should be there in user table with int(1). 
 
Login form

<div class="flash-message">
@if(Session::has('login'))
<p class="alert alert-danger" role="alert">{{ Session::get('login') }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
@endif
</div>           

<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
@endif
@endforeach
</div>

<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
  <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Name/Mobile/E-Mail') }}</label>
  <div class="col-md-6">
    <input id="email" type="text" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
    @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div>
</div>
<div class="form-group row">
  <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
  <div class="col-md-6">
    <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
    @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div>
</div>
<div class="form-group row">
  <div class="col-md-6 offset-md-4">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
      <label class="form-check-label" for="remember"> {{ __('Remember Me') }} </label>
    </div>
  </div>
</div>

<div class="form-group row mb-0">
  <div class="col-md-8 offset-md-4">
    <button type="submit" class="btn btn-primary"> {{ __('Login') }} </button>
    @if (Route::has('password.request')) <a class="btn btn-link" href="{{ route('password.request') }}"> {{ __('Forgot Your Password?') }} </a> @endif </div>
</div>
</form>

Prevent back history.

Create a middleware named PreventBackHistory

and add the below lines.

<?php
namespace App\Http\Middleware;

use Closure;

class PreventBackHistory
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')

            ->header('Pragma','no-cache')

            ->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT');
    }
}


Now Open the kernal.php.
Find  protected $routeMiddleware and add below line.

'prevent-back-history' => \App\Http\Middleware\PreventBackHistory::class,

In your route.php file write these lines.

Route::group(['middleware' => 'prevent-back-history'],function()
{

*********** Write your route files here. example************
           Route::get('/home', 'HomeController@index')->name('home');

});


Logout from Other device.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\User;
***************************************************
 
Add a field name session_id with varchar(100).

To logout from other device add below lines in login controller.

protected function sendLoginResponse(Request $request)
    {
         $request->session()->regenerate();
        $previous_session = Auth::User()->session_id;
        if ($previous_session) {
            Session::getHandler()->destroy($previous_session);
        }
   
        Auth::user()->session_id = Session::getId();
        Auth::user()->save();
        $this->clearLoginAttempts($request);
   
        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }

How to check status of user before login?

Create a middlewear named CheckStatus

and add the below lines.

<?php
namespace App\Http\Middleware;

use Closure;
use Auth;
use Session;

class CheckStatus
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if(Auth::check() && Auth::user()->status != '1'){
            Auth::logout();
            $request->session()->flash('alert-danger', 'Your Account is deactivated.');
            return redirect('/login')->with('erro_login', 'Your error text');
        }
        return $response;
    }
}

Now Open the kernal.php.
Find  protected $routeMiddleware and add below line.

'checkstatus' => \App\Http\Middleware\CheckStatus::class,

Next: In loginController contructor should be updated as below.

public function __construct()  { $this->middleware(['guest','checkstatus'])->except('logout');  }

Next: In  your login.blade.php the error should be there.


<div class="flash-message"> @foreach (['danger', 'warning', 'success', 'info'] as $msg)
            @if(Session::has('alert-' . $msg))
            <p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
            @endif
            @endforeach </div>

Note. In your user table status field with int(1) should be there.

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...