How to login and get the API token with username and password?

Two simple methods, for Register and Login via API. These are only the basics, how to authenticate. I used the Cockpit internal Methods, only added the Endpoints.
Note: returning the whole user-object is not the best solution, you need to think about a cleanup of this data.

Register

    $restApi->addEndPoint('/auth/register', [
        /**
         * @OA\POST(
         *     path="/auth/register",
         *     tags={"auth"},
         *     @OA\Response(response="200", description="Register via API")
         * )
         */
        'POST' => function($params, $app) {
            $userController = new \System\Controller\Users($app, ['action' => 'user', 'params' => $params]);

            error_reporting(0); // there is a, not avoidable, warning in create. to get clean output, disable error reporting
            $user = $userController->save();
            return $user
        },
    ]);

Login


    $restApi->addEndPoint('/auth/check', [
        /**
         * @OA\POST(
         *     path="/auth/check",
         *     tags={"auth"},
         *     @OA\Response(response="200", description="Login via API")
         * )
         */
        'POST' => function($params, $app) {
            $user = $app->helper('auth')->authenticate($app->request->param('auth'));

            return $user
        }
    ]);
1 Like