vendredi 1 juillet 2016

NodeJS JWT token verification

I'm trying to verify a signed token and extract information from it using NodeJS.

I have a token named userToken in the browser right now, it has been saved after I logged in (I use auth0 to login by the way).

I tried to verify my token here manually : http://jwt.io , it works and gives me payload data without a problem. However, I can't do the same thing with NodeJS. How can I do it?

I read the docs but I couldn't get it. https://github.com/auth0/express-jwt

Here's my server.js

var http = require('http');
var express = require('express');
var cors = require('cors');
var app = express();
var jwt = require('express-jwt');
var dotenv = require('dotenv');

dotenv.load();

var authenticate = jwt({
    secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
    audience: process.env.AUTH0_CLIENT_ID
});


// view engine setup
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));

app.set('view engine', 'jade');


app.configure(function () {

    // Request body parsing middleware should be above methodOverride
    app.use(express.bodyParser());
    app.use(express.urlencoded());
    app.use(express.json());
    app.use(cors());

    app.use(app.router);
});


app.get('/', function (req, res) {
    res.render('index');
});

app.get('/test', function(req,res) {
    // how do I check it?
});


var port = process.env.PORT || 3001;

http.createServer(app).listen(port, function (err) {
    console.log('listening in http://localhost:' + port);
});

PHP RabbitMq thread falling at the end of the process

I'm having an error at the end of the execution of a thread on PHP. I take some youtube links from a RabbitMQ queue and try to download it with youtube-dl but it returns the following error right after the first thread ends:

PHP Fatal error: Uncaught exception 'PhpAmqpLibExceptionAMQPIOException' with message 'Error reading data. Received 0 instead of expected 7 bytes' in /home/eliecer/Vídeos/php-thread-master/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Wire/IO/StreamIO.php:161

Here is the receiver code that is causing the error

require_once("Thread.php");
require_once("ThreadQueue.php");
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLibConnectionAMQPConnection;


function paralel( $name ,$id) {
  echo "Iniciando", "n";
  $title= shell_exec('youtube-dl --get-filename -o "%(title)s.%(ext)s" '.$name);
   $f ='youtube-dl -o "/home/eliecer/Documentos/%(title)s.%(ext)s" '.$name;
     shell_exec($f);
     echo "FInalizado", "n";
    // HERE IS WHERE IT FAILS
    }

$connection = new AMQPConnection('localhost', 5672, 'ernarvaezm', '12345678');
$channel = $connection->channel();

$channel->queue_declare('videos_queue', false, false, false, false);

echo ' * Waiting for messages. To exit press CTRL+C', "n";

$callback = function($msg){
    $t1 = new Thread('paralel');
    $data = json_decode($msg->body, true);
    $t1->start($data['link'],$data['id']);
    $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
  };

$channel->basic_qos(null, 1, null);
$channel->basic_consume('videos_queue', '', false, false, false, false, $callback);

while(count($channel->callbacks)) {

    $channel->wait();
}

$channel->close();
$connection->close();

Any ideas why this error might be about?

deduplicate JSON Array

How to add item in array for each duplicate ?

Change :

[
  {
     "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60",
     "planning":[
                   {
                   "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84",
                   "start":2016-01-01
                   },
                   {
                   "uuid":"37994EE3-F7E5-4199-A160-6D0B04D287D9",
                   "start":2016-01-02
                   }
                ]
  },
  {
     "uuid":"6BF57C74-F111-4901-A1C3-17E3B094C37E",
     "planning":[
                   {
                   "uuid":"21E386E9-0527-4EC2-81B5-A4F01B780B46",
                   "start":2016-03-01
                   },
                   {
                   "uuid":"D590A52C-DC9B-448E-A157-504CCA13FB45",
                   "start":2016-04-02
                   }
                ]
  }
]

to :

[
  {
     "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60",
     "planning":{
                   "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84",
                   "start":2016-01-01
                }
  },
  {
     "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60",
     "planning":{
                   "uuid":"37994EE3-F7E5-4199-A160-6D0B04D287D9",
                   "start":2016-01-02
                }
  },
  {
     "uuid":"6BF57C74-F111-4901-A1C3-17E3B094C37E",
     "planning":{
                "uuid":"21E386E9-0527-4EC2-81B5-A4F01B780B46",
                   "start":2016-03-01
                }
  },
  {
     "uuid":"6BF57C74-F111-4901-A1C3-17E3B094C37E",
     "planning":{
                "uuid":"D590A52C-DC9B-448E-A157-504CCA13FB45",
                "start":2016-04-02
                }
  }
]

I have tried this below , but planning's value is always first item value. This code remove planning'value with the current planning item.

var i= 0;
angular.forEach(data, function(value, key){
  if(value.planning.length>0){
    angular.forEach(value.planning, function(planningvalue, planningkey){
      $scope.out.push(value);
      $scope.out[i].planning=planningvalue;
      console.log($scope.out[i]);
      i=i+1;
    });
  }
});

Thanks

$_POST variable is empty (and I have used name attributes)

This has been posted here many times and I've read through many of the solutions to no avail.

I'm just starting to learn PHP, and I can't even get a simple example from W3 schools to work correctly.

Here is my html code - "index.html" (as simple as possible)

<html>
    <head>
        <title>Search my Database</title>
        <link rel="stylesheet" href ="style.css">
        <!--<meta http-equiv="refresh" content="1">-->
        <meta name = "viewport" content="width=device-width, initial-scale =1.0">
    </head>
    <body>


            <form action="submit.php" method="post">

                <input type="text" name="username">


                <input type="text" name="password">
                <br>
                <input type="submit" name="submit" class="submit">
            </form>




    </body>



</html>

And here is the file "submit.php":

<html>
<body>


Welcome <?php echo $_POST["username"]; ?><br>
Your password is <?php echo $_POST["password"]; ?>

</body>
</html>

When I enter data into the text boxes and submit the form the output of submit.php is as follows:

Welcome 
Your password is

I have tried using $_REQUEST and I have tried editing php.ini (even though all the values were already high enough to allow for a single line of text to be posted)

Any suggestions? I just want to get started on PHP

c - running 2 threads in parallel with a shared variable

Just a beginner to threads, I'm just doing a task which involves these 2 threads.

#include <stdio.h>
#include <pthread.h>

int count = 0;

void waitFor(unsigned int secs)
{
    unsigned int retTime = time(0) + secs;
    while(time(0) < retTime);
}

void func1(void * args)
{
    printf("In func1 ...n");
    long i = 0;
    while(1){
        i++;
        if(count == 1)
            break;
    }
    printf("The total number counted is: %ld n", i);
    count = 0;
    i = 0;
}

void func2(void * args)
{
    printf("In func2 ...n");
    waitFor(3);
    count = 1;
}


int main()
{
    pthread_t th1, th2;

    int j = 0;
    while(j++ < 4){
        printf("nRound:t%dn", j);

        pthread_create(&th1, NULL, (void*)func1,NULL);
        pthread_create(&th2, NULL, (void*)func2, NULL);

        pthread_join(th1,NULL);
        pthread_join(th2,NULL);
        waitFor(3);
    }

    return 0;
}

I've read various references and to my understanding pthread_join() means that if there are 2 or more threads, then they will wait for one thread to finish its execution and then next one will start executing and so on.

But when i run this program, the moment pthread_join(th1) is executed, both threads are created and executed 'concurrently'. How is this happening? Output:

Round:  1
In func2 ...
In func1 ...
The total number counted is: 897651254 

Round:  2
In func1 ...
In func2 ...
The total number counted is: 1051386065

........

My goal is to run these 2 threads in parallel. For now, join seems to do this; or am I going wrong somewhere?

And I've read that using volatile is not preferred for threads in C. So is there any way I could use count as a signal from thread 2 to 1?

Angular 2 http post request is not being called out

I am using angular 2 to make a get request and a post request. My get request works fine, but for my post, I do not see the request is made when checking my Firebug Net panel.

The code methods look like follows. I also have subscribe methods invoking them from a component class, which should not be relevant to this issue.

import {Injectable} from "angular2/core";
import {Http, Response, Headers, RequestOptions,  Jsonp, URLSearchParams} from "angular2/http";
import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/map'; 

 @Injectable()
export class MyService{
    constructor (private _http: Http){}  


testPost(){      

    var json = JSON.stringify({"userId": 111, "givenName": "CZ"});
    var body = "json="+json;
    var headers = new Headers({ 'Content-Type': 'application/json' });
    var options = new RequestOptions({ headers: headers });

    return this._http.post("http://mylocal.post.url", body, options)
        .map(this.extractData)
        .catch(this.handleError);

}

  private extractData(res: Response) {
    alert("test whether this method is reached");

    let body = res.json();
    return body.data || { };
  }

  private handleError (error: any) {
    alert("test whether this method is reached");

    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }     

 //testGet method is running well
testGet(link:string){

    return this._http.get(link)
    .map(res => res);

}     
}

I put an alert statement at the beginning of two helper methods. None of the alerts is reached. And I don't see any request called to the my local post url when debugging with Firebug.

While my testGet method works correctly, I just don't know what is missing for the testPost.

insert data with ajax in yii2?

i am trying to insert data to a database table using ajax in yii2. but i don't really know how to go about it i want to send the post data to the controller the problem seems to come from the ajax script .it is meant to show me the value of rate which is 'up'. instead the alert show me.

this is my view class

<?php

use yiiwidgetsListView;
use yiidataArrayDataProvider;
use appmodelsMyProfile;
use appmodelsLikeDiscussion;
use yiiwidgetsActiveForm;
use commonmodelsTopic;
use commonmodelsThumbs;
use commonmodelsComment;
use commonmodelsCandidate;
use yiiwidgetsPjax;
use yiihelpersHtml;
use frontendassetsAppAsset;

$this->title = 'My Yii Application';
?>
<button  id="save" name="save" class="readmore">up</button>  

this is my js file.

var fac= document.getElementById("save");
  fac.onclick = function fun()
    {

    $.ajax({
      url: '/index.php?r=site%2Fblog',
       type: 'post',
        data:{"rate": 'up'},
        success:function(data){
            alert(data);
        }

     });

    }   

this is my contoller class

   public function actionBlog()
    { 
     $thumbs= new Thumbs(); 
     if(isset($_POST['rate'])){
  $thumbs->user=Yii::$app->user->identity->email;
          $thumbs->topic_id = 1;
          $thumbs->rate = $_POST['rate'];
        $thumbs->load($_POST);
         $thumbs->save();
     }

         return $this->render('blog');

    } 

this is what i get as the alert

enter image description here