Beispiel #1
0
<?php

use Illuminate\Database\Capsule\Manager as DB;
use API\Core\Tool;
use API\Model\Plugin;
use API\OAuthServer\OAuthHelper;
$version_plugins = Tool::makeEndpoint(function ($version) {
    OAuthHelper::needsScopes(['version', 'plugins']);
    $plugins = Tool::paginateCollection(Plugin::short()->with('authors', 'versions', 'descriptions')->withAverageNote()->descWithLang(Tool::getRequestLang())->withGlpiVersion($version));
    Tool::endWithJson($plugins);
});
$app->get('/version/:version/plugin', $version_plugins);
$app->options('/version/:version/plugin', function () {
});
Beispiel #2
0
 /**
  * This decorates a lambda function that
  * serves as an endpoint, it makes
  * use of try{}catch{} to generate
  * various responses
  */
 public static function makeEndpoint($callable)
 {
     $decoratedEndpoint = function () use($callable) {
         $args = func_get_args();
         try {
             try {
                 call_user_func_array($callable, $args);
             } catch (\Exception $e) {
                 global $app;
                 if (!preg_match('/^API\\\\Exception/', get_class($e))) {
                     switch (get_class($e)) {
                         case 'League\\OAuth2\\Server\\Exception\\InvalidRequestException':
                             $parameter = explode('"', $e->getMessage())[1];
                             switch ($parameter) {
                                 case 'client_secret':
                                     $clientId = null;
                                     $clientSecret = null;
                                     if ($app->request->post('client_id')) {
                                         $clientId = $app->request->post('client_id');
                                     }
                                     if ($app->request->post('client_secret')) {
                                         $clientSecret = $app->request->post('client_secret');
                                     }
                                     throw (new \API\Exception\ClientSecretError($clientId, $clientSecret))->childOf($e);
                                     break;
                                 case 'access token':
                                     throw (new \API\Exception\NoAccessToken())->childOf($e);
                                     break;
                             }
                             break;
                         case 'League\\OAuth2\\Server\\Exception\\InvalidClientException':
                             $clientId = null;
                             $clientSecret = null;
                             if ($app->request->post('client_id')) {
                                 $clientId = $app->request->post('client_id');
                             }
                             if ($app->request->post('client_secret')) {
                                 $clientSecret = $app->request->post('client_secret');
                             }
                             throw (new \API\Exception\ClientSecretError($clientId, $clientSecret))->childOf($e);
                             break;
                         case 'League\\OAuth2\\Server\\Exception\\AccessDeniedException':
                             if (isset($app->request->headers['authorization'])) {
                                 $token = $app->request->headers['authorization'];
                             } else {
                                 $token = null;
                             }
                             throw (new \API\Exception\AccessDenied($token))->childOf($e);
                             break;
                         case 'League\\OAuth2\\Server\\Exception\\InvalidRefreshException':
                             if ($app->request->post('refresh_token')) {
                                 $token = $app->request->post('refresh_token');
                             } else {
                                 $token = null;
                             }
                             throw (new \API\Exception\InvalidRefreshToken($token))->childOf($e);
                             break;
                         case 'League\\OAuth2\\Server\\Exception\\InvalidScopeException':
                             $parameter = explode('"', $e->getMessage())[1];
                             throw (new \API\Exception\InvalidScope($parameter))->childOf($e);
                             break;
                         case 'League\\OAuth2\\Server\\Exception\\InvalidCredentialsException':
                             throw (new \API\Exception\InvalidCredentials($app->request->post('username') ? $app->request->post('username') : null, $app->request->post('password') ? strlen($app->request->post('password')) : 0))->childOf($e);
                             break;
                         case 'Slim\\Exception\\Stop':
                             // we just let SLim halt() the app
                             break;
                         default:
                             // ServiceError exception will use
                             // file, line and exception message as private
                             // data and send the simple code (without
                             // critical information to the user)
                             $serviceError = new \API\Exception\ServiceError($e->getFile(), $e->getLine(), $e->getMessage());
                             // we don't use ->childOf() on this one,
                             // we're already provinding File, Line and Message
                             // of the Exception
                             throw $serviceError;
                             break;
                     }
                 } else {
                     throw $e;
                 }
             }
         } catch (ErrorResponse $e) {
             $e->log();
             return Tool::endWithJson(["error" => $e->getRepresentation(true)], $e->httpStatusCode);
         }
     };
     return $decoratedEndpoint;
 }
Beispiel #3
0
    $all = Tool::paginateCollection(\API\Model\Author::mostActive()->contributorsOnly());
    Tool::endWithJson($all);
};
$top = function () use($app) {
    $top = \API\Model\Author::mostActive(10)->get();
    Tool::endWithJson($top);
};
$single = function ($id) use($app) {
    $single = \API\Model\Author::withPluginCount()->find($id);
    Tool::endWithJson($single);
};
$author_plugins = function ($id) use($app) {
    $author_plugins = \API\Model\Author::find($id);
    if (!$author_plugins) {
        return Tool::endWithJson(["error" => "Cannot find author"]);
    }
    Tool::endWithJson(Tool::paginateCollection(\API\Model\Plugin::with('versions', 'authors')->short()->withDownloads()->withAverageNote()->descWithLang(Tool::getRequestLang())->whereAuthor($author_plugins->id)));
};
// HTTP REST Map
$app->get('/author', $all);
$app->get('/author/top', $top);
$app->get('/author/:id', $single);
$app->get('/author/:id/plugin', $author_plugins);
$app->options('/author', function () {
});
$app->options('/author/top', function () {
});
$app->options('/author/:id', function ($id) {
});
$app->options('/author/:id/plugin', function ($id) {
});
Beispiel #4
0
                case 'subject':
                    if (gettype($body->contact->subject) != 'string' || strlen($body->contact->subject) > 280) {
                        throw new InvalidField('subject');
                    }
                    break;
                case 'message':
                    if (gettype($body->contact->message) != 'string' || strlen($body->contact->message) > 16000) {
                        throw new InvalidField('message');
                    }
                    break;
            }
        }
    }
    // Sending mail
    $mailer = new Mailer();
    $mailer->sendMail('user_message.html', Tool::getConfig()['msg_alerts']['local_admins'], '[MSG] ' . $body->contact->subject, ['firstname' => $body->contact->firstname, 'lastname' => $body->contact->lastname, 'email' => $body->contact->email, 'message' => $body->contact->message], [$body->contact->email => $body->contact->firstname . ' ' . $body->contact->lastname]);
    // also saving message in database
    $message = new Message();
    $message->first_name = $body->contact->firstname;
    $message->last_name = $body->contact->lastname;
    $message->email = $body->contact->email;
    $message->subject = $body->contact->subject;
    $message->message = $body->contact->message;
    $message->sent = DB::raw('NOW()');
    $message->save();
    Tool::endWithJson(["success" => true]);
});
// HTTP REST Map
$app->post('/message', $send);
$app->options('/message', function () {
});
Beispiel #5
0
    if (isset($body->homepage_url)) {
        if (gettype($body->homepage_url) != 'string' || !App::isValidUrl($body->homepage_url)) {
            throw new InvalidField('homepage_url');
        } else {
            $user_app->homepage_url = $body->homepage_url;
        }
    }
    if (isset($body->description)) {
        if (gettype($body->description) != 'string' || !App::isValidDescription($body->description)) {
            throw new InvalidField('description');
        } else {
            $user_app->description = $body->description;
        }
    }
    $user_app->save();
    Tool::endWithJson($user_app);
});
$user_delete_app = Tool::makeEndpoint(function ($id) use($app, $resourceServer) {
    OAuthHelper::needsScopes(['user', 'user:apps']);
    $body = Tool::getBody();
    $user_id = $resourceServer->getAccessToken()->getSession()->getOwnerId();
    $user = User::where('id', '=', $user_id)->first();
    $user_app = $user->apps()->find($id);
    if ($user_app) {
        $user_app->delete();
        $app->halt(200);
    } else {
        throw new ResourceNotFound('App', $id);
    }
});
// HTTP REST Map
Beispiel #6
0
<?php

/**
 * Search
 *
 * This REST module hooks on
 * following URLs
 *
 * /search
 */
use API\Core\Tool;
use Illuminate\Database\Capsule\Manager as DB;
// Minimal length of search string
$search_min_length = 2;
$search = function () use($app) {
    global $search_min_length, $allowed_languages;
    $body = Tool::getBody();
    if ($body == NULL || !isset($body->query_string) || strlen($body->query_string) < $search_min_length) {
        return Tool::endWithJson(["error" => "Your search string needs to " . "have at least " . $search_min_length . " chars"], 400);
    }
    $query_string = $body->query_string;
    $_search = Tool::paginateCollection(\API\Model\Plugin::short()->with('authors', 'versions', 'descriptions')->withDownloads()->withAverageNote()->descWithLang(Tool::getRequestLang())->where('name', 'LIKE', "%{$query_string}%")->orWhere('plugin_description.short_description', 'LIKE', "%{$query_string}%")->orWhere('plugin_description.long_description', 'LIKE', "%{$query_string}%"));
    Tool::endWithJson($_search);
};
$app->post('/search', $search);
$app->options('/search', function () {
});
Beispiel #7
0
\API\Core\DB::initCapsule();
use API\Core\Tool;
$app = new \Slim\Slim();
// Loading all REST modules
// with their endpoints like that:
// inside 'src/endoints'
$dir_endpoints = opendir('src/endpoints');
while ($ent = readdir($dir_endpoints)) {
    // For each .php file
    if (preg_match('/^(.*)\\.php$/', $ent, $m)) {
        $endpoint = $m[0];
        // Read the file with PHP
        require 'src/endpoints/' . $endpoint;
    }
}
closedir($dir_endpoints);
// Logs to error_log specified in virtualhost
$app->error(function (\Exception $e) {
    Tool::endWithJson(["error" => "Server error"], 500);
    Tool::log($e->getMessage());
});
// JSON 404 response
$app->notFound(function () {
    Tool::endWithJson(["error" => "invalid endpoint"], 404);
});
// Welcoming browsers when they reach /api
$app->get('/', function () use($app) {
    echo file_get_contents(__DIR__ . '/welcome.html');
});
// Ready to serve with Slim
$app->run();
Beispiel #8
0
    if ($watch) {
        $watch->delete();
    } else {
        $app->halt(404);
    }
    $app->halt(200);
});
$user_search = Tool::makeEndpoint(function () {
    OAuthHelper::needsScopes(['users:search']);
    $body = Tool::getBody();
    if (!isset($body->search) || gettype($body->search) != 'string') {
        throw new InvalidField('search');
    }
    $search = $body->search;
    $results = User::select(['username', 'realname'])->where('username', 'LIKE', "%{$search}%")->orWhere('realname', 'LIKE', "%{$search}%")->orWhere('email', '=', $search)->get();
    Tool::endWithJson($results);
});
$user_send_password_reset_link = Tool::makeEndpoint(function () use($app) {
    $body = Tool::getBody();
    if (!isset($body->email) || gettype($body->email) !== 'string') {
        throw new InvalidField('email');
    }
    // -- <this_is_not_used_for_now> --
    // rejecting if request isn't signed by
    // a recaptcha captcha
    // if (!isset($body->recaptcha_response) ||
    //     gettype($body->recaptcha_response) !== 'string') {
    //    throw new InvalidRecaptcha;
    // }
    // $recaptchaStuff = new ReCaptcha(Tool::getConfig()['recaptcha_secret']);
    // $resp = $recaptchaStuff->verify($body->recaptcha_response);
Beispiel #9
0
 * Returns the complete list of emails
 * that are available through the
 * external accounts
 */
$oauth_external_emails = Tool::makeEndpoint(function () use($app, $resourceServer) {
    OAuthHelper::needsScopes(['user']);
    $user = OAuthHelper::currentlyAuthed();
    $externalAccounts = $user->externalAccounts()->get();
    $emails = [];
    foreach ($externalAccounts as $externalAccount) {
        $oAuth = new OAuthClient($externalAccount->service);
        $_emails = $oAuth->getEmails($externalAccount->token);
        foreach ($_emails as $email) {
            $emails[] = ["email" => $email, "service" => $externalAccount->service];
        }
    }
    Tool::endWithJson($emails);
});
$app->get('/user/external_accounts', $user_external_accounts);
$app->delete('/user/external_accounts/:id', $user_delete_external_account);
$app->get('/oauth/available_emails', $oauth_external_emails);
$app->get('/oauth/associate/:service', $user_associate_external_account);
$app->post('/oauth/authorize', $authorize);
$app->options('/user/external_accounts', function () {
});
$app->options('/oauth/available_emails', function () {
});
$app->options('/oauth/authorize', function () {
});
$app->options('/oauth/associate/:service', function () {
});