I'm using web-push-php library for my project. The user can register/un-register for web notification but the message does NOT push to the specific user. following are my codes
main.js
'use strict';
const applicationServerPublicKey = ew.vars.PubKey;
const pushButton = document.querySelector('.pushBTN');
let isSubscribed = false;
let swRegistration = null;
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
//CODE HERE
//1
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
})
.catch(function(error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
//2
function initializeUI() {
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
//3
function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}
if (isSubscribed) {
pushButton.innerHTML = '<i class="fas fa-bell-slash text-danger"></i>';
} else {
pushButton.innerHTML = '<i class="fas fa-bell text-success"></i>';
}
pushButton.disabled = false;
}
//4
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
initializeUI();
})
//5
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
}
//6
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
//7
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
//8
function updateSubscriptionOnServer(subscription) {
// TODO: Send subscription to application server
if (subscription) {
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
fetch('webpushregister.php', {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))) : null,
token: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))) : null,
axn: 'subscribe'
})
}).then(function(response) {
return response.text();
}).then(function(response) {
console.log(response);
}).catch(function(err) {
// Error :(
console.log('error');
});
} else {
//subscriptionDetails.classList.add('is-invisible');
}
}
//9
function unsubscribeUser() {
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
//updating database
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
fetch('webpushregister.php', {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))) : null,
token: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))) : null,
axn: 'unsubscribe'
})
}).then(function(response) {
return response.text();
}).then(function(response) {
console.log(response);
}).catch(function(err) {
// Error :(
console.log('error removing from db');
throw new error('error removing from db');
});
//end updating database
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn();
});
}
//10
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
// TODO: Tell application server to delete subscription
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
my sw.js
'use strict';
//1
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Codelab';
const options = {
body: 'Yay it works.4444444444',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
const notificationPromise = self.registration.showNotification(title, options);
event.waitUntil(notificationPromise);
});
//2
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://developers.google.com/web/')
);
});
//installing web application
self.addEventListener("install", function(event) {
event.waitUntil(preLoad());
});
var preLoad = function(){
console.log("Installing web app");
return caches.open("offline").then(function(cache) {
console.log("caching index and important routes");
return cache.addAll(["/", "/offline.html"]);
});
};
self.addEventListener("fetch", function(event) {
event.respondWith(checkResponse(event.request).catch(function() {
return returnFromCache(event.request);
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};
var addToCache = function(request){
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
var returnFromCache = function(request){
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match("offline.html");
} else {
return matching;
}
});
});
};
and my php file
<?php
$siteconf = new SiteConfig();
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
$subscriber = ExecuteRow("SELECT * FROM subscribers ORDER BY id DESC LIMIT 1");
$auth = array(
'VAPID' => array(
'subject' => 'https://github.com/Minishlink/web-push-php-example/',
'publicKey' => $siteconf->PublicKey, // don't forget that your public key also lives in app.js
'privateKey' => $siteconf->PrivateKey, // in the real world, this would be in a secret file
),
);
// array of notifications
$notifications = [
[
'subscription' => Subscription::create([
'endpoint' => $subscriber['endpoint'],
'publicKey' => $siteconf->PublicKey,
'authToken' => $subscriber['auth'],
]),
'payload' => 'hello !',
],
];
$webPush = new WebPush($auth);
// send multiple notifications with payload
foreach ($notifications as $notification) {
$webPush->sendNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
);
}
/**
* Check sent results
* #var MessageSentReport $report
*/
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
echo "[v] Message sent successfully for subscription {$endpoint}.";
} else {
echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}
/**
* send one notification and flush directly
* #var \Generator<MessageSentReport> $sent
*/
$sent = $webPush->sendNotification(
$notifications[0]['subscription'],
$notifications[0]['payload'], // optional (defaults null)
true // optional (defaults false)
);
?>
I'm trying to send message to the last user in our database. I receive success message but the push message does NOT deliver.
What's the reason? how to fix it?
You are missing the following:
'contentEncoding' => $message["contentEncoding"]
It should be placed under the comment // array of notifications.
I am having an issue regarding this but it's the opposite of yours. I am only able to send a notification for the very last row but not the other rows.
Related
I am new to ionic and I am trying to understand an app that has basic http query to communicate with the database, but I am facing a problem.
There is a page that show a list which has been taken from the database. There are two operations that can be performed on this list - insert and update. The problem occurres when I try to make an update. The record in the database is updated but not the list in the application is not. However, when I insert a new record the list got updated with the new record including all previous changes, that were not shown in the list.
Here is the type script for the list page:
export class CrudHttpListPage {
items: any;
constructor(public loading: LoadingProvider, private toast: ToastProvider, public modal: ModalController, private crud: CrudHttpProvider) { }
ionViewDidLoad() {
this.load();
}
load() {
this.loading.present();
this.crud.read.then(res => {
this.items = res;
if (res) this.loading.dismiss();
});
}
add() {
let modal = this.modal.create('CrudHttpDetailPage', { action: 1 });
modal.present();
modal.onDidDismiss(data => {
console.log(data);
if (data) this.load();
});
}
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load();
});
}
Here is the typescript code for the add and edit page:
export class CrudHttpDetailPage {
private form: FormGroup;
action: number;
data: any = { title: '', text: '' };
constructor(private view: ViewController, private toast: ToastProvider, private loading: LoadingProvider, private crud: CrudHttpProvider, private fb: FormBuilder, public params: NavParams) {
this.action = params.data.action;
this.data = params.data && params.data.data || this.data;
console.log(params.data);
this.form = this.fb.group({
id: [this.data && this.data.id],
title: [this.data && this.data.title, Validators.required],
text: [this.data && this.data.text, Validators.required]
});
}
submit() {
this.loading.present();
console.log(this.form.value);
this.crud.save(this.form.value).then(data => {
// this.dataNotes.id = data;
console.log(data);
this.loading.dismiss();
this.view.dismiss(this.form.value);
}, err => {
console.log(err);
this.loading.dismiss();
this.toast.showWithClose(err);
this.close();
});
}
close() {
this.view.dismiss();
}
}
Here are the http operations:
const SERVER_URL: any = {
getNormal: ConstantVariable.APIURL + 'index.php/tbl_note',
getLimit: ConstantVariable.APIURL + 'limit.php',
};
#Injectable()
export class CrudHttpProvider {
limitData: number = 10;
datas: any = [];
constructor(public http: Http) {
this.datas = null;
}
get read() {
return new Promise(resolve => {
this.http.get(SERVER_URL.getNormal).map(res => res.json()).subscribe(data => {
console.log(data.dataNotes);
resolve(data.dataNotes);
});
});
}
save(item) {
let headers: any = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }),
options: any = new RequestOptions({ headers: headers });
if (item.id) {
return new Promise((resolve, reject) => {
this.http.post(SERVER_URL.getNormal + '/' + item.id, item, options).map(res => res.json()).subscribe((data) => {
console.log(data);
resolve(data.dataNotes);
}, (err) => {
reject(err);
console.log("error: " + err);
});
});
}
else {
return new Promise(resolve => {
this.http.post(SERVER_URL.getNormal, item, options)
.map(res => res.json())
.subscribe(data => {
// console.log(data);
resolve(data.dataNotes[0].id);
}, error => {
console.log("error " + error);
});
});
}
}
and last here is the PHP file:
<?php
header('Access-Control-Allow-Origin: *');
require_once('config.php');
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
if ($value===null) return null;
return mysqli_real_escape_string($link,(string)$value);
},array_values($input));
// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
$set.=($i>0?',':'').'`'.$columns[$i].'`=';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
// create SQL based on HTTP method
if ($method == "POST" AND $key != "") { $method = 'PUT'; }
if ($method == "GET" AND $key != "") { $method = 'DELETE'; }
switch ($method) {
case 'GET':
$sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
case 'PUT':
$sql = "update `$table` set $set where id=$key"; break;
case 'POST':
$sql = "insert into `$table` set $set"; break;
case 'DELETE':
$sql = "delete from `$table` where id=$key"; break;
}
// excecute SQL statement
$result = mysqli_query($link,$sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error());
}
// print results, insert id or affected row count
echo "{\"status\":\"ok\", \"dataNotes\":";
if ($method == 'GET') {
if (!$key) echo '[';
for ($i=0;$i<mysqli_num_rows($result);$i++) {
echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
}
if (!$key) echo ']';
} elseif ($method == 'POST') {
$set = '"id":"'.mysqli_insert_id($link).'"';
for ($i=1;$i<count($columns);$i++) {
$set.=($i>0?',':'').'"'.$columns[$i].'":';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
echo "[{".$set."}]";
} elseif ($method == 'DELETE') {
echo '[{"id":"'.$key.'"}]';
} else {
echo mysqli_affected_rows($link);
}
echo "}";
// close mysql connection
mysqli_close($link);
The issue might be here:
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load(); // <---- seems this.load() is not executing
});
}
Seems this.load() is not executing after modal.onDidDismiss:
- check modal is dismissing
- check if data is not null/undefined
- check running this.load(), with no if() statement, does it run?
you may be able to find the answer there
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
console.log('Modal has dismissed!!');
// if (data) this.load(); // comment for check
this.load();
});
}
i finally solved the problem. what cause the issue is that i have two files to make a connection to the database one for the website and the other is for the mobile application and it seems the one which i use in the mobile application is broken so i remove this file and connect to the old file and the problem solved
I'm trying to save image to php application (made with laravel 6.0) using React Native. Here is my react native image picker
var ImagePicker = NativeModules.ImageCropPicker;
here is my image save function
addImages = async () => {
const { image, images } = this.state
const access_token = await AsyncStorage.getItem('access_token')
try {
let data = new FormData();
images.map((image, i) => {
data.append('id', id);
data.append('uri', image.uri);
data.append('type', image.mime);
data.append('name', 'test.jpg');
});
fetch(apiConfig.apiUrl + '/api/save-image', {
method: 'POST',
headers: {
'Content-Type' : 'multipart/form-data',
'Authorization': 'Bearer ' + access_token,
},
body:data
})
.then(function (response) {
return response.json();
})
.then(function (data) {
try {
console.log(data);
} catch (error) {
console.log(error);
}
}.bind(this))
.catch((error) => {
console.log(error)
});
}catch (error) {
console.log(error)
}
}
Here is my php code
public function saveImage(Request $request)
{
header( "Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Origin: *");
try {
$file= array('file'=>$request->uri);
Storage::disk('public')->put($request->imgName,File::get($file->file));
return response()->json(['true'=>'Successfully Created'], 200);
} catch (\Exception $e) {
Log::info('vehicle image: ', [$e->getMessage()]);
return response()->json(['error'=>$e], 200);
}
}
When I try to save I'm getting SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
when I return the $request->uri I'm getting something like this file:///data/user/0/com.carup/cache/react-native-image-crop-picker/IMG_20191103_161929.jpg
How can I fix this?
How can I fix this?
You need to specify file name as the third parameter to data.append:
data.append('file', image.uri, 'test.jpg');
Finally I have fixed it with Base64 method. Here is my code.
pick images with base64
pickMultipleBase64=()=> {
ImagePicker.openPicker({
multiple: true,
width: 300,
height: 300,
includeBase64: true,
includeExif: true,
}).then(images => {
this.setState({
images: images.map(image => {
return {uri: `data:${image.mime};base64,`+ image.data, width: image.width, height: image.height,type:image.mime}
}),
});
}).catch(e => alert(e));
}
And uploaded with other details like this
addImages = async () => {
const { image, images, stockNo } = this.state
const access_token = await AsyncStorage.getItem('access_token')
if(access_token == null) {
return(
this.gotoLogin()
)
}
this.setState({
isLoading:true,
message:'',
status:true
})
try {
let data = new FormData();
images.map((image, i) => {
data.append('id', id);
data.append('stock', stockNo);
data.append('chassis', chassis_no);
data.append('file'+i, this.state.images[i].uri);
data.append('type'+i, this.state.images[i].type);
imageCount++
});
data.append('imageCount', imageCount);
// console.log(data);
fetch(apiConfig.apiUrl + '/api/save-image', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + access_token,
},
body:data
})
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
imageCount = 0
try {
this.setState({
isLoading: false,
message:data.true ? data.true:data.error,
messageColor:data.true ? CarColors.success : CarColors.error,
btnStatus:true
// chassis:''
})
if(data.true){
this.setState({
image:null,
images: null,
})
}
} catch (error) {
this.removeToken();
console.log('1 '+error);
}
}.bind(this))
.catch((error) => {
this.setState({
isLoading: false,
message:'error',
messageColor:CarColors.error,
})
console.log(error)
});
}catch (error) {
console.log(error)
}
And my php(laravel) code is like this. Here I have created a new folder (with vehicle id) in storage and save images to separate folders.
public static function saveImage($request)
{
$dir = "./storage/vehicle/" . $request->id;
if (is_dir($dir) === false) {
mkdir($dir);
}
DB::beginTransaction();
try {
for ($i = 0; $i < $request->imageCount; $i++) {
$type = [];
$file = 'file' . $i;
$mime = 'type' . $i;
$data = $request->$file;
$type = explode('/', $request->$mime);
$extension = $type[1];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$Imgdata =Images::create([
'vehicle_id' => $request->id,
'img_name' => $i.'.'.$extension,
'img_ext' => $extension,
'img_order' => '0',
]);
Storage::disk('vehicle')->put($request->id . '/' . $i . '.' . $extension, $data);
}
//Update Vehicle table ImageStatus
$Vehicle = Vehicle::where('id',$request->id)->update([
'img_status' => '1',
]);
return response()->json(['true' => 'Successfully Uploaded'], 200);
} catch (\Exception $e) {
DB::rollback();
Log::info('vehicle image name save issue: ', [$e->getMessage()]);
return 'false';
}
}
Hope this will help others who are going to upload multiple images with react native
I know this topic already exist on this platform. I have searched through online but I didn't get the rightful answer pertaining to my problem.
I created a login page which needs to access API but every time I clicked on the Login button the error comes out.
I have tried different ways but still couldn't figure it out.
Below is my source codes:
Login.html
<ion-content class="login-content" padding>
<ion-row class="logo-row">
<ion-col></ion-col>
<ion-col >
<img src="../assets/imgs/logo.png" class="img-responsive " id="img2">
</ion-col>
<ion-col></ion-col>
</ion-row>
<form (submit)="doLogin()">
<ion-item>
<ion-input [(ngModel)]="credentials.email" name="email" type="text" placeholder="Email Address" ></ion-input>
</ion-item>
<ion-item>
<ion-input [(ngModel)]="credentials.password" name="password" type="password" placeholder="Password"></ion-input>
</ion-item>
<button ion-button class="submit-btn" block type="submit">
Login
</button>
</form>
<button ion-button class="register-btn" block clear (click)="register()">
Create New Account
</button>
</ion-content>
AuthServive.ts
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import 'rxjs/add/operator/map';
let apiUrl = 'http://localhost:90/mySchool/api2/get.php?';
#Injectable()
export class AuthService {
constructor(public http: Http) {}
login(credentials) {
let urlDest = "http://localhost:90/mySchool/api2/get.php?username=" + credentials.email + "&password=" + credentials.password;
return this.http.get(urlDest)
.map( (res:Response) => res.json());
/* return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(apiUrl+'login', JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});*/
}
register(data) {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(apiUrl+'guest/signup', JSON.stringify(data), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
logout(){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('X-Auth-Token', localStorage.getItem('token'));
this.http.post(apiUrl+'logout', {}, {headers: headers})
.subscribe(res => {
localStorage.clear();
}, (err) => {
reject(err);
});
});
}
}
Login.ts
import { Component } from '#angular/core';
import { NavController, LoadingController, ToastController } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import { TabsPage } from '../tabs/tabs';
import { RegisterPage } from '../register/register';
import { HomePage } from '../home/home';
export class User {
email: string;
password: string;
}
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
credentials: User = {
email: '',
password: ''
}
items:any;
loading: any;
//loginData = { email:'', password:'' };
//data: any;
constructor(public navCtrl: NavController, public authService: AuthService, public loadingCtrl: LoadingController, private toastCtrl: ToastController) {}
doLogin() {
//this.showLoader();
this.authService.login(this.credentials)
.subscribe(
datas => {
//this.loading.dismiss();
if(datas.result){
this.navCtrl.push(HomePage, {
email: datas.data.id
})
}else{
alert("Invalid user or password")
}
});
/*this.authService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
localStorage.setItem('token', this.data.access_token);
this.navCtrl.setRoot(TabsPage);
}, (err) => {
this.loading.dismiss();
this.presentToast(err);
});*/
}
register() {
this.navCtrl.push(RegisterPage);
}
showLoader(){
this.loading = this.loadingCtrl.create({
content: 'Processing...'
});
this.loading.present();
}
presentToast(msg) {
let toast = this.toastCtrl.create({
message: msg,
duration: 3000,
position: 'bottom',
dismissOnPageChange: true
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
}
get.php
<?php
header('Access-Control-Allow-Origin: *');
// Set up the PDO parameters
$Mysqli = new mysqli('127.0.0.1', 'root', '', 'cihmeeting');
$login = addslashes($_GET['email']);
$Tsenha = addslashes($_GET['password']);
//$senha= md5($Tsenha);
$erro = "";
$erro .= empty($login) ? "Enter your email \n" : "";
$erro .= empty($senha) ? "Enter your password \n" : "";
$arr = array();
if(empty($erro)){
$query = "SELECT * FROM users WHERE email = '$login' and password = '$Tsenha'";
$result = $Mysqli->query($query);
if($result->num_rows > 0){
//login Logged
$obj = $result->fetch_object();
$arr['result'] = true;
$arr['data']['id'] = $obj->id;
$arr['data']['zone_code'] = $obj->zone_code;
$arr['data']['first_name'] = $obj->first_name;
$arr['data']['email'] = $obj->email;
}else{
$arr['result'] = false;
$arr['msg'] = "Invalid login details";
}
}else{
$arr['result'] = false;
$arr['msg'] = $erro;
}
echo json_encode($arr);
?>
Could someone please point me to the right direction.
It's because your API doesn't return valid JSON response. You should catch these errors:
login(credentials) {
let urlDest = "http://localhost:90/mySchool/api2/get.php?username=" + credentials.email + "&password=" + credentials.password;
return this.http.get(urlDest)
.map( (res:Response) => res.json())
.catch(error => {
// handle error here
console.log('Server error');
});
}
I want to retrieve the id of the user that's currently online. But I CANNOT do it with the following code:
Route::middleware('auth:api')->post('/optionelections', function (Request $request) {
return $request->user();
});
The reason is that I keep getting the same unauthorised error from Laravel. I've been trying to fix this error for days and I can't seem to find a solution. So I'm trying to do it in a different way but I don't know how. I'm currently using Passport to store my token and my client_id in local storage.
this is my apply_election.vue
import {apiDomain} from '../../config'
export default {
name: 'applyForElection',
data () {
return {
election: {},
newOption: {'election_id': ''},
//this is where the user_id should come
newOption: {'user_id': ''}
}
},
methods: {
createOption: function () {
var itemId = this.$route.params.id
this.newOption.election_id = itemId
this.$http.post(apiDomain + 'optionelections', this.newOption)
.then((response) => {
this.newOption = {'election_id': itemId}
alert('you applied!')
this.$router.push('/electionsnotstarted')
}).catch(e => {
console.log(e)
alert('there was an error')
this.$router.push('/electionsnotstarted')
})
}
},
created: function () {
var itemId = this.$route.params.id
this.$http.get('http://www.nmdad2-05-elector.local/api/v1/elections/' + itemId)
.then(function (response) {
this.election = response.data
})
}
}
And this in my OptionElectionsController.php
public function store(Request $request)
{
$optionElection = new OptionElection();
$optionElection->user_id = $request['user_id'];
$optionElection->option = "something";
$optionElection->votes = 0;
$optionElection->election_id = $request['election_id'];
$optionElection->accepted = 0;
if ($optionElection->save()) {
return response()
->json($optionElection);
}
}
This is my Auth.js
export default function (Vue) {
Vue.auth = {
setToken (token, expiration) {
localStorage.setItem('token', token)
localStorage.setItem('expiration', expiration)
},
getToken () {
var token = localStorage.getItem('token')
var expiration = localStorage.getItem('expiration')
if (!token || !expiration) {
return null
}
if (Date.now() > parseInt(expiration)) {
this.destroyToken()
return null
} else {
return token
}
},
destroyToken () {
localStorage.removeItem('token')
localStorage.removeItem('expiration')
},
isAuthenticated () {
if (this.getToken()) {
return true
} else {
return false
}
}
}
Object.defineProperties(Vue.prototype, {
$auth: {
get: () => {
return Vue.auth
}
}
})
}
You are using the TokenGuard of Laravel, There many way to let the guard recognise the authentication, the best methods:
Send the token in api_token attribute in the request's query.
this.newOption.api_token = token;
Send the token in Authorization header with Bearer prefix.
{
headers: {
Authorization: 'Bearer THE_TOKEN'
}
}
well I need send username and password for generate the token for a login, the problem always that I send from the client (angular) response with error, but when I send it from postman work fine.
In cakephp 3.
public function initialize()
{
parent::initialize();
$this->Auth->allow(['add', 'token', 'me']);
}
public function token()
{
$user = $this->Auth->identify();
if (!$user)
{
throw new UnauthorizedException('Invalid username or password');
}
$this->set([
'success' => true,
'data' => [
'user_id' => $user['id'],
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
in angular how I send it
$scope.doLogin = function()
{
dataLogin = {
username: vm.username,
password: vm.password
};
console.log(dataLogin);
// call the Auth.login() function
//$scope.processing = true;
$scope.error = '';
Auth.login(dataLogin)
.then(function(data) {
if (data.success)
$state('home');
else
console.log(data);
$scope.error = data.message;
});
};
and
authFactory.login = function(dataLogin) {
return apiService.request('POST', '/api/users/token', dataLogin).then(function(data) {
AuthToken.setToken(data.token);
return data;
});
};
apiService for app angular
(function(){
angular
.module('appDekma')
.factory('apiService', apiService);
apiService.$inject = ['$http'];
function apiService($http) {
return {
request: sendRequest
};
function sendRequest(method, endpoint, data) {
var API_HOST = 'http://localhost/dekma_backend';
var req = {
method: method || 'GET',
url: API_HOST + endpoint,
data: data || '',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Headers': 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token',
'Access-Control-Max-Age': '3600'
}
};
return $http(req)
.then(successCallback, errorCallback);
function successCallback(response)
{
return response.data;
}
function errorCallback(error) {
var message = 'Something terrible happened!';
if (error.data && error.data.code)
{
switch (error.data.code)
{
case 500:
break;
case 401:
break;
case 403:
break;
case 404:
message = 'Could not find content';
break;
default:
break;
}
}
return error.data;
}
}
}
})();
angular.module('app').config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider, urls) {
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function ($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;// JWT token stored in localstorage
config.headers.Accept = 'application/json';
}
return config;
},
'responseError': function (response) {
console.log(response);
if (response.status === 401 || response.status === 403 || response.status === 500) {
var login_url = urls.BASE+'users/login';
}
return $q.reject(response);
}
};
}]);
$routeProvider
.when('/', {
templateUrl: "public/html/" + 'your_html_page.html',
controller: 'your_anuglar_controller'
})
.otherwise({ redirectTo: '/' });
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>