public function testRoute() { $customer = Customer::whereEmail('*****@*****.**')->first(); $token1 = JWTAuth::attempt(["email" => '*****@*****.**', "password" => "admin"]); $token2 = JWTAuth::fromUser($customer); $access_token = $token1; $response = $this->call('GET', '/testtoken', [], [], array('HTTP_authorization' => 'bearer ' . $access_token, "HTTP_custom" => "custom header")); $this->assertTrue($response->isOk()); }
public function login(Request $request) { $credentials = $request->only('email', 'password'); if (!($token = \JWTAuth::attempt($credentials))) { return response()->json(['error' => 'invalid_credentials'], 401); } return response()->json(['token' => $token, 'user' => ['id' => \JWTAuth::toUser($token)->id, 'name' => \JWTAuth::toUser($token)->name, 'email' => \JWTAuth::toUser($token)->email]]); }
public function in() { $credentials = \Request::only('email', 'password'); if ($token = \JWTAuth::attempt($credentials)) { $response = response()->json(['token' => $token]); } else { $response = response()->json(['errors' => ['The email/password is invalid.']], 400); } return $response; }
public function authenticate($userCredentials) { if(!$token = \JWTAuth::attempt($credentials)) { //throw exception } $user = \JWTAuth::setToken($token)->toUser(); return $user; }
public function authenticate(Request $request) { try { $credentials = \Request::only('email', 'password'); if (!($token = \JWTAuth::attempt($credentials))) { return \Response::json(['error' => 'invalid_credentials'], 401); } return \Response::json(compact('token')); } catch (JWTException $e) { return \Response::json(['error' => 'could_not_create_token'], 500); } }
/** * Handle login request to the application. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function store(Request $request) { $validator = \Validator::make($request->all(), ['email' => 'required|email', 'password' => 'required|min:6']); if ($validator->fails()) { return $this->respondValidationError($validator); } $token = is_api_request() ? \JWTAuth::attempt($request->only('email', 'password')) : Auth::attempt($request->only('email', 'password'), $request->has('remember')); if (!$token) { return $this->respondLoginFailed(); } event('users.login', [Auth::user()]); return $this->respondCreated($request->input('return'), $token); }
/** * @api {post} /auth/login 登录 * @apiDescription 登录 * @apiName auth/login * @apiGroup Auth * @apiPermission none * @apiParam {Email} email 邮箱 * @apiParam {String} password 密码 * @apiVersion 0.1.0 * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL21vYmlsZS5kZWZhcmEuY29tXC9hdXRoXC90b2tlbiIsImlhdCI6IjE0NDU0MjY0MTAiLCJleHAiOiIxNDQ1NjQyNDIxIiwibmJmIjoiMTQ0NTQyNjQyMSIsImp0aSI6Ijk3OTRjMTljYTk1NTdkNDQyYzBiMzk0ZjI2N2QzMTMxIn0.9UPMTxo3_PudxTWldsf4ag0PHq1rK8yO9e5vqdwRZLY * } * @apiErrorExample {json} Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UserNotFound" * } */ public function login() { $validator = \Validator::make($this->request->all(), ['email' => 'required|email', 'password' => 'required']); $credentials = $this->request->only('email', 'password'); if (!($token = \JWTAuth::attempt($credentials))) { $validator->after(function ($validator) { $validator->errors()->add('error_msg', '用户名或密码错误'); }); } if ($validator->fails()) { return $this->errorBadRequest($validator->messages()); } return $this->response->array(['token' => $token]); }
/** * Authenticate the user by their credentials * * @param array $data * @return \Illuminate\Http\JsonResponse */ public function authenticate(array $data) { try { // Attempt to verify the credentials and create a token for the user if (!($token = \JWTAuth::attempt($data))) { return $this->response()->array(['error' => 'invalid_credentials'])->setStatusCode(401); } } catch (JWTException $e) { // Something went wrong whilst attempting to encode the token return $this->response()->array(['error' => 'could_not_create_token'])->setStatusCode(500); } // Authentication passed and return the token return $token; }
public function authenticate(Request $request) { $credentials = $request->only('email', 'password'); try { // verify the credentials and create a token for the user if (!($token = JWTAuth::attempt($credentials))) { return response()->json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong return response()->json(['error' => 'could_not_create_token'], 500); } // if no errors are encountered we can return a JWT return response()->json(compact('token')); }
public function signin() { $credentials = \Input::only('email', 'password'); $validator = \Validator::make($credentials, User::getApiAuthRules()); if ($validator->passes()) { try { if (!($token = \JWTAuth::attempt($credentials))) { return \API::response()->array(['error' => 'invalid_credentials'])->statusCode(401); } } catch (JWTException $e) { return \API::response()->array(['error' => 'could_not_create_token'])->statusCode(500); } } else { throw new \Dingo\Api\Exception\StoreResourceFailedException('Could not signin.', $validator->errors()); } return compact('token'); }
public function testChangePassword() { // Check authenticate $res = $this->call('PUT', '/me/password'); $results = json_decode($res->getContent()); $this->assertEquals('error', $results->status); $this->assertEquals('authenticate', $results->type); $this->assertEquals('Token is not provided.', $results->message); $credentials = ['email' => '*****@*****.**', 'password' => '123456']; $token = JWTAuth::attempt($credentials); // Input is empty $res = $this->call('PUT', '/me/password', [], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $this->assertEquals(400, $res->getStatusCode()); $results = json_decode($res->getContent()); $this->assertEquals('error', $results->status); $this->assertEquals('validation', $results->type); $this->assertObjectHasAttribute('old_password', $results->errors); $this->assertEquals('The old password field is required.', $results->errors->old_password[0]); $this->assertObjectHasAttribute('password', $results->errors); $this->assertEquals('The password field is required.', $results->errors->password[0]); // Check validate input $res = $this->call('PUT', '/me/password', ['old_password' => '1234', 'password' => '1234', 'password_confirmation' => '123'], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $this->assertEquals(400, $res->getStatusCode()); $results = json_decode($res->getContent()); $this->assertEquals('error', $results->status); $this->assertEquals('validation', $results->type); $this->assertObjectHasAttribute('old_password', $results->errors); $this->assertEquals('The old password must be at least 6 characters.', $results->errors->old_password[0]); $this->assertObjectHasAttribute('password', $results->errors); $this->assertEquals('The password confirmation does not match.', $results->errors->password[0]); $this->assertEquals('The password must be at least 6 characters.', $results->errors->password[1]); // Old password is wrong $res = $this->call('PUT', '/me/password', ['old_password' => '123456789', 'password' => '12345678', 'password_confirmation' => '12345678'], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $this->assertEquals(400, $res->getStatusCode()); $results = json_decode($res->getContent()); $this->assertEquals('error', $results->status); $this->assertEquals("The old password is incorrect.", $results->message); $this->assertEquals('validation', $results->type); // Change password success $res = $this->call('PUT', '/me/password', ['old_password' => '123456', 'password' => '12345678', 'password_confirmation' => '12345678'], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $this->assertEquals(204, $res->getStatusCode()); $checkPassword = Auth::attempt(['id' => 1, 'password' => '12345678']); $this->assertTrue($checkPassword); }
public function auth(AuthRequests $request) { $credentials = $request->only(['username', 'password']); $user = User::where('username', $credentials['username'])->first(); if (!$user) { return $this->responseUnauthorized('Wrong credentials'); } $customClaims = ['user_id' => $user->id]; try { // attempt to verify the credentials and create a token for the user if (!($token = \JWTAuth::attempt($credentials, $customClaims))) { 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); } //$token = ['token' => $token]; // all good so return the token return response()->json(compact('token')); }
public function login() { $validator = \Validator::make($this->request->all(), ['mobile' => 'required', 'password' => 'required']); $account = $this->request->get('mobile'); //查询用户是否被删除 $del_user_user_name = Customer::onlyTrashed()->where('user_name', $account)->first(); $del_user_mobile = Customer::onlyTrashed()->where('mobile', $account)->first(); if ($del_user_user_name || $del_user_mobile) { return return_rest('0', array('token' => '', 'customer' => array('id' => '', 'avatar' => '', 'type' => '', 'nickname' => '', 'name' => '', 'user_name' => '', 'mobile' => '')), '您已被移出!'); } $password = $this->request->get('password'); $credentials_mobile = array('mobile' => $account, 'password' => $password); $credentials_user_name = array('user_name' => $account, 'password' => $password); $token = \JWTAuth::attempt($credentials_mobile) ? \JWTAuth::attempt($credentials_mobile) : \JWTAuth::attempt($credentials_user_name); if (!$token) { // $validator->after(function ($validator) { // //$validator->errors()->add('error_msg', '用户名或密码错误'); // return $this->errorBadRequest(return_rest('0','','用户名或密码错误','10021')); // }); return return_rest('0', array('token' => '', 'customer' => array('id' => '', 'avatar' => '', 'type' => '', 'nickname' => '', 'name' => '', 'user_name' => '', 'mobile' => '')), '用户名或密码错误'); } if ($validator->fails()) { //return $this->errorBadRequest($validator->messages()); $messages = $validator->messages(); $mobiles = $messages->get('mobile'); foreach ($mobiles as $mobile) { if ($mobile == 'The selected mobile is invalid.') { return $this->errorBadRequest(return_rest('0', '', '手机号码未注册')); } } return return_rest('0', array('token' => '', 'customer' => array('id' => '', 'avatar' => '', 'type' => '', 'nickname' => '', 'name' => '')), '请按照规则输入手机号码'); } //登录成功 获取用户信息 $customer = Customer::select('id', 'type', 'name', 'nickname', 'avatar', 'user_name', 'mobile')->where('user_name', $this->request->get('mobile'))->orWhere('mobile', $this->request->get('mobile'))->first(); return return_rest('1', compact('token', 'customer'), '登陆成功'); }
public function authenticate(Request $request) { $credentials = $request->only('email', 'password'); try { // verify the credentials and create a token for the user if (!($token = \JWTAuth::attempt($credentials))) { $response = new ApiResponse(); $response->status = 'error'; $response->message = ['id' => '', 'code' => 'invalid_credentials', 'description' => 'The credentials provided are not valid']; return \Response::json($response); } } catch (JWTException $e) { // something went wrong $response = new ApiResponse(); $response->status = 'error'; $response->message = ['id' => '', 'code' => 'could_not_create_token', 'description' => 'The token could not be created']; return \Response::json($response); } // if no errors are encountered we can return a JWT $response = new ApiResponse(); $response->status = 'success'; $response->message = ['token' => $token]; return \Response::json($response); }
Route::auth(); Route::get('/', 'HomeController@index'); Route::get('/app', ['as' => 'notes.app', 'uses' => 'NotesController@index']); Route::get('home', function () { if (\Auth::check()) { return redirect()->route('notes.app'); } return redirect('/login'); }); }); $api = app('Dingo\\Api\\Routing\\Router'); $api->version('v1', ['middleware' => ['api.throttle', 'cors'], 'limit' => 100, 'expires' => 5], function ($api) { $api->post('auth', function () { $credentials = Request::only('email', 'password'); try { if (!($token = JWTAuth::attempt($credentials))) { return response()->json(['error' => 'Bad credentials'], HttpResponse::HTTP_UNAUTHORIZED); } } catch (JWTException $e) { return response()->json(['error' => 'could not create token'], HttpResponse::HTTP_INTERNAL_SERVER_ERROR); } return response()->json(compact('token')); }); $api->delete('auth', ['uses' => 'App\\Http\\Controllers\\Api\\UsersController@logout']); $api->get('/', function () { return response()->json('Rabbitnote API'); }); $api->group(['prefix' => 'users/{user}', 'namespace' => '\\App\\Http\\Controllers\\Api'], function ($api) { $api->resource('notes', 'NotesController'); }); $api->get('user', '\\App\\Http\\Controllers\\Api\\UsersController@index');
public function setUp() { parent::setUp(); $this->make('App\\User', ['email' => $this->getStub()['email'], 'password' => Hash::make($this->getStub()['password'])]); $this->token = (string) JWTAuth::attempt(['email' => $this->getStub()['email'], 'password' => $this->getStub()['password']]); }
public function testRestoreFromTrash() { $credentials = ['email' => '*****@*****.**', 'password' => '123456']; $token = JWTAuth::attempt($credentials); // test find not found $res = $this->call('POST', '/users/5/restore', [], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $this->assertEquals('404', $res->getStatusCode()); // test restore user $user = factory(App\User::class)->create(); $res = $this->call('POST', '/users/' . $user->id . '/trash', [], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $res = $this->call('POST', '/users/' . $user->id . '/restore', [], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $this->assertEquals('204', $res->getStatusCode()); $exists = App\User::find($user->id); $this->assertEquals($user->name, $exists->name); $existsTrash = App\User::onlyTrashed()->count(); $this->assertEquals(0, $existsTrash); }
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- */ use Illuminate\Http\Request; use Ciccio\Components\Helper; // Just leaving this here Route::get('/', function () { return view('welcome'); }); // Prefix the API Route::group(['as' => 'api::', 'prefix' => '/v1'], function () { // Posts Route::resource('posts', '\\Ciccio\\Components\\Posts\\PostsController'); Route::resource('categories', '\\Ciccio\\Components\\Categories\\CategoryController'); Route::post('/signin', function () { $credentials = Input::only('email', 'password'); if (false === ($token = JWTAuth::attempt($credentials))) { // Bad login return Response::json(['Error' => 'Can\'t log you in.'], 403); } return Response::json(compact('token')); }); });
public function testToken() { $credentials = ['email' => '*****@*****.**', 'password' => '123456']; $token = JWTAuth::attempt($credentials); $res = $this->call('GET', '/me', [], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); }
public function testCanPermissionAndHasRole() { $this->withoutMiddleware(); $user = factory(App\User::class)->create(['password' => bcrypt('123456')]); $credentials = ['email' => $user->email, 'password' => '123456']; $token = JWTAuth::attempt($credentials); $editor = factory(Role::class)->create(['name' => 'editor', 'active' => 1]); $partner = factory(Role::class)->create(['name' => 'partner', 'active' => 1]); // add role to user $user->attachRole($editor); $this->assertEquals(true, $user->hasRole('editor')); $this->assertEquals(false, $user->hasRole('admin')); $this->assertEquals(false, $user->can('delete-user')); $this->assertEquals(false, $user->can(['delete-user', 'create-user'])); // Add permission NodePermission::model()->tree('[{"id":2, "name":"2"},{"id":3, "name":"delete-user","children":[{"id":4, "name":"create-post","children":[{"id":5, "name":"5"},{"id":6, "name":"6"}]}]},{"id":7, "name":"7"}]'); PermissionRole::create(['permission_id' => 3, 'role_id' => $editor->id, 'status' => 1]); $this->assertEquals(true, $user->can('delete-user')); $this->assertEquals(true, $user->can(['delete-user', 'create-user'])); $this->assertEquals(false, $user->can('create-post')); $user->attachRole($partner); PermissionRole::create(['permission_id' => 4, 'role_id' => $partner->id, 'status' => 1]); $this->assertEquals(true, $user->can('create-post')); $this->assertEquals(true, $user->can(['create-post', 'delete-post'])); $this->assertEquals(true, $user->can(['create-post', 'delete-post', 'delete-user'])); }
} $token = JWTAuth::fromUser($user); return response()->json(compact('token')); }); Route::post('signin', function (Request $request) { $validator = Validator::make($request->all(), ['email' => 'required|email|max:255', 'password' => 'required|max:255']); if ($validator->fails()) { return response()->json(['error' => 'Validation Error', 'validation_errors' => $validator->errors()], 400); } $credentials = $request->only('email', 'password'); try { $user = User::where('email', $request->email)->firstOrFail(); } catch (ModelNotFoundException $e) { return response()->json(['error' => 'invalid_credentials'], 401); } if (!($token = JWTAuth::attempt($credentials, ['name' => $user->name]))) { return response()->json(['error' => 'invalid_credentials'], 401); } return response()->json(compact('token')); }); // Test route for restricted data (to be removed) Route::get('restricted', ['middleware' => 'jwt.auth', function () { $token = JWTAuth::getToken(); $user = JWTAuth::toUser($token); return response()->json(['data' => ['email' => $user->email, 'registered_at' => $user->created_at->toDateTimeString()]]); }]); Route::get('user/{id}', function ($id) { $user = User::find($id); return response()->json(['user' => $user]); }); Route::get('test', function () {
public function testDeleteSuccess() { $credentials = ['email' => '*****@*****.**', 'password' => '123456']; $token = JWTAuth::attempt($credentials); $routePermission = factory(RoutePermission::class)->create(['route' => '/users', 'permissions' => json_encode(['review']), 'roles' => json_encode(['manager'])]); $res = $this->call('DELETE', "/routePermissions/{$routePermission->id}", [], [], [], ['HTTP_Authorization' => "Bearer {$token}"]); $this->assertEquals(204, $res->getStatusCode()); $exists = RoutePermission::find($routePermission->id); $this->assertNull($exists); }