APIでユーザーIDとパスワードを検証してログインさせる機能を作っています。
APIはユーザーIDとパスワードが正しければステータスコード200を、間違えていればステータスコード400を返してきます。
200が返ってきた場合は問題なく動作するのですが、400が返ってきたときになぜか404エラーが表示されてしまします。
API単体での動作をFirefoxのアドオン「HTTP Requester」などでチェックすると、問題なく意図したとおりに動いていることを確認できます。
###ログインコントローラ
php
1class Controller_Login extends Controller 2{ 3 private $fields = [ 4 'username', 5 'password' 6 ]; 7 8 public function action_index() 9 { 10 // 既にログイン済ならダッシュボードへ 11 if (Auth::check()) 12 { 13 Response::redirect('dashboard'); 14 } 15 16 // バリデーションルール 17 $val = Validation::forge(); 18 $val->add('username','ID')->add_rule('required'); 19 $val->add('password','パスワード')->add_rule('required'); 20 21 if (Input::method() === 'POST') 22 { 23 // 入力値をセッションに保持 24 foreach ($this->fields as $field) 25 { 26 Session::set_flash($field, Input::post($field)); 27 } 28 29 // バリデーションとCSFRトークンチェック 30 if ($val->run() && Security::check_token()) 31 { 32 $id = Input::post('username'); 33 $password = Input::post('password'); 34 35 // 認証API 36 $auth = new Authentication(); 37 if ($auth->check($id, $password)) 38 { 39 $user = Model_User::findFromUsername($id); 40 41 if ($user) 42 { 43 Auth::force_login($user->id); 44 } 45 else 46 { 47 $user_id = Auth::create_user($id, Str::random('alnum', 16), Str::random('alnum', 16).'@example.com'); 48 Auth::force_login($user_id); 49 } 50 Auth::remember_me(); 51 52 Response::redirect('dashboard'); 53 } 54 55 Session::set_flash('login.error', 'IDもしくはパスワードが違います。'); 56 } 57 } 58 59 return View::forge('login', [ 60 'val' => $val, 61 ]); 62 } 63}
###APIアクセスクラス
php
1class Authentication 2{ 3 /** 4 * 認証APIへIDとパスワードを送る 5 * 6 * 認証が成功の場合true 7 * 認証が失敗の場合false 8 * を返す 9 * 10 * @param integer $id 11 * @param string $password 12 * @return boolean 13 */ 14 public function check($id, $password) 15 { 16 $curl = Request::forge(API_URL, 'curl'); 17 $curl->set_method('post'); 18 $curl->set_params([ 19 'id' => $id, 20 'password' => $password, 21 ]); 22 $curl->set_header('Content-Type', 'application/json'); 23 $curl->execute(); 24 $response = $curl->response(); 25 26 if ($response->status == 200) 27 { 28 return true; 29 } 30 31 return false; 32 } 33}
###API
php
1class Controller_Api extends Controller_Rest 2{ 3 protected $format = 'json'; 4 5 public function post_auth() 6 { 7 $request = Input::json(); 8 9 if (!($request['id'] && $request['password'])) 10 { 11 return $this->response([ 12 'message' => '失敗時メッセージ' 13 ], 400); 14 } 15 16 if ($request['id'] === '0123456789' && $request['password'] === 'password') 17 { 18 return $this->response([ 19 'message' => '成功時メッセージ' 20 ]); 21 } 22 23 return $this->response([ 24 'message' => '失敗時メッセージ' 25 ], 400); 26 } 27}
どのようにすれば404エラーを表示させずにできるでしょうか?
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/04/21 23:31 編集