前面實作完註冊功能後,接下來就來講解如何登入。機制大致上如下:
public function login(Request $request){
$email = $request->auth_email;
$password = $request->auth_password;
/*
...
*/
}
public function login(Request $request){
/*
...
*/
$user = User::where('email', $email)->first();
if(!$user){
return response(['message' => 'Login failed. Please check email id']);
}
/*
...
*/
}
public function login(Request $request){
/*
...
*/
if(!Hash::check($password, $user->password)){
return response(['message' => 'Login failed. Please check password']);
}
/*
...
*/
}
public function login(Request $request){
/*
...
*/
// 較安全:每次登入重新生成新的 token
$user->update(['api_token', Str::random(60)]);
return response(['message' => 'Login successfully', 'api_token' => $user->api_token]);
}
完整程式碼:
*UsersController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class UsersController extends Controller
{
/*
...
*/
public function login(Request $request){
$email = $request->auth_email;
$password = $request->auth_password;
$user = User::where('email', $email)->first();
if(!$user){
return response(['message' => 'Login failed. Please check email id']);
}
if(!Hash::check($password, $user->password)){
return response(['message' => 'Login failed. Please check password']);
}
return response(['message' => 'Login successfully', 'api_token' => $user->api_token]);
}
}
錯誤情形1:email
錯誤情形2:password incorrect
正確
會員註冊和登入功能大致完成,目前尚未實作驗證 ( Authorization ),等待 user 的所有 API 做好之後就會開始動工。接下來介紹 index 和 show,敬請期待!