afabris

at Codeten Ltd

Experience

1,530

1 Best Reply Awards

  • Member Since 4 Months Ago
  • 6 Lessons Completed
  • 0 Favorites

19th October, 2017

afabris left a reply on Allowing Access To API Via Token And Session • 1 month ago

Thanks I tried, but something seems missing. Auth::check() does not work - user is not logged in. If I add guard('auth:api') or any other still does not work.

However, I found the easier solution. routes.php uses web guard, and my api_routes uses api guard. web guard is session and api guard is token.

So I moved APIs that need to use session for authorisation to routes.php and left APIs that need to use token for authorisation in api_routes.php. This works exactly as I need. I hope it will help someone in the future.

afabris left a reply on MySQL Creating Updatable View From Two Tables • 1 month ago

@Snapey Here is the scenario maybe you have a better idea how to get around it. My Laravel App has user and roles database, and with it I can have a unknown number of other apps, lets say Mantis like in example above, WP, etc. That is all on the same server. I want to have seamless user integration in all apps. As each app has its own user authorization and user tables as it is independent system. Now the idea with views was to create a replacement user table which would get some columns from Laravel and some from the app I am trying to integrate. In this case I do not have to change every single query in every single app. Now while this successfully fools the app when reading the data, it does not work when it wants to update the data. The idea of syncing the user data is not good for this project, as it is unknown which apps will be there, and their potential structure of user and role data. I can get user data from APIs, and that works in some cases, where apps do not query user table too often and in too many places. The idea is to change the apps as little as possible, for stability and upgrade-ability. Also the solution should work for any app with minor modifications. I know there is no perfect solution, but any ideas how would you or anybody else approach this would be quite useful. Thanks in advance, Andre

17th October, 2017

afabris left a reply on MySQL Creating Updatable View From Two Tables • 1 month ago

@Snapey it says in the article (link above) that under certain conditions they are. At the bottom in the comments there is a example how to do this. However it is above my current knowledge.

afabris started a new conversation Allowing Access To API Via Token And Session • 1 month ago

I have APIs that can be accessed by 3rd party apps, and APIs that need to be accessed by users. 3rd party apps are on the same server and share the database, so I managed this using in config/auth.php


'api' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

Users however are on the different server, and they need to use token, so in this case I need to use:

'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

However I need to use this at the same time. Is there a simple way to accomplish this (Laravel 5.2).

Thanks, Andre

afabris left a reply on Multiple Guards At One Route? • 1 month ago

What is stopping this to happen? I mean as a logged in user, you surely can execute DB query to list all partners and vice versa.

afabris started a new conversation MySQL Creating Updatable View From Two Tables • 1 month ago

Ok, I want to create a view based on two user tables. View has to be updatable.

I have

CREATE OR REPLACE
ALGORITHM=UNDEFINED 
DEFINER=`root`@`localhost` SQL SECURITY DEFINER
VIEW `mantis_user_table` AS select 
        `front_myadmin`.`users`.`id` AS `id`,
        `front_myadmin`.`users`.`username` AS `username`,
        CONCAT(`front_myadmin`.`users`.`firstname`, ' ',  `front_myadmin`.`users`.`lastname`)  AS `realname`,
        `front_myadmin`.`users`.`email` AS `email`,
        `front_myadmin`.`users`.`password` AS `password`,
        `front_myadmin`.`users`.`enable` AS `enabled`,
        `front_myadmin`.`users`.`created_at` AS `date_created`,
        `front_mybugs`.`appsforce_user_table`.`protected` AS `protected`,
        `front_mybugs`.`appsforce_user_table`.`access_level` AS `access_level`,
        `front_mybugs`.`appsforce_user_table`.`login_count` AS `login_count`,
        `front_mybugs`.`appsforce_user_table`.`lost_password_request_count` AS `lost_password_request_count`,
        `front_mybugs`.`appsforce_user_table`.`failed_login_count` AS `failed_login_count`,
        `front_mybugs`.`appsforce_user_table`.`cookie_string` AS `cookie_string`,
        `front_mybugs`.`appsforce_user_table`.`last_visit` AS `last-visit` 
      
        from `front_myadmin`.`users` , `front_mybugs`.`appsforce_user_table` WHERE `front_myadmin`.`users`.`id` =  `front_mybugs`.`appsforce_user_table`.`id`;

But while this works and view is created as well as readable, I cannot update the underlying tables: Database query failed. Error received from database was #1393: Can not modify more than one base table through a join view 'front_mybugs.mantis_user_table' for the query: UPDATE mantis_user_table

I am far from SQL expert, and this is as far as my knowledge goes. At this link it seems that I have to use INNER JOIN (https://dev.mysql.com/doc/refman/5.5/en/view-updatability.html) but have no idea how to apply it to above code.

Any help really welcome at this stage!

8th October, 2017

afabris left a reply on How To Appraoch API Call From A External Site - Issue With Invalid Credentials. "Invalid Credentials." • 1 month ago

I have this resolved. Due to multiple bugs, it did not work. One of the things were issues with .htaccess files, etc. Ended up using token authentication, instead of basic.auth as well

7th October, 2017

afabris started a new conversation How To Appraoch API Call From A External Site - Issue With Invalid Credentials. "Invalid Credentials." • 1 month ago

Hello

I have an issue that I cannot resolve, so I hope community might share some light. I have Laravel App, and it has APIs. Mostly they work fine, except when I get external request and that does not work - I get Invalid credentials response

So my kernel.php has this

protected $middlewareGroups = [
         'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\Language::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

        'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class
        ],
    ];

my RouteServiceProvide.php

protected function mapWebRoutes(Router $router)
    {
        $router->group([
            'namespace' => $this->namespace, 'middleware' => 'web',
        ], function ($router) {
            require app_path('Http/routes.php');
        });
    }
    
    protected function mapApiRoutes(Router $router){
        $router->group([
            'middleware' => 'api', 'namespace' => $this->namespace.'\API', 'prefix' => 'api'
        ], function ($router) {
            $router->group([
                'prefix' => 'v1'
            ], function(){
                require app_path('Http/api_routes.php');
            });
        });
    }

my api_routes.php

Route::get('init/{email}', '[email protected]');

And BackAPIs controller has

public function __construct() {
        $this->middleware('auth.basic');
    }

and

 function init(Request $request, $email) {

        try {
            $decrypted = decrypt($email);

.......

My external application is using the code straight from Postman (which seems to work fine and I get required responses)

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://appsforce.front/api/v1/init/eyJpdiI6ImN5Y2hteTJtbGFXUjZoMkJNU3I4RHc9PSIsInZhbHVlIjoiZDJEVWRwVHJFazE2SldkSzIwMGVha1V0aEdQVDJQWjdjb2RLZ1RcL1VHQU09IiwibWFjIjoiZjM2NzA3NzIzZjc5NjkyNmRlZTgwMzAyZmEyMDQ1OTE0YTYwYTlhNGJmN2MwNzc3YTI5OGQ4NDZhNjEzYWU5YyJ9",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic YWZAYXBwc2ZvcmNlLmNvLnVrOmFwcHNmb3JjZQ==",
    "cache-control: no-cache",
    "postman-token: 6ee8747a-0d3a-3660-09d9-c0449f1bc877"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
dd($response);

My problem is that I always get Invalid credentials. "Invalid credentials."

I tried many things, but it just does not want to play game. Any ideas are welcome.

Many thanks in advance.

13th September, 2017

afabris left a reply on .env File Is Not Generated Via Forge APIs Or Recipes • 2 months ago

Thanks @karni I also noticed that https://forge.laravel.com/api-documentation#create-server should return credentials. And then I can use another API to manually create .env file. But I did not see API which would just generate it automatically

12th September, 2017

afabris left a reply on $errors Is Always Empty On Login Screen • 2 months ago

I have found what was wrong: In Kernel.php I had this code:

  protected $middleware = [
         'App\Http\Middleware\Language',
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

When I removed Start Session and Share Errors From Session the issue was resolved. However, I removed everything else except for last CheckForMaintenance and the app resumed working as normal, so I have no idea what all this doing in my code.

9th September, 2017

afabris left a reply on $errors Is Always Empty On Login Screen • 2 months ago

Thanks, it seems it is only once (I have seen the issue if it redirects twice on forums and checked routes:list to make sure web is not duplicated). First call is: Request URL:http://appsforce.back/login Request Method:POST Status Code:302 Found Second is: Request URL:http://appsforce.back/ Request Method:GET Status Code:200 OK and the rest is CSS and Javascripts.

in Routes.php Route::get('/', '[email protected]'); and that function in controller executes return view('auth.login');

Does it mean that Controller 'loses' the $error message?

afabris left a reply on $errors Is Always Empty On Login Screen • 2 months ago

The code put there is just for testing to see does it create error message at all, and it does. I did not change anything in the vendor folder anyway.

However I also tried this to get to the bottom of it - In my controller I have

\Session::flash('msg', 'Changes Saved.' );
        return redirect('mygroups')->with('status', 'Department created!');

And in my view I have

<?php echo '<pre>';
                    var_dump(session()->all()); ?>
                    @if (session('status'))
                    <div class="alert alert-success">
                        {{ session('status') }}
                    </div>
                    @endif
                    @if (Session::has('msg'))
                    <div class="alert alert-success">
                        {!!Session::get('msg')!!}
                    </div>
                    @endif

But no mesages are diplayed. It seems once it hits the routes it dissapears.

afabris started a new conversation $errors Is Always Empty On Login Screen • 2 months ago

Hello, this is a bit wierd, but I am stuck, and could not find anything similar on the web. On the login screen I want to display login errors. Now this works fine in basic laravel installation, but it does not work on mine:

I put this in AuthenticatesUsers.php

protected function sendFailedLoginResponse(Request $request)
    {
 $err = $this->loginUsername();
        $err2 = $this->getFailedLoginMessage();
        
        return redirect('login')
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);

Just to make sure that I do get the error messages. And this works In routes.php I added:

$errors = Session::get('errors');
    if ($errors != null) dd ($errors);

In order to test does it actually create $error before it redirects back to login view but the $errors are null, so when I try to display login $errors in the view it always fails.

Any ideas what could I check to make sure it works as it shoudl?

Thanks

Andre

7th September, 2017

afabris left a reply on .env File Is Not Generated Via Forge APIs Or Recipes • 2 months ago

Thanks, but when I run that it says: You are already using composer version 1.5.1 (stable channel). So I guess it is up-to-date

afabris started a new conversation .env File Is Not Generated Via Forge APIs Or Recipes • 2 months ago

This is the scenario. We want fully automated server creation and app installation. We have Forge and Linode accounts and via Forge APIs successfully create server instance. We then want to execute recepy, to get our App from the Git, and then set it up. Git clone works fine, Composer install works fine, and it fails on Migrate as the .env file is not set up. Forge does send the credentials via e-mail, but this is not good, I cannot create .env files manually for each installation. If I use Forge web site, and go to site, enter the Git link, it works, pulls the code, executes composer, migrates the databases and creates .env

Apparently this is the script that it uses, but it does not work as a recepy (does not create .env)

cd /home/forge/default git pull origin master composer install --no-interaction --prefer-dist --optimize-autoloader echo "" | sudo -S service php5.6-fpm reload

if [ -f artisan ] then php artisan migrate --force fi

Any ideas? Many thanks, Andre

12th July, 2017

afabris left a reply on API Call With CURL Resolves Auth::user() To NULL While HTTP Call In Browser Works Fine • 4 months ago

Many thanks guys for your help. Adding cookie was part of the solution. I also had to edit auth.php, to user session for APIs as well:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],

afabris left a reply on API Call With CURL Resolves Auth::user() To NULL While HTTP Call In Browser Works Fine • 4 months ago

Hm, I actually do not need and cannot use tokens. I log in user in Laravel, and manage their access to external applications. So external application should call APIs in Laravel, and fetch the environment settings as well as logged in user, their roles etc. When the external application starts it does not know the logged in user and cannot get its token.

External application is on the same server, and it has access to the session, and I wanted to use cURL to fetch some data. As you said there is no session in cURL, and therefore stuff like Auth::user() fails. I need to somehow use the same session in cURL call, or use some alternative to cURL which would maintain the same session. I googled this extensively, tried a number of ideas, but still failed. Any ideas are welcome :)

I have no idea is it at all possible to fetch the user token based on session info that I have in external information.

afabris left a reply on API Call With CURL Resolves Auth::user() To NULL While HTTP Call In Browser Works Fine • 4 months ago

Ok, that makes sense, so how do I work around it?

afabris started a new conversation API Call With CURL Resolves Auth::user() To NULL While HTTP Call In Browser Works Fine • 4 months ago

Hello, I am really stuck on this weird thing. I made API calls, routes etc, and it all works fine when I test it in browser. For example this http://appsforce.back/api/v1/100000001/env Returns {"code":200,"message":"Request was succesfull","data":{"host":"127.0.0.1","dbuser":"root","dbpassword":"","dbprefix":"back_"}} While: $url = $_SERVER['HTTP_HOST'] .'/api/v1/100000002/env'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPGET, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response_json = curl_exec($ch); curl_close($ch); $response=json_decode($response_json, true); Returns same result. So far is so good if I don't use in my code call to Auth::user();

So this is the code that returns result: $user = \Auth::user(); $env = array( 'host' => $_ENV['DB_HOST'], 'dbuser' => $_ENV['DB_USERNAME'], 'dbpassword' => $_ENV['DB_PASSWORD'], 'dbprefix' => $_ENV['DB_PREFIX']); $response = array( 'code' => 200, 'message' => $this->codes['200'], 'data' => $user, ); return $response; If I put 'data' =>$user this returns NULL, while 'data' => $env returns correct $_ENV settings when called via cURL.

For my APIs I need to use \Auth::user() and I just cannot get it to work through cURL while HTTP calls in browser work just fine and the user is returned: {"code":200,"message":"Request was succesfull","data":{"id":10,"username":"afabris","firstname":"Andre","lastname": ......

many thanks, Andre

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.