Commit 6a97699f authored by jinyonson's avatar jinyonson

注册登录

parent a9941392
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
use Helpers;
public function __construct(){
}
}
<?php
namespace App\Http\Controllers\Api;
use App\Exceptions\BaseException;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Translation\Tests\Dumper\JsonFileDumperTest;
use Tymon\JWTAuth\JWTAuth;
class UserController extends Controller
{
protected $jwt;
public function __construct(JWTAuth $jwt)
{
$this->jwt = $jwt;
}
//登录
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:60',
'password' => 'required',
]);
try {
if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
return response()->json(['user_not_found'], 404);
}
} catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], 500);
} catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], 500);
}catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent' => $e->getMessage()], 500);
}
return JsonResponse::create([
'success'=>'200',
'msg'=>'ok',
'data'=>[
'user'=>Auth::user(),
'token'=>$token
]
]);
}
//注册
public function store(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:60',
'password' => 'required',
]);
$request['password'] = \Hash::make($request->password);
$user = new User();
$user->name='xiaoming';
$user->email=$request->email;
$user->password=$request['password'];
$bool=$user->save(); //保存
return JsonResponse::create([
'success'=>'200',
'msg'=>'ok',
'data'=>[
'bool'=>$bool,
]
]);
}
public function decode(Request $request){
throw new BaseException('订单',200);
}
}
<?php
namespace App\Models;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authuser;
class User extends Authuser implements JWTSubject
{
use Notifiable;
protected $hidden = ['password'];
protected $fillable = [
'name', 'email', 'password','remember_token'
];
public function getJWTIdentifier()
{
return $this->getKey(); /*自己可以定义的生成token的参数,我用的是将主键加密*/
}
public function getJWTCustomClaims()
{
return [];
}
protected $table = "users";
//定义主键
protected $primaryKey = "id";
}
......@@ -13,7 +13,9 @@ class AppServiceProvider extends ServiceProvider
*/
public function boot()
{
//
app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
return new \Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});
}
/**
......
......@@ -9,7 +9,9 @@
"encore/laravel-admin": "^1.6",
"fideloper/proxy": "~4.0",
"laravel/framework": "5.6.*",
"laravel/tinker": "~1.0"
"laravel/tinker": "~1.0",
"dingo/api": "2.0.0-alpha1",
"tymon/jwt-auth": "^1.0.0-rc.1"
},
"require-dev": {
"filp/whoops": "~2.0",
......
This diff is collapsed.
<?php
return [
/*
|--------------------------------------------------------------------------
| Standards Tree
|--------------------------------------------------------------------------
|
| Versioning an API with Dingo revolves around content negotiation and
| custom MIME types. A custom type will belong to one of three
| standards trees, the Vendor tree (vnd), the Personal tree
| (prs), and the Unregistered tree (x).
|
| By default the Unregistered tree (x) is used, however, should you wish
| to you can register your type with the IANA. For more details:
| https://tools.ietf.org/html/rfc6838
|
*/
'standardsTree' => env('API_STANDARDS_TREE', 'x'),
/*
|--------------------------------------------------------------------------
| API Subtype
|--------------------------------------------------------------------------
|
| Your subtype will follow the standards tree you use when used in the
| "Accept" header to negotiate the content type and version.
|
| For example: Accept: application/x.SUBTYPE.v1+json
|
*/
'subtype' => env('API_SUBTYPE', ''),
/*
|--------------------------------------------------------------------------
| Default API Version
|--------------------------------------------------------------------------
|
| This is the default version when strict mode is disabled and your API
| is accessed via a web browser. It's also used as the default version
| when generating your APIs documentation.
|
*/
'version' => env('API_VERSION', 'v1'),
/*
|--------------------------------------------------------------------------
| Default API Prefix
|--------------------------------------------------------------------------
|
| A default prefix to use for your API routes so you don't have to
| specify it for each group.
|
*/
'prefix' => env('API_PREFIX', null),
/*
|--------------------------------------------------------------------------
| Default API Domain
|--------------------------------------------------------------------------
|
| A default domain to use for your API routes so you don't have to
| specify it for each group.
|
*/
'domain' => env('API_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| Name
|--------------------------------------------------------------------------
|
| When documenting your API using the API Blueprint syntax you can
| configure a default name to avoid having to manually specify
| one when using the command.
|
*/
'name' => env('API_NAME', null),
/*
|--------------------------------------------------------------------------
| Conditional Requests
|--------------------------------------------------------------------------
|
| Globally enable conditional requests so that an ETag header is added to
| any successful response. Subsequent requests will perform a check and
| will return a 304 Not Modified. This can also be enabled or disabled
| on certain groups or routes.
|
*/
'conditionalRequest' => env('API_CONDITIONAL_REQUEST', true),
/*
|--------------------------------------------------------------------------
| Strict Mode
|--------------------------------------------------------------------------
|
| Enabling strict mode will require clients to send a valid Accept header
| with every request. This also voids the default API version, meaning
| your API will not be browsable via a web browser.
|
*/
'strict' => env('API_STRICT', false),
/*
|--------------------------------------------------------------------------
| Debug Mode
|--------------------------------------------------------------------------
|
| Enabling debug mode will result in error responses caused by thrown
| exceptions to have a "debug" key that will be populated with
| more detailed information on the exception.
|
*/
'debug' => env('API_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Generic Error Format
|--------------------------------------------------------------------------
|
| When some HTTP exceptions are not caught and dealt with the API will
| generate a generic error response in the format provided. Any
| keys that aren't replaced with corresponding values will be
| removed from the final response.
|
*/
'errorFormat' => [
'message' => ':message',
'errors' => ':errors',
'code' => ':code',
'status_code' => ':status_code',
'debug' => ':debug',
],
/*
|--------------------------------------------------------------------------
| API Middleware
|--------------------------------------------------------------------------
|
| Middleware that will be applied globally to all API requests.
|
*/
'middleware' => [
],
/*
|--------------------------------------------------------------------------
| Authentication Providers
|--------------------------------------------------------------------------
|
| The authentication providers that should be used when attempting to
| authenticate an incoming API request.
|
*/
'auth' => [
'jwt' => 'Dingo\Api\Auth\Provider\JWT',
],
/*
|--------------------------------------------------------------------------
| Throttling / Rate Limiting
|--------------------------------------------------------------------------
|
| Consumers of your API can be limited to the amount of requests they can
| make. You can create your own throttles or simply change the default
| throttles.
|
*/
'throttling' => [
],
/*
|--------------------------------------------------------------------------
| Response Transformer
|--------------------------------------------------------------------------
|
| Responses can be transformed so that they are easier to format. By
| default a Fractal transformer will be used to transform any
| responses prior to formatting. You can easily replace
| this with your own transformer.
|
*/
'transformer' => env('API_TRANSFORMER', Dingo\Api\Transformer\Adapter\Fractal::class),
/*
|--------------------------------------------------------------------------
| Response Formats
|--------------------------------------------------------------------------
|
| Responses can be returned in multiple formats by registering different
| response formatters. You can also customize an existing response
| formatter with a number of options to configure its output.
|
*/
'defaultFormat' => env('API_DEFAULT_FORMAT', 'json'),
'formats' => [
'json' => Dingo\Api\Http\Response\Format\Json::class,
],
'formatsOptions' => [
'json' => [
'pretty_print' => env('API_JSON_FORMAT_PRETTY_PRINT_ENABLED', false),
'indent_style' => env('API_JSON_FORMAT_INDENT_STYLE', 'space'),
'indent_size' => env('API_JSON_FORMAT_INDENT_SIZE', 2),
],
],
];
......@@ -146,6 +146,8 @@ return [
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
Dingo\Api\Provider\LaravelServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
/*
* Package Service Providers...
......
......@@ -14,7 +14,7 @@ return [
*/
'defaults' => [
'guard' => 'web',
'guard' => 'api',
'passwords' => 'users',
],
......@@ -42,7 +42,7 @@ return [
],
'api' => [
'driver' => 'token',
'driver' => 'jwt',
'provider' => 'users',
],
],
......@@ -67,7 +67,7 @@ return [
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
'model' => App\Models\User::class,
],
// 'users' => [
......
This diff is collapsed.
<?php
use Illuminate\Http\Request;
//use Illuminate\Http\Request;
//
///*
//|--------------------------------------------------------------------------
//| API Routes
//|--------------------------------------------------------------------------
//|
//| Here is where you can register API routes for your application. These
//| routes are loaded by the RouteServiceProvider within a group which
//| is assigned the "api" middleware group. Enjoy building your API!
//|
//*/
//
//Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
//});
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
$api = app("Dingo\Api\Routing\Router");
$api->version('v1', function ($api) {
$api->group(["namespace" => "App\Http\Controllers\Api",'middleware'=>'auth:api'], function ($api) {
$api->post('decode', 'AccountController@decode');
});
$api->group(["namespace" => "App\Http\Controllers\Api"], function ($api) {
$api->post('login', 'UserController@login');
$api->post('reg', 'UserController@store');
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment