Exemple #1
2
 /**
  * Handle a registration request for the application.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function postRegister(Request $request)
 {
     $validator = $this->validator($request->all());
     if ($validator->fails()) {
         $this->throwValidationException($request, $validator);
     }
     $token = JWTAuth::fromUser($this->create($request->all()), $this->customClaims());
     $response = new JsonResponse(['token' => $token], 200);
     $response->header('Authorization', 'Bearer ' . $token);
     return $response;
 }
Exemple #2
1
 private function jsonResponse($status, $arguments)
 {
     $content = isset($arguments[0]) ? $arguments[0] : '';
     $headers = isset($arguments[1]) ? $arguments[1] : $this->_jsonHeaders;
     $headers = array_merge($this->_jsonHeaders, $headers);
     $options = isset($arguments[2]) ? $arguments[2] : $this->_jsonOptions;
     $response = new IlluminateJsonResponse($content, $status, [], $options);
     foreach ($headers as $key => $value) {
         $response->header($key, $value, true);
     }
     return $response;
 }
Exemple #3
1
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     if (!auth()->check()) {
         return JsonResponse::create('Not found', '304');
     }
     return auth()->user()->messagesRecv()->orderBy('id', 'desc')->paginate(15);
 }
Exemple #4
1
 public function __construct($data = null, $status = 200, $headers = array(), $options = 0)
 {
     parent::__construct($data, $status, $headers, $options);
     if ($data != null) {
         $this->data($data);
     }
 }
 public function subscribeCount()
 {
     $MailChimp = new MailChimp($this->api_key);
     $params = ['fields' => 'stats.member_count'];
     $result = $MailChimp->get('lists/' . $this->list_key, ['fields' => 'id,name,stats.member_count']);
     return JsonResponse::create($result);
 }
 /**
  * @Post("/", as="lang.change")
  * @return Response
  */
 public function lang(Request $request, CookieJar $cookieJar)
 {
     $resp = JsonResponse::create();
     \Session::set('language', $request->get('language'));
     //$resp->withCookie(\Cookie::forever());
     return $resp;
     //
 }
Exemple #7
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)
 {
     $debug = env('APP_DEBUG', false);
     $message = $e->getMessage();
     if (!$message) {
         $message = 'An error occurred';
     }
     $debugData = ['exception' => get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => explode("\n", $e->getTraceAsString())];
     $responseData = ['message' => $message];
     if ($e instanceof HttpExceptionInterface) {
         if (method_exists($e, 'getResponse')) {
             if ($e instanceof TransformableInterface) {
                 $responseData = $e->transform(app(ValidationExceptionTransformer::class));
             } else {
                 $responseData = $e->getResponse();
             }
         }
     }
     if ($debug) {
         $responseData['debug'] = $debugData;
     }
     $response = parent::render($request, $e);
     $response = new JsonResponse($responseData, $response->getStatusCode(), $response->headers->all(), JSON_PRETTY_PRINT);
     $response->exception = $e;
     app('Asm89\\Stack\\CorsService')->addActualRequestHeaders($response, $request);
     return $response;
 }
 public function invoice()
 {
     $consulta = \DB::table('planilla')->where('numero_planilla', DB::raw("(select max(`numero_planilla`) from planilla)"))->where('central_id', 11)->get();
     foreach ($consulta as $c) {
         return JsonResponse::create(++$c->numero_planilla);
     }
 }
Exemple #9
0
 public function store(Request $request)
 {
     try {
         $data = $request->all();
         $estado = "";
         if ($data["vistoAutoriza"] == false || $data["vistoJefe"] == false) {
             $estado = "ESPERANDO";
         } else {
             if ($data["vistoAutoriza"] == true && $data["vistoJefe"] == true) {
                 $estado = "AUTORIZADO";
             }
         }
         $permiso = new Permiso();
         $permiso->estado = $estado;
         $permiso->fechaSalida = $data["fechaSalida"];
         $permiso->fechaEntrada = $data["fechaEntrada"];
         $permiso->horaSalida = $data["horaSalida"];
         $permiso->horaEntrada = $data["horaEntrada"];
         $permiso->TipoPermisos_id = $data["motivoPermiso"];
         $permiso->Empleados_id = $data["funcionario"];
         $permiso->otroMotivo = $data["otroMotivo"];
         $permiso->remuneracion = $data["remuneracion"];
         $permiso->vistoAutoriza = $data["vistoAutoriza"];
         $permiso->vistoJefe = $data["vistoJefe"];
         $permiso->save();
         return JsonResponse::create(array('message' => "Permiso enviado exitosamente"), 200);
     } catch (Exception $exc) {
         return JsonResponse::create(array('message' => "No se pudo guardar el Permiso", "exception" => $exc->getMessage(), "request" => json_encode($data)), 401);
     }
 }
 /**
  * Check the results of the authorization attempt, and return the appropriate response.
  *
  * @param JsonResponse|Response $auth
  * @return JsonResponse|Response
  */
 private function checkAuth($auth)
 {
     $data = json_decode($auth->content());
     $response = '';
     if (isset($data->error)) {
         // An error was returned, so let's send it back to the user
         $errors = new MessageBag([$data->error => [$data->message]]);
         $response = redirect()->back()->withErrors($errors);
     } elseif (isset($data->jwtoken)) {
         // A JWT was returned, so let's use it to run the postLogin function
         $response = $this->userAuth->postLogin($data->jwtoken);
     } else {
         // Something is awry, so let's abort
         abort(501);
     }
     return $response;
 }
 public function getPlanilla($viaje)
 {
     $consulta = Planilla::select('*')->where('viaje_id', $viaje)->first()->load('viaje');
     $consulta['giros'] = \DB::table('giros')->join('viaje_giros', 'giros.id', '=', 'viaje_giros.giro_id')->join('viajes', 'viaje_giros.viaje_id', '=', 'viajes.id')->where('viajes.id', $viaje)->select('*')->get();
     $consulta['pasajeros'] = \DB::table('pasajeros')->join('viaje_pasajeros', 'pasajeros.id', '=', 'viaje_pasajeros.pasajero_id')->where('viajes.id', $viaje)->join('viajes', 'viaje_pasajeros.viaje_id', '=', 'viajes.id')->select('*')->get();
     $consulta['paquetes'] = \DB::table('paquetes')->join('viaje_paquetes', 'paquetes.id', '=', 'viaje_paquetes.paquete_id')->where('viajes.id', $viaje)->join('viajes', 'viaje_paquetes.viaje_id', '=', 'viajes.id')->select('*')->get();
     $consulta['conductor'] = Viaje::find($viaje)->conductor;
     return JsonResponse::create($consulta);
 }
 public function getAllEpisodesForShow($showId)
 {
     if (!is_numeric($showId)) {
         return [];
     }
     $episodes = $this->api->getEpisodesOfShow($showId);
     $episodes = $this->formatEpisodes($episodes);
     return JsonResponse::create($episodes);
 }
Exemple #13
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)
 {
     if ($e instanceof ModelNotFoundException) {
         $e = new NotFoundHttpException($e->getMessage(), $e);
     } elseif ($e instanceof NotFoundHttpException) {
         return JsonResponse::create(["status" => "error", "message" => "the api is not found"]);
     }
     return parent::render($request, $e);
 }
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     try {
         $documento = Documento::find($id);
         $documento->delete();
         return JsonResponse::create(array('message' => "Documento  Eliminado Correctamente", "request" => json_encode($id)), 200);
     } catch (Exception $ex) {
         return JsonResponse::create(array('message' => "No se pudo Eliminar el documento", "exception" => $ex->getMessage(), "request" => json_encode($id)), 401);
     }
 }
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     try {
         $categoria = Categoria::find($id);
         $categoria->delete();
         return JsonResponse::create(array('message' => "Categoria Eliminado Correctamente", "request" => json_encode($id)), 200);
     } catch (Exception $ex) {
         return JsonResponse::create(array('message' => "No se pudo Eliminar la marca", "exception" => $ex->getMessage(), "request" => json_encode($id)), 401);
     }
 }
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function show($id)
 {
     $cliente = Cliente::find($id);
     if (!$cliente) {
         $cliente = Cliente::where('identificacion', $id)->first();
         if (!$cliente) {
             return JsonResponse::create(array("message" => 'No se encontro el cliente puede registrarlo si continua'), 400);
         }
     }
     return $cliente;
 }
Exemple #17
0
 public function __construct($data = null, $status = 200, $headers = array(), $options = 0)
 {
     if ($data instanceof \Exception) {
         $data = array("code" => $data->getCode(), "error" => $data->getMessage());
     } else {
         // move the prepare function here
         Carbon::setToStringFormat('Y-m-d\\TH:i:s.z\\Z');
         $data = ParseHelper::prepareResponse($data);
     }
     parent::__construct($data, $status, $headers, $options);
 }
 /**
  * Constructor.
  *
  * @param int                           $httpStatusCode   HTTP status code
  * @param mixed                         $errorCode        Internal error code
  * @param string                        $errorTitle       Error description
  * @param Illuminate\Support\MessageBag $errors           Validation errors
  */
 public function __construct($httpStatusCode, $errorCode, $errorTitle, ValidationMessages $errors = NULL)
 {
     $data = ['errors' => []];
     if ($errors) {
         foreach ($errors->keys() as $field) {
             foreach ($errors->get($field) as $message) {
                 $data['errors'][] = ['status' => $httpStatusCode, 'code' => $errorCode, 'title' => 'Validation Fail', 'detail' => $message, 'meta' => ['field' => $field]];
             }
         }
     }
     parent::__construct($data, $httpStatusCode);
 }
Exemple #19
0
 public function packages($repo)
 {
     $path = '/';
     $file = 'packages.json';
     $response = $this->proxy->loadIgnoreLocalCache($this->makeUrl($repo, $path, $file), $this->makeLocalPath($repo, $path, $file));
     $content = json_decode($response, true);
     foreach (['notify', 'notify-batch', 'search'] as $key) {
         $content[$key] = config('composer.repository.' . $repo) . $content[$key];
     }
     $content['providers-url'] = '/' . $repo . $content['providers-url'];
     return JsonResponse::create($content);
 }
 /**
  * Update the specified resource in storage.
  *
  * @param  Request  $request
  * @param  int  $id
  * @return Response
  */
 public function update(Request $request, $id)
 {
     try {
         $data = $request->all();
         $subcategoria = Subcategoria::find($id);
         $subcategoria->nombre = $data["nombre"];
         $subcategoria->categoria = $data["categoria"];
         $subcategoria->save();
         return JsonResponse::create(array('message' => "Subcategoria Modificada Correctamente", "request" => json_encode($data)), 200);
     } catch (Exception $exc) {
         return JsonResponse::create(array('message' => "No se pudo Modificar la subcategoria", "exception" => $exc->getMessage(), "request" => json_encode($data)), 401);
     }
 }
 public function crearPlanilla($viaje_id, $conductor_id)
 {
     $central = Conductor::find($conductor_id)->first();
     $planilla = new Planilla();
     $planilla->viaje_id = $viaje_id;
     $planilla->central_id = $central->central_id;
     $planilla->numero_planilla = $this->generarNumeroPlanilla($conductor_id);
     if ($planilla->save()) {
         return JsonResponse::create('Se creo la planilla correctamente');
     } else {
         return JsonResponse::create('Error al crear la planilla');
     }
 }
 /**
  * Add headers needed for CORS.
  *
  * @return $this
  */
 private function addCorsHeaders()
 {
     if (isset($_SERVER['SERVER_SOFTWARE']) && preg_match('/nginx/', $_SERVER['SERVER_SOFTWARE'])) {
         $accessControlAllowCredentials = 'false';
         if (env('ACCESS_CONTROL_ALLOW_HEADERS')) {
             $accessControlAllowCredentials = 'true';
         }
         $this->response->header('Access-Control-Allow-Origin', env('ACCESS_CONTROL_ALLOW_ORIGIN'));
         $this->response->header('Access-Control-Allow-Credentials', $accessControlAllowCredentials);
         $this->response->header('Access-Control-Allow-Methods', env('ACCESS_CONTROL_ALLOW_METHODS'));
         $this->response->header('Access-Control-Allow-Headers', env('ACCESS_CONTROL_ALLOW_HEADERS'));
     }
     return $this;
 }
 public function renderAsRestAPI($request, \Exception $e)
 {
     if ($e instanceof HttpResponseException) {
         return $e->getResponse();
     } elseif ($e instanceof ModelNotFoundException) {
         $e = new NotFoundHttpException($e->getMessage(), $e);
     } elseif ($e instanceof AuthorizationException) {
         $e = new HttpException(403, $e->getMessage());
     } elseif ($e instanceof ValidationException && $e->getResponse()) {
         return $e->getResponse();
     }
     $fe = FlattenException::create($e);
     $data = env("APP_DEBUG", false) ? $fe->toArray() : ["message" => "whoops, something wrong."];
     return JsonResponse::create($data, 500);
 }
 public function getPlanilla($central_id, $planilla_id)
 {
     $tipoEmpresa = $this->verificartipoCentral($central_id);
     if ($tipoEmpresa->empresa->tipo == '1') {
         $planilla = PlanillaEspecial::find($planilla_id);
         $planilla['tipo'] = 'especial';
         $planilla->load('viaje.conductor', 'central');
         return JsonResponse::create($planilla);
     } else {
         $planilla = Planilla::find($planilla_id);
         $planilla['tipo'] = 'normal';
         $planilla->load('viaje.conductor', 'central.ciudad.departamento');
         return JsonResponse::create($planilla);
     }
 }
 /**
  * @param Request $request
  * @return View|\Symfony\Component\HttpFoundation\Response|static
  */
 public function indexAction(Request $request)
 {
     if ($request->getMethod() == 'GET') {
         return view('hours-control.index');
     }
     $hourControls = $this->repository->getAllPaginate($request, 10);
     $rows = [];
     foreach ($hourControls as $hourControl) {
         $row = json_decode(json_encode($hourControl), true);
         $row['day'] = Date::conversion($hourControl->day);
         $row['edit'] = route('hours-control.edit', ['id' => $hourControl->id]);
         $row['delete'] = route('hours-control.remove', ['id' => $hourControl->id]);
         $rows[] = $row;
     }
     return JsonResponse::create(['rows' => $rows, 'total' => $hourControls->total()]);
 }
 public function autenticar(Request $request)
 {
     try {
         $data = $request->all();
         $usuario = $data['username'];
         $clave = $data['pass'];
         $user = DB::select(DB::raw("Select usuario,clave,rol,cedula,estado from usuarios \n                         WHERE usuario =  '" . $usuario . "'  AND clave = '" . $clave . "'"));
         if (empty($user)) {
             return JsonResponse::create(array('message' => "KO", "request" => json_encode('Datos Incorrectos')), 200);
         } else {
             return JsonResponse::create(array('message' => "OK", "request" => json_encode($user)), 200);
         }
     } catch (Exception $exc) {
         return JsonResponse::create(array('message' => "No se puedo autenticar el usuario", "request" => json_encode($data)), 401);
     }
 }
 /**
  * Update the specified resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function update(Request $request, $id)
 {
     $data = $request->all();
     $vehiculo = Vehiculo::find($id);
     $vehiculo->cupos = $data['cupos'];
     //        $vehiculo->placa = $data["placa"];
     //        $vehiculo->modelo = $data["modelo"];
     //        $vehiculo->color = $data["color"];
     //        $vehiculo->codigo_vial = $data["codigo_vial"];
     //        $vehiculo->cupos = $data["cupos"];
     //        $vehiculo->identificacion_propietario = $data["identificacion_propietario"];
     //        $vehiculo->nombre_propietario = $data["nombre_propietario"];
     //        $vehiculo->tel_propietario = $data["tel_propietario"];
     $vehiculo->save($data);
     return JsonResponse::create(array('message' => "Vehiculo actualizado correctametne."), 200);
 }
Exemple #28
0
 public function getRetrasoDia(Request $request)
 {
     try {
         $data = $request->all();
         $empleado = $data["empleado"];
         $fecha = $data["fecha"];
         $result = DB::select(DB::raw("Select * from entradassalidas \n                        WHERE Empleados_id = {$empleado} AND fecha = '{$fecha}'"));
         if (count($result) > 0) {
             return $result;
         } else {
             return 0;
         }
     } catch (Exception $exc) {
         return JsonResponse::create(array('message' => "No se pudo guardar el Horario", "exception" => $exc->getMessage(), "request" => json_encode($data)), 401);
     }
 }
 public function __construct($document = null, $request = null, $status = 200, $headers = [], $options = 0)
 {
     if (!$request instanceof Request) {
         throw new \InvalidArgumentException(sprintf('Request is not an instance of %s', Request::class));
     }
     if ($document === null) {
         $document = new Document();
     } elseif (!$document instanceof Document) {
         throw new \InvalidArgumentException(sprintf('Document is not an instance of %s', Document::class));
     }
     $headers = array_merge(['Content-Type' => self::MIME_TYPE], self::$defaultHeaders, $headers);
     $this->applyPreferHeader($document, $request, $headers, $options);
     $document->sort(self::$defaultSorting, self::$controlsSorting, self::$metaSorting);
     parent::__construct($document, $status, $headers, $options);
     $this->applyEtag($request);
 }
 public function testResultsArePreparedCorrectly()
 {
     $batchRequest = new BatchRequest($this->routerMock, $this->configMock, new \Optimus\BatchRequest\ResultFormatter\OptimusResultFormatter(), new \Optimus\BatchRequest\ResponseFormatter\OptimusResponseFormatter(), $this->dbMock);
     $this->dbMock->shouldReceive('rollback')->times(1);
     $errorResponse = new Response('', 500);
     $exception = new \Exception('Exception', 25);
     $errorResponse->exception = $exception;
     $results = $batchRequest->prepareResults([JsonResponse::create(['data' => 'json'], 200), $errorResponse]);
     $firstKey = array_keys($results['responses'])[0];
     $this->assertEquals('error', $results['status']);
     $this->assertEquals(200, $results['responses'][$firstKey]->statusCode);
     $this->dbMock->shouldReceive('commit')->times(1);
     $results = $batchRequest->prepareResults([JsonResponse::create(['data' => 'json'], 200)]);
     $this->assertEquals('success', $results['status']);
     $this->assertEquals(200, $results['responses'][0]->statusCode);
 }