Example #1
0
$authMiddleware = function () {
    return function (\Slim\Http\Request $request, \Slim\Http\Response $response, $next) {
        $token = null;
        $tokenObject = null;
        if ($request->hasHeader('X-User-Token')) {
            $token = $request->getHeader('X-User-Token');
            $tokenObject = \Dullahan\Model\UserToken::where('value', $token)->first();
        }
        if ($request->hasHeader('X-App-Token')) {
            $token = $request->getHeader('X-App-Token');
            $tokenObject = \Dullahan\Model\App::where('token', $token)->first();
        }
        // Allow access token as URL parameter in case custom headers are not supported by the client platform
        if ($request->getParam('app_token')) {
            $token = $request->getParam('app_token');
            $tokenObject = \Dullahan\Model\App::where('token', $token)->first();
        }
        if (!$token) {
            $error = ['message' => 'Access token missing', 'errorCode' => 'ACCESS_TOKEN_MISSING'];
            return $response->withJson($error, 401, JSON_PRETTY_PRINT);
        }
        if (!$tokenObject) {
            $error = ['message' => 'Access token invalid', 'errorCode' => 'ACCESS_TOKEN_INVALID'];
            return $response->withJson($error, 401, JSON_PRETTY_PRINT);
        }
        // If we are using user token, make the user object globally available to the application in the container
        if ($request->hasHeader('X-User-Token')) {
            $container = $this;
            $container->user = $tokenObject->user;
        }
        $response = $next($request, $response);