<?php
namespace App\Http\Middleware;

use Closure;
use DB;

class AuthenticateToken
{
	public function handle($request, Closure $next)
	{
		$user_id = 0;
		$user_access_level = 1;

		$token = $request->header('X-Access-Token');
		if($token) {
			$result = DB::table($_ENV['TOKEN_TABLE'])->where($_ENV['TOKEN_COLUMN'], $token)->first();

			if($result) {
				$user_id = $result['id'];

				$authUser = new \App\Http\Controllers\Auth\User($user_id);
				$user_access_level = $authUser->getTakenServicesByUser();
			}
		}
		
		$request->attributes->set('user_id', $user_id);
		$request->attributes->set('user_access_level', $user_access_level);
		$request->attributes->set('user_access_token', $token);

		return $next($request);
	}
}