Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class UploadController extends Controller {
- public $serializer = [
- 'class' => 'yiirestSerializer',
- 'collectionEnvelope' => 'items',
- ];
- public function behaviors()
- {
- $behaviors = parent::behaviors();
- $behaviors['authenticator'] = [
- 'class' => JwtHttpBearerAuth::className()
- ];
- return $behaviors;
- }
- public function actionIndex() {
- //Work with User
- }
- }
- public function actionLogin()
- {
- $username = Yii::$app->request->post('username');
- $password = Yii::$app->request->post('password');
- $provider = new ActiveDataProvider([
- 'query' => User::find()
- ->where(['user_name' => $username])->asArray()->one(),
- ]);
- $result = $provider->query;
- if($result)
- {
- if (Yii::$app->getSecurity()->validatePassword($password, $result['user_pass']))
- {
- $tokenId = base64_encode(mcrypt_create_iv(32));
- $issuedAt = time();
- $notBefore = $issuedAt; //Adding 10 seconds
- $expire = $notBefore + 5184000; // Adding 60 Days
- $serverName = 'your-site.com';
- $data = [
- 'iat' => $issuedAt, // Issued at: time when the token was generated
- 'jti' => $tokenId, // Json Token Id: an unique identifier for the token
- 'iss' => $serverName, // Issuer
- 'nbf' => $notBefore, // Not before
- 'exp' => $expire, // Expire
- 'data' => [ // Data related to the signer user
- 'id' => $result['user_id'],
- 'username' => $result['user_name'],
- 'mobile' => $result['user_mobile'],
- 'email' => $result['user_email'],
- 'city' => $result['user_city'],
- 'state' => $result['user_state'],
- 'country' => $result['user_country'],
- 'picture' => $result['user_picture'],
- ]
- ];
- $jwt = JWT::encode(
- $data,
- JWT_KEY,
- 'HS512'
- );
- $response = [
- 'status' => true,
- 'message' => 'Login Success..',
- 'era_tkn' => $jwt,
- ];
- }
- else
- {
- $response = [
- 'status' => false,
- 'message' => 'Wrong username or password.',
- ];
- }
- }
- else
- {
- $response = [
- 'status' => false,
- 'message' => 'Wrong username or password.',
- ];
- }
- return $response;
- }
- public function check_token()
- {
- $headers = Yii::$app->request->headers;
- $token = $headers->get('era_tkn');
- if($token)
- {
- try{
- $valid_data = JWT::decode($token, JWT_KEY, array('HS512'));
- $valid_data = $valid_data->data;
- }catch(Exception $e){
- $valid_data = $e->getMessage();
- }
- }
- else
- {
- $valid_data = 'Required Authentication';
- }
- return $valid_data;
- }
- $user_data = $this->check_token();
- if (!empty($user_data->id))
- {
- echo $user_data->id;
- }
- else
- {
- echo "Invalid Token.";
- }
Add Comment
Please, Sign In to add comment