public function update(Request $request, $id) { $categoria = Category::findOrFail($id); $categoria->fill($request->all()); $categoria->save(); return $this->success('Categoria atualizado'); }
public function update(Request $request, $id) { $user = User::findOrFail($id); $user->fill($request->all()); $user->save(); return $this->success('User atualizado'); }
/** * @param Request $request * @param array $rules * @param array $messages * @param array $customAttributes */ public function validate(Request $request, array $rules, array $messages = [], array $customAttributes = []) { $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes); if ($validator->fails()) { throw new ValidationHttpException($validator->errors()); } }
public function q(Request $request) { $search = $request->input("q"); //todo: parse 'q' in separate class and return an array of parameters. // See: https://developer.github.com/v3/search/#search-repositories $matches = []; //look specifically for field limiter 'in' $match = preg_match('/^(?<q>.*)\\bin:(?<in>.*)/us', $search, $matches[]); if ($match) { //just look for uri if (isset($matches[0]['in'])) { $fields = explode(',', $matches[0]['in']); foreach ($fields as $field) { if ('uri' == $field) { //lookup the uri in elements $element = $this->elementRepository->findBy('uri', $matches[0]['q']); if ($element) { return $this->sendResponse($element->toArray(), "element found"); } //lookup the uri in concepts $concept = $this->conceptRepository->findBy('uri', $matches[0]['q']); if ($concept) { return $this->sendResponse($concept->toArray(), "concept found"); } } else { } } } } }
public function update(Request $request, $id) { $restaurant = Restaurant::findOrFail($id); $restaurant->fill($request->all()); $restaurant->save(); return $this->success('Restaurante atualizado'); }
public function update(Request $request, $category_id, $item_id) { $item = Item::findOrFail($item_id); $item->fill($request->all()); $item->save(); return $this->success('Item atualizado'); }
public function update(Request $request, $order_id) { $order = Order::findOrFail($order_id); $order->fill($request->all()); $order->save(); return $this->success('Pedido atualizado'); }
/** * Authenticate user with credentials. * * @param Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function login(Request $request) { $credentials = $request->only('email', 'password'); if (!($token = $this->auth->attempt($credentials))) { return response()->json(['error' => 'invalid_credentials'], 401); } $user = $this->auth->setToken($token)->toUser(); return response()->json(['data' => compact('token', 'user')]); }
public function login(Request $request) { $credentials = $request->only('email', 'password'); try { // verify the credentials and create a token for the user if (!($token = JWTAuth::attempt($credentials))) { return $this->response->errorUnauthorized(); } } catch (JWTException $e) { // something went wrong return $this->response->errorInternal(); } return $this->response->array(['token' => $token]); }
function ACRequest(Request $request) { $this->apiUrl = "http://ac.firefly.cc/"; $authenticator = new AcAuth("Firefly Digital", "AC Web Timer", "*****@*****.**", "&11Rebma", $this->apiUrl); $token = $authenticator->issueToken(); if ($token instanceof AcToken) { $client = new AcClient($token); $params = $request->all(); $request_type = $params['request_type']; $call = $params['path_info']; unset($params['path_info'], $params['request_type']); $response = $client->{$request_type}($call, $params); print json_encode($response->getJson()); } }
/** * Execute the rate limiting for the given request. * * @param \Dingo\Api\Http\Request $request * @param int $limit * @param int $expires * * @return void */ public function rateLimitRequest(Request $request, $limit = 0, $expires = 0) { $this->request = $request; // If the throttle instance is already set then we'll just carry on as // per usual. if ($this->throttle instanceof Throttle) { // // If the developer specified a certain amount of requests or expiration // time on a specific route then we'll always use the route specific // throttle with the given values. } elseif ($limit > 0 || $expires > 0) { $this->throttle = new Route(['limit' => $limit, 'expires' => $expires]); $this->keyPrefix = md5($request->path()); // Otherwise we'll use the throttle that gives the consumer the largest // amount of requests. If no matching throttle is found then rate // limiting will not be imposed for the request. } else { $this->throttle = $this->getMatchingThrottles()->sort(function ($a, $b) { return $a->getLimit() < $b->getLimit(); })->first(); } if (is_null($this->throttle)) { return; } $this->prepareCacheStore(); $this->cache('requests', 0, $this->throttle->getExpires()); $this->cache('expires', $this->throttle->getExpires(), $this->throttle->getExpires()); $this->cache('reset', time() + $this->throttle->getExpires() * 60, $this->throttle->getExpires()); $this->increment('requests'); }
public function backend(Request $request) { // grab credentials from the request $credentials = $request->only('email', 'password'); try { // attempt to verify the credentials and create a token for the user if (!($token = $this->auth->attempt($credentials))) { return response()->json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could_not_create_token'], 500); } // all good so return the token return response()->json(compact('token')); }
/** * Boot the service provider. * * @author Morten Rugaard <*****@*****.**> * * @return void */ public function boot() { // Set response static instances $this->setResponseStaticInstances(); // Configure the "Accept"-header parser DingoHttpRequest::setAcceptParser($this->app['Dingo\\Api\\Http\\Parser\\Accept']); // Rebind API router $this->app->rebinding('api.routes', function ($app, $routes) { $app['api.url']->setRouteCollections($routes); }); // Initiate HTTP kernel $kernel = $this->app->make('Illuminate\\Contracts\\Http\\Kernel'); /// Add middlewares to HTTP request $this->app[NodesHttpMiddlewareRequest::class]->mergeMiddlewares($this->gatherAppMiddleware($kernel)); // Prepend request middleware $this->addRequestMiddlewareToBeginning($kernel); // Replace route dispatcher $this->app['events']->listen(DingoEventRequestWasMatched::class, function (DingoEventRequestWasMatched $event) { $this->replaceRouteDispatcher(); $this->updateRouterBindings(); }); // Load project routes $this->loadRoutes(); // Register namespace for API views $this->loadViewsFrom(__DIR__ . '/../resources/views', 'nodes.api'); // Register publish groups $this->publishGroups(); }
protected function createRequest($uri, $method, array $headers = []) { $request = Request::create($uri, $method); foreach ($headers as $key => $value) { $request->headers->set($key, $value); } return $request; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { if ($this->validator->validateRequest($request)) { $request = HttpRequest::createFromExisting($request); return $this->sendRequestThroughRouter($request); } return $next($request); }
/** * Boot the service provider. * * @return void */ public function boot() { $this->setResponseStaticInstances(); Request::setAcceptParser($this->app['Dingo\\Api\\Http\\Parser\\Accept']); $this->app->rebinding('api.routes', function ($app, $routes) { $app['api.url']->setRouteCollections($routes); }); }
public function testProvidersAreFilteredWhenSpecificProviderIsRequested() { $this->router->shouldReceive('getCurrentRoute')->once()->andReturn($route = m::mock('Dingo\\Api\\Routing\\Route')); $this->router->shouldReceive('getCurrentRequest')->once()->andReturn($request = Request::create('foo', 'GET')); $provider = m::mock('Dingo\\Api\\Auth\\Provider\\Provider'); $provider->shouldReceive('authenticate')->once()->with($request, $route)->andReturn((object) ['id' => 1]); $this->auth->extend('one', m::mock('Dingo\\Api\\Auth\\Provider\\Provider')); $this->auth->extend('two', $provider); $this->auth->authenticate(['two']); $this->assertEquals($provider, $this->auth->getProviderUsed()); }
public function testControllerOptionsMergeAndOverrideRouteOptions() { $request = Request::create('foo', 'GET'); $route = new Route($this->adapter, $this->container, $request, ['uri' => 'foo', 'methods' => ['GET', 'HEAD'], 'action' => ['scopes' => ['foo', 'bar'], 'providers' => ['foo'], 'limit' => 5, 'expires' => 10, 'throttle' => 'Foo', 'version' => ['v1'], 'conditionalRequest' => false, 'uses' => 'Dingo\\Api\\Tests\\Stubs\\RoutingControllerStub@index']]); $this->assertEquals(['foo', 'bar', 'baz', 'bing'], $route->scopes(), 'Route did not setup scopes correctly.'); $this->assertEquals(['foo', 'red', 'black'], $route->getAuthProviders(), 'Route did not setup authentication providers correctly.'); $this->assertEquals(10, $route->getRateLimit(), 'Route did not setup rate limit correctly.'); $this->assertEquals(20, $route->getRateExpiration(), 'Route did not setup rate limit expiration correctly.'); $this->assertTrue($route->hasThrottle(), 'Route did not setup throttle correctly.'); $this->assertInstanceOf('Dingo\\Api\\Tests\\Stubs\\BasicThrottleStub', $route->getThrottle(), 'Route did not setup throttle correctly.'); }
/** * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException */ public function testAuthenticationFailsAndExceptionIsThrown() { $exception = new UnauthorizedHttpException('test'); $request = Request::create('test', 'GET'); $route = new Route($this->adapter, $this->container, $request, ['uri' => '/test', 'action' => ['providers' => []]]); $this->auth->shouldReceive('check')->once()->with(false)->andReturn(false); $this->auth->shouldReceive('authenticate')->once()->with([])->andThrow($exception); $this->router->shouldReceive('getCurrentRoute')->once()->andReturn($route); $this->middleware->handle($request, function () { // }); }
/** * Boot the service provider. * * @return void */ public function boot() { $this->setupConfig(); Http\Response::setFormatters($this->prepareConfigValues($this->app['config']['api.formats'])); Http\Response::setTransformer($this->app['api.transformer']); Http\Response::setEventDispatcher($this->app['events']); $config = $this->app['config']['api']; Http\Request::setAcceptParser(new Http\Parser\Accept($config['standardsTree'], $config['subtype'], $config['version'], $config['defaultFormat'])); $this->app->rebinding('api.routes', function ($app, $routes) { $app['api.url']->setRouteCollections($routes); }); }
public function authenticate(Request $request, UserRepository $userRepository) { // grab credentials from the request $credentials = $request->only('email', 'password'); // TODO Move user authentication code somewhere more appropriate $previousException = null; if ($credentials["email"] === null) { $previousException = new NotFoundHttpException("User not found.", null, 0xc00101); } if ($credentials["password"] === null) { // TODO Test after code \Eos\Exceptions\Factory::collection() throw new NotFoundHttpException("User not found.", $previousException, 0xc00102); } else { if ($previousException !== null) { throw $previousException; } } // Try to find user by email $user = $userRepository->findWhere(["email" => $credentials["email"]]); if (count($user) === 0) { // The user could not found by that email throw new NotFoundHttpException("User not found.", null, 0xc00103); } /** * @var \Eos\Entities\User $user */ $user = $user[0]; if (!Hash::check($credentials["password"], $user->password)) { // Password mismatch throw new NotFoundHttpException("User not found.", null, 0xc00104); } try { $token = JWTAuth::fromUser($user); } catch (JWTException $exception) { throw new \Exception("Couldn't create token", 0xc00105); } return response()->json(["token" => $token, "user" => ["first_name" => $user->first_name, "middle_name" => $user->middle_name, "last_name" => $user->last_name, "email" => $user->email]]); }
public function update(Request $request, $id) { $validator = \Validator::make($request->all(), ['id' => 'required', 'email' => 'required|email|unique:users', 'name' => 'required', 'password' => 'min:6']); if ($validator->fails()) { throw new StoreResourceFailedException('Could not able to update user.', $validator->errors()); } $user = User::findorfail($id); $user->email = $request->get('email'); $user->name = $request->get('name'); if ($request->get('password')) { $user->password = Hash::make($request->get('password')); } if ($user->save()) { return $this->response->array(['message' => 'User has been updated successfully', 'status' => 200]); } else { return $this->response->array(['message' => 'Unable to update user. Please try again', 'status' => 200]); } }
/** * Gather the middlewares for the route. * * @param \Dingo\Api\Http\Request $request * * @return array */ protected function gatherRouteMiddlewares($request) { if ($route = $request->route()) { return $this->router->gatherRouteMiddlewares($route); } return []; }
public function testAdapterDispatchesRequestsThroughRouter() { $this->container['request'] = Http\Request::create('/foo', 'GET'); $this->router->version('v1', function () { $this->router->get('foo', function () { return 'foo'; }); }); $response = $this->router->dispatch($this->container['request']); $this->assertEquals('foo', $response->getContent()); }
/** * Handle an incoming request. * * @param \Dingo\Api\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $search = $request->input('q'); $bar = $request->getQueryString(); return $next($request); }
function declineUser(Request $request) { $data = $request->only('token'); \DB::table('tmp_users')->where('token', '=', $data['token'])->delete(); return $this->response->noContent(); }
/** * Parse the includes. * * @param \Dingo\Api\Http\Request $request * * @return void */ public function parseFractalIncludes(Request $request) { $includes = $request->get($this->includeKey); if (!is_array($includes)) { $includes = array_filter(explode($this->includeSeparator, $includes)); } $this->fractal->parseIncludes($includes); }
public function testGettingTheRemainingLimit() { $this->limiter->extend(new ThrottleStub(['limit' => 10, 'expires' => 200])); $this->limiter->rateLimitRequest(Request::create('test', 'GET')); $this->assertEquals(9, $this->limiter->getRemainingLimit()); }
public function testExceptionsHandledByRenderAreReroutedThroughHandler() { $request = ApiRequest::create('foo', 'GET'); $this->log->shouldReceive('error')->once()->with($exception = new HttpException(404)); $response = $this->exceptionHandler->render($request, $exception); $this->assertEquals('{"message":"404 Not Found","status_code":404}', $response->getContent()); }
public function testRateLimitingWithRouteThrottle() { $request = Request::create('test', 'GET'); $route = m::mock('Dingo\\Api\\Routing\\Route'); $route->shouldReceive('hasThrottle')->once()->andReturn(true); $route->shouldReceive('getThrottle')->once()->andReturn(new ThrottleStub(['limit' => 10, 'expires' => 20])); $route->shouldReceive('getRateLimit')->once()->andReturn(0); $route->shouldReceive('getRateExpiration')->once()->andReturn(0); $this->router->shouldReceive('getCurrentRoute')->once()->andReturn($route); $response = $this->middleware->handle($request, function ($request) { return new Response('foo'); }); $this->assertArrayHasKey('x-ratelimit-limit', $response->headers->all()); $this->assertArrayHasKey('x-ratelimit-remaining', $response->headers->all()); $this->assertArrayHasKey('x-ratelimit-reset', $response->headers->all()); $this->assertEquals(9, $response->headers->get('x-ratelimit-remaining')); $this->assertEquals(10, $response->headers->get('x-ratelimit-limit')); }