Angularjs $cookieProvider unknown provider error - angularjs

I use a custom authentication service to store my authentication token, authToken. This stores the received user profile into a client side cache with $cookieStorage.put() method. When i run, i get the unrecognized provider error:
authToken:
appModule.factory('authToken',['$cookieStorage',
function($cookieStorage) {
var cachedStorage;
return {
setToken: function(token) {
cachedStorage = token;
$cookieStorage.put('userToken', token);
},
getToken: function() {
if (!cachedStorage) {
cachedStorage = $cookieStorage.get('userToken');
}
},
isAuthenticated: function() {
return !!this.getToken();
}
};
}]);
where i use it:
appModule.controller('AuthenticationController',
function ($scope, accountRepository,authToken) {
$scope.login = function(credentials) {
var profile = accountRepository.login(credentials);
profile.success(function(data) {
if (data) {
var userData = {
username: data.username,
firstName: data.firstName,
lastName: data.lastName,
isLogged: true
}
alert('success', 'OK', 'You are now registered' + userData.firstName);
authToken.setToken(userData);
}
});
}
});
the ngCookie module is inserted into appModule, this works fine because i have used it before.

It is $cookieStore not $cookieStorage
https://docs.angularjs.org/api/ngCookies/service/$cookieStore

Related

Unable to store values in mongoDb?

My API log:
OPTIONS /api/signup 204 14.010 ms - -
req.body { '{"name":"rahul jain","mobile":"343453","email":"inayath#cantern.in","password":"123","cpassword":"123"}': '' }
POST /api/signup 200 9.296 ms - 56
I'm making a post request from angular.js to node.js server and here is my angular.js code:
.controller('RegisterCtrl', function($scope, AuthService, $state, $http) {
$scope.user = {
name: '',
mobile:'',
email:'',
password:'',
cpassword:''
};
$scope.signup = function() {
console.log("user",$scope.user);
$http.post("http://localhost:8080/api/signup", $scope.user )
.then(function (response) {
return response;
});
};
})
Here is my node.js code:
apiRoutes.post('/signup', function(req, res) {
console.log("req",req.body);
if (!req.body.name || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
} else {
var newUser = new User({
name: req.body.name,
mobile: req.body.mobile,
email: req.body.email,
password: req.body.password,
cpassword: req.body.cpassword
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
I think that req.body object having key-value and key is my whole data. Is that correct? Please help me out, thanks in advance.

Sending an access token to server using AngularJS

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?

satellizer then not called after authentication

I'm very new to angular, so my knowledge is based on tutorials and even then I don't succeed.
I need to authenticate using a google account. That works, I get a token where my api calls could be authorized with. But after login the pop up window should dismiss and I should be redirected to the homepage. This doesn't work.
this is my controller
angular.module('MyApp').controller('loginController', ['$scope', '$auth', '$location','loginService', loginController]);
function loginController($scope, $auth, $location, loginService) {
$scope.authenticate = function(provider) {
$auth.authenticate(provider).then(function(data) {
loginService.saveToken(data.data.token);
console.log('You have successfully signed in with ' + provider + '!');
$location.path('http://localhost/#/home');
});
};
};
in app.js I have my configuration. this is not my work but a friend who is an intern as wel as me, he is responsible for a mobile application, where he uses the same function to get his token, and it works.
authProvider.google({
clientId: CLIENT_ID,
redirectUri: 'http://localhost:3000/api/users/signIn'
});
$authProvider.storage = 'localStorage'; // or 'sessionStorage'
$authProvider.loginRedirect = 'http://localhost/#/home';
This is the controller in node where the url is redirected to (google developer console)
router.get('/signIn', function(req, res) {
//console.log(req);
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
if (!err) {
https.get("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + tokens.access_token, function(response) {
// Continuously update stream with data
var body = '';
response.setEncoding('utf8');
response.on('data', function(d) {
body += d;
});
// Data fetched
response.on('end', function() {
var parsed = JSON.parse(body);
// Check if client_id is from the right app
if (parsed.issued_to == '343234242055-vd082vo0o8r8lmfvp1a973736fd98dht.apps.googleusercontent.com') {
User.getGoogleId(parsed.user_id, function(err, user) {
if (err) {
res.status(500).send({
message: 'not authorized app'
});
}
// No user returned, create one
if (!user) {
// Request user info
oauth2Client.setCredentials(tokens);
plus.people.get({
userId: 'me',
auth: oauth2Client
}, function(err, plusUser) {
if (err) res.status(500).send({
message: 'not authorized app'
});
else {
// Create new user
User.create(plusUser.name.givenName, plusUser.name.familyName, (plusUser.name.givenName + "." + plusUser.name.familyName + "#cozmos.be").toLowerCase(), parsed.user_id, function(err, newUser) {
if (err) res.status(500).send({
message: 'not authorized app'
});
else {
res.statusCode = 200;
return res.send({
response: 'Success',
id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
token: tokens.access_token
});
}
});
}
});
} else {
// Return user
res.statusCode = 200;
return res.send({
response: 'Success',
id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
token: tokens.access_token
});
}
});
}
// if not right app, return unauthorized response
else {
res.status(500).send({
message: 'not authorized app'
});
}
});
});
}
});
});
So I login, I get asked to give permission to the application to use my account info, I get a json response where I can see my name, email and token, and that's it
Even within the company where I work, no one could find an answer. So I came with a solution myself. I don't use satellizer anymore.
.when('/access_token=:access_token', {
template: '',
controller: function($window, $http, $location, $rootScope) {
var hash = $location.path().substr(1);
var splitted = hash.split('&');
var params = {};
for (var i = 0; i < splitted.length; i++) {
var param = splitted[i].split('=');
var key = param[0];
var value = param[1];
params[key] = value;
$rootScope.accesstoken = params;
}
console.log(params.access_token);
var json = {
Token: params.access_token
};
$window.localStorage['token'] = params.access_token;
$http.post('http://localhost:3000/api/users/signIn', json).success(function(data, status) {
console.log(data);
}).error(function(err) {
console.log(err);
});
$location.path("/home");
}
/*controller: 'createNewsFeed',
templateUrl: 'homepage.html'*/
}).
So redirect the page by itself. Because the authentication works on the backend side, I can get a access token, which is the only thing I really need for future use of my rest api. I defined a route where, after receiving the json with the token, my browser is manually redirected to with $window.location. So when that page is loaded (not visible for the user, it goes too fast to notice) I analyse the token, save the token, analyse authentication, when that is successful I manually redirect to the homepage.

$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.
});
});

Unable to minify JS

Before implementing Firebase authentication this JS file successfully minifyed without any problems.
The file works without any problems when using the none-midifyed version, I'm unable to test the minifyed version as Atom will not allow me to minify and save due to the following error (See attached)!
I'm using and following Scotch.io's advice: https://scotch.io/tutorials/declaring-angularjs-modules-for-minification
Any pointers/advice would be great!
Error
Controller JS
var fbcontrollers = angular.module('fbcontrollers', []);
fbcontrollers.controller('authCtrl', ['$scope', 'Auth', '$location', function($scope, Auth, $location) {
$scope.auth = Auth;
$scope.user = $scope.auth.$getAuth();
// Store User Data
function userData() {
var isNewUser = true;
var fire = new Firebase('https://courtyard-bridal.firebaseio.com/');
fire.onAuth(function(authData) {
if (authData && isNewUser) {
fire.child("users").child(authData.uid).set({
name: getName(authData),
email: getEmail(authData),
provider: authData.provider
});
}
function getName(authData) {
switch (authData.provider) {
case 'password':
return authData.password.email.replace(/#.*/, '');
case 'facebook':
return authData.facebook.displayName;
}
}
function getEmail(authData) {
switch (authData.provider) {
case 'password':
return authData.password.email;
case 'facebook':
return authData.facebook.email;
}
}
});
}
// Facebook Login
$scope.fblogin = function() {
var scope = {
scope: 'email'
};
$scope.auth.$authWithOAuthPopup('facebook', scope).then(function(auth) {
// Store Data
userData();
// Redirtect on Success
$location.path('/dash');
}).catch(function(error) {
console.log('error');
});
};
// Default Form Data
$scope.form = ({
'email': '',
'password': ''
});
// Login Form
$scope.login = function() {
var email = $scope.form.email;
var password = $scope.form.password;
$scope.authData = null;
$scope.auth.$authWithPassword({
email: email,
password: password
}).then(function(Auth) {
$scope.authData = Auth;
$location.path('/dash');
}).catch(function(error) {
console.log(error);
});
};
// Register (Create User) Form
$scope.register = function() {
var email = $scope.form.email;
var password = $scope.form.password;
// Create User
$scope.auth.$createUser({
email: email,
password: password
}).then(function(Auth) {
// Store Data
userData();
// Login Created User
$scope.authData = null;
$scope.auth.$authWithPassword({
email: email,
password: password
}).then(function(Auth) {
$scope.authData = Auth;
$location.path('/dash');
}).catch(function(error) {
console.log('error');
});
}).catch(function(error) {
console.log(error);
});
};
}]);
fbcontrollers.controller('dashCtrl', ['$scope', 'Auth', '$location', function($scope, Auth, $location) {
$scope.auth = Auth;
$scope.user = $scope.auth.$getAuth();
if($scope.user.provider === 'facebook') {
$scope.id = $scope.user.uid;
$scope.name = $scope.user.facebook.displayName;
$scope.email = $scope.user.facebook.email;
$scope.profile = $scope.user.facebook.profileImageURL;
} else if ($scope.user.provider === 'password') {
$scope.id = $scope.user.uid;
$scope.name = $scope.user.password.email.replace(/#.*/, '');
$scope.email = $scope.user.password.email;
$scope.profile = $scope.user.password.profileImageURL;
}
console.log($scope.user);
// Logout
$scope.logout = function() {
$scope.auth.$unauth();
$location.path('/auth');
};
}]);
I am pretty sure the problem is connected with the use of catch. Note that catch is a keyword in javascript, used in exception (error) handling. Promises use catch as a method name and that's a bit of a collision. In general it's safer to use it indirectly:
}).then(function(...) {
...
})['catch'](function(error) {
...
});
The same applies to the finally keyword.

Resources