no response after axios.post() - vue.js

Hey I'm working on a Login system on my vue project and have the problem that there seems to be no response from the backend.
This is the backend function:
auth.post('/login', async function (req, res) {
const { email, password } = req.body;
console.log(req);
if(email !== "" && password !== "") {
const account = await User.findOne({ where: { email: email} });
if (account) {
if (await account.validPassword(password)) {
// Generate an access token
const accessToken = jwt.sign({ id: account.id }, SECRET);
const account_data =
{
'id': account.id,
'firstName': account.firstName,
'lastName': account.lastName,
'email': account.email,
'isAdmin': account.isAdmin
}
res.send({accessToken, account_data});
} else {
res.status(200).json("Username or password incorrect");
}
} else {
res.send('Username or password incorrect');
}
} else {
res.send('Username or password incorrect');
}
})
This is the method were I call the action
methods: {
async loginUser(){
let user = await this.$store.dispatch('loginUser', this.loginInfo);
if(user.error){
alert(user.error)
} else {
alert('Thank you for signing in, ' + user.firstName);
}
},
}
This is the action:
async loginUser({commit}, loginInfo){
console.log(loginInfo)
try{
let response = await axios({
method: 'POST',
url: 'http://localhost:4000/api/auth/login',
data: loginInfo,
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}});
let user = response.data;
console.log(user);
commit('SET_CURRENT_USER', user);
} catch (e){
alert(e);
return {e}
}
}
Neither the console.log in the try function or in the catch function is triggered.

Related

React Native - FETCH Response is empty - API Status 500 - POST Call

signIn = () => {
//post data to express backend
fetch('http://10.0.2.2:3000/api/v1/auth', {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: `login=${this.state.login}&password=${this.state.password}`
})
.then((response) => response.json())
.then ((res => {
if(res.status === 200) {
AsyncStorage.setItem('user', this.state.login);
this.props.navigation.navigate('Authorized')
} else {
alert("Response:", res);
}
}))
.done();
}
The above is for React-Native. And below is the express backend:
router.post('/', function(req,res){
var login= req.body.login;
var password = req.body.password;
var sql = `SELECT * FROM users WHERE username = '${login}' OR number = '${login}' AND password = ${password}`
db.query(sql, function (err, rows, fields) {
if (err) {
res.status(500).send({error: 'Something went wrong!'})
} else {
if(rows.length > 0) {
if (rows[0].password == password) {
res.status(200).send({success: 'Login Successful'})
}
} else {
res.status(404).send({error: 'Email or Password does not match!'})
}
}
})
});
I think there is nothing getting into a response or maybe some other problem which I am unable to figure out the moment.

user.setPassword is not a function - passport local mongoose

I am implementing a reset password feature on for the users of my website. However, it seems to throw this error when the user confirms new password at the reset.ejs page.
The following steps are being performed correctly:
Token sent on mail
When clicked on token, new password page opens
When user enters new password and confirm new password and hits the button to save the new password, the function in users.js user.setPassword does not work as the error is mentioned below. It is a built in function of passport-local-mongoose.
ERROR: user.savePassword is not a function
Including all the code files below:
users.js:
var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({dest: './uploads'});
var passport = require('passport');
var mongoose = require('mongoose');
var LocalStrategy = require('passport-local').Strategy;
var randomstring = require("randomstring");
var User = require('../models/user');
var data=require('../models/data');
var checklist=require("../models/checklist");
var async = require("async");
var crypto = require("crypto");
var passportLocalMongoose=require("passport-local-mongoose");
// "use strict";
const nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'dataseedltd#gmail.com',
pass: 'mypassword'
}
});
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register/:type', function(req, res, next) {
res.render('user/register.ejs',{title:'Register',type:req.params.type});
});
router.get('/login', function(req, res, next) {
res.render('user/login.ejs', {title:'Login'});
});
router.post('/login',
passport.authenticate('local',{failureRedirect:'/users/login', failureFlash: 'Invalid username or password'}),
function(req, res) {
var previouspath=req.cookies.previouspath;
if(req.cookies.checklist==undefined){
req.flash('success', 'You are now logged in');
if(req.user.as=='seller'){
if(previouspath!=undefined){
if(previouspath.length!=0)
res.redirect(previouspath);
else
res.redirect('/buyer');
}
else
res.redirect('/buyer');
}
else {
if(previouspath!=undefined){
if(previouspath.length!=0)
res.redirect(previouspath);
else
res.redirect('/buyer');
}
else
res.redirect('/buyer');
}
}
else{
var ids=req.cookies.checklist['data']
var checks=[];
for(var i=0;i<ids.length;i++){
checks.push({user:req.user,data:ids[i]});
}
checklist.insertMany(checks,function(err, d) {
if(err)console.log(err);
res.clearCookie('checklist');
req.flash('success', 'You are now logged in');
if(req.user.as=='seller'){
if(previouspath.length!=0)
res.redirect(previouspath);
else
res.redirect('/seller')
}
else {
if(previouspath.length!=0)
res.redirect(previouspath);
else
res.redirect('/buyer')
}
});
}
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(function(username, password, done){
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) return done(err);
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message:'Invalid Password'});
}
});
});
}));
router.post('/register/:type',function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var institution=req.body.institution;
var education=req.body.education;
var proffession=req.body.proffession;
var country=req.body.country;
//check if email does not already exists
//check if username does not already exists
User.find({ $or: [ { email: { $eq: req.body.email } }, { username: { $eq: req.body.username } } ] },function(err,data){
if(err)console.log(err);
if(data.length!=0){
console.log(data.length);
req.flash('success','email or username is repeated.');
res.redirect('/users/register/'+req.params.type);
}
else
{
var password = req.body.password;
var password2 = req.body.password2;
var as =req.params.type;
// Form Validator
req.checkBody('name','Name field is required').notEmpty();
req.checkBody('email','Email field is required').notEmpty();
req.checkBody('email','Email is not valid').isEmail();
req.checkBody('username','Username field is required').notEmpty();
req.checkBody('password','Password field is required').notEmpty();
// Check Errors
var errors = req.validationErrors();
if(errors){
res.render('user/register.ejs', {
errors: errors
});
} else{
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
as :as,
institution:institution,
education:education,
proffession:proffession,
country:country
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
// res.location('/');
var token=randomstring.generate(7);
var to=req.body.email;
var subject='Email Confirmation from dataSeed ';
var message='<h1>Use this code to register </h1><p>Your verification Code is: <h2>'+token+'</h2></p>';
var mailOptions=sendmail(to,subject,message);
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
}
else
{
res.render('user/emailconfirmation.ejs',{username:req.body.username,token:token});
}
});
}
}
});
function sendmail(to,subject,message){
var mailOptions = {
from: 'dataseedltd#gmail.com',
to: to,
subject: subject,
html: message
};
return mailOptions;
}
router.post('/emailconfirmation/:token',function(req, res) {
if(req.params.token==req.body.token){
req.flash('success', 'You are now registered and can login');
res.redirect('/');
}
else{
User.remove({username:req.body.username},function(err,data){
if(err)console.log(err);
res.redirect('/');
});
}
});
});
router.get('/logout', function(req, res){
req.logout();
req.flash('success', 'You are now logged out');
res.redirect('/users/login');
});
//Forgot Password
router.get('/forgot',function(req,res){
res.render("forgotpassword.ejs");
});
router.post('/forgot', function(req, res, next) {
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
req.flash('success', 'No account with that email address exists.');
return res.redirect('/users/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'dataseedltd#gmail.com',
pass: 'mypassword'
}
});
var mailOptions = {
to: user.email,
from: 'dataseedltd#gmail.com',
subject: 'Node.js Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/users/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
console.log('mail sent');
req.flash('success', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
done(err, 'done');
});
}
], function(err) {
if (err) return next(err);
res.redirect('/users/forgot');
});
});
router.get('/reset/:token', function(req, res) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('success', 'Password reset token is invalid or has expired.');
return res.redirect('/users/forgot');
}
res.render('reset', {token: req.params.token});
});
});
router.post('/reset/:token', function(req, res) {
async.waterfall([
function(done) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('back');
}
if(req.body.password === req.body.confirm) {
user.setPassword(req.body.password, function(err) {
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
req.logIn(user, function(err) {
done(err, user);
});
});
})
} else {
req.flash("error", "Passwords do not match.");
return res.redirect('back');
}
});
},
function(user, done) {
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'dataseedltd#gmail.com',
pass: 'mypassword'
}
});
var mailOptions = {
to: user.email,
from: 'dataseedltd#gmail.com',
subject: 'Your password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('success', 'Success! Your password has been changed.');
done(err);
});
}
], function(err) {
res.redirect('/login');
});
});
module.exports = router;
users.js (model):
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var passportLocalMongoose=require("passport-local-mongoose");
mongoose.connect('mongodb://localhost/dataseed');
var db = mongoose.connection;
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
profileimage:{
type: String
},
as:{
type:String
},
institution:{
type:String
},
education:{
type:String
},
proffession:{
type:String
},
country:{
type:String
},
resetPasswordToken: String,
resetPasswordExpires: Date
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
callback(null, isMatch);
});
}
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
It seems like you don't have a method called setPassword defined under user model. This is mainly because you haven't plugin the passport-local-mongoose to UserSchema. Add UserSchema.plugin(passportLocalMongoose); before creating the model from UserSchema. like this
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var passportLocalMongoose=require("passport-local-mongoose");
mongoose.connect('mongodb://localhost/dataseed');
var db = mongoose.connection;
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
profileimage:{
type: String
},
as:{
type:String
},
institution:{
type:String
},
education:{
type:String
},
proffession:{
type:String
},
country:{
type:String
},
resetPasswordToken: String,
resetPasswordExpires: Date
});
UserSchema.plugin(passportLocalMongoose);
var User = module.exports = mongoose.model('User', UserSchema);

user.comparePassword is not a function

I got stuck on hashed password validation with bcrypt-nodejs, nodeJS (expressJS) and mongoose. User can register and code generates hashed password but when I try to validate that password with comparePassword function in login page it does not work and gives me error user.comparePassword is not a function
Here is the code:
Database:
UserSchema.pre('save', async function(next){
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt){
if(err) return next(err)
bcrypt.hash(user.password, salt,null, function(err,hash){
if(err) return next(err)
user.password = hash
next()
})
})
})
UserSchema.methods.comparePassword = async function(candidatePassword, cb){
bcrypt.compare(candidatePassword, this.password, function(err, isMatch){
if(err) return cb(err);
cb(null, isMatch)
})
}
Route:
router.post('/', async (req, res) => {
try {
const {username, password} = req.body;
const user = await User.findOne({username}).lean();
if (!user) {
return res.status(404).send({
message: 'user is not registered'
});
}
if(username.trim().length < 1 && password.trim().length < 1){
return res.status(409).send({message: 'username & password is required'})
}
// if (user.password !== password) {
// return res.status(403).send({
// message: 'user password invalid'
//});
//}
user.comparePassword(password, function(err, isMatch){
if(err){
return res.status(500).send({message: err.message})
}
if(!isMatch){
return res.status(403).send({
message: 'user password invali'
});
}
req.session.user = user;
const redirectTo = '/dashboard';
if (
req.is('application/json') // request content type is json
|| // or
req.xhr // is ajax
) {
// respond with json response
return res.status(200).send({redirectTo});
}
// not ajax request
// then respond redirect header
res.redirect(redirectTo);
})
const mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
SALT_WORK_FACTOR = 10;
const userDataModal = mongoose.Schema({
username: {
type: String,
required : true,
unique:true
},
password: {
type: String,
required : true
}
});
userDataModal.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
userDataModal.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
// Users.index({ emaiId: "emaiId", fname : "fname", lname: "lname" });
const userDatamodal = module.exports = mongoose.model("usertemplates" , userDataModal)
//inserting document
userDataModel.findOne({ username: reqData.username }).then(doc => {
console.log(doc)
if (doc == null) {
let userDataMode = new userDataModel(reqData);
// userDataMode.password = userDataMode.generateHash(reqData.password);
userDataMode.save({new:true}).then(data=>{
let obj={
success:true,
message: "New user registered successfully",
data:data
}
resolve(obj)
}).catch(err=>{
reject(err)
})
}
else {
resolve({
success: true,
docExists: true,
message: "already user registered",
data: doc
}
)
}
}).catch(err => {
console.log(err)
reject(err)
})
//retriving and checking
// test a matching password
user.comparePassword(requestData.password, function(err, isMatch) {
if (err){
reject({
'status': 'Error',
'data': err
});
throw err;
} else {
if(isMatch){
resolve({
'status': true,
'data': user,
'loginStatus' : "successfully Login"
});
console.log('Password123:', isMatch); // -> Password123: true
}

Express "Can't set headers after they are sent" after deploying to Heroku

after deploying my server code to Heroku I'm getting the error "Can't set headers after they are sent". I fetch my login data
fetch("url", {
method: "POST",
mode: "cors",
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
//"Content-Type": "application/json"
},
body: requestBody
}).then((res, next) => {
if(res.ok){
res.json().then((json) => {
if(json.verifystate){
this.props.navigation.navigate('Home')
}
else{
this.setState({isAuthentic:false});
}
});
}else{
next();
}
})
And it calls my server post method
app.post('/users/auth', function(req, res) {
loginData(db, req.body.email, req.body.password, req.body.mphone, function(result){
if(result == 1){
res.send({"verifystate":1});
}else if(result == 2){
res.send({"verifystate":2});
}else{
res.send({"verifystate":3});
}
});
//console.log('json: '+JSON.stringify(data));
});
edit: Login function
module.exports = function loginData(db, email, myPlaintextPassword, mphone, callback){
var collectionUser = db.collection('users');
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
var queryStr = {"emails.address": email};
collectionUser.findOne(queryStr, function(err, result) {
if(err)
{
return;
}else if(result != null){
bcrypt.compare(myPlaintextPassword, result.services.password.bcrypt, function(err, res) {
console.log("conpare result: ", res);
if(res){
callback("1");
}else{
callback("3");
}
});
if(!result.services.resume || result.services.resume.appLoginToken == null
|| !result.services.resume.appLoginToken.date || !result.services.resume.appLoginToken.base64Token){
var tokenStr = email + Math.random(1,100);
tokenStr = Base64.encode(tokenStr);
queryStr = {
"services.resume.appLoginToken.date": Date(),
"services.resume.appLoginToken.base64Token": tokenStr
};
var newDate = { "services.resume.appLoginToken.date": Date() }
var temp = {"emails.address": email};
collectionUser.update(temp,
{ $set: {"services.resume.appLoginToken.date": Date()} }, function(err, result) {
if(err)
{
return;
}else {
}
});
collectionUser.update(temp,
{ $set: {"services.resume.appLoginToken.base64Token": tokenStr} }, function(err, result) {
if(err)
{
return;
}else {
}
});
}else{
console.log("already have token");
}
}else{
callback("2")
}
});
});
});
};
And when it gets to res.send({"verifystate:"1}) it then throws the aforementioned error. Any help would be great thanks.
if(!res.headersSent){
res.send('hello world');
}
or
if(!res.headersSent){
res.json({message: 'hello world'});
}
you probably have a callback that fires more than once, often times this is with event emitters.
As a side note, I really recommend using 2 spaces for indentation with JS, because so much code is nested. And I also recommend putting else and .then() on a newline, more readable.
I did not read the whole code but you could try this:
module.exports = function loginData(db, email, myPlaintextPassword, mphone, callback) {
let collectionUser = db.collection('users');
bcrypt.genSalt(saltRounds, function (err, salt) {
bcrypt.hash(myPlaintextPassword, salt, function (err, hash) {
let queryStr = {"emails.address": email};
collectionUser.findOne(queryStr, function (err, result) {
if (err) {
//You should do something here or it would take you to an error , just an return won't work, you've to call a callback that send the error message
//callback(0)
} else if (result !== null) {
if (!result.services.resume || result.services.resume.appLoginToken === null
|| !result.services.resume.appLoginToken.date || !result.services.resume.appLoginToken.base64Token) {
let tokenStr = email + Math.random(1, 100), temp = {"emails.address": email};
tokenStr = Base64.encode(tokenStr);
queryStr = {
"services.resume.appLoginToken.date": new Date(),
"services.resume.appLoginToken.base64Token": tokenStr
};
collectionUser.update(temp,
{$set: {"services.resume.appLoginToken.date": new Date()}}, function (err, result) {
});
collectionUser.update(temp,
{$set: {"services.resume.appLoginToken.base64Token": tokenStr}}, function (err, result) {
});
} else {
console.log("already have token");
}
bcrypt.compare(myPlaintextPassword, result.services.password.bcrypt, function (err, res) {
console.log("conpare result: ", res);
if (res) {
callback(1);
} else {
callback(3);
}
});
} else {
callback(2);
}
});
});
})
};
And this:
app.post('/users/auth', function (req, res) {
loginData(db, req.body.email, req.body.password, req.body.mphone, function (result) {
res.send({verifystate: result});
});
});

Firebase authentication in Ionic not working

I am trying to build an ionic application which does basic authentication.
My registration system is working in terms of pushing data into my Firebase URL and logging the user in, adding user into the Login and Auth system, but my login is not doing proper Authentication. Note, this is just the first step - my aim is the check if the user's UID matches the UID I have stored in firebaseurl/uids/firebasekey/uid. I get this error:
Login Failed! TypeError: Cannot read property 'email' of undefined(…)
this is the error that is caught.
Even though I know the user with that email exists in the Firebase instance.
Here is my LoginCtrl:
.controller('LoginCtrl', ['Auth', '$state', '$location', '$scope', '$rootScope', '$firebaseAuth', '$window',
function (Auth, $state, $location, $scope, $rootScope, $firebaseAuth, $window) {
// check session
//$rootScope.checkSession;
// Create a callback to handle the result of the authentication
$scope.user = {
email: this.email,
password: this.password
};
$scope.validateUser = function (user) {
$rootScope.show('Please wait.. Authenticating');
console.log('Please wait.. Authenticating');
var email = this.user.email;
var password = this.user.password;
/* Check user fields*/
if (!email || !password) {
$rootScope.hide();
$rootScope.notify('Error', 'Email or Password is incorrect!');
return;
}
/* All good, let's authentify */
Auth.$authWithPassword({
email: email,
password: password
}).then(function (authData) {
console.log(authData);
$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
$rootScope.hide();
}).catch(function (error) {
console.log("Login Failed!", error);
if (error.code == 'INVALID_EMAIL') {
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'INVALID_PASSWORD') {
$rootScope.notify('Invalid Password');
}
else if (error.code == 'INVALID_USER') {
$rootScope.notify('Invalid User');
}
else {
$rootScope.notify('Oops something went wrong. Please try again later');
}
$rootScope.hide();
//$rootScope.notify('Error', 'Email or Password is incorrect!');
});
};
this.loginWithGoogle = function loginWithGoogle() {
Auth.$authWithOAuthPopup('google')
.then(function (authData) {
$state.go($location.path('app/meals'));
});
};
this.loginWithFacebook = function loginWithFacebook() {
Auth.$authWithOAuthPopup('facebook')
//Use the authData factory
.then(function (authData) {
$state.go($location.path('app/meals'));
});
};
}
])
And here is my SignupCtrl:
.controller('SignUpCtrl', [
'$scope', '$rootScope', '$firebaseAuth', '$window', 'Auth',
function ($scope, $rootScope, $firebaseAuth, $window, Auth) {
$scope.user = {
firstname: this.firstname,
lastname: this.lastname,
email: "",
password: ""
};
$scope.createUser = function () {
var firstname = this.user.firstname;
var lastname = this.user.lastname;
var email = this.user.email;
var password = this.user.password;
//https://www.firebase.com/docs/web/guide/login/password.html
if (!email || !password) {
$rootScope.notify("Please enter valid credentials");
return false;
}
$rootScope.show('Please wait.. Registering');
$rootScope.auth.$createUser(
{email: email, password: password})
.then(function (user) {
console.log('user is created');
$rootScope.hide();
$rootScope.userEmail = user.email;
var usersRef = new Firebase('https://foodsharingapp.firebaseio.com/users');
var keyRef = usersRef.push({
'uid': user.uid,
'email': email,
'firstname': firstname,
'lastname': lastname
});
var uidRef = new Firebase('https://foodsharingapp.firebaseio.com/uids/' + user.uid + '/' + keyRef.key());
uidRef.set({'registered': true});
$window.location.href = ('#/app/meals');
}, function (error) {
console.log('error unfortunately');
$rootScope.hide();
if (error.code == 'INVALID_EMAIL') {
console.log('invalid email');
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'EMAIL_TAKEN') {
console.log('email taken');
$rootScope.notify('Email Address already taken');
}
else {
console.log('not sure what happened');
$rootScope.notify('Oops something went wrong. Please try again later');
}
});
}
Auth.$onAuth(function (user) {
if (user === null) {
console.log("Not logged in yet");
} else {
console.log("Logged in as", user.uid);
}
$scope.user = user; // This will display the user's name in our view
});
}
])
And here is my Auth factory:
app.factory('Auth', ['rootRef', '$firebaseAuth',function(rootRef, $firebaseAuth){
return $firebaseAuth(rootRef);
}]);
And here is my app.js related to Auth:
$rootScope.userEmail = null;
$rootScope.baseUrl = 'https://foodsharingapp.firebaseio.com/';
var authRef = new Firebase($rootScope.baseUrl);
$rootScope.auth = $firebaseAuth(authRef);
$rootScope.authData = authRef.getAuth();
$rootScope.logout = function() {
authRef.unauth();
$rootScope.authDataCallBack;
};
$rootScope.checkSession = function() {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
} else {
console.log("No session so logout");
$rootScope.userEmail = null;
$window.location.href = '#/auth/signin';
}
}
$rootScope.authDataCallBack = function(authData) {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
$window.location.href = '#/auth/signin';
}
};
//Listens for changes
authRef.onAuth($rootScope.authDataCallback);
Note, the other issue is that the onAuth function in the app.js function is not working.
How should I clean up my code? What am I doing wrong? I am using a bunch of tutorials etc and I don't think the right way.
I have figured out the issue.
$rootScope.userEmail = user.email;
I was calling this line when user is actually undefined as a variable (though $scope.user has been defined).
login controller code
function ($scope, $stateParams, $firebaseAuth, $state) {
$scope.user = {
'email': '',
'password': ''
};
$scope.signIn = function(){
$scope.errorBox = '';
const promise = firebase.auth().signInWithEmailAndPassword($scope.user.email, $scope.user.password);
promise.then(resp => {
$state.go('zazzycoinsActivities');
})
.catch(err => {
$scope.$apply(function(){
$scope.errorBox = err.message;
});
});
};
}
this might work for you too it worked for me......