$ok = 0;
    }
}
if (!$ok) {
    $rsp = array('error' => $error);
    local_send_json($rsp);
    exit;
}
# Purge the grant
api_oauth2_grant_tokens_delete($grant_token);
# Generate the access token (check to make sure one doesn't already exist)
$access_token = api_oauth2_access_tokens_get_for_user_and_key($user, $key_row);
if (!$access_token) {
    $perms = $grant_token['perms'];
    $ttl = $grant_token['ttl'];
    $rsp = api_oauth2_access_tokens_create($key_row, $user, $perms, $ttl);
    if (!$rsp['ok']) {
        $rsp = array('error' => 'server_error');
        local_send_json($rsp);
        exit;
    }
    $access_token = $rsp['token'];
}
# Okay, soup for you!
$perms_map = api_oauth2_access_tokens_permissions_map();
$scope = $perms_map[$access_token['perms']];
$expires = $access_token['expires'];
$expires_in = $expires - time();
$rsp = array('access_token' => $access_token['access_token'], 'scope' => $scope, 'expires' => $expires, 'expires_in' => $expires_in);
local_send_json($rsp);
exit;
        $GLOBALS['smarty']->assign("title", $title);
        $GLOBALS['smarty']->assign("perms", $perms);
        $GLOBALS['smarty']->assign("ttl", $ttl);
        $step = 2;
    }
    if ($ok && $conf) {
        $key = null;
        $token = null;
        $step = 3;
        $description = "";
        $rsp = api_keys_create($GLOBALS['cfg']['user']['id'], $title, $description);
        $key = $rsp['key'];
        if (!$rsp['ok']) {
            $ok = 0;
        }
        if ($ok) {
            $rsp = api_oauth2_access_tokens_create($key, $GLOBALS['cfg']['user'], $perms, $ttl);
            $token = $rsp['token'];
            if (!$rsp['ok']) {
                $ok = 0;
            }
        }
        $GLOBALS['smarty']->assign("try_update", 1);
        $GLOBALS['smarty']->assign("update_ok", $ok);
        $GLOBALS['smarty']->assign_by_ref("api_key", $key);
        $GLOBALS['smarty']->assign_by_ref("token", $token);
    }
}
$GLOBALS['smarty']->assign("step", $step);
$GLOBALS['smarty']->display("page_api_oauth2_authenticate_like_magic.txt");
exit;