Advertisement
Guest User

Api Auth

a guest
Mar 18th, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: mfarid
  5. * Date: 11/03/18
  6. * Time: 20.54
  7. */
  8.  
  9. namespace api\modules\v1\controllers;
  10. use Yii;
  11. use common\models\User;
  12.  
  13.  
  14. class AuthController extends \yii\rest\Controller
  15. {
  16.  
  17. public function init()
  18. {
  19. parent::init(); // TODO: Change the autogenerated stub
  20. }
  21.  
  22. public function actionLogin(){
  23.  
  24. $username = strip_tags(Yii::$app->request->post('username'));
  25. $password = strip_tags(Yii::$app->request->post('password'));
  26.  
  27. if(empty($username)){
  28. return $this->returnApiError(404,'Missing the required parameter username when login',null);
  29. }
  30.  
  31. if(empty($password)){
  32. return $this->returnApiError(404,'Missing the required parameter password when login',null);
  33. }
  34.  
  35. $activeUser=User::findByUsername($username);
  36. if(empty($activeUser)) {
  37. return $this->returnApiError(404, 'User not found!', null);
  38. }
  39. if(!$activeUser->validatePassword($password)){
  40. return $this->returnApiError(404, 'Password not match!', null);
  41.  
  42. }
  43.  
  44. try{
  45.  
  46. if (is_null($activeUser->access_token)) {
  47. $activeUser->access_token = Yii::$app->getSecurity()->generateRandomString();
  48. $activeUser->save();
  49. }
  50.  
  51. $roleItem = Yii::$app->authManager->getRolesByUser($activeUser->id);
  52. $roleName = '';
  53. foreach ($roleItem as $item) {
  54. $roleName=$item->name;
  55. }
  56. $params=[
  57. 'code'=>200,
  58. 'message'=>'Login Successfull',
  59. 'data'=>[
  60. 'id'=>$activeUser->id,
  61. 'username'=>$activeUser->username,
  62. 'role_name'=>$roleName,
  63. 'email'=>$activeUser->email,
  64. 'access_token'=>$activeUser->access_token
  65. ],
  66. ];
  67.  
  68. return $params;
  69.  
  70.  
  71. }catch (\Exception $e){
  72. return $this->returnApiError(404, 'Login error!', null);
  73.  
  74. }
  75.  
  76. }
  77.  
  78.  
  79. public function returnApiError($code,$message,$data=null){
  80. return[
  81. 'code'=>$code,
  82. 'message'=>$message,
  83. 'data'=>$data
  84. ];
  85. }
  86.  
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement