how to set and get session with koajs and koa-session? - koa

im already read from the documentation and also find some tutorial like tutorialspoint. But, so far i dont know how to create and use session with koa. Here's my code:
router.post('/login', async ctx => {
const user = ctx.request.body
const name = user.name
const email = user.email
const password = user.password
const users = require('./client').db('mydatabase').collection('users')
const userExist = await users.findOne({"name": name})
const emailExist = await users.findOne({"email": email})
if(userExist || emailExist) {
this.session.email = email
ctx.body = this.session.email
}
})
above code give error below:
TypeError: Cannot set properties of undefined (setting 'email')
Previously i've learn a lot from laravel, Here's how we create and use the session with laravel:
//creating session
...
session([
'email' => $request->input('email')
])
...
//use session
$email = session('email')
...
can you tell me? or do you have better example? Thanks

Related

Shopify GraphQL PHP

I'm having some issues with using Shopify's GraphQL API. I've already made a bunch of REST calls, but for this one I would need GraphQL.
I'm trying to add videos to certain products and this is what I have so far:
mutation productCreateMedia($productId: ID!, $media: [CreateMediaInput!]!) {
productCreateMedia(productId: $productId, media: $media) {
media {
alt
}
mediaUserErrors {
code
field
message
}
product {
id
}
}
}
and for variables, I have an array of:
$gid = "gid://shopify/Product/".row('shopifyID');
$videoLink = "https://www.youtube.com/watch?v=".row('youtubeID');
$media = array('originalSource'=>$videoLink,'mediaContentType'=>'EXTERNAL_VIDEO');
$variables = array ('productId'=>$gid,'media'=>$media);
I use the next function for the call:
function graph($query , $variables = []){
$domain = 'domain.myshopify.com';
$url = 'https://'.$domain.'/admin/api/2020-01/graphql.json';
$request = ['query' => $query];
if(count($variables) > 0) { $request['variables'] = $variables; }
$req = json_encode($request);
$parameters['body'] = $req;
$stack = HandlerStack::create();
$client = new \GuzzleHttp\Client([
'handler' => $stack,
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-Shopify-Access-Token'=>'myAPIpass' // shopify app accessToken
],
]);
$response = $client->request('post',$url,$parameters);
return $body = json_decode($response->getBody(),true);
}
But what I'm getting back is:
Variable productId of type ID! was provided invalid value
I used php-shopify SDK for REST API, but couldn't figure out how it works for GraphQL, so went with the usual way of just calling the JSON endpoint.
Any help in what I'm doing wrong here?
So...to answer my own question...the shopify ID string has to be base 64 encoded.
I added just this line and it works now:
$gid = base64_encode($gid);

Error adding new event to google calender Google_Service_Exception (401) { "error": "unauthorized_client", "error_description": "Unauthorized" }

When i try to submit a new event to my google calender in a laravel project I always face this error:
Google_Service_Exception (401)
{ "error": "unauthorized_client", "error_description": "Unauthorized" }
I created new OAuth credentials for calendar api and added it to .env file as shown:
I am also using google+ api so that each user can access his calender to update his events via OAuth 2
I tried to add new OAuth credentials but the problem still persist I also tried to delegate domain-wide authority to my service account by adding client id added to the .env file & scope and authorize them but nothing changed I also waited for 24 hours waiting the changes to take place but also nothing changed
Here is the function am using to create new events:
public function doCreateEvent(Event $evt, Request $request)
{
$this->validate($request, [
'title' => 'required',
'calendar_id' => 'required',
'datetime_start' => 'required|date',
'datetime_end' => 'required|date'
]);
$title = $request->input('title');
$calendar_id = $request->input('calendar_id');
$start = $request->input('datetime_start');
$end = $request->input('datetime_end');
$start_datetime = Carbon::createFromFormat('Y/m/d H:i', $start);
$end_datetime = Carbon::createFromFormat('Y/m/d H:i', $end);
$cal = new \Google_Service_Calendar($this->client);
$event = new \Google_Service_Calendar_Event();
$event->setSummary($title);
$start = new \Google_Service_Calendar_EventDateTime();
$start->setDateTime($start_datetime->toAtomString());
$event->setStart($start);
$end = new \Google_Service_Calendar_EventDateTime();
$end->setDateTime($end_datetime->toAtomString());
$event->setEnd($end);
// Create new conference
$conference = new \Google_Service_Calendar_ConferenceData();
$entryPoint = new \Google_Service_Calendar_EntryPoint();
$entryPoint->setAccessCode('wx12z3s');
$entryPoint->setEntryPointType('video');
$entryPoint->setLabel('meet.google.com/wx12z3s');
$entryPoint->setMeetingCode('wx12z3s');
$entryPoint->setPasscode('wx12z3s');
$entryPoint->setPassword('wx12z3s');
$entryPoint->setPin('wx12z3s');
$entryPoint->setUri('https://meet.google.com/wx12z3s');
$conference->setEntryPoints($entryPoint);
$conferenceSolution = new \Google_Service_Calendar_ConferenceSolution();
$conferenceSolution->setIconUri(null);
$conferenceSolution->setKey(new \Google_Service_Calendar_ConferenceSolutionKey());
$conference->setConferenceSolution($conferenceSolution);
$conferenceRequest = new \Google_Service_Calendar_CreateConferenceRequest();
$conferenceRequest->setRequestId($request->_token);
$conferenceSolutionKey = new \Google_Service_Calendar_ConferenceSolutionKey();
$conferenceSolutionKey->setType("hangoutsMeet");
$conferenceRequest->setConferenceSolutionKey($conferenceSolutionKey);
$conferenceRequest->setStatus(new \Google_Service_Calendar_ConferenceRequestStatus());
$conference->setCreateRequest($conferenceRequest);
$event->setConferenceData($conference);
//attendee
if ($request->has('attendee_name')) {
$attendees = [];
$attendee_names = $request->input('attendee_name');
$attendee_emails = $request->input('attendee_email');
foreach ($attendee_names as $index => $attendee_name) {
$attendee_email = $attendee_emails[$index];
if (!empty($attendee_name) && !empty($attendee_email)) {
$attendee = new \Google_Service_Calendar_EventAttendee();
$attendee->setEmail($attendee_email);
$attendee->setDisplayName($attendee_name);
$attendees[] = $attendee;
}
}
$event->attendees = $attendees;
}
$created_event = $cal->events->insert($calendar_id, $event);
$evt->title = $title;
$evt->calendar_id = $calendar_id;
$evt->event_id = $created_event->id;
$evt->datetime_start = $start_datetime->toDateTimeString();
$evt->datetime_end = $end_datetime->toDateTimeString();
$evt->save();
return redirect('/event/create')
->with('message', [
'type' => 'success',
'text' => 'Event was created!'
]);
}
I am using a G suite account so that I can add events and assign hangout meet conferences to it but the problem keeps showing when i try to add newly created event to the user calender
The problem was the access token I am trying to use to access user calendar is wrong. When I deleted all user data and of course his access token saved to the database and tried to login again so that a new record created to the user with a new access token the problem solved and I can now access his calendar and create new events

Invalid argument Supplied for foreach() Axios Laravel

I have a Vue.js form and I submit the form using Axios. I'm able to save the data to my database. However, when I want to save my dynamically added input fields I get this error message...
Invalid argument supplied for foreach
The problem is that it's not an array but it should be. As you can see, I would like to send the teams[] array from the Vue component to the Laravel backend with Axios. When i console.log() teams [object object], [object object].
app.js
new Vue({
el: '#regapp',
data: {
username: '',
email: '',
password: '',
password_confirmation: '',
teams: [
{
name: '',
role: '',
linkedin: '',
profileimg: ''
}
],
methods: {
onSubmit() {
axios.defaults.headers.common["X-CSRF-TOKEN"] = document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content");
let formData = new FormData();
formData.append('username', this.username);
formData.append('email', this.email);
formData.append('password', this.password);
formData.append('password_confirmation', this.password_confirmation);
formData.append('teams', this.teams);
axios.post('register', formData)
.then(response => alert('Success'))
.catch(error => this.errors.record(error.response.data.errors));
}
}
}
});
Controller.php
protected function create(array $data)
{
$user = new User();
$user->name = $data['username'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->save();
// Here I try to loop trough teams and save each of them names into db.
if ($data['teams'][0] != NULL) {
$format = (array)$data;
foreach ($format['teams'] as $teams) { // The error is here
$team = new Team();
$team->user_id = $user->id;
$team->tmembername = $teams->name;
$team->save();
}
}
return $user;
}
Thanks Hassan for the help.
The problem was that this.teams is an array of objects - it just tries to convert the Object to a String, hence getting [object Object].
So i can't do this:
formData.append('teams', this.teams);
I had to:
var teammemb = JSON.stringify(this.teams);
Then:
formData.append('teams', teammemb);
On my RegisterController.php
$csapat = (json_decode($data['teams']));
if (is_array($csapat) || is_object($csapat)) {
// in this contition, foreach gonna work only array or object exist
foreach ($csapat as $teams) {
$team = new Team();
$team->ico_id = $ico->id;
$team->tmembername = $teams->name;
$team->save();
}
}
It works now.

Struggling to store token for AdSense API

I've successfully managed to connect to the AdSense API and run a report. However, it requires a log in each time I run it, so it won't run as a cron job.
I've found a few other questions related to this. Some advise a service account, while others point out that a service account does not work with AdSense. The proposed solution is to store a token on my server, but I've been struggling to get that to work. Here is my code so far (which works, but requires manual log in):
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApplicationName('My Application name');
$client->setClientId(' MY ID ');
$client->setClientSecret(' MY SECRET ');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(' MY KEY '); // API key
$accountId = " MY ACCOUNT " ;
$adClientId = " MY CLIENT " ;
// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
$startDate = '2015-11-01';
$endDate = 'today';
$optParams = array(
'metric' => array(
'EARNINGS'),
'dimension' => array('DATE'),
'sort' => '+DATE',
'filter' => array(
'CUSTOM_CHANNEL_NAME==Mega Seating Plan'
)
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $startDate,
$endDate, $optParams);
if (isset($report) && isset($report['rows'])) {
// Get results.
foreach($report['rows'] as $row) {
$date = $row[0] ;
$earnings[$date] = $row[1] ;
}
} else {
print "No rows returned.\n";
}
Can anybody give me any pointers about how I can incorporate token storage into the above code, please?
Thank you to #jkns.co for the previous answer here which helped me to get it working.
Here's my final code:
$scriptUri = "I HAD TO PUT MY ABSOLUTE URL HERE, OTHERWISE THE CRON JOB WOULD LOOK IN THE WRONG PLACE" ;
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt ("force"); // This line had to be added to force the approval prompt and request a new token
$client->setApplicationName('My Application name');
$client->setClientId('BLAH');
$client->setClientSecret('BLAH');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('BLAH'); // API key
$accountId = "BLAH" ;
$adClientId = "BLAH" ;
// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
// If it successfully authenticates, I request the refresh token
$refreshToken = $client->getRefreshToken();
storeRefreshToken($refreshToken) ; // This function stores the token in MySQL
}
else { // Otherwise it loads the refresh token from MySQL
$refreshToken = getRefreshToken() ;
$client->refreshToken($refreshToken);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}

Parse Javascript - Relation is not a function

I'm trying to understand how relation works and i did wrote this simple script:
var Parse = require('parse/node');
Parse.initialize('myAppId');
Parse.serverURL = 'http://localhost:1337/parse';
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', 'the_username');
userQuery.find()
.then(user => {
return user;
})
.then(user => {
var Systems = Parse.Object.extend("systems");
var systemQuery = new Parse.Query(Systems);
systemQuery.equalTo('customer', 'myCustomer');
systemQuery.find()
.then(system => {
var relation = user.relation('systems_ref'); // HERE I GET RELATION IS NOT A FUNC
relation.add(system);
console.log('Adding relation');
user.save()
.then(response => console.log('user saved'))
.catch(error => console.log('Error saving', error));
}).catch(error => console.log('Error find system', error));
});
But in the line where i try to get user.relation i have the error "Relation is not a function".
I have look others example on how to create a relation, but i dont see difference in my code...
I have the user (that is a sublcass of ParseObject), and on it i'm trying to access relation method...
You may use it as follows:
To add the Post to User with the JavaScript SDK:
var user = Parse.User.current();
var relation = user.relation("posts");
relation.add(post);
user.save();

Resources