public function index(FacebookAuthentication $request, FacebookGraphClient $client, FacebookUserResolver $resolver)
 {
     $data = $client->init($request->token)->getUser(['id', 'email', 'first_name', 'last_name']);
     $user = $resolver->findOrCreateUser($data);
     $customClaims = ['name' => $user->name, 'email' => $user->email, 'role' => $user->role, 'gravatar' => $user->gravatar];
     return api_response(200, ['token' => JWTAuth::fromUser($user, $customClaims)]);
 }
 public function changeEmail(EmailChange $request)
 {
     $newEmail = $request->input('new_email');
     $this->auth->user()->update(['email' => $newEmail]);
     $this->tokens->delete($newEmail);
     return api_response(200);
 }
 public function delete(Comment $comment)
 {
     if (auth()->user()->isNot($comment->user) && auth()->user()->role != 'admin') {
         throw new OwnershipException();
     }
     return api_response($comment->delete() ? 200 : 500);
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @param  int  $maxAttempts
  * @param  int  $decayMinutes
  * @return mixed
  */
 public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
 {
     $key = $this->resolveRequestSignature($request);
     if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
         return api_response(429, [], ['Retry-After' => $this->limiter->availableIn($key), 'X-RateLimit-Limit' => $maxAttempts, 'X-RateLimit-Remaining' => 0]);
     }
     $this->limiter->hit($key, $decayMinutes);
     return $next($request)->withHeaders(['X-RateLimit-Limit' => $maxAttempts, 'X-RateLimit-Remaining' => $maxAttempts - $this->limiter->attempts($key) + 1]);
 }
Example #5
0
File: init.php Project: nolka/k5
function logout($req, $hash, $apiId, $sign)
{
    $af = new AccountManager();
    $result = $af->Logout($hash);
    if ($result) {
        return api_response(array('LoggedOut' => $result));
    } else {
        return api_error(ApiErrorCode::AuthAlreadyLoggedOut, 'Account already logged out!');
    }
}
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, \Closure $next)
 {
     $token = $this->auth->setRequest($request)->getToken();
     if ($token) {
         $user = $this->auth->authenticate($token);
         if (!$user) {
             return api_response(400, ['error' => 'Failed to retrieve a user from given token']);
         }
         $this->events->fire('tymon.jwt.valid', $user);
     }
     return $next($request);
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, \Closure $next)
 {
     if (!($token = $this->auth->setRequest($request)->getToken())) {
         throw new JWTException('The token could not be parsed from the request');
     }
     $user = $this->auth->authenticate($token);
     if (!$user) {
         return api_response(400, ['error' => 'Failed to retrieve a user from given token']);
     }
     $this->events->fire('tymon.jwt.valid', $user);
     return $next($request);
 }
 public function recoverPassword(PasswordRecovery $request)
 {
     User::where('email', $request->email)->update(['password' => bcrypt($request->input('new_password'))]);
     $this->tokens->delete($request->email);
     return api_response(200);
 }
Example #9
0
 public function refresh()
 {
     $token = JWTAuth::parseToken()->refresh();
     return api_response(200, compact('token'));
 }
Example #10
0
 /**
  * Render an exception into an HTTP response.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Exception  $e
  * @return \Illuminate\Http\Response
  */
 public function render($request, Exception $e)
 {
     /**
      * General
      */
     if ($e instanceof NotFoundHttpException) {
         Log::info($request->url());
         return api_response(404);
     } elseif ($e instanceof ModelNotFoundException) {
         return api_response(404);
     } elseif ($e instanceof MethodNotAllowedHttpException) {
         return api_response(405, $e->getHeaders());
     } elseif ($e instanceof TooManyRequestsHttpException) {
         return api_response(429, $e->getHeaders());
     } elseif ($e instanceof BadRequestHttpException) {
         return api_response(400, ['message' => $e->getMessage()]);
     }
     /**
      * Authentication
      */
     if ($e instanceof TokenExpiredException) {
         return api_response(401, ['token' => 'expired']);
     } elseif ($e instanceof TokenInvalidException) {
         return api_response(400, ['token' => 'invalid']);
     } elseif ($e instanceof JWTException) {
         return api_response(400, ['token' => 'absent']);
     }
     /**
      * Guzzle
      */
     if ($e instanceof ClientException) {
         return api_response(400);
     } elseif ($e instanceof TransferException) {
         return api_response(500);
     }
     /**
      * Posts and comments
      */
     if ($e instanceof OwnershipException) {
         return api_response(400, ['error' => 'You are neither author of this item nor site administrator']);
     } elseif ($e instanceof PostAlreadyPublishedException) {
         return api_response(400, ['error' => 'Can\'t perform this request because specified post was already published']);
     } elseif ($e instanceof PostNotPublishedException) {
         return api_response(400, ['error' => 'Can\'t perform this request on the post that is not yet published']);
     }
     /**
      * Everything else will return internal server error in production
      */
     if (config('app.env') == 'production') {
         return api_response(500);
     }
     return parent::render($request, $e);
 }
Example #11
0
 public function response(array $errors)
 {
     return api_response(422, ['errors' => $errors]);
 }
Example #12
0
 public function delete(Post $post)
 {
     if (auth()->user()->isNot($post->user) && auth()->user()->role != 'admin') {
         throw new OwnershipException();
     }
     if ($post->delete()) {
         Cache::tags('posts')->flush();
         return api_response(200);
     } else {
         return api_response(500);
     }
 }
 public function index(Request $request)
 {
     $query = $request->input('query');
     return api_response(200, ['results' => ['category1' => ['name' => 'Posts', 'results' => Post::published()->where('title', 'like', "%{$query}%")->orderBy('published_at', 'desc')->limit(5)->get(['title', 'slug'])], 'category2' => ['name' => 'Users', 'results' => User::where('name', 'like', "%{$query}%")->limit(5)->get()]]]);
 }
 public function finishSignup(AccountCreation $request)
 {
     User::create(['email' => $request->email, 'name' => $request->name, 'password' => bcrypt($request->password)]);
     $this->tokens->delete($request->email);
     return api_response(201);
 }
Example #15
0
if ($auth) {
    list($response, $request, $detail, $value) = array_pad(array_filter(explode('/', $_SERVER['REQUEST_URI'], 5)), 5, null);
    if ($response) {
        if ($detail) {
            $request = preg_replace('/[^a-z]/i', '', $request);
            $file = "./requests/{$request}.inc";
            try {
                $json = $response === 'xml' ? false : true;
                if (!in_array($response, $valid_responses)) {
                    throw new Exception("The API does not support that response type: {$response}.");
                }
                if (!in_array($request, $valid_requests)) {
                    throw new Exception("The API does not support that request type: {$request}.");
                }
                if (file_exists($file)) {
                    require $file;
                } else {
                    throw new Exception("The API request type used failed to load: {$request}.");
                }
            } catch (Exception $e) {
                api_response(500, 'Internal Server Error', $e->getMessage(), array(), $json);
            }
        } else {
            api_response(404, 'Not Found', 'The API Request URI is incomplete. Please consult the documentation.');
        }
    } else {
        api_response(206, 'Partial Content', 'The API has no page to display. Please consult the documentation.');
    }
} else {
    api_response(403, 'Forbidden', $auth_message, array(), $json);
}
 public function validateEmailToken(AsyncValidationOfEmailToken $request)
 {
     return api_response(200);
 }
Example #17
0
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
    return api_response(200);
});
/**
 * Auth
 */
Route::group(['prefix' => 'auth', 'namespace' => 'Auth'], function () {
    /**
     * Signup
     */
    Route::post('signup/finish', 'SignupController@finishSignup');
    Route::post('signup', 'SignupController@signup')->middleware('throttle:2,1');
    /**
     * Access Token
     */
    Route::post('authenticate', 'AuthController@authenticate');
    Route::get('refresh', 'AuthController@refresh');
    /**
     * Facebook signup and authentication
 public function showUser(User $user)
 {
     return api_response(200, ['user' => $user->toArray(), 'activities' => $user->logs()->published()->orderBy('published_at', 'desc')->simplePaginate(10)->toArray()]);
 }