Parse the token from the request.
public static parseToken ( $method = 'bearer', $header = 'authorization', string $query = 'token' ) : JWTAuth | ||
$query | string | |
return | JWTAuth |
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!\JWTAuth::getToken()) { return response()->json(['status' => 401, 'error' => 'token_absent'], 200); } else { try { $authenticate = \JWTAuth::parseToken()->authenticate(); if (!$authenticate) { return response()->json(['status' => 401, 'error' => 'user_not_found'], 200); } } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) { return response()->json(['status' => 401, 'error' => 'token_expired'], 200); } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) { return response()->json(['status' => 401, 'error' => 'token_invalid'], 200); } } return $next($request); }
/** * * @param Request $request */ public function __construct(Request $request) { $this->request = $request; $this->middleware('jwt.auth'); $this->middleware('api', ['except' => 'GenerateApiKey']); $user = \JWTAuth::parseToken()->authenticate(); $this->user = $user; $ticket = new TicketController(); $this->ticket = $ticket; $model = new Tickets(); $this->model = $model; $thread = new Ticket_Thread(); $this->thread = $thread; $attach = new Ticket_attachments(); $this->attach = $attach; $ticketRequest = new TicketRequest(); $this->ticketRequest = $ticketRequest; $faveoUser = new User(); $this->faveoUser = $faveoUser; $team = new Teams(); $this->team = $team; $setting = new Settings(); $this->setting = $setting; $helptopic = new Help_topic(); $this->helptopic = $helptopic; $slaPlan = new Sla_plan(); $this->slaPlan = $slaPlan; $priority = new Priority(); $this->priority = $priority; $department = new Department(); $this->department = $department; $source = new Ticket_source(); $this->source = $source; }
/** * Update a address by id * @return array */ public function update(Request $request, $id) { $jugador_data = json_decode($request->getContent(), true); \JWTAuth::parseToken(); $user = \JWTAuth::parseToken()->authenticate(); $editedJugador = NULL; try { if ($id == $user->id_jugador) { $editedJugador = $this->repository->update($jugador_data, $id); $file = $request->file("foto"); if (!empty($file)) { $file->move("images/jugadores/", $user->id_jugador . ".jpg"); } return response()->json($editedJugador); } else { return ResponseMessage::invalidPermission(); } } catch (\Exception $e) { if ($e instanceof ValidatorException) { return response()->json($e->toArray(), 400); } else { return response()->json($e->getMessage(), 500); } } }
public function join($eventId) { $user = \JWTAuth::parseToken()->toUser(); $event = \App\Event::find($eventId); $event->users()->attach($user->id); response()->json(['message' => 'User Joined Event'], 200); }
/** * Updates particular creator * * @param int $id * @return boolean */ public function update() { $user = JWTAuth::parseToken()->toUser(); $creator = $this->creator->createCreator(Input::all(), $user['id']); return $this->response->array($creator); // $user = JWTAuth::parseToken()->toUser(); // $creator = $this->creator->updateCreator(Input::all(), $user['id']); // return $this->response->array($creator); }
public function expired($e) { $token = \JWTAuth::parseToken(); Config::package('tymon/jwt-auth', 'jwt'); $ttl = Config::get('jwt::refresh_ttl'); $iat = Carbon::createFromTimestamp($token->getPayload()->get('iat')); $now = Carbon::now(); // if renew ttl is expired too, return 401, otherwise let // the application generate a new token to frontend if ($iat->diffInMinutes($now) >= $ttl) { unset($iat, $now, $ttl); return response_failure(Lang::get('errors.api.auth.expired'), Config::get('status.error.unauthorized')); } unset($iat, $now, $ttl); }
public function getAuthenticatedUser() { try { if (!($user = JWTAuth::parseToken()->authenticate())) { return response()->json(['user_not_found'], 404); } } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) { return response()->json(['token_expired'], $e->getStatusCode()); } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) { return response()->json(['token_invalid'], $e->getStatusCode()); } catch (Tymon\JWTAuth\Exceptions\JWTException $e) { return response()->json(['token_absent'], $e->getStatusCode()); } // the token is valid and we have found the user via the sub claim return response()->json(compact('user')); }
/** * Update a address by id * @return array */ public function update(Request $request, $id) { \JWTAuth::parseToken(); $user = \JWTAuth::parseToken()->authenticate(); $alert_data = json_decode($request->getContent(), true); try { $alert = $this->repository->update($alert_data, $id); return response()->json($alert); } catch (\Exception $e) { if ($e instanceof ValidatorException) { return response()->json($e->toArray(), 400); } else { return response()->json($e->getMessage(), 500); } } }
public function debug() { $passport['id'] = 0; $passport['name'] = 'guest'; $passport['roles'] = ['guest']; try { $user = \JWTAuth::parseToken()->authenticate(); } catch (JWTException $e) { $user = null; } if ($user) { $passport['id'] = $user->getId(); $passport['name'] = $user->name; $passport['roles'] = array_values($user->getRoles()); } return response()->json($passport); }
return $app->welcome(); }); // Auth endpoint $app->post('v1/auth/login', 'AuthController@postLogin'); $app->group(['prefix' => 'v1', 'middleware' => 'jwt.auth'], function ($app) { // Get a group and its users $app->get('/group/{id}', function ($id) { $group = Group::with('user')->with('users')->find($id); return response()->json($group); }); // Get the timeline of certain group $app->get('/group/{id}/messages', function ($id) { }); // Create a group $app->post('/group', function (Request $request) { $user = JWTAuth::parseToken()->authenticate(); $group = new Group(); $group->name = $request->input('name'); $group->description = $request->input('description'); $group->user_id = $user->id; $group->save(); return response()->json($group); }); // Update a group $app->put('/group/{id}', function () { }); // Assign user to a group $app->post('/group/{id}/user', function (Request $request, $id) { $user_id = $request->input('user_id'); $user = User::find($user_id); if (!$user) {
/** * Saves a address into the database * @return void */ public function store(Request $request) { $retoData = $request->all(); try { //if(empty($_POST['mensaje'])) array_push($error,"Ingrese un mensaje."); if (!checkdate($retoData['mes'], $retoData['dia'], $retoData['ano'])) { return ResponseMessage::dateNotValid(); } if ($retoData['ano'] . "-" . $retoData['mes'] . "-" . $retoData['dia'] == date("Y-m-d") && $retoData['hora'] <= date("H")) { return ResponseMessage::hourNotValid(); } if ($retoData['ano'] . "-" . $retoData['mes'] . "-" . $retoData['dia'] < date("Y-m-d")) { return ResponseMessage::dateNotValid(); } $equipo = $this->equiposRepository->find($retoData['id_equipo']); $retador = $this->equiposRepository->find($retoData['id_retador']); $tienePartidos = DB::table("partidos_equipos")->join("partidos", "partidos_equipos.id_partido", "=", "partidos.id_partido")->where("id_equipo", "=", $retoData['id_equipo'])->where("fecha", "=", $retoData['ano'] . "-" . $retoData['mes'] . "-" . $retoData['dia'])->where("horario", "=", $retoData['hora'] . ":" . $retoData['minutos'] . ":00")->count(); if ($tienePartidos > 0) { return ResponseMessage::teamNotAvailable($equipo["data"]["equipo"]); } $tengoPartidos = DB::table("partidos_equipos")->join("partidos", "partidos_equipos.id_partido", "=", "partidos.id_partido")->where("id_equipo", "=", $retoData['id_retador'])->where("fecha", "=", $retoData['ano'] . "-" . $retoData['mes'] . "-" . $retoData['dia'])->where("horario", "=", $retoData['hora'] . ":" . $retoData['minutos'] . ":00")->count(); if ($tengoPartidos > 0) { return ResponseMessage::notAvailable(); } \JWTAuth::parseToken(); $user = \JWTAuth::parseToken()->authenticate(); $equiposCapitan = $this->JugadoresEquiposRepository->findWhere(['id_jugador' => $user->id_jugador, 'capitan' => 't', 'id_equipo' => $retoData['id_retador']]); if (count($equiposCapitan) == 0) { return ResponseMessage::invalidPermission(); } //consultar capita n del equipo retado $capitanretado = DB::table('jugadores_equipos')->wherein("capitan", array("t", "s"))->where("id_equipo", "=", $retoData['id_equipo'])->join("jugadores", "jugadores.id_jugador", "=", "jugadores_equipos.id_jugador")->get(); $fechaReto = $retoData['ano'] . "-" . $retoData['mes'] . "-" . $retoData['dia']; $horaReto = $retoData['hora'] . ":" . $retoData['minutos'] . ":00"; $arrayReto = array('id_equipo' => $equipo["data"]["id"], 'id_retador' => $retador["data"]["id"], 'mensaje' => isset($retoData['mensaje']) ? $retoData['mensaje'] : '', 'tipo' => $retoData['tipo'], 'fecha' => $fechaReto, 'hora' => $horaReto, 'lugar' => $retoData['lugar']); $reto = $this->repository->create($arrayReto); foreach ($capitanretado as $destinatario) { /*$datos['destinatario']=$destinatario; $datos['equipo']=$equipo; $datos['retador']=$retador; $datos['reto']=$reto; $datos['cadena']=base64_encode("aceptarreto||".$equipo->id_equipo."||".$retador->id_equipo."||".$destinatario->id_jugador."||".$reto->id_reto); if($_POST['tipo']=='a') $datos['tipo']="Amistoso"; else $datos['tipo']="Competitivo"; $datos['mensaje']=$_POST['mensaje']; Mail::send('mails.reto', $datos, function($message) use ($destinatario) { $message->to($destinatario->email)->subject('Tu equipo ha sido retado'); });*/ $alertaArray = array('id_jugador' => $destinatario->id_jugador, 'estado' => 'a', 'id_tipo_alerta' => 2, 'id_referencia' => $reto["data"]["id"]); $alerta = $this->AlertasRepository->create($alertaArray); if (getenv('APP_ENV') == "production") { $url = 'http://pruebas.quepartido.com/front/public/'; } else { $url = 'http://quepartido.com/'; } $alerta_text = '<div onclick="window.open(' . $url . 'equipos/perfil?id_equipo=' . $retador["data"]["id"] . '\')" class="orange">' . strtoupper($retador["data"]["equipo"]) . '</div><span class="message" > quiere enfrentar a tu equipo ' . strtoupper($equipo["data"]["equipo"]) . ' el día ' . $reto["data"]["fecha"] . ' a las ' . date("H:i", strtotime($reto["data"]["fecha"] . " " . $reto["data"]["fecha"])) . '</span><br><input name="button" type="button" class="send4" onclick="responderAlerta(' . $alerta["data"]["id"] . ',' . $reto["data"]["id"] . ',\'t\')" style="height: 30" id="button" value=" ACEPTAR "><input name="button" type="button" class="send3" style="height: 30" id="button" onclick="responderAlerta(' . $alerta["data"]["id"] . ',' . $reto["data"]["id"] . ',\'f\')" value=" RECHAZAR ">'; $alerta_app = strtoupper($retador["data"]["equipo"]) . ' quiere enfrentar a tu equipo ' . strtoupper($equipo["data"]["equipo"]) . ' el día ' . $reto["data"]["fecha"] . ' a las ' . date("H:i", strtotime($reto["data"]["fecha"] . " " . $reto["data"]["hora"])); $updateArray = array('alerta' => $alerta_text, 'alerta_app' => $alerta_app); $alerta = $this->AlertasRepository->update($updateArray, $alerta["data"]["id"]); } //Realizar reserva si viene if (isset($retoData['id_campo'])) { $campo = Campo::where("id_campo", "=", $retoData['id_campo'])->join("canchas", "campos.id_cancha", "=", "canchas.id_cancha")->first(); $fechado = explode("-", $reto->fecha); $traddia['1'] = "Lunes"; $traddia['2'] = "Martes"; $traddia['3'] = "Miercoles"; $traddia['4'] = "Jueves"; $traddia['5'] = "Viernes"; $traddia['6'] = "Sabado"; $traddia['7'] = "Domingo"; $tradMes['01'] = "Enero"; $tradMes['02'] = "Febrero"; $tradMes['03'] = "Marzo"; $tradMes['04'] = "Abril"; $tradMes['05'] = "Mayo"; $tradMes['06'] = "Junio"; $tradMes['07'] = "Julio"; $tradMes['08'] = "Agosto"; $tradMes['09'] = "Septiembre"; $tradMes['10'] = "Octubre"; $tradMes['11'] = "Noviembre"; $tradMes['12'] = "Diciembre"; $fechaformat = strtr(date("N", strtotime($reto->fecha)), $traddia) . ", " . $fechado[2] . " de " . strtr($fechado[1], $tradMes) . " de " . $fechado[0]; $reserva = new Reserva(); $reserva->id_cancha = $campo->id_cancha; $reserva->fecha = $reto->fecha; $reserva->hora = $retoData['horareserva'] . ":00:00"; $reserva->id_jugador = $usuario->id_jugador; $reserva->id_campo = $campo->id_campo; $reserva->total_horas = $retoData['horas']; $reserva->save(); } return response()->json($reto); } catch (\Exception $e) { if ($e instanceof ValidatorException) { return response()->json($e->toArray(), 400); } else { return response()->json($e->getMessage(), 500); } } }
/** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return \JWTAuth::parseToken()->authenticate(); }
/** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $user = JWTAuth::parseToken()->toUser(); $input = Input::all(); // if userId is set in input, check if // there is an attempt to update another // user preference if (isset($input['userId'])) { if ($user['id'] != $input['userId']) { return $this->response->errorForbidden(); } } $input['schedule'] = $this->convertToCronTime($input['schedule']); $input['userId'] = $user['id']; $input['jobname'] = 'rsync-' . $input['userId']; $this->server->update($input, $id); $server = $this->server->find($id); $server['schedule'] = $this->convertToHumanTime($server['schedule']); return $server; }
/** * Signs in a user using JWT */ Route::post('/signin', function () { $credentials = Input::only('email', 'password'); if (!($token = JWTAuth::attempt($credentials))) { return Response::json(false, HttpResponse::HTTP_UNAUTHORIZED); } return Response::json(compact('token')); }); /** * Fetches a restricted resource from the same domain used for user authentication */ Route::get('/restricted', ['before' => 'jwt-auth', function () { $token = JWTAuth::getToken(); $user = JWTAuth::toUser($token); return Response::json(['data' => ['email' => $user->email, 'registered_at' => $user->created_at->toDateTimeString()]]); }]); /** * Fetches a restricted resource from API subdomain using CORS */ Route::group(['domain' => 'api.jwt.dev', 'prefix' => 'v1'], function () { Route::get('/restricted', function () { try { JWTAuth::parseToken()->toUser(); } catch (Exception $e) { return Response::json(['error' => $e->getMessage()], HttpResponse::HTTP_UNAUTHORIZED); } return ['data' => 'This has come from a dedicated API subdomain with restricted access.']; }); });
Route::get('/home', 'PagesController@index'); Route::get('/receipts', 'PagesController@receipts'); Route::get('/categories', 'PagesController@categories'); Route::get('/categories/{category}', ['as' => 'category.browse', 'uses' => 'PagesController@browseCategory']); Route::get('admin', ['as' => 'admin.home', 'uses' => 'AdminPagesController@home']); Route::get('admin/receipts', ['as' => 'admin.receipts', 'uses' => 'AdminPagesController@receipts']); Route::get('admin/categories', ['as' => 'admin.categories', 'uses' => 'AdminPagesController@categories']); Route::get('admin/categories/{category}', ['as' => 'admin.category.browse', 'uses' => 'AdminPagesController@browseCategory']); Route::get('business', ['as' => 'business.home', 'uses' => 'BusinessPagesController@home']); Route::get('business/receipts', ['as' => 'business.receipts', 'uses' => 'BusinessPagesController@receipts']); Route::get('business/promotions', ['as' => 'business.promotions', 'uses' => 'BusinessPagesController@promotions']); Route::get('business/promotions/create', ['as' => 'business.promotions.create', 'uses' => 'BusinessPagesController@createPromotion']); Route::controllers(['auth' => 'Auth\\AuthController', 'password' => 'Auth\\PasswordController']); Route::any('jwt/create', ['uses' => 'TokensController@authenticate']); Route::get('jwt', function () { $user = JWTAuth::parseToken(); return $user->toArray(); }); Route::resource('api/me/receipts', 'ReceiptsApiController', ['except' => ['show', 'edit', 'create']]); Route::resource('api/me/categories', 'CategoriesApiController', ['except' => ['show', 'edit', 'create']]); Route::get('api/me/receiptscategories/', ['as' => 'api.me.receipts.categories.index', 'uses' => 'ReceiptsCategoriesApiController@index']); Route::post('api/me/receipts/{receipt}/categories/{category}', ['as' => 'api.me.receipts.categories.store', 'uses' => 'ReceiptsCategoriesApiController@store']); Route::delete('api/me/receipts/{receipt}/categories/{category}', ['as' => 'api.me.receipts.categories.destroy', 'uses' => 'ReceiptsCategoriesApiController@destroy']); Route::resource('api/promotions', 'PromotionsController', ['only' => ['store', 'index']]); Route::any('ocr', function () { $a = Request::all(); file_put_contents(public_path() . '/images/malakies/input2.jpg', $a); return 'ok'; $text = "\n\nGAZOO\nKA®E MHAP\n{TAP AH TOYPIZTIKH TEKNEKH\nWYXAFQFIKH ENE\nUEIPAIQI 111240121w A®HNA\nTHA:210341388&\nA.®,M: 997793450 % A01: AflHNQN :1\n\nHMEF’.: 14/06/2015 11:34:31\nTPA11:DEL XEPB: 1AMEIO .\nAHOAEIEH AIANIKHZ 1111AH£HX\n\nA/A:87891\nEIAOZ rlozor A;IA cb n A\nE§5§E830 1,00 1,80 13\nEKHTQZH 0,00\nEYNOAO 1,80\n\nEYXAPIXTOYME noAy\n\n\n\n"; $text = str_replace('?', '7', $text); $text = str_replace('&', '8', $text);
/** * @api {post} /auth/refreshToken jwt刷新token * @apiDescription jwt刷新token * @apiName auth/refreshToken * @apiGroup Auth * @apiPermission JWT * @apiVersion 0.1.0 * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头 * @apiHeaderExample {json} Header-Example: * { * "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL21vYmlsZS5kZWZhcmEuY29tXC9hdXRoXC90b2tlbiIsImlhdCI6IjE0NDU0MjY0MTAiLCJleHAiOiIxNDQ1NjQyNDIxIiwibmJmIjoiMTQ0NTQyNjQyMSIsImp0aSI6Ijk3OTRjMTljYTk1NTdkNDQyYzBiMzk0ZjI2N2QzMTMxIn0.9UPMTxo3_PudxTWldsf4ag0PHq1rK8yO9e5vqdwRZLY" * } * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * token: 9UPMTxo3_PudxTWldsf4ag0PHq1rK8yO9e5vqdwRZLY.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL21vYmlsZS5kZWZhcmEuY29tXC9hdXRoXC90b2tlbiIsImlhdCI6IjE0NDU0MjY0MTAiLCJleHAiOiIxNDQ1NjQyNDIxIiwibmJmIjoiMTQ0NTQyNjQyMSIsImp0aSI6Ijk3OTRjMTljYTk1NTdkNDQyYzBiMzk0ZjI2N2QzMTMxIn0.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 * } */ public function refreshToken() { $newToken = \JWTAuth::parseToken()->refresh(); return $this->response->array(['token' => $newToken]); }
/** * Delete a record by id * @return array */ public function destroy($equipoId, $id) { \JWTAuth::parseToken(); $user = \JWTAuth::parseToken()->authenticate(); if ($id != $user->id_jugador) { $equiposCapitan = $this->JugadoresEquiposRepository->scopeQuery(function ($query) use($id, $user) { return $query->where('id_jugador', $user->id_jugador)->whereIn('capitan', ['t', 's'])->where('id_equipo', $id); })->all(); if (count($equiposCapitan) == 0) { return ResponseMessage::notIsCaptain(); } } $jugadores = \App\Models\JugadoresEquipos::where('id_equipo', $equipoId)->where('id_jugador', $id)->delete(); return response()->json(true); }
/** * Bootstrap any application services. * * @return void */ public function boot() { \App\Notes\Note::updated(function ($note) { event(new \App\Events\SomeEvent(\JWTAuth::parseToken()->toUser())); }); }