Error connecting to firebase 3 from Ionic app - angularjs

Getting an error trying to connect to firebase 3 from Ionic app. The app's working fine and the new v3 config etc is fine, I'm sure the code is fine but I'm adding it below just incase.
I think it's my setup of firebase, Signin Method Email/Password is enabled. Do I need the plist file as suggested for the ios apps? The instructions are confusing as there's no specific ionic instructions, just ios, android and web.
Any suggestions as to how to move forward? ( Google seem to have made really complicated something that before was much simpler :( )
Thank you.
Here's my connection error (is there a way to get a better error than this?):
code: "auth/network-request-failed", message: "A network error (such as timeout, interrupted connection or unreachable host) has occurred."}
code
:
"auth/network-request-failed"
message
:
"A network error (such as timeout, interrupted connection or unreachable host) has occurred."
Here's my config data in index.html
<script>
// Initialize Firebase
var config = {
apiKey: "myapikeymyapikeymyapikey",
authDomain: "myapp.firebaseapp.com",
databaseURL: "https://myapp.firebaseio.com",
storageBucket: "myapp.appspot.com",
};
firebase.initializeApp(config);
Here's the firebase code in the app:
.factory('userService', function($rootScope, $window, $timeout, firebaseDBRef, firebaseAuthRef, firebaseUserRef, myStocksArrayService, myStocksCacheService, notesCacheService, modalService) {
var login = function(user, signup) {
var email = user.email;
var password = user.password;
firebaseAuthRef.signInWithEmailAndPassword(email, password)
.then(function() {
$rootScope.currentUser = authData;
if(signup) {
modalService.closeModal();
}
else {
myStocksCacheService.removeAll();
notesCacheService.removeAll();
loadUserData(authData);
modalService.closeModal();
$timeout(function() {
$window.location.reload(true);
}, 400);
}
})
.catch(function(error) {
console.log("Login Failed!", error);
return false;
});
};
var signup = function(user) {
firebaseAuthRef.createUserWithEmailAndPassword(user.email, user.password)
.then(function(userData) {
console.log(userData);
login(user, true);
firebaseDBRef.child('emails').push(user.email);
firebaseUserRef.child(userData.uid).child('stocks').set(myStocksArrayService);
var stocksWithNotes = notesCacheService.keys();
stocksWithNotes.forEach(function(stockWithNotes) {
var notes = notesCacheService.get(stockWithNotes);
notes.forEach(function(note) {
firebaseUserRef.child(userData.uid).child('notes').child(note.ticker).push(note);
});
});
})
.catch(function(error) {
console.log("Error creating user:", error);
return false;
});
};
var logout = function() {
firebaseAuthRef.signOut();
notesCacheService.removeAll();
myStocksCacheService.removeAll();
$window.location.reload(true);
$rootScope.currentUser = '';
};
var updateStocks = function(stocks) {
firebaseUserRef.child(getUser().uid).child('stocks').set(stocks);
};
var updateNotes = function(ticker, notes) {
firebaseUserRef.child(getUser().uid).child('notes').child(ticker).remove();
notes.forEach(function(note) {
firebaseUserRef.child(getUser().uid).child('notes').child(note.ticker).push(note);
});
};
var loadUserData = function(authData) {
firebaseUserRef.child(authData.uid).child('stocks').once('value', function(snapshot) {
var stocksFromDatabase = [];
snapshot.val().forEach(function(stock) {
var stockToAdd = {ticker: stock.ticker};
stocksFromDatabase.push(stockToAdd);
});
myStocksCacheService.put('myStocks', stocksFromDatabase);
},
function(error) {
console.log("Firebase error –> stocks" + error);
});
firebaseUserRef.child(authData.uid).child('notes').once('value', function(snapshot) {
snapshot.forEach(function(stocksWithNotes) {
var notesFromDatabase = [];
stocksWithNotes.forEach(function(note) {
notesFromDatabase.push(note.val());
var cacheKey = note.child('ticker').val();
notesCacheService.put(cacheKey, notesFromDatabase);
});
});
},
function(error) {
console.log("Firebase error –> notes: " + error);
});
};
var getUser = function() {
return firebaseAuthRef.currentUser;
};
if(getUser()) {
$rootScope.currentUser = getUser();
}
return {
login: login,
signup: signup,
logout: logout,
updateStocks: updateStocks,
updateNotes: updateNotes,
getUser: getUser
};
})

You must add the plist! Don't you have it already?!
Then you have to add it to your app:
NOTE; if you download it more than one time it will be showing with numbers (2) or (3) or (4) so delete these numbers at your xcode, the file name should be GoogleService-Info.plist. If it's anything else, it wont work.

Related

$localStorage can't be loaded in some devices on start [duplicate]

This question already exists:
Permission is ALLOWED but not WRITE Android AngularJS with Ionic
Closed 7 years ago.
Hello everybody I have a problem a long time and decided to post , on some devices(more common 4.1-4.4 no sdcard) $localStorage it is not loaded(already tried use SQLiete, File), but I believe he can save when you authentication because there is application cache. I am weeks for reply but i can not know what the problem is , I can not find solution.
OBS [1]: I've done several tests on my phone ( it works ) by removing the sdcard , but this is not the problem the application works normally.
[2] When installed on an emulator android 4.1 without SDCARD , I encounter the following error in CMD " rm failed for -f , Read only file system"
[3] Already I checked in AndroidManifest and permissions are correct
My permissions: whitelist
camera
media-capture
device
statusbar
file
file-transfer
imagepicker
media
network-information
file-opener2
sqlite-storage
ms-adal
x-toast
socialsharing.
My routine is: CHECKS(READ) localStorage ->
IF OK : AUTH AUTOMATIC -> UPDATE LOCALSTORAGE -> GO HOME PAGE.
ELSE : USERS INFORMATION LOGIN AND PASSWORD -> AUTH -> SAVE LOCALSTORAGE -> GO HOME PAGE.
Look my code:
app.factory('Auth', function ($http, $q) {
loginAuth = function (login, pswd) {
var def = $q.defer();
var url = "XXXXXXXXXXX";
var uuid = device.uuid;
$http({
method: 'GET',
dataType: "json",
url: url + 'GetLoginUser',
params: { login: login, pswd: pswd, cdUuid: uuid }
}).success(function (data) {
def.resolve(data);
}).error(function (data) {
def.reject("error");
});
return def.promise;
};
return {
Login: function (login,pswd) {
return loginAuth(login, pswd);
}
};
});
app.factory('User', function ($cordovaSQLite, $localStorage,$q) {
var user = {
idUser: '',
name: '',
email: '',
pswd: '',
imgProfile: ''
};
setUser = function (objUsuario) {
user.idUser = objUsuario.idUsuario;
user.name = objUsuario.nome;
user.email = objUsuario.email;
user.pswd = objUsuario.senha;
user.imgProfile = objUsuario.imgProfile;
};
deleteUser = function () {
delete $localStorage.user;
};
return {
Set: function (data) {
setUser(data);
},
Get: function () {
return user;
},
Delete: function () {
deleteUser();
}
};
});
app.controller('LoginCtrl', function ($scope, $ionicLoading, $timeout, $state, $ionicPopup, $http, $localStorage,Auth, UtilApp, User) {
$scope.user = {
login: "",
pswd: ""
}
$scope.checkUser = function () {
UtilApp.Show();
try {
if (angular.isDefined($localStorage.user)) {
Auth.Login($localStorage.user.email, $localStorage.user.pswd).then(function (data) {
try {
$localStorage.user = data;
User.Set($localStorage.user);
UtilApp.Hide();
$state.go('app.feed');
} catch (err) {
UtilApp.Hide();
UtilApp.AlertShow('ERRO', 'XXXXXXXXXX');
}
},
function (data) {
UtilApp.Hide();
if (UtilApp.CheckConnection() == "0") {
UtilApp.AlertShow('XXXX', 'XXXXXXX.');
} else {
UtilApp.AlertShow('XXXX', data.Message);
}
});
} else {
UtilApp.Hide();
}
}
catch (err) {
UtilApp.Hide();
}
};
$scope.logar = function () {
UtilApp.Safe($scope, function () {
UtilApp.Show();
var login = $scope.user.login;
var pswd = $scope.user.pswd;
if (login.trim() && pswd.trim() != "") {
Auth.Login(login, pswd).then(function (data) {
try {
$localStorage.user = data;
User.Set($localStorage.user);
UtilApp.Hide();
$state.go('app.feed');
} catch (err) {
UtilApp.Hide();
UtilApp.AlertShow('XXXX', 'XXXXXX');
}
},
function (data) {
UtilApp.Hide();
if (UtilApp.CheckConnection() == "0") {
UtilApp.AlertShow('xxxxxxxx', 'XXXXXXXXXXX');
} else {
UtilApp.AlertShow('XXXX', data.Message);
}
});
} else {
UtilApp.Hide();
UtilApp.AlertShow('XXXXXX', 'XXXXXXXXXXXXXXXX');
}
});
};
setTimeout($scope.checkUser(), 10000);
});
Thank you in advance
I found the error in some devices, the device was not " ready " , and gave except in time to get the uuid for authentication.
Solution: check after the device is ready.
Ionic:
controller('MyCtrl', function($scope, Platform) {
Platform.ready(function() {
// Platform stuff here.
});
});

$scope var not updating on Parse update

I am building an app using ionic and parse. I am updating a boolean in parse based on a click. Everything works on parse end, I see the user object updated in the console after the function runs, however the scope variable is not updating until user logs out, comes back to the page, and then usually has to even refresh again just to see the $scope.isInstagramLinked updated to its true value.
Controller
var app = angular.module('myApp.controllers.account', []);
app.controller('AccountCtrl', function ($scope, $state, $cordovaOauth, AuthService) {
$scope.isInstagramLinked = AuthService.user.attributes.is_instagram_linked;
$scope.linkInstagram = function() {
$cordovaOauth.instagram('######', [], {})
.then(function(result) {
console.log("Response Object -> " + JSON.stringify(result));
console.log(result.access_token);
// save the access token & get user info
AuthService.setInstagramAccessToken(result.access_token).then(function() {
console.log('Token saved!');
});
}, function(error) {
console.log("Error -> " + error);
});
}
$scope.unlinkInstagram = function() {
AuthService.removeInstagramInfo().then(function() {
console.log('Insta unlinked');
console.log(AuthService.user.attributes);
});
}
});
Service
var app = angular.module('myApp.services.authentication', []);
app.service('AuthService', function ($q, $http, $ionicPopup) {
var self = {
user: Parse.User.current(),
'setInstagramAccessToken': function(token) {
var d = $q.defer();
var user = self.user;
user.set("instagram_access_token", token);
user.save(null, {
success: function(user) {
self.user = Parse.User.current();
d.resolve(self.user);
},
error: function(user, error) {
$ionicPopup.alert({
title: "Save Error",
subTitle: error.message
});
d.reject(error);
}
});
self.setInstagramUserInfo(token);
return d.promise;
},
'setInstagramUserInfo': function(token) {
var d = $q.defer();
var endpoint = 'https://api.instagram.com/v1/users/self?access_token=' + token + '&callback=JSON_CALLBACK';
$http.jsonp(endpoint).then(function(response) {
console.log(response.data.data.username);
console.log(response.data.data.id);
var user = self.user;
user.set('is_instagram_linked', true);
user.set('instagram_username', response.data.data.username);
user.set('instagram_user_id', response.data.data.id);
user.save(null, {
success: function(user) {
self.user = Parse.User.current();
d.resolve(self.user);
},
error: function(user, error) {
$ionicPopup.alert({
title: "Save Error",
subTitle: error.message
});
d.reject(error);
}
});
});
},
'removeInstagramInfo': function() {
var d = $q.defer();
var user = self.user;
user.set('is_instagram_linked', false);
user.set('instagram_access_token', null);
user.set('instagram_username', null);
user.set('instagram_user_id', null);
user.save(null, {
success: function(user) {
self.user = Parse.User.current();
d.resolve(self.user);
},
error: function(user, error) {
$ionicPopup.alert({
title: "Save Error",
subTitle: error.message
});
d.reject(error);
}
});
return d.promise;
}
};
return self;
});
I tried something like this at the end of the function but get an error saying Error: [$rootScope:inprog] $digest already in progress
$scope.$apply(function () {
$scope.isInstagramLinked = false;
});
I'm guessing that you're assuming that the following line
$scope.isInstagramLinked = AuthService.user.attributes.is_instagram_linked;
is going to make '$scope.isInstagramLinked' update anytime 'AuthService.user.attributes.is_instagram_linked' updates. That's not the case, though. Because 'AuthService.user.attributes.is_instagram_linked' references a primitive (boolean) value, it just assigns it - it doesn't maintain any kind of reference to it - that only happens with objects.
You need to manually set $scope.isInstangramLinked = true in the $cordovaOauth.instagram() success/"then" handler.
tl;dr:
$scope.isLinked = false;
someFunction().then(function(){
$scope.isLinked = true; // this is what you're missing
})
.error(function(err){...})
If you don't want to set it manually, you can also use $scope.$watch to watch 'AuthService.user.attributes.is_instagram_linked' for changes, and then update '$scope.isInstagramLinked' when it does.

router.post returns error "undefined is not a function" .Using mongo and express.js

I'm trying to buld an app using files from LINK .I found that posting is where the code breaks.Has express js changed or is it syntax mistake ?
The router.post breaks once it reaches Maid.registerMaid(new Maid({... .I'm able to make it work using .save() but could anyone explain why this callback is beaking ?
Putting the code below.. sorry, i'm a beginner in M.E.A.N
API.js
var express = require('express'),
router = express.Router(),
passport = require('passport');
User = require('../models/user.js');
Maid = require('../models/maid.js');
router.post('/AddMaid', function(req, res) {
console.log(req.body, req.body.FirstName,req.body.LastName);
Maid.registerMaid(new Maid({ FirstName: req.body.FirstName }), ({LastName: req.body.LastName}), function(err, account) {
if (err) {
return res.status(500).json({err : err})
}
return res.status(200).json({status: 'Registration successful!'});
});
});
Services.js
angular.module('myApp').factory('AuthService',['$q', '$timeout', '$http', function ($q, $timeout, $http) {
var user = null;
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
registerMaid: registerMaid
});
function registerMaid(Fname, Lname) {
var deferred = $q.defer();
$http.post('/maid/AddMaid', {
FirstName : Fname,
LastName : Lname
}).success(function(data, status) {
if (status === 200 && data.status) {
deferred.resolve();
} else {
deferred.reject();
}
}).error(function(data) {
debugger;
alert("Error in Services AddMaid");
deferred.reject();
});
return deferred.promise;
} }]);
Controllers.js
angular.module('myApp').controller('AddMaidController', ['$scope', '$http','$location', 'AuthService', function($scope, $http,$location, AuthService) {
console.log(AuthService.getUserStatus());
$scope.register = function () {
$scope.error = false;
$scope.disabled = true;
AuthService.registerMaid($scope.registerForm.FirstName,$scope.registerForm.LastName).then(function () {
$scope.disabled = false;
$scope.registerForm = {};
}).catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
});
};}]);
maid.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Maid = new Schema({
First_Name: String,
Last_Name: String
});
module.exports = mongoose.model('maids', Maid);
First of all you globally defined ur User and Maid modules, that is not a good practice.
Error occurs because your Maid module (Maid model on server side, i.e. Nodejs) doesnt have registerMaid method. You need to use Maid.create instead

Upload Image Directly From Browser Using AngularJS Amazon S3

I am trying to upload images from my browser to Amazon S3 directly, but getting the error of AWS not being defined:
public/modules/users/controllers/settings.client.controller.js
16 | var bucket = new AWS.S3({
^ 'AWS' is not defined.
18 | credentials: new AWS.Credentials($scope.creds.access_key, $scope.creds.secret_key)
^ 'AWS' is not defined.
Below is my code:
'use strict';
angular.module('users').controller('SettingsController', ['$scope', '$http', '$location', 'Users', 'Authentication',
function($scope, $http, $location, Users, Authentication) {
$scope.user = Authentication.user;
$scope.profpic = '';
$scope.creds = {
bucket: 'bucket_name',
access_key: '',
secret_key: ''
};
$scope.upload = function() {
// Configure The S3 Object
var bucket = new AWS.S3({
region : 'us-east-1',
credentials: new AWS.Credentials($scope.creds.access_key, $scope.creds.secret_key)
});
if($scope.file) {
var params = { Bucket: $scope.creds.bucket, Key: $scope.file.name, ContentType: $scope.file.type, Body: $scope.file, ServerSideEncryption: 'AES256' };
bucket.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
alert(err.message);
return false;
}
else {
// Success!
alert('Upload Done');
}
})
.on('httpUploadProgress',function(progress) {
// Log Progress Information
console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
});
}
else {
// No File Selected
alert('No File Selected');
}
};
// If user is not signed in then redirect back home
if (!$scope.user) $location.path('/');
// Check if there are additional accounts
$scope.hasConnectedAdditionalSocialAccounts = function(provider) {
for (var i in $scope.user.additionalProvidersData) {
return true;
}
return false;
};
// Check if provider is already in use with current user
$scope.isConnectedSocialAccount = function(provider) {
return $scope.user.provider === provider || ($scope.user.additionalProvidersData && $scope.user.additionalProvidersData[provider]);
};
// Remove a user social account
$scope.removeUserSocialAccount = function(provider) {
$scope.success = $scope.error = null;
$http.delete('/users/accounts', {
params: {
provider: provider
}
}).success(function(response) {
// If successful show success message and clear form
$scope.success = true;
$scope.user = Authentication.user = response;
}).error(function(response) {
$scope.error = response.message;
});
};
// Update a user profile
$scope.updateUserProfile = function(isValid) {
if (isValid) {
$scope.success = $scope.error = null;
var user = new Users($scope.user);
user.$update(function(response) {
$scope.success = true;
Authentication.user = response;
}, function(response) {
$scope.error = response.data.message;
});
} else {
$scope.submitted = true;
}
};
// Change user password
$scope.changeUserPassword = function() {
$scope.success = $scope.error = null;
$http.post('/users/password', $scope.passwordDetails).success(function(response) {
// If successful show success message and clear form
$scope.success = true;
$scope.passwordDetails = null;
}).error(function(response) {
$scope.error = response.message;
});
};
}
])
.directive('fileread', [function(){
return {
scope: {
fileread: '='
},
link: function(scope, element, attributes) {
element.bind('change', function(changeEvent) {
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
scope.fileread = loadEvent.target.result;
});
};
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
};
}]);
Not sure what th eproblem is, as this is my very first time using Angular & dealing wi/ S3.
Are you sure you added the AWS script.
From looking at this:
https://github.com/aws/aws-sdk-js
I believe you may have forgot this in your HTML file:
<head>
....
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.17.min.js"></script>
....
</head>
Or if it is stored locally:
<head>
....
<script src="path/to/file/aws-sdk-2.1.17.min.js"></script>
....
</head>
Or something similar
If you are using aws in the backend & a Node server then you'll need use require it like this (however looking at your code it looks like you are doing it in the frontend):
var AWS = require('aws-sdk');
http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-intro.html

Mongoose "Create" method - Is there no callback? (Using passport and angular)

I am using mongoose to create a user object on register. This works fine and any errors are returned as expected.
However, I want to log the user on right after they register (so registering logs you on if there are no errors).
I have the following for the register.
register_controller:
$scope.submitRegister = function() {
AuthenticationService.register(this.details).success(function() {
$log.debug('/POST to /api/register worked');
});
}
services.js:
.service('AuthenticationService', function($http, $timeout, $q, $session, $flash) {
...
this.register = function(details) {
var register = $http.post('/api/register', details);
register.success(function() {
console.log("User added fine");
}).error(function() {
console.log("error!!!");
});
return register;
};
...
users.js:
app.post('/api/register', authentication.register);
passport's authenticate.js:
module.exports = {
...
register: function(req, res){
var User = require('./controllers/api/login_api');
User.create({name: req.body.name, email: req.body.email, password: req.body.password}, function(err){
if (err) {
console.log(err);
return;
}
console.log("User added");
return res.send(200);
});
},
...
The error is reported back fine, no troubles, but I would have thought it would report something else back (like the created object?) which I could use down the line so my register_controller can have in the success function(object) {... login(object);...}.
Is this a limitation in the .create method or am I missing something obvious?
Thank you.
Two things to change in your server code:
passport's authenticate.js:
module.exports = {
...
register: function(req, res){
var User = require('./controllers/api/login_api');
User.create({name: req.body.name, email: req.body.email, password: req.body.password}, function(err, user){
if (err) {
console.log(err);
return;
}
console.log("User added");
return res.send(200, user);
});
},
...
I've added user to your callback Mongoose model.create api - return the created object to the CB
And to change the catch in your client:
.service('AuthenticationService', function($http, $timeout, $q, $session, $flash) {
...
this.register = function(details) {
var register = $http.post('/api/register', details);
register.success(function(user) {
console.log(user);
}).error(function() {
console.log("error!!!");
});
return register;
};
...
Now you can do with the created user object whatever you need

Resources