Group middleware not working in Laravel 8 for protected URL after logged in when hit login in URL it's show login page - laravel-8

After logged in I hit login in URL its show login page
$path=$request->path();
$emailcheck = session()->get('email');
if(!Session::get('email') && $path !=="skc-admin/login"){
//echo Session::get('email');
return redirect('/');
//echo $path;
}elseif($path =="skc-admin/login" && Session::get('email') ){
return redirect("skc-admin/dashboard");
}
return $next($request);

Related

How to implement code for OAuth 2.0 Authorization for Google Directory API Without Command Line Interface

I have seen code in google directory api documentation for command line interface and have worked with it, the code works fine. But I want write code that runs without terminal and runs when on a page when the page is loaded because i have to run the code in the terminal every hour after it's expired, is there anyway i can get the code to run when i visit the page of authorization code.
The code work's with command-line interface, but i want it to work without command-line, what can i do?
Given Below is the code from Google Directory API and the URL:
URL : https://developers.google.com/admin-sdk/directory/v1/quickstart/php
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('G Suite Directory API PHP Quickstart');
$client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
// Print the first 10 users in the domain.
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 10,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
if (count($results->getUsers()) == 0) {
print "No users found.\n";
} else {
print "Users:\n";
foreach ($results->getUsers() as $user) {
printf("%s (%s)\n", $user->getPrimaryEmail(),
$user->getName()->getFullName());
}
}
I have also tried to implement the code from OAuth 2.0 for Web Server Applications in wordpress page with the template but it's not working, which is from https://developers.google.com/identity/protocols/oauth2/web-server#php_1
and this is my code:
<?php
require __DIR__ . '/vendor/autoload.php';
session_start();
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
$client = new Google_Client();
$client->setApplicationName('G Suite Directory API PHP Quickstart');
$client->addScope(Google_Service_Directory::ADMIN_DIRECTORY_USER);
$client->setAuthConfig('/path/to/credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Directory($client);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Google oAuth not working after 3600 seconds

I'm using google oAuth for getting youtube latest streaming. It works for 3600 seconds. But then it stopped working. After some researching at stackoverflow, many people wrote to use "SetAccessType": "offline" .
I did it but same result.
Here is my snippet.
<?php
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
$stream_id = "";
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
$OAUTH2_CLIENT_ID = '972289696318-q037nr25oti8gs5h7hcj5lfkl7erklh6.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'cbmQyfeXWGb93RkN7KSHLQKB';
$client = new Google_Client();
$client->setAccessType('online');
$client->setClientId($OAUTH2_CLIENT_ID);
//$client->setExpires_in('10000000');
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
//print_r($youtube);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
/*
if ($client->isAccessTokenExpired()) {
$refreshToken = $client->getRefreshToken();
//print_r($refreshToken);
// $client->refreshToken($refreshToken);
$newAccessToken = $client->getAccessToken();
$newAccessToken['refresh_token'] = $refreshToken;
file_put_contents($credentialsPath, json_encode($newAccessToken));
}
*/
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Execute an API request that lists broadcasts owned by the user who
// authorized the request.
//print_r($youtube);
$broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
'id,snippet',
array(
'mine' => 'true',
));
//print_r($broadcastsResponse);
$htmlBody .= "<h3>Live Broadcasts</h3><ul>";
$count = 0;
foreach ($broadcastsResponse['items'] as $broadcastItem) {
// print_r($count+1);
$count = $count+1;
if($count == 1) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $broadcastItem['snippet']['title'],
$broadcastItem['id']);
$stream_id = $broadcastItem['id'];
}
// print_r($broadcastItem);
}
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'Replace_me') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Live Broadcasts</title>
</head>
<body>
<?php echo $stream_id; ?>
</body>
</html>
Any idea what can i do?
NB: My purpose is, any one can authenticate here and can get latest youtube streaming id. But I'm struct with oAuth after 3600 seconds.
:(
Your Access Token has an expiry time. The expiry usually is half an hour (1800 seconds), although this can vary. The value is set by the Authentication Server. The expiry time is sent to you along with the Access Token.
After the Access Token expires, the server will no longer accept it. You must request a new one using your Refresh Token. You should have gotten it along with the first Access Token.
If you do not have a Refresh Token, you'll have to log in again.

Woocommerce how do I redirect to a Specific Page upon Login?

When a user logs in Woocommerce open the MyAccount Page
I need to go to detailing a range of Services we offer.
On that page I want to set a Tick Box if they agree to be called by our Sales staff.
If the users selects this - I would like to set a Session variable which I can use at Cart.
Here are some snippets that will guide you to do that
After login:-
// Custom redirect for users after logging in
add_filter('woocommerce_login_redirect', 'wcs_login_redirect');
function wcs_login_redirect( $redirect ) {
$redirect = 'http://google.com/';
return $redirect;
}
After login but just after register:-
// Custom redirect for users after logging in
add_filter('woocommerce_registration_redirect', 'wcs_register_redirect');
function wcs_register_redirect( $redirect ) {
$redirect = 'http://google.com/';
return $redirect;
}
Redirect the user based on their role :-
function wc_custom_user_redirect( $redirect, $user ) {
// Get the first of all the roles assigned to the user
$role = $user->roles[0];
$dashboard = admin_url();
$myaccount = get_permalink( wc_get_page_id( 'myaccount' ) );
if( $role == 'administrator' ) {
//Redirect administrators to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'shop-manager' ) {
//Redirect shop managers to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'editor' ) {
//Redirect editors to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'author' ) {
//Redirect authors to the dashboard
$redirect = $dashboard;
} elseif ( $role == 'customer' || $role == 'subscriber' ) {
//Redirect customers and subscribers to the "My Account" page
$redirect = $myaccount;
} else {
//Redirect any other role to the previous visited page or, if not available, to the home
$redirect = wp_get_referer() ? wp_get_referer() : home_url();
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );

ZF2 - init or something that is called in every module controller

I have a Module called "Backend" and in this module I want to check for valid authentication on all pages except the backend_login page. How do I do this? I tried to add it to the onBootstrap in the Backend/Module.php , but it turns out that is called in my other modules as well... which is of course not what I want.
So how do I do this?
Thanks in advance!
To get clear information about zf2 authentication you can follow:
ZF2 authentication
adapter auth
database table auth
LDAP auth
digest auth....These all are different methods here is an example of database table auth:
in every controller's action, where you need user auth something should like this:
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
public function login($credential)
{
$bcrypt = new Bcrypt();
$user = new User();
$auth = new AuthenticationService();
$user->exchangeArray($credential);
$password = $user->password;
$data = $this->getUserTable()->selectUser($user->username);
if (!$data){
$message = 'Username or password is not correct!';
}
elseif($auth->getIdentity() == $user->username){
$message = 'You have already logged in';
}
elseif($bcrypt->verify($password, $data->password)){
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter(
$dbAdapter,
'user',
'username',
'password'
);
$authAdapter -> setIdentity($user->username) -> setCredential($data->password);
$result = $auth->authenticate($authAdapter);
$message = "Login succesfull.Welcome ".$result->getIdentity();
} else {
$message = 'Username or password is not correct';
}
return new ViewModel(array("message" =>$message));
}
Like this in every action you can check whether it is authenticated or not
if($auth -> hasIdentity()){
//your stuff
}
else{
//redirected to your login route;
}
I had once a similar problem and figured it out within my Module.php in the onBootstrap() function. Try this, it worked for me:
class Module {
// white list to access with being non-authenticated
//the list may contain action names, controller names as well as route names
protected $whitelist = array('login');
//....
public function onBootstrap($e){
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$list = $this->whitelist;
$auth = new AuthenticationService();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
$match = $e->getRouteMatch();
// No route match, this is a 404
if (!$match instanceof RouteMatch) {
return;
}
// Route is whitelisted
$action = $match->getParam('action');
if (in_array($action, $list) ) {
return;
}
// User is authenticated
if ($auth->hasIdentity()){
return;
}
// the user isn't authenticated
// redirect to the user login page, as an example
$router = $e->getRouter();
$url = $router->assemble(array(
'controller' => 'auth',
'action'=>'login'
), array(
'name' => 'route_name',
));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
}
Or you may see bjyauthorize.

In yii login functionality when password is wrong

In yii i am creating login functionality. When user enters correct username but wrong password i want to make serach in database for this correct username and want to put that username's id into loginattemmpt table and display wrong password message to him. So can please someone help me.
in userIdentity.php save data in table .
public function authenticate() {
$user = User::model()->findByAttributes(array('username' => $this->username));
if ($user === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
}
elseif($user->password !== crypt($this->password, $salt))
{ // save $user->id in attempt table here .
$this->errorCode = self::ERROR_PASSWORD_INVALID;
}else{
//set id
}
and in file from where authenticate function is called setError.
$this->_identity = new UserIdentity($this->username, $this->password);
if (!$this->_identity->authenticate())
if ($this->_identity->errorCode === UserIdentity::ERROR_USERNAME_INVALID) {
$this->addError('password', 'Incorrect email Id');
}elseif($this->_identity->errorCode === UserIdentity::ERROR_PASSWORD_INVALID){
$this->addError('password', 'Incorrect Password');
}