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'
}
}
Related
So starting by giving a brief of the issue. I have defined a function to get data from my api and the function is:
Future<void> getProductDetailsData(params) async {
if (_isNetworkAvail) {
await apiBaseHelper
.getAPICall(getProductData, params)
.then((getdata) async => {
if (getdata.containsKey('data'))
{
productDataList = (getdata['data']['items'] as List)
.map((data) => ProductModel.fromJson(data))
.toList(),
tempProductDataList.addAll(productDataList),
}
});
} else {
setState(() {
_isNetworkAvail = false;
});
}
}
and the params I have given is Future<void> myData = getProductDetailsData({'id': widget.dealerId.toString()});
and then I have used myData in the future of the FutureBuilder.
now I have defined a MultiSelectDialogField and on its onConfirm I want to change the params so that I can get a particular data as per the given params. So for this I have done this
onConfirm: (results) {
setState(() {
myData = getProductDetailsData({
'id': widget.dealerId.toString(),
'categoryId': "23",
});
});
}
But the issue is that the FutureBuilder is not getting updated and only showing data with params as {'id': widget.dealerId.toString()}
You just need to use either await or .then to get value from future. Inside your .then you need to call setState.
Future<void> getProductDetailsData(params) async {
if (_isNetworkAvail) {
apiBaseHelper
.getAPICall(getProductData, params)
.then((getdata) async => {
if (getdata.containsKey('data'))
{
productDataList = (getdata['data']['items'] as List)
.map((data) => ProductModel.fromJson(data))
.toList(),
tempProductDataList.addAll(productDataList),
}
setState(() {}); //here
});
} else {
setState(() {
_isNetworkAvail = false;
});
}
}
better
Future<void> getProductDetailsData(params) async {
if (_isNetworkAvail) {
final getdata = await apiBaseHelper
.getAPICall(getProductData, params);
if (getdata.containsKey('data'))
{
....
}
setState(() {});
} else {
setState(() {
_isNetworkAvail = false;
});
}
also you can just use await and call setState on next line. Also you can use FutureBuilder.
I had integrated the Razorpay payment gateway in my magento site. It's working absolutely fine in web and mobile browser. But when I try to make the payment using in-app browsers (from Instagram, Facebook) I am facing the blank page issue. So I found the solution that I need to pass the callback URL along with other input parameter to payment gateway. Here I got stuck, what should be the callback URL here? Can anyone help me to resolve this!
Here is my code:
/app/code/Razorpay/Magento/view/frontend/web/js/view/payment/method-renderer/razorpay-method.js
define(
[
'Magento_Checkout/js/view/payment/default',
'Magento_Checkout/js/model/quote',
'jquery',
'ko',
'Magento_Checkout/js/model/payment/additional-validators',
'Magento_Checkout/js/action/set-payment-information',
'mage/url',
'Magento_Customer/js/model/customer',
'Magento_Checkout/js/action/place-order',
'Magento_Checkout/js/model/full-screen-loader',
'Magento_Ui/js/model/messageList'
],
function (Component, quote, $, ko, additionalValidators, setPaymentInformationAction, url, customer, placeOrderAction, fullScreenLoader, messageList) {
'use strict';
return Component.extend({
defaults: {
template: 'Razorpay_Magento/payment/razorpay-form',
razorpayDataFrameLoaded: false,
rzp_response: {}
},
getMerchantName: function() {
return window.checkoutConfig.payment.razorpay.merchant_name;
},
getKeyId: function() {
return window.checkoutConfig.payment.razorpay.key_id;
},
context: function() {
return this;
},
isShowLegend: function() {
return true;
},
getCode: function() {
return 'razorpay';
},
isActive: function() {
return true;
},
isAvailable: function() {
return this.razorpayDataFrameLoaded;
},
handleError: function (error) {
if (_.isObject(error)) {
this.messageContainer.addErrorMessage(error);
} else {
this.messageContainer.addErrorMessage({
message: error
});
}
},
initObservable: function() {
var self = this._super(); //Resolves UI Error on Checkout
if(!self.razorpayDataFrameLoaded) {
$.getScript("https://checkout.razorpay.com/v1/checkout.js", function() {
self.razorpayDataFrameLoaded = true;
});
}
return self;
},
/**
* #override
*/
/** Process Payment */
preparePayment: function (context, event) {
if(!additionalValidators.validate()) { //Resolve checkout aggreement accept error
return false;
}
var self = this,
billing_address,
rzp_order_id;
fullScreenLoader.startLoader();
this.messageContainer.clear();
this.amount = quote.totals()['base_grand_total'] * 100;
billing_address = quote.billingAddress();
this.user = {
name: billing_address.firstname + ' ' + billing_address.lastname,
contact: billing_address.telephone,
};
if (!customer.isLoggedIn()) {
this.user.email = quote.guestEmail;
}
else
{
this.user.email = customer.customerData.email;
}
this.isPaymentProcessing = $.Deferred();
$.when(this.isPaymentProcessing).done(
function () {
self.placeOrder();
}
).fail(
function (result) {
self.handleError(result);
}
);
self.getRzpOrderId();
return;
},
getRzpOrderId: function () {
var self = this;
$.ajax({
type: 'POST',
url: url.build('razorpay/payment/order'),
/**
* Success callback
* #param {Object} response
*/
success: function (response) {
fullScreenLoader.stopLoader();
if (response.success) {
self.renderIframe(response);
} else {
self.isPaymentProcessing.reject(response.message);
}
},
/**
* Error callback
* #param {*} response
*/
error: function (response) {
fullScreenLoader.stopLoader();
self.isPaymentProcessing.reject(response.message);
}
});
},
renderIframe: function(data) {
var self = this;
this.merchant_order_id = data.order_id;
var options = {
key: self.getKeyId(),
name: self.getMerchantName(),
amount: data.amount,
handler: function (data) {
self.rzp_response = data;
self.placeOrder(data);
},
order_id: data.rzp_order,
modal: {
ondismiss: function() {
self.isPaymentProcessing.reject("Payment Closed");
}
},
notes: {
merchant_order_id: '',
merchant_quote_id: data.order_id
},
prefill: {
name: this.user.name,
contact: this.user.contact,
email: this.user.email
},
callback_url: url.build('rest/default/V1/carts/mine/payment-information', {}),
_: {
integration: 'magento',
integration_version: data.module_version,
integration_parent_version: data.maze_version,
}
};
if (data.quote_currency !== 'INR')
{
options.display_currency = data.quote_currency;
options.display_amount = data.quote_amount;
}
this.rzp = new Razorpay(options);
this.rzp.open();
},
getData: function() {
return {
"method": this.item.method,
"po_number": null,
"additional_data": {
rzp_payment_id: this.rzp_response.razorpay_payment_id,
order_id: this.merchant_order_id,
rzp_signature: this.rzp_response.razorpay_signature
}
};
}
});
}
);
In the above code renderIframe function will pass the parameter to payment gateway, here I need to pass the callback URL. I tried to set it as rest/default/V1/carts/mine/payment-information but got 401 Unauthorised error. Please help me resolve this issue.
I have done the same thing with amazon payment.
As i remember you should act on this part of codes :
function () {
self.placeOrder();
}
And how i changed
function () {
$.when(self.placeOrder()).done(
function () {
///redirect;
}
}
But when i tried on the browser, i've still got some wrong cases then i decided to make a workaround by putting an event with jquery :
$( document ).ajaxStop(function() {
//redirect
});
This works right because after all ajaxs are finished we get the order is placed. That is the time to redirect.
Hope this helps.
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
$location.path not redirecting after successful return from php. Data returned from php page is not empty . No problem with php file its returning correct data .The problem is $location.path is not working I referred many sites but I could not find solution help me..
angular.module(MyApp).controller(Part3Controller, function ($scope, LoginService) {
$scope.IsLogedIn = false;
$scope.Message = '';
$scope.Submitted = false;
$scope.IsFormValid = false;
$scope.MyLogin = {
USER_ID:'' ;
Password: '';
};
//Check is Form Valid or Not // Here f1 is our form Name
$scope.$watch(f1.$valid, function (newVal) {
$scope.IsFormValid = newVal;
});
$scope.Login = function () {
$scope.Submitted = true;
if ($scope.IsFormValid) {
LoginService.GetUser($scope.MyLogin).then(function (d) {
if (d.data.USER_ID != null) {
$scope.IsLogedIn = true;
$location.Path(/LandingPage/FetchMenu);
}
else {
alert('Invalid Credential!');
}
});
}
};
})
.factory('LoginService, function ($http) {
var fac = {};
fac.GetUser = function (d) {
return $http({
url:/Data/UserLogin,
method: POST,
data: JSON.stringify(d),
headers: {content-type:application/json}
});
};
return fac;
});
You haven't injected $location:
angular.module(MyApp).controller(Part3Controller,
function ($scope, LoginService) {
Should be:
angular.module(MyApp).controller(Part3Controller,
function ($location, $scope, LoginService) {
My goal to achieve is:
first to insert new database record with http post, resolve with stateProvider and grab the new id and change view and stateParams.
i have this code for my http post service
myApp.service('postService', ['$http', function($http) {
this.insertNew = function() {
$http.post('create_new.php')
.success(function(data) {
return data;
});
};
create_new.php returns the ID like this (it works, proved with console)
return json_encode($data);
and the stateProvider looks like this (section)
$stateProvider
.state('newRecord', {
resolve: {
newArtID: ['postService',
function(postService) {
return postService.insertNew();
}]
},
params: {
artID: <-- new ID from DB
},
i did tests with stateParams in serval variations (in resolve and by params). how can i bring the new ID to stateParams, so i can access from the views?
Thanks for any help!
I'm not so sure your oder of operations is correct. params is for when you already have that data. You should return the data from your resolve, then you can access it in your scope, for ex:
Service:
.service('postService', function ($http) {
this.insertNew = function () {
return $http.post('create_new.php').then(function (data) {
return data;
});
}
})
Route:
$stateProvider
.state('newRecord', {
views: {
"main": {
controller: 'SomeCtrl',
templateUrl: '...'
}
},
resolvedId: {
newArtID: function (postService) {
return postService.insertNew().then(function (response) {
return response;
});
}
}
})
Controller:
.controller('SomeCtrl', function (resolvedId) {
var newID = resolvedId.id; //depending on what is returned
});