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.
});
});
Related
I'm working with angularfire, where I just want to implement authentication with firebase, but for some reason it keeps spitting out AUTHENTICATION_DISABLED error whenever I make a authWithPassword and createUser
I cloned the skeleton code from https://github.com/firebase/angularfire-seed
And it works fine when I run it in my local machine, however, after adding more functionalities, it doesn't work anymore.
Here is my code for login.js
"use strict";
angular.module('myApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
controller: 'LoginCtrl',
templateUrl: 'login/login.html'
});
}])
.controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', function($scope, Auth, $location, fbutil) {
d3.select('svg').remove();
d3.select('svg').remove();
$scope.email = null;
$scope.pass = null;
$scope.confirm = null;
$scope.createMode = false;
$scope.login = function(email, pass) {
$scope.err = null;
Auth.$authWithPassword({ email: email, password: pass }, {rememberMe: true})
.then(function(authData/* user */) {
console.log("Logged in as : " + authData.uid);
//$location.path('/account');
}, function(err) {
console.log("Error occured :(");
$scope.err = errMessage(err);
});
};
$scope.createAccount = function() {
$scope.err = null;
if( assertValidAccountProps() ) {
var email = $scope.email;
var pass = $scope.pass;
// create user credentials in Firebase auth system
Auth.$createUser({email: email, password: pass})
.then(function() {
// authenticate so we have permission to write to Firebase
return Auth.$authWithPassword({ email: email, password: pass });
})
.then(function(user) {
// create a user profile in our data store
var ref = fbutil.ref('users', user.uid);
return fbutil.handler(function(cb) {
ref.set({email: email, name: name||firstPartOfEmail(email)}, cb);
});
})
.then(function(/* user */) {
// redirect to the account page
console.log("User saved");
//$location.path('/account');
}, function(err) {
console.log("Error in createAccount");
$scope.err = errMessage(err);
});
}
};
function assertValidAccountProps() {
if( !$scope.email ) {
$scope.err = 'Please enter an email address';
}
else if( !$scope.pass || !$scope.confirm ) {
$scope.err = 'Please enter a password';
}
else if( $scope.createMode && $scope.pass !== $scope.confirm ) {
$scope.err = 'Passwords do not match';
}
return !$scope.err;
}
function errMessage(err) {
return angular.isObject(err) && err.code? err.code : err + '';
}
function firstPartOfEmail(email) {
return ucfirst(email.substr(0, email.indexOf('#'))||'');
}
function ucfirst (str) {
// inspired by: http://kevin.vanzonneveld.net
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
}]);
Any insight on why it's not working would be very helpful. If there is any information about dependencies I'll post them right away.
I'm trying to use Django REST Framework's token-based authentication scheme with an AngularJS client. I'm able to successfully retrieve and store a token from the server, but I'm having trouble figuring out how to attach the token to subsequent responses. Here's the service that manages logging in and saving a token:
angular.module('mymodule')
.factory('loginService', function ($http, $window) {
var api_base = "link to my api";
return {
async: function() {
return $http.get(api_base + "authentication/login/").then(function (response) {
return response.data;
}, function errorCallback(response) {
console.log("Testuser API Error: " + response);
return null;
});
},
loginUser: function(email, password) {
self.saveToken = function(auth_token) {
$window.localStorage['jwtToken'] = auth_token;
};
self.getToken = function() {
return $window.localStorage['jwtToken'];
};
console.log("...to listing " + email);
return $http.post("link to my api/authentication/login/", {
email: email,
password: password
}).then(function(response) {
if(response.config.url.indexOf("link to my api") === 0 && response.data.auth_token) {
self.saveToken(response.data.auth_token);
}
return response;
});
}
};
});
Here's the controller associated with the above service to handle logging in:
angular.module('mymodule').controller("LoginController", function(loginService, $scope) {
$scope.loginusers = [];
$scope.refresh = function() {
loginService.async().then(function(data) {
if (data == null)
return;
console.log(data[0]["email"]);
$scope.loginusers = [];
for (var loginuser in data)
$scope.loginusers.push(loginuser);
});
};
$scope.refresh();
// Test //
$scope.loginTestUser = function() {
console.log("something...");
loginService.loginUser(
$scope.email,
$scope.password
)
};
//////
});
And here's the service that I'd like to use for displaying a user's profile after the token is sent back to the server.
angular.module('mymodule').factory("profileService", function($http, loginService, $httpProvider) {
var api_base = "link to my api";
$httpProvider.interceptors.push(function($q, $window) {
return {
'request': function(config) {
config.headers['Token'] = $window.localStorage['jwtToken'];
return config;
}
};
});
return {
async: function() {
return $http.get(api_base + "authentication/me/").then(function (response) {
return response.data[0];
}, function errorCallback(response) {
console.log("Profile API Error: " + response);
return null;
});
}
};
});
How should I be approaching this?
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.
I try to make facebook registration module in my app. Facebook API is faster than my Angular controller, so promise should be used here. The problem is that $q seems to be an empty object and defer function is undefined.
module:
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'herecomesmycode');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$q', '$ionicPlatform', '$state', 'authService', 'datacontext', '$location'];
function FacebookAPI(UserService, $q, $ionicLoading, fbAppId, $state, authService, datacontext, $location) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
};
and here $q.defer is undefined:
function fbRegister() {
console.log($q.defer);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
Without using promise, it gets fast from API but all variables I want to fill with values from API, are initiated before API finishes and are undefined.
The whole module:
(function() {
'use strict';
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'myappkey');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$ionicPlatform', '$state', 'authService', '$q'];
function FacebookAPI(UserService, $ionicLoading, fbAppId, $state, authService, $q) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
}
function fbRegister() {
console.log($q);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
function getApiData() {
var formData = {};
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email,birthday", ["public_profile", "email", "user_birthday"],
function (result) {
if (result.gender == "male") {
result.gender = '1';
} else {
result.gender = '2';
}
formData = {
name: result.first_name + " " + result.last_name,
email: result.email,
birthday: new Date(result.birthday),
gender: result.gender
}
console.log("moduł" + formData);//here we have nice and neat data
return formData;
}, function(res) {
});
}
};
//This is the success callback from the login method
function fbLoginSuccess(response) {
var fbLogged = $q.defer();
if (!response.authResponse) {
fbLoginError("Cannot find the authResponse");
return;
}
var expDate = new Date(
new Date().getTime() + response.authResponse.expiresIn * 1000
).toISOString();
var authData = {
id: String(response.authResponse.userID),
access_token: response.authResponse.accessToken,
expiration_date: expDate
}
authService.facebookLogin(response.authResponse.accessToken).then(function() {
fbLogged.resolve(authData);
});
};
//This is the fail callback from the login method
function fbLoginError(error) {
var fbLogged = $q.defer();
fbLogged.reject(error);
alert(error);
$ionicLoading.hide();
};
//this method is to get the user profile info from the facebook api
function getFacebookProfileInfo() {
var info = $q.defer();
facebookConnectPlugin.api('/me', "",
function(response) {
info.resolve(response);
},
function(response) {
info.reject(response);
}
);
return info.promise;
}
//This method is executed when the user press the "Login with facebook" button
function fbLogin() {
if (!cordova) {
//this is for browser only
facebookConnectPlugin.browserInit(fbAppId);
}
//check if we have user's data stored
var user = UserService.getUser();
facebookConnectPlugin.getLoginStatus(function(success) {
//alert(JSON.stringify(success, null, 3));
if (success.status === 'connected') {
// the user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email", ["public_profile", "email"],
function(result) {
//alert("Result: " + JSON.stringify(result));
//alert(result.first_name);
})
var accessToken = success.authResponse.accessToken;
authService.facebookLogin(accessToken).then(function() {
$state.go('app.map');
}, function(err) { alert('auth failed: ' + JSON.stringify(err, null, 2)); });
} else {
//if (success.status === 'not_authorized') the user is logged in to Facebook, but has not authenticated your app
//else The person is not logged into Facebook, so we're not sure if they are logged into this app or not.
$ionicLoading.show({
template: 'Loging in...'
});
// permissions from facebook
facebookConnectPlugin.login([
'email',
'public_profile',
'user_about_me',
'user_likes',
'user_location',
'read_stream',
'user_photos'
], fbLoginSuccess, fbLoginError);
fbLogged.promise.then(function(authData) {
var fb_uid = authData.id,
fb_access_token = authData.access_token;
//get user info from FB
getFacebookProfileInfo().then(function(data) {
var user = data;
user.picture = "http://graph.facebook.com/" + fb_uid + "/picture?type=large";
user.access_token = fb_access_token;
//save the user data
//store it on local storage but it should be save it on a database
UserService.setUser(user);
$ionicLoading.hide();
$state.go('app.map');
});
});
}
});
}
})();
I am creating and sending a UID on the server side to the client side when the user visits a web page. I would like to use that UID as the subfolder to store each project a particular user posts to the server. I'm trying to figure out how best to accomplish this. When I use the code below, I am unable to access the UID in the Projects factory from the UserFactory.
Javascript (Angular):
myApp.factory('UserFactory', function UserFactory($http, API_URL, AuthTokenFactory, $q) {
return $http.get(API_URL + '/api/authenticate').then(function success(response) {
AuthTokenFactory.setToken(response.data.token);
return response;
});
});
myApp.factory('AuthTokenFactory', function AuthTokenFactory($window) {
var store = $window.localStorage;
var key = 'auth-token';
return {
getToken: getToken,
setToken: setToken
};
function getToken() {
return store.getItem(key);
}
function setToken(token) {
if (token) {
store.setItem(key, token);
} else {
store.removeItem(key);
}
}
});
myApp.factory('Projects', function($http, API_URL, UserFactory, AuthTokenFactory) {
var uid = UserFactory.response.data.token
var Projects = {
};
Projects.get = function(id) {
return $http.get(API_URL + '/api/projects/' + uid + id);
};
Projects.create = function(userData) {
return $http.post(API_URL + '/api/projects/' + uid, userData).then(function error(response) {
var data = response.data;
});
};
return Projects;
});
Node
apiRouter.get('/authenticate', function(req, res) {
var uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
var token = jwt.sign({
uid: uid
}, superSecret, {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
message: 'Enjoy your token!',
uid: uid,
token: token
});
});