I am trying to find a way to create a simple login form with Angularjs and Firebase. I currently have a simple signup form, which adds a userName into my firebase database. All I need to know is how to get a login page that accepts a user once the userName is identified in the firebase system, and to possibly make a callback error if there is no such userName within the database. This is my signup form:
<html ng-app="myApp">
<body ng-controller="userCtrl">
<div class="centerForm">
<form>
<div class="form-group">
<label for="exampleInputUser">Username</label>
<input type="username" ng-model="userName" class="form-control" id="exampleInputUser" placeholder="username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" ng-model="userPassword" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<table class="nav" align="center">
<tr>
<td>
<p><button type="submit" class="btn btn-primary" ng-click="saveUser()">Submit</button>
Sign Up</p>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
and this is my sign up code:
<script>
angular.module('myApp', [])
.controller('userCtrl', function($scope) {
$scope.userName ="";
$scope.userPassword="";
$scope.myData = new Firebase( "https://myfirebaseapp.firebaseio.com/")
$scope.saveUser = function() {
$scope.myData.push({userName: $scope.userName});
};
});
</script>
My login form would then look something like:
<html ng-app="myApp">
<body ng-controller="userCtrl">
<div class="centerForm">
<form>
<div class="form-group">
<label for="exampleInputUser1">Username</label>
<input type="username" ng-model="userName" class="form-control" id="exampleInputUser1" placeholder="username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" ng-model="userPassword" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<table class="nav" align="center">
<tr>
<td>
<p><button type="submit" class="btn btn-primary" ng-click="loginUser()">Submit</button>
Sign Up</p>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
AngularFire exists for this reason- to bind Angular with Firebase.
Here's a working example. This is the login controller:
var app = angular.module('appName');
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://yourtester.firebaseio.com");
return $firebaseAuth(ref);
}
]);
app.controller('loginCtrl', ['$scope', '$state', '$http', 'Auth',
function($scope, $state, $http, Auth) {
$scope.auth = Auth;
$scope.auth.$onAuth(function(authData) {
$scope.authData = authData;
});
$scope.login = function() {
Auth.$authWithPassword({
email: $scope.email,
password: $scope.password
})
.then(function(authData) {
console.log('Logged in as:', authData.uid);
//$state.go('profile');
})
.catch(function(err) {
console.log('error:',err);
//$state.go('login');
});
};
}
]);
And this is the login.html file:
<body ng-app='appName' ng-controller="loginCtrl">
<h1>Login!</h1>
<form ng-submit='login()'>
<div class="form-group">
<label for="email">Email address</label>
<input id="email" ng-model='email' type="email" placeholder="Email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input id="password" ng-model='password' type="password" placeholder="Password" required>
</div>
<button class="btn btn-success">Login</button>
</form>
I'm using angular JS and my login function for Firebase looks like this in the controller:
app.factory("Auth", ["$firebaseAuth",function($firebaseAuth) {
var ref = new Firebase("https://myfirebaseapp.firebaseio.com");
return $firebaseAuth(ref);
}]);
$scope.login = function() {
$scope.authObj.$authWithPassword({
name: $scope.data.name,
email: $scope.data.email,
password: $scope.data.password
}).then(function(authData) {
authenticated = true;
console.log("Logged in as:", authData.uid, authenticated);
$location.path("profile");
check();
}).catch(function(error) {
authenticated = false;
console.error("Authentication failed:", error);
check();
});
}
Related
I have a controller for signing in firebase
$scope.addUser = function() {
firebase.auth().signInWithEmailAndPassword($scope.Email,$scope.Password).then(function(authData) {
authenticated = true;
console.log("Logged in as:", authData.uid, authenticated);
$location.path("/user_manual");
}).catch(function(error) {
authenticated = false;
console.error("Authentication failed:", error);
$location.path("/");
});
};
And a login.html form
<center><h1>Login</h1></center>
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-2"></div>
<label class="col-sm-2 control-label">Email:</label>
<div class="col-sm-4">
<input class="form-control" id="Email"
ng-model="Email" placeholder="Email"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<label class="col-sm-2 control-label">Password:</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="Password"
ng-model="Password" placeholder="Password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<label class="col-sm-2 control-label"></label>
<div class="col-sm-4">
<a ng-click="addUser()" class="btn btn-small btn-primary">Login</a>
</div>
</div>
</form>
</div>
As I click on login button it doesn't load user_manual.html for the first time but clicking it on three times it loads user_manual.
The same is with logout button:
I have logout function :
scope.logout = function(){
$window.alert("Do you really want to logout?");
firebase.auth().signOut().then(function() {
$location.path("/");
}).catch(function(error) {
});
And a logout button as:
<a ng-click="logout()" ng-confirm-click="Do you want to logout" class="btn btn-small btn-primary">logout</a>
It also redirects to $location.path("/") on clicking the button twice.
Here is the main controller app.js:
var app = angular.module('myApp',['ngRoute','firebase','ng-fusioncharts','chart.js','720kb.datepicker']);
var config = {
*******************************
};
firebase.initializeApp(config);
var user = firebase.auth().currentUser;
app.config(function($routeProvider){
$routeProvider
.when('/', {
controller: 'UserAdd',
templateUrl: 'views/users/user_login.html'
})
.when('/user_manual', {
controller: 'UserManual',
templateUrl: 'views/user_manual/user_manual.html'
})
.otherwise({
redirectTo: '/'
});
});
Why the buttons not work on a single click action?
I have a form inside a bootstrap modal.But I can't able to get the values of form on controller side with scope variable.
https://plnkr.co/edit/FjKXUpoBDdvQqomI97ml?p=preview
My original code has another problem also. when I click on submit button it will refresh the whole page and submit function is not executing.
My form:
<div class="modal-body">
<form class="form-horizontal" name="contact" ng-submit="contactForm()">
<div class="form-group">
<label class="col-lg-3 control-label">Name* :</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="name" name="_name" ng-model="_name" > </div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email* :</label>
<div class="col-lg-8">
<input class="form-control" type="email" id="email" name="_email" ng-model="_email" required> </div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Mobile* :</label>
<div class="col-lg-8 row">
<div class="col-lg-4">
<input type="text" class="form-control" ng-model="_cc" placeholder="+91" name="_cc"> </div>
<div class="col-lg-8">
<input class="form-control" type="text" ng-model="_mobile" maxlength="10" ng-pattern="/^[0-9]{5,10}$/" id="mobile" name="_mobile"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Message :</label>
<div class="col-lg-8">
<textarea class="form-control" rows="2" name="_condition" ng-model="_condition"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-7 col-lg-5">
<button type="submit" class="btn btn-primary" id="contactSubmit" >Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div></div>
</form>
</div>
Controller:
$scope.contactForm = function(){
console.log($scope._condition,$scope._name,$scope._email,$scope._cc,$scope._mobile);
};
You are opening the modal using plain jQuery approach which is not going to work in Angular, because opened modal is not connected to Angular application, so it doesn't know that modal has to be handled, HTML parsed, etc.
Instead you should use directives properly, or in case of modal dialog you can simply use existent ones, like Angular UI project, which brings ready Bootstrap directives for Angular. In your case you need $modal service and inject the $http service to have your data posted.
Here is the working plunker using angular-ui bootstrap.
PLUNKER:https://plnkr.co/edit/rjtHJl0udyE0PTMQJn6p?p=preview
<html ng-app="plunker">
<head>
<script src="https://code.angularjs.org/1.2.18/angular.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
<script src="script.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<form ng-submit="submit()">
<div class="modal-body">
<label>Email address:</label>
<input type="email" ng-model="user.email" />
<label>Password</label>
<input type="password" ng-model="user.password" />
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<input type="submit" class="btn primary-btn" value="Submit" />
</div>
</form>
</script>
<button class="btn" ng-click="open()">Open Modal</button>
</div>
</body>
</html>
JS:
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log,$http) {
$scope.user = {
email: '',
password: null,
};
$scope.open = function () {
$modal.open({
templateUrl: 'myModalContent.html', // loads the template
backdrop: true, // setting backdrop allows us to close the modal window on clicking outside the modal window
windowClass: 'modal', // windowClass - additional CSS class(es) to be added to a modal window template
controller: function ($scope, $modalInstance, $log, user) {
$scope.user = user;
$scope.submit = function () {
$log.log('Submiting user info.'); // kinda console logs this statement
$log.log(user);
$http({
method: 'POST',
url: 'https://mytesturl.com/apihit',
headers: {
"Content-type": undefined
}
, data: user
}).then(function (response) {
console.log(response);
$modalInstance.dismiss('cancel');
}, function (response) {
console.log('i am in error');
$modalInstance.dismiss('cancel');
});
//$modalInstance.dismiss('cancel'); // dismiss(reason) - a method that can be used to dismiss a modal, passing a reason
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
user: function () {
return $scope.user;
}
}
});//end of modal.open
}; // end of scope.open function
};
I'm trying to make a contact form, and the server side is working pretty well. But I don't know how to connect Angular to the html form and send it with Express. Any would appreciate any help.
My Express
router.get('/sendQuote', function(req, res) {
var data = req.query;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
});
So, my html:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">
And the main problem is here, how to glue Angular with HTML and Express. I can send emails, but get undefined in the fields of Name, Email and so on. :
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.sendMail = function () {
$scope.message = {};
$http.get('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
I think you should start by making this request a POST and not a GET request.
router.post('/sendQuote', function(req, res) {
var data = req.body;
var mailOptions = {
from: 'planacte#gmail.com', // sender address
name: data.contactName,
email: data.contactEmail,
to: data.email, // list of receivers
subject: "Request for a Quote from " + data.contactName, // Subject line
text: data.contactMsg, // plaintext body
html: '<p> email: ' + data.contactEmail +
'</p><p> phone: ' + data.contactPhone + '</p><br>'
+data.contactMsg // html body
};
console.log(mailOptions)
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
res.send(200); // let the client know it sent ok.
});
Now, let's take a look at your Angular code. It seems you want the object $scope.message to hold your form fields data. You should define this as an object at the beginning of your controller.
app.controller('MainCtrl', ['$scope', '$interval', '$http', '$location', '$anchorScroll',
function($scope, $interval, $http, $location, $anchorScroll) {
$scope.message = {};
$scope.sendMail = function () {
//$scope.message = {}; -- this was clearing the object
$http.post('/send/sendQuote', $scope.message).
success(function(data, status, headers, config) {
// you can clear $scope.message if you want here
// $scope.message = data.message;
console.log($scope.message)
});
}
}]);
HTML had one ng-model not binding to the message object:
<form id="contact" class="contact-form" ng-submit="sendMail()" novalidate>
<div class="message"></div>
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="name" class="nameform form-control input-lg" placeholder="name" ng-model="message.contactName" required>
</div>
<div class="form-group">
<input type="email" name="email" class="emailform form-control input-lg" placeholder="email" ng-model="message.contactEmail" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="phoneform form-control input-lg" placeholder="phone" ng-model="message.contactPhone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<div class="form-group">
<textarea name="message" class="messageform form-control input-lg" placeholder="custom text" ng-model="message.contactMsg" required></textarea>
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12">
<input type="submit" class="btn btn-custom up form-button" value="Send Message">
after Signup, how to be automatically redirected to the authentificate page and put the login and the password in the form of authenficate.html ?
the signupCtrl
demoApp.controller('signupCtrl',function($scope,$http,$location,User) {
User=$scope.user;
$scope.verification = function(isValid,User) {
User=$scope.user;
if (isValid) {
$scope.message = "Submitted ";
console.log(User);
console.log(User.type);
if(User.type=="recruteur")
{
window.alert("bonjour recruteur "+ User.email);
$location.path("/auth");
}
else {
window.alert("bonjour condidat "+ User.email);
$location.path("/auth");
}
} else {
$scope.message = "There are still invalid fields below";
}
};
});
the SINGUP.html
<body ng-controller="signupCtrl">
<form name="registrationForm" novalidate
ng-submit="submit(registrationForm.$valid)">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-group"
ng-model="user.email"
required />
</div>
<div>
<label>Password</label>
<input type="password" name="password"
ng-model="user.password"
required/>
</div>
<div>
<button type="submit" ng-click="verification(registrationForm.$valid,registrationForm.user)">Register!</button>
</div>
</form>
</body>
controller authentificate:
demoApp.controller('personCtrl',function ($scope, $http,$location,User) {
console.log(User);
var person=User;
$scope.emaill=person.email;
$scope.pwd=person.password;
console.log(person);
});
authentificate page:
<body>
<form>
<input type="text" ng-model="emaill">
<input type="password" ng-model="pwd">
<input type="submit" value="Connexion" ng-click="connexion(person)">
</form>
</body>
the route provider
demoApp.config(['$routeProvider',
function($routeProvider){
//systeme de routage
console.log('rederction');
$routeProvider.when ('/auth',{templateUrl: 'authentficate.html',
controller: 'personCtrl'})
.otherwise({redirectTo: 'Signup.html'}
);
}
]);
You can put the data that is needed for the session in a Service.
https://docs.angularjs.org/guide/services
But dont put the Password there, only the Username and an Authentication token.
Check here for a complete sample for an token based authentication
https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
I am learning how to use AngularJS, and I can't get a custom ng-click function to work. What I want to do is fire a $http.post request that contains data from my forms ($scope.email, $scope.username, $scope.password). So far I've tried only passing in email, but nothing happens when I click the submit button (there is no POST request fired, I am checking this with firebug). I tried passing it directly as $scope.email, or as a variable (as shown below).
I have a main page (index.html), that uses ng-view to load html using ngRoute. This the the route code:
.when('/register', {
templateUrl: 'views/register.html',
controller: 'RegisterCtrl'
})
Here is my register.html:
<div class="container">
<div class="col-xs-2 col-sm-3 col-md-4"></div>
<div class="col-xs-8 col-sm-6 col-md-4">
<h1>Sign Up:</h1>
<form>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" ng-model="email">
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" ng-model="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" ng-model="password">
</div>
<button type="submit" class="btn btn-primary col-xs-5" ng-click="register">Sign up</button>
<div class="col-xs-2"></div>
<button class="btn btn-info col-xs-5">Go to log in</button>
</form>
</div>
</div>
and my controller:
'use strict';
angular.module('angularApp')
.controller('RegisterCtrl', function ($scope, $http) {
$scope.email = '';
$scope.username = '';
$scope.password = '';
$scope.register = function() {
// TODO ADD VALIDATION
var email = $scope.email;
var username = $scope.username;
var password = $scope.password;
// $http request
$http.post('http://localhost/PTC/API/new_user.php', email).
success(function(data) {
console.log(data);
}).
error(function(data) {
console.log(data);
});
};
});
it should have function () brackets to call function like ng-click="register()"
OR for more better way rather than using ng-click on form you could replace it with ng-submit directive
Markup
<form name="myForm" ng-click="register()">
...fields here..
<button type="submit" class="btn btn-primary col-xs-5">Sign up</button>
<div class="col-xs-2"></div>
<button class="btn btn-info col-xs-5">Go to log in</button>
</form>
Additionally you need to give form name to your form, so that you could get better controller over form validation.