Cannot read property 'message' of undefined - angularjs

I develop method of login in my website, but i have problem in login.controller.js
I have this error:
TypeError: Cannot read property 'message' of undefined .
at login.controller.js:35
'use strict';
export default class LoginController {
user = {
name: '',
email: '',
password: ''
};
errors = {
login: undefined
};
submitted = false;
/*#ngInject*/
constructor(Auth, $state) {
this.Auth = Auth;
this.$state = $state;
}
login(form) {
this.submitted = true;
if(form.$valid) {
this.Auth.login({
email: this.user.email,
password: this.user.password,
rememberme: this.user.remember
})
.then(() => {
// Logged in, redirect to home
this.$state.go('main');
})
.catch(err => {
this.errors.other = err.message;
});
}
}
}

export default class LoginController {
/* #ngInject */
constructor(Auth, $state) {
this.Auth = Auth;
this.$state = $state;
this.user = {
name: null,
email: null,
password: null
};
this.errors = {
login: null,
others: null // This was needed;
};
this.submitted = false;
}
login(form) {
this.submitted = true;
if (form.$valid) {
this.Auth.login({
email: this.user.email,
password: this.user.password,
rememberme: this.user.remember
})
.then(() => {
return this.$state.go('main');
})
.catch((err) => {
console.log(err); // see what 'err' looks like here
this.errors.other = err.message;
})
.finally(() => {
// Logged in, redirect to home
console.log('last thing');
});
}
}
}
I moved your variables into the constructor. Put a console.log in to see what err looks like. It's possible 'message' simply does not exist on err. Also this.errors.others needed to be declared.

Related

Access Prop Type passed to function MERN Stack

I'm currently passing my resetPassword variable through the updateUserPassword function using prop types. The function then checks the response message from the api route that I have setup and changes the boolean value of resetPassword.isMatched.
The issue is that I can't seem to get access to the updated isMatched value on submit. How would I output the true or false value of the isMatched variable?
The updateUserPassword function successfully sets the resetPassword.isMatched to either true or false dependent on the res.data.msg I just can't access it within my initial component.
//*** Onsubmit that passes the prop types to updateUserPassword ***//
onSubmit = e => {
e.preventDefault();
const resetPassword = {
email: this.username,
password: this.state.password,
password2: this.state.password2,
isMatched: false
};
this.props.updateUserPassword(resetPassword);
};
//*** Passing prop types to as function ***//
ResetPassword.propTypes = {
updateUserPassword: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired
};
//*** #route POST api/users/resetPassword ***//
router.post("/resetpassword", (req, res) => {
User.findOne({ email: req.body.email }).then(user => {
if (!user) {
return res.status(400).json({ email: "User does not exist" });
} else {
const updPassword = req.body.password;
// Check password
bcrypt.compare(updPassword, user.password).then(isMatch => {
if (isMatch) {
res.status(200).send({
msg: 'passwords match',
isMatched: true
})
} else {
// Hash password before saving in database
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(resetPassword, salt, (err, hash) => {
if (err) throw err;
user.password = hash;
user
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
}
});
});
//*** Reset User Password function that accepts resetPassword ***//
export const updateUserPassword = (resetPassword) => dispatch => {
axios
.post("/api/users/resetpassword", resetPassword)
.then(res => {
if (res.data.msg === 'passwords match') {
resetPassword.isMatched = true;
} else {
resetPassword.isMatched = false;
}
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};

How To login with Facebook using react?

I have used "react-facebook-login" this package for login Facebook I
have got a response from Facebook and get token and then I forward
token to backend and the backend will be sending some JSON like
{userId: "1",sessionID: "2" successInd: "true"}
I want when I got a success is true then I go next page which is my dashboard page.
here is my code :-
class App extends Component {
constructor() {
super();
this.state = { isAuthenticated: false, user: null, token: ''};
}
logout = () => {
this.setState({isAuthenticated: false, token: '', user: null})
};
onFailure = (error) => {
alert(error);
};
twitterResponse = (response) => {
const token = response.headers.get('x-auth-token');
response.json().then(user => {
if (token) {
this.setState({isAuthenticated: true, user, token});
}
});
};
facebookResponse = (response) => {
const tokenBlob = new Blob([JSON.stringify({access_token: response.accessToken}, null, 2)], {type : 'application/json'});
const options = {
method: 'POST',
body: tokenBlob,
mode: 'cors',
cache: 'default'
};
fetch('http://localhost:4000/api/v1/auth/facebook', options).then(r => {
const token = r.headers.get('x-auth-token');
r.json().then(user => {
if (token) {
this.setState({isAuthenticated: true, user, token})
}
});
})
};

Check browser cookie in AngularJS

I set cookie by hapi-auth-cookie. Can i check in AngularJS is cookie exists?
data.js
server.register(Cookie, function(err) {
if(err) {
console.error(err);
throw err;
}
server.auth.strategy('session', 'cookie', {
password: 'fuckthebritisharmytooralooralooraloo',
isSecure: false,
cookie: 'session',
ttl: 24*60*60*1000
});
server.route({
method: 'POST',
path: '/login',
config: {
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false
}
},
handler: function(req, res) {
if (req.auth.isAuthenticated) {
console.info('Already!');
req.cookieAuth.clear(); // Delete
return res.redirect('/');
}
var username = req.payload.username;
db.get('user_' + req.payload.username).then(function(data) {
var user = data;
var pass = data.password;
if(!user) {
return console.error('Can`t find user!');
}
var password = req.payload.password;
return Bcrypt.compare(password, pass, function(err, isValid) {
if(isValid) {
req.server.log('Boom, okay!');
req.cookieAuth.set(user);
return res.redirect('/');
}
return res.redirect('/login');
})
})
.catch((err) => {
if (err) {
console.error(err);
throw err;
}
});
}
}
});
});
You can access like this if you are using Angularjs 1.4 and above
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
$scope.session = $cookies.get('session');
}]);

Redirect after email authentication

I'm having trouble redirecting the user after successful login, i've read the documentation for Firebase and tried several things but no luck so far
Can anyone point me into the right direction ?
Thanks in advance,
Jérémie.
Here's the controller.js
.controller('LoginCtrl', function($scope, $ionicPopup, $state, Auth) {
$scope.data = {};
$scope.login = function() {
Auth.login($scope.data.email, $scope.data.password).then(function() {
$state.go("tab-discover");
})
.error(function() {
var alertPopup = $ionicPopup.show({
title: 'Mauvais identifiants',
template: 'Veuillez recommencer'
});
});
}
$scope.signup = function() {
Auth.signup($scope.data.email, $scope.data.password)
.error(function() {
var alertPopup = $ionicPopup.show({
title: 'Erreur',
template: 'Un probleme est survenu'
});
});
}
})
And the services.js
.factory("Auth", function(FURL, $firebaseAuth) {
var ref = new Firebase(FURL);
var auth = $firebaseAuth(ref);
var Auth = {
user: {},
login: function(email, password){
console.log("loginService", email, password);
return ref.authWithPassword({
"email": email,
"password": password
}, function(error, authData) {
if (error) {
console.log("La connexion a echoué!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
})
},
signup: function(email, password){
console.log("signupService", email, password);
return ref.createUser({
"email": email,
"password": password
}, function(error, userData) {
if (error) {
switch (error.code) {
case "EMAIL_TAKEN":
console.log("The new user account cannot be created because the email is already in use.");
break;
case "INVALID_EMAIL":
console.log("The specified email is not a valid email.");
break;
default:
console.log("Error creating user:", error);
}
} else {
console.log("Successfully created user account with uid:", userData.uid);
}
}).then(function(){
return Auth.login(email, password);
})
}
}
return Auth;
})
It looks like firebase is using callbacks where you're trying to return it as a promise with then. A simple fix would be to pass a callback to your login function and call it inside the firebase callback:
login: function(email, password, callback, onError){
console.log("loginService", email, password);
ref.authWithPassword({
"email": email,
"password": password
}, function(error, authData) {
if (error) {
onError(error);
} else {
callback(authData);
}
})
Then call it like this:
Auth.login($scope.data.email, $scope.data.password, function (data) {
console.log("Authenticated successfully with payload:", data);
$state.go("tab-discover");
}, function (error) {
console.log("La connexion a echoué!", error);
});

Angular firebase, cant login using factory

I get an error when i try to login using this code. The part of creating the user works perfectly and the login methods I used are nearly identical. But chrome gives me this error message:
TypeError: undefined is not a function
at Object.loginUser (http://localhost:8080/js/app.js:28:10)
at Scope.HomeController.$scope.loginUser (http://localhost:8080/js/app.js:197:9)
This is the html:
<button ng-click="createUser(email, password)">Create user</button>
<button ng-click="loginUser(email, password)">Login</button>
In the controller:
$scope.createUser = function(email, password) {
Auth.createUser(email, password);
}
$scope.loginUser = function(email, password) {
Auth.loginUser(email, password);
}
And the factory:
(function () {
angular
.module("myQuiz")
.factory("Auth", ["$firebaseAuth", function($firebaseAuth) {
var ref = new Firebase("https://angularquiz.firebaseio.com/");
return {
createUser: function(email, password) {
ref.createUser({
email: email,
password: password
}, function(error, userData) {
if(error) {
console.log("Error creating user: ", error);
} else {
console.log("Succesfully created an account with uid: " + userData.uid);
}
});
},
loginUser: function(email, password) {
ref.authwithPassword({
email: email,
password: password
}, function(error, authData) {
if(error) {
console.log("Login failed! " + error);
} else {
console.log(authData + "Succesfully authenticated!");
}
});
}
}
}]);
})();
typo, its authWithPassword not authwithPassword!
it works now

Resources