Push notifications with Ionic (1.3)? - ionic-framework

I am trying to set up push notifications with Ionic, mainly by following the official docs: https://docs.ionic.io/services/push/.
However I'm not sure where to call certain bits of code, e.g. $ionicPush.register(). Has anyone come across a recent / up-to-date tutorial that's helpful with this? Tutorials that I've come across use deprecated bits of code, e.g. ionic add.

If you are using Ionic User as well here is the flow I use. These are various functions
$scope.signupForm={};//user object
$scope.beginSignUp=function(){
//sign up
var details = {
'email': $scope.signupForm.email,
'password': $scope.signupForm.pass,
'details':{
'name':$scope.signupForm.dn,
'image':$scope.signupForm.dp
}
}
Ionic.Auth.signup(details).then(signupSuccess, function(err){
});
}
$scope.signupSuccess=function(){
console.log("ionic sign up sucess, now login the user");
var authProvider = 'basic';
var authSettings = { 'remember': true };
var loginDetails = {
'email': $scope.signupForm.email,
'password': $scope.signupForm.pass
};
Ionic.Auth.login(authProvider, authSettings, loginDetails)
.then(authSuccess, function(err){
});
}
function authSuccess(){
console.log("Ionic Login Success ");
var ionic_user = Ionic.User.current();
ionic_user.details.name =$scope.signupForm.dn;
ionic_user.details.image = $scope.signupForm.dp;
ionic_user.save();
registerPush();
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('home', {}, {reload: true});
}
function registerPush(){
console.log("Calling Register Push");
$ionicPush.init({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
Ionic.User.current();
$ionicPush.saveToken(data.token);
//unregister after checking
},
"pluginConfig": {
"ios": {
"badge": true,
"sound": true
},
"android": {
"iconColor": "#FA2B2E",
"senderID": "GCM Project No.",
"icon":"notification"
}
}
});
$ionicPush.register();
}
Use the model signupForm for storing user's email, password etc etc and call beginSignUp() on a button click. Or if it is a login call signupSuccess()

Related

Braintree PCI compliance issue

I have been continuously getting an email by brain tree on PCI Compliance regards and need confirmation on following two things which have been asked.
What is the Braintree payment integration method on our website? (Hint: It’s one of these)
Drop in UI or hosted field
Braintree SDK Custom integration
Following is the javascript code we've used . I went through the Braintree site on this regards but couldn't conclude upon this.
Additional Notes : We've made some changes on braintree vendor file.
var subscribed_user = "1";
$('#cc').on('click', function (e) {
$('#cc-info').show().attr('aria-hidden', true).css('visibility', 'visible');
});
var button = document.querySelector('#paypal-button');
var button1 = document.querySelector('#card-button');
var form = document.querySelector('#checkout-form');
var authorization = 'AuthHeaderxxxxxxxx=';
// Create a client.
braintree.client.create({
authorization: authorization
}, function (clientErr, clientInstance) {
// Stop if there was a problem creating the client.
// This could happen if there is a network error or if the authorization
// is invalid.
if (clientErr) {
console.error('Error creating client:', clientErr);
return;
}
/* Braintree - Hosted Fields component */
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '10pt',
'color': '#e3e3e3 !important; ',
'border-radius': '0px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111',
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) { /*Handle error in Hosted Fields creation*/
return;
}
button1.addEventListener('click', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) { /* Handle error in Hosted Fields tokenization*/
document.getElementById('invalid-field-error').style.display = 'inline';
return;
}
/* Put `payload.nonce` into the `payment-method-nonce` input, and thensubmit the form. Alternatively, you could send the nonce to your serverwith AJAX.*/
/* document.querySelector('form#bt-hsf-checkout-form input[name="payment_method_nonce"]').value = payload.nonce;*/
document.querySelector('input[name="payment-method-nonce"]').value = payload.nonce;
form.submit();
button1.setAttribute('disabled', 'disabled');
});
}, false);
});
// Create a PayPal component.
braintree.paypal.create({
client: clientInstance,
paypal: true
}, function (paypalErr, paypalInstance) {
// Stop if there was a problem creating PayPal.
// This could happen if there was a network error or if it's incorrectly
// configured.
if (paypalErr) {
console.error('Error creating PayPal:', paypalErr);
return;
}
if ($('select#paypal-subs-selector option:selected').val() == '') {
button.setAttribute('disabled', 'disabled');
}
$('select#paypal-subs-selector').change(function () {
if ($('select#paypal-subs-selector option:selected').val() == '') {
button.setAttribute('disabled', 'disabled');
} else {
// Enable the button.
button.removeAttribute('disabled');
}
});
button.addEventListener('click', function () {
if(subscribed_user) {
// Popup Error for changing subscription.
swal({
html: true,
title: "",
text: "You are cancelling in the middle of subscription.<br/>If you do so you will not be refunded remaining days of your subscription.",
confirmButtonColor: '#605ca8',
confirmButtonText: 'Yes',
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Proceed !",
closeOnConfirm: true
}, function (isConfirm) {
if (isConfirm) {
show_payment_methods(paypalInstance);
}
});
} else{
show_payment_methods(paypalInstance);
}
}, false);
});
});
Any help would be highly appreciated.
Your code says Braintree - Hosted Field component And you don’t use anything like this which I found by searching “Braintree api”. I think you’re safe to say you use hosted fields.

Vue.js 2 and auth0 authentication resulting with 'nonce'

I am trying to implement auth0 in my Vue.js 2 application.
I followed this link to implement the auth0 lock:
https://github.com/auth0-samples/auth0-vue-samples/tree/master/01-Login
This is my application in Login.vue:
HTML:
<div v-show="authenticated">
<button #click="logout()">Logout</button>
</div>
<div v-show="!authenticated">
<button #click="login()">Login</button>
</div>
Javascript:
function checkAuth() {
return !!localStorage.getItem('id_token');
}
export default {
name: 'login',
data() {
return {
localStorage,
authenticated: false,
secretThing: '',
lock: new Auth0Lock('clientId', 'domain')
}
},
events: {
'logout': function() {
this.logout();
}
},
mounted() {
console.log('mounted');
var self = this;
Vue.nextTick(function() {
self.authenticated = checkAuth();
self.lock.on('authenticated', (authResult) => {
console.log(authResult);
console.log('authenticated');
localStorage.setItem('id_token', authResult.idToken);
self.lock.getProfile(authResult.idToken, (error, profile) => {
if (error) {
console.log(error);
return;
} else {
console.log('no error');
}
localStorage.setItem('profile', JSON.stringify(profile));
self.authenticated = true;
});
});
self.lock.on('authorization_error', (error) => {
console.log(error);
});
});
},
methods: {
login() {
this.lock.show();
},
logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
this.authenticated = false;
}
}
}
I am pretty sure that it already worked, but suddenly it doesnt work anymore.
My callbacks defined in auth0: http://127.0.0.1:8080/#/backend/login
That is also how I open the login in my browser.
When I login it I only get this in my localStorage:
Key: com.auth0.auth.14BK0_jsJtUZMxjiy~3HBYNg27H4Xyp
Value: {"nonce":"eKGLcD14uEduBS-3MUIQdupDrRWLkKuv"}
I also get redirected to http://127.0.0.1:8080/#/ so I do not see any network requests.
Does someone know where the problem is?
I ran the demo from auth0 with my Domain/Client and it worked without any problem.
Obviously I do not get any errors back in my console.
Atfer research I finally found the answer to my problem.
The reason, why it is not working is because my vue-router does not use the HTML5 History Mode (http://router.vuejs.org/en/essentials/history-mode.html).
To have it working without the history mode, I had to disable the redirect in my lock options and to disable auto parsing the hash:
lock: new Auth0Lock(
'clientId',
'domain', {
auth: {
autoParseHash: false,
redirect: false
}
}
)
Reference: https://github.com/auth0/lock

Understanding session in sailsJs with Passport

I have had many problems, when I want to get information from user model. I read some solutions, but I didnt understand.
This is my code:
* AuthController
var passport = require('passport');
module.exports = {
_config: {
actions: false,
shortcuts: false,
rest: false
},
login: function(req, res) {
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
req.logIn(user, function(err) {
if (err) res.send(err);
return res.send({
message: info.message,
user: user
});
});
})(req, res);
},
logout: function(req, res) {
req.logout();
res.redirect('/');
},
signup: function (req, res) {
var data = req.allParams();
User.create({email:data.email,password:data.password,name:data.name}).exec(function(error,user){
if(error) return res.negotiate(err);
if(!user)return res.negotiate(err);
return res.ok();
});
}
};
*view
<h1>List of my dates</h1>
<h1><%= email %></h1>
<h1><%= req.user.name %></h1>
*model
attributes: {
email: {
type: 'email',
required: true,
unique: true
},
password: {
type: 'string',
minLength: 6,
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(user, cb) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
console.log(err);
cb(err);
} else {
user.password = hash;
cb();
}
});
});
}
};
Only works if I use res.render('view', {email: req.user.email}) but, I would like to use the user data in many views. I cant write methods with Current user params, becouse dont work.
Thanks.
It is unclear to me what your actual problem is or what the question actually is but I will try to help.
Look here:
login: function(req, res) {
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
...
})(req, res);
},
There you are adding data (locals) to the ejs and the values are message and user so in the ejs you must reference it as this, so you will use user.name and not req.user.name? I'm not sure why you're binding the (req, res) either.
It's confusing because your ejs uses the email value but I don't see it there as a local so maybe thats your problem, it must be defined?
Consider the following simple example:
// User Controller
// GET request /signin
// The signin form
signin(req, res) {
// Load the view from app/views/*
return res.view('signin', {
title: 'Sign In'
});
},
// POST request to /signin
// This was posted from the signin form
// Use io.socket.post(...) to do this from the signin form
// Can use window.location.replace('/account') on successful request
authenticate(req, res) {
// The data posted, email and password attempt
var data = req.allParams();
// Does it match?
User.findOne({
email: data.email,
// This is stupid, don't ever use plain text passwords
password: data.password
})
.exec(function(err, user) {
// Server related error?
if (err) res.serverError(err.message);
// No user was found
if (!user) res.badRequest('Username or password not found');
// Sign the user in
req.session.userId = user.id;
// User was found
res.ok();
});
},
// GET request to /account
// Displays the users information
// Can use policies to ensure that only an authenticated user may access their own account information
account(req, res) {
// If the user is not signed in
// This is an alternative to using the sails policy isLoggedIn
if (!req.session.userId) res.redirect('/signin');
// Get the users details
User.findOne({
id: req.session.userId
})
.exec(function(err, user) {
// Server related error?
if (err) res.serverError(err.message);
// No user was found
if (!user) res.redirect('/signin');
// Load the ejs file that displays the users information
return res.view('account/index', {
title: 'Account Information',
user: user
});
});
},
// Account View
<p>Email: {{user.email}}</p>
<p>Password: {{user.password}}</p>
Check this out if you want to deal with password encryption: http://node-machine.org/machinepack-passwords
And this if you want to deal with the strength tests (when the user sets the password): https://www.npmjs.com/package/owasp-password-strength-test
This is as passport seems overkill if you're only doing local authentication?

Why my ionic app FCMPlugin.onNotification() does not get called for incoming push notifications

I'm using cordova-plugin-fcm for handling push notification subscriptions and watching for incoming notifications.
This was all working when I set it up about a month ago. I still receive push notifications when the app is closed or in the background.
But if the app is in the foreground I get no notification. Which is actually fine because I was handling that with FCMPlugin.onNotification callback when everything was working.
And FCMPlugin.onNotification callback, success or error in my $ionPlatform.ready() never run no matter the state of the app.
Subscribe factory - Used in Rooms factory
myApp.factory('pushSubscribe', [
'$firebaseArray',
function ($firebaseArray) {
return $firebaseArray.$extend({
$$added: function(room){
// Room topic is the $id of the chat room
FCMPlugin.subscribeToTopic(room.key,
function(success){
//Success is being ran here with "OK" response
//when a new chat room is added
},
function(error){
// Not seeing any errors here
}
);
},
$$removed: function(room){
FCMPlugin.unsubscribeFromTopic(room.key);
}
});
}]);
Rooms factory - registers chatters for push notifications
myApp.factory('Rooms', [
'$firebaseArray',
'$firebaseObject',
'userService',
'pushSubscribe',
function ($firebaseArray, $firebaseObject, userService, pushSubscribe) {
var ref = firebase.database().ref(),
user = userService.getUser();
userRoomsRef = firebase.database().ref('user-rooms').child(user.$id),
roomsRef = firebase.database().ref('/rooms'),
userRoom = new pushSubscribe(userRoomsRef);// Subscribes the current user to push notifications for all of their user-rooms
return {
// CRUD methods for rooms here
}
}]);
app.js .run() - Supposed to listen for incoming notifications and handle them according to the state of the app but it isn't.
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
FCMPlugin.onNotification(
function(data){ //callback
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
console.log( JSON.stringify(data) );
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
console.log( JSON.stringify(data) );
}
},
function(msg){ //success handler
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){ //error handler
console.log('Error registering onNotification callback: ' + err);
}
);
});
node-gcm push router - Hosted on Heroku all chats hit routers url
var router = require('express').Router();
var firebase = require('firebase');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var gcm = require('node-gcm');
var sender = new gcm.Sender('MY_AUTH_TOKEN');
router.get('/', function(req, res){
res.status(200).json({ message: 'GET route on router'});
});
router.post('/', jsonParser, function(req, res){
firebase.auth().verifyIdToken(req.body.token)
.then(function(user){
var message = new gcm.Message({
priority: 'high',
notification: {
click_action: "FCM_PLUGIN_ACTIVITY",
title: req.body.sender_name,
body: req.body.message
},
data: {
state: req.body.state,
roomId: req.body.roomId,
sender_imgUrl: req.body.sender_imgURL
}
});
sender.send(message, { topic: req.body.topic }, function(err, response){
if(err){
res.status(500).json({ error: err });
} else {
res.status(200).json({ response: 'Push notification sent' });
}
});
})
.catch(function(err){
res.status(500).json({ response: err });
});
});
module.exports = router;
The send message method
$scope.sendMessage = function() {
// Get the users auth jwt to verify them on the node router
firebase.auth().currentUser.getToken(true)
.then(function(userToken){
$http({
method: 'POST',
url:'MY_HEROKU_HOSTED_NODE_ROUTER_URL',
data:{
token: userToken,
message: $scope.IM.textMessage,
sender_name: $scope.user.name,
topic: '/topics/' + $state.params.roomId,
state: 'app.room',
roomId: $state.params.roomId,
sender_imgURL: $scope.user.pic,
chatters: chatters
}
})
.then(function(res){
//Chats factory updates Firebase chat record
Chats.send($scope.user, $scope.IM.textMessage);
$scope.IM.textMessage = "";
})
.catch(function(err){
debugger;
});
});
};

with ouath.io how to create the OAuth.create to use as on the callback

With oauth.io how to make a OAuth.create for twitter
for facebook it is
facebook_auth = OAuth.create("facebook", { oauth_token: "token_here" }, {
"url": "https://graph.facebook.com",
"cors": true,
"query": {
"access_token": "token_here"
}
});
that way you can use it on different parts of your website not just the callback after sign in.
facebook_auth.get('/me?fields=name,email').done(function (data) {
});
otherwise you're stuck only with the callback:
OAuth.callback('facebook', function (err, result) {
result.get('/me?fields=name,email').done(function (data) {
});
});
this is link to their documentation:
https://oauth.io/docs/api
For twitter, it's the same syntaxe than with facebook
var twitterTokens
OAuth.popup('twitter', function(err, res){
twitterTokens = res
})
//then elsewhere
function createTwitter() {
return OAuth.create('twitter', twitterTokens)
}
var twitter = createTwitter()
twitter.get(....)
The 3rd parameter is optional