I've seen posts about this problem before, but they're either outdated or offer a solution very similar to my setup.
Basically, I have two functions in my controller: authCtrl.login and authCtrl.register. The register's call to Auth.$createUserWithEmailAndPassword() works fine, but the login's call to Auth.$authWithPassword() does not, as I'm getting a "..is not a function" error. Can't for the life of me figure out what is wrong here.
Here's my setup:
auth.service.js:
angular.module('angularfireSlackApp')
.factory('Auth', function($firebaseAuth, $firebaseObject){
var auth = $firebaseAuth();
return auth;
});
auth.controller.js:
angular.module('angularfireSlackApp')
.controller('AuthCtrl', function(Auth, $state){
var authCtrl = this;
authCtrl.user = {
email: '',
password: ''
};
authCtrl.login = function() {
// Why is this not a function
Auth.$authWithPassword(authCtrl.user)
.then(function (auth){
$state.go('home');
}, function (error){
authCtrl.error = error;
});
}
authCtrl.register = function() {
Auth.$createUserWithEmailAndPassword(authCtrl.user.email, authCtrl.user.password)
.then(function (user){
authCtrl.login();
}, function (error){
authCtrl.error = error;
});
}
});
try $signInWithEmailAndPassword
See documentation:
https://github.com/firebase/angularfire/blob/master/docs/reference.md#signinwithemailandpasswordemail-password
Maybe a more complete answer building on what Aaron Saunders answered using angularjs and angularfire:
var auth = $firebaseAuth();
$scope.loginUser = function (email, password) {
auth.$signInWithEmailAndPassword(email, password).then(function(firebaseUser) {
console.log("User Logged in successfully with uid: " + firebaseUser.uid);
}).catch(function(error) {
console.log("An Authentication error occurred: " + error);
});
};
Related
I have problem with my Lambda, actually in promise nodejs. I have wrote code like this in my Lambda:
'use strict'
const Alexa = require('alexa-sdk');
const mqtt = require('mqtt');
const APP_ID = undefined;
const WELCOME_MESSAGE = 'Welcome to the lamp control mode';
const WELCOME_REPROMT = 'If you new please say help'
const HELP_MESSAGE = 'In this skill you can controlling lamp to turn off or on, dim the lamp, change the lamp color and schedule the lamp';
const STOP_MESSAGE = 'Thanks for using this skill, Goodbye!';
const OFF_RESPONSE = 'Turning off the lamp';
const ON_RESPONSE = 'Turning on the lamp';
const DIM_RESPONSE = 'Dimming the lamp';
const CHANGE_RESPONSE = 'Changing the lamp color';
const AFTER_RESPONSE = 'Wanna control something again ?';
const handlers = {
'LaunchRequest': function () {
this.emit(':ask', WELCOME_MESSAGE, WELCOME_REPROMT);
},
'OnOffIntent' : function () {
var status = this.event.request.intent.slots.status.value;
var location = this.event.request.intent.slots.location.value;
console.log(status);
console.log(location);
if (status == 'on') {
// Promise Start
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
// Promise END
// this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
} else if (status == 'off') {
this.emit(':ask', OFF_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
}
},
'DimIntent' : function () {
// to do here
},
'ChangeColorIntent' : function () {
// to do here
},
'ShceduleIntent' : function () {
// to do here
},
'AMAZON.HelpIntent': function () {
this.emit(':ask', HELP_MESSAGE, 'Wanna control something ?');
},
'AMAZON.StopIntent': function () {
this.emit(':tell', STOP_MESSAGE);
}
};
exports.handler = function (event, context, callback) {
const alexa = Alexa.handler(event, context, callback);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
}
I test my code with Service Simulator in Alexa Developer and get this result :
Result Image
So I checked output in Lambda and I got this error report :
Error in Lamda
Can anyone please help me? I have no idea with this because this is my first trial :)
The crux of your error seems to be this specific line in the log:
Cannot read property 'emit' of undefined
And after following the flow of your program, it's likely ocurring here:
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
// It's probably ocurring in this line below
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
)
The log is saying that you tried using this, it's undefined and doesn't have an emit property. Thats ocurring because of how this works in Js. You could workaround this problem by saving a reference to this
var that = this;
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
that.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
I would also recommend reading up a bit on "How 'this' works in Javascript"
MDN
Stack Overflow - "how does 'this' work"
I am trying to achieve user login
and logout using angularJS and web Api
But the server always return badrequest (400)
exception
the error is coming from this bit of code
AuthApp.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var authServiceFactory = {};
var _authentication =
{
isAuth: false,
userName: ""
};
// this is the login function
authServiceFactory.login = function (loginData)
{
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password; //is not working
//var data = { username: loginData.userName, password: loginData.password, grant_type: "password" }; // I try this and is not working too
//data = $.param(data);
// how should I format my data for the web API to understand
var deferred = $q.defer();
// alert(data);
$http.post('/token', data, {
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err) {
// _logout();
deferred.reject(err);
});
return deferred.promise;
}
authServiceFactory.logout = function ()
{
localStorageService.remove("authenticationData");
_authentication.isAuth = false;
_authentication.userName = "";
}
return authServiceFactory;
}]);
using postman to further see the error
this appears
{ "error": "unsupported_grant_type" }
I made google search but still no solution; how can I resolve this issue?
thanks in advance!!
I'm doing this login exercise where users can login and post notes, and view the notes that they've posted. My problem is when I logout and login with a different user I see the notes from the previous user.
Here's an illustration:
I log in with a different user then this shows up:
I restart the page and the appropriate note shows up:
The controller for this:
exports.homeController = function ($scope, $location, $q, $users, $window, $notes, $http) {
var auth = function () {
var userInfo = $users.getUserInfo()
if (userInfo) {
return $q.when(userInfo)
} else {
return $q.reject({ authenticated: false })
}
}
$scope.userInfo = auth()
myNotes($scope.userInfo.$$state.value.accessToken) // I invoke my function to get the notes for each specific user but it doesn't seem to work.
$scope.logout = function () {
$users.logout()
.then(function (results) {
$scope.userInfo = null
$scope.myNotes = null
$location.path('/')
}, function (err) {
console.log(err)
})
}
$scope.notes = {
notes: ''
}
$scope.postNote = function () {
$notes.postNotes($scope.userInfo.$$state.value.accessToken, $scope.notes)
.then(function (result) {
$scope.myNotes.push($scope.notes)
$scope.notes = ''
}, function (err) {
console.log(err)
})
}
function myNotes (user_id) {
$notes.getMyNotes(user_id)
.then(function (result) {
console.log(result)
$scope.myNotes = result.data
}, function (err) {
console.log(err)
})
}
}
This is the app https://login-sys.herokuapp.com/
I've found your non-minified code for the services.
Based on that I think the problem is that you declare var deferred = $q.defer() one time in the $notes service.
I think it should be "renewed" every time the service methods are called:
function getMyNotes (user_id) {
var deferred = $q.defer();
$http.get('/api/myNotes/' + user_id + '?access_token=' + user_id)
.then(function (result) {
deferred.resolve(result)
}, function (err) {
deferred.reject(err)
});
return deferred.promise
}
Similarly in postNotes.
The second time you return the same promise with the same value, so your homeController's getMyNotes function will get the same result despite the $notes service making a new request.
In the $users service's logout and signup functions you are already using it correctly.
I started to work with Angular two months ago so sorry in advance if my question is duplicate.
Although, I found similar question AngularJS Promises $q.all and SignalR I don't know how to fit that in my code.
I get data from the server by signalR and I want to show landing page as long as I don't get all the data from the server. I try to do that with $q.all but I got error. Bellow is my code and error that I get.
Here is my service:
var menuItemshub = new Hub(‘menuItemsHub’, {
rootPath: $rootScope.defaultRootPath,
//server side methods
methods: [‘getMenuItems’],
queryParams: {
‘token’: $rootScope.loggedInUser.accessToken,
},
//handle connection error
errorHandler: function (error) {
console.error(error);
}
});
var countrieshub = new Hub(‘countriesHub’, {
rootPath: $rootScope.defaultRootPath,
//server side methods
methods: [‘getCountries’],
queryParams: {
‘token’: $rootScope.loggedInUser.accessToken,
},
//handle connection error
errorHandler: function (error) {
console.error(error);
}
});
var menuItemshubInitDone = function () {
return menuItemshub.promise.done();
};
var countrieshubInitDone = function () {
return countrieshub.promise.done();
};
var getMenuItems = function () {
return menuItemshub.getMenuItems();
};
var getCountries = function () {
return countrieshub.getCountries();
};
Here is my controller
configurationService.menuItemshubInitDone().then(function () {
configurationService.getMenuItems().then(function (response) {
// Success
$rootScope.menuItems = response.MenuItems;
}, function (error) {
});
});
configurationService.countrieshubInitDone().then(function () {
configurationService.getCountries().then(function (response) {
// Success
$rootScope.countries = response.Countries;
$rootScope.selectedAction = $rootScope.countries;
$rootScope.setAction($rootScope.selectedAction[0]);
}, function (error) {
});
});
And I want to do something like:
var all = $q.all([configurationService.getCountries(),
configurationService.getMenuItems()]);
all.then(function () {
$rootScope.showLandingPage = false;
});
I get following error SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started. I tried with
$q.when([configurationService.menuItemshubInitDone()]);
and then to call $q.all but i get the same error again.
I have been trying to find the solution for few days by googling but I couldn't figure out what I need to do.
Thank you for help in advance.
I have found what I was doing wrong. Here is code that works fine now, in case if somebody else get stuck as I was:
$scope.userConfigurations = function () {
var all = $q.all([getMenuItems, getCountries]);
all.then(function () {
$rootScope.showLandingPage = false;
});
var getMenuItems = configurationService.menuItemshubInitDone().then(function () {
configurationService.getMenuItems().then(function (response) {
// Success
$rootScope.menuItems = response.MenuItems;
}, function (error) {
});
});
var getCountries = configurationService.countrieshubInitDone().then(function () {
configurationService.getCountries().then(function (response) {
// Success
$rootScope.countries = response.Countries;
$rootScope.selectedAction = $rootScope.countries;
$rootScope.setAction($rootScope.selectedAction[0]);
}, function (error) {
});
});
In my AngularJS application I'm using WebSocket to connect the application and the API.
My problem is that after making a handshake I want to reroute the user to a new view. This should happen automatic after the call succeeded, this doesn't happen, however if I run the function again it works fine, how can this be?
Error:
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Controller:
...
$scope.signIn = function(){
if($scope.loginForm.$valid){
socketService.handshake($scope.login.username, $scope.login.password, function(response){
if(response.payload.success){
$scope.user = $scope.login;
$scope.user.isLoggedIn = true;
$scope.user = sharedProperties.setUser($scope.user);
$scope.login = {};
$location.path('view/' + sharedProperties.getConfig().views[0].route);
} else {
console.log('Error : Login failed');
}
});
}
};
...
SocketService:
...
var service = {},
socket;
service.handshake = function(username, password, callback){
handshake(username, password, function(response){
callback(response);
});
};
function handshake(username, password, callback){
var jsonObject = {
'agmt': '00001',
'usr': username,
'pwd': password,
"request": 'INIT'
};
socket = new WebSocket(config.socketAddress);
socket.onopen = function () {
console.log("Server is on!");
console.log('json', jsonObject);
socket.send(JSON.stringify(jsonObject));
};
socket.onmessage = function (response) {
console.log('\n' + new Date().toUTCString() + '\nServer responded');
console.log('handshake data : ', response);
callback(JSON.parse(response.data));
};
};
...