Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Created by PhpStorm.
- * User: mfarid
- * Date: 11/03/18
- * Time: 20.54
- */
- namespace api\modules\v1\controllers;
- use Yii;
- use common\models\User;
- class AuthController extends \yii\rest\Controller
- {
- public function init()
- {
- parent::init(); // TODO: Change the autogenerated stub
- }
- public function actionLogin(){
- $username = strip_tags(Yii::$app->request->post('username'));
- $password = strip_tags(Yii::$app->request->post('password'));
- if(empty($username)){
- return $this->returnApiError(404,'Missing the required parameter username when login',null);
- }
- if(empty($password)){
- return $this->returnApiError(404,'Missing the required parameter password when login',null);
- }
- $activeUser=User::findByUsername($username);
- if(empty($activeUser)) {
- return $this->returnApiError(404, 'User not found!', null);
- }
- if(!$activeUser->validatePassword($password)){
- return $this->returnApiError(404, 'Password not match!', null);
- }
- try{
- if (is_null($activeUser->access_token)) {
- $activeUser->access_token = Yii::$app->getSecurity()->generateRandomString();
- $activeUser->save();
- }
- $roleItem = Yii::$app->authManager->getRolesByUser($activeUser->id);
- $roleName = '';
- foreach ($roleItem as $item) {
- $roleName=$item->name;
- }
- $params=[
- 'code'=>200,
- 'message'=>'Login Successfull',
- 'data'=>[
- 'id'=>$activeUser->id,
- 'username'=>$activeUser->username,
- 'role_name'=>$roleName,
- 'email'=>$activeUser->email,
- 'access_token'=>$activeUser->access_token
- ],
- ];
- return $params;
- }catch (\Exception $e){
- return $this->returnApiError(404, 'Login error!', null);
- }
- }
- public function returnApiError($code,$message,$data=null){
- return[
- 'code'=>$code,
- 'message'=>$message,
- 'data'=>$data
- ];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement