主要功能是guest()
和intended()
:
演示
Authenticate
中间件 - 用于验证访问 url 的用户是否已登录。
class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//check if user is not logged in.
if (Sentinel::check() === false) {
//If ajax, send back ajax response
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
//redirect guest to login page
return redirect()->guest('/login');
}
}
return $next($request);
}
}
RESTful UserController
,我们处理所有登录尝试
/**
* POST: Login
*
* @param Request $request
* @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
//Authenticate User if possible
if ($this->service->user->loginByEmail($request->only(['email','password','remember_me']))) {
//Authentication Successful - Redirect to url that guest was trying to access, else redirect to home page.
return redirect()->intended('/');
} else {
//Authentication error, redirect back to login page with input
return redirect('/login')->withErrors(['password_incorrect' => 'Your password is incorrect. Please try again.'])->withInput();
}
}
已经在框架中的函数声明
Illuminate\Routing\Redirector
/**
* Create a new redirect response, while putting the current URL in the session.
*
* @param string $path
* @param int $status
* @param array $headers
* @param bool $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function guest($path, $status = 302, $headers = [], $secure = null)
{
//Store current full URL in session
$this->session->put('url.intended', $this->generator->full());
//Redirect
return $this->to($path, $status, $headers, $secure);
}
/**
* Create a new redirect response to the previously intended location.
*
* @param string $default
* @param int $status
* @param array $headers
* @param bool $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function intended($default = '/', $status = 302, $headers = [], $secure = null)
{
//Get path that guest was trying to access
$path = $this->session->pull('url.intended', $default);
//Redirect
return $this->to($path, $status, $headers, $secure);
}