Authorized user can't create new user [Firebase] - javascript

I use angular2 + firebase.
There's something wrong in my code.
When user is logged in, functions createUser and removeUser doesn't work without errors. Without logging in it works properly. I got parts of code from firebase tutorial. The same thing when i'm trying to use google auth service.
app.controller("AuthCtrl", ["$scope", "$firebaseAuth",
function($scope, $firebaseAuth) {
var ref = new Firebase("...");
var Auth = $firebaseAuth(ref)
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$createUser({
email: $scope.email,
password: $scope.password
}).then(function(userData) {
$scope.message = "User created with uid: " + userData.uid;
$scope.email = "";
$scope.password = "";
}).catch(function(error) {
$scope.error = error;
});
};
$scope.removeUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$removeUser({
email: $scope.email,
password: $scope.password
}).then(function() {
$scope.message = "User removed";
$scope.email = "";
$scope.password = "";
}).catch(function(error) {
$scope.error = error;
});
};
$scope.login = function(){
Auth.$authWithPassword({
email: $scope.emaillog,
password: $scope.passwordlog
}).then(function(authData) {
$scope.authData = Auth.$getAuth();
console.log("Logged in as:", authData.uid);
}).catch(function(error) {
console.error("Authentication failed:", error);
});
}
}
]);
<div ng-app="App">
<div ng-controller="AuthCtrl">
<div>
<h2>Login</h2>
<form>
Email: <input ng-model="emaillog" type="text" placeholder="email">
Password: <input ng-model="passwordlog" type="text" placeholder="password">
<br><br>
<button ng-click="login()">Login</button>
</form>
</div>
<div ng-if = "authData">
<h2>Managing users</h2>
<form>
Email: <input ng-model="email" type="text" placeholder="email">
Password: <input ng-model="password" type="text" placeholder="password">
<br><br>
<button ng-click="createUser()">Create User</button>
<button ng-click="removeUser()">Remove User</button>
<p ng-if="message">Message: <strong>{{ message }}</strong></p>
<p ng-if="error">Error: <strong>{{ error }}</strong></p>
</form>
</div>
</div>
</div>
I've found the answer here what is the difference between ng-if and ng-show/ng-hide

Related

Local storage is missing an ID Token, Please authenticate

Getting Local storage is missing an ID Token, Please authenticate. My end goal is to get the user signed up through AWS Cognito and then add a row in my DynamoDB table. I am able to get the user in the user pool but not able to add the details to DynamoDB. Unable to figure out the error any help will be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Javascript SDK-->
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.410.0.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.min.js"></script>
<script src="https://rawgit.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js"></script>
</head>
<body>
<fieldset >
<h1 class="h3 mb-3 font-weight-normal" id="titleheader">Register an Account</h1>
<form>
<input type="email" class="form-control" id="emailInputRegister" placeholder="Email" pattern=".*" required><br><br>
<input type="password" class="form-control" id="passwordInputRegister" placeholder="Password" pattern=".*" required><br><br>
<input type="personalname" class="form-control" id="personalnameRegister" placeholder="First Name" pattern=".*" required><br><br>
<input type="personalname2" class="form-control" id="personalnameRegister2" placeholder="Last Name" pattern=".*" required><br><br>
<input type="text" class="form-control" id="organizationRegister" placeholder="Organization" pattern=".*" required><br><br>
<input type="text" class="form-control" id="jobTitleRegister" placeholder="JobTitle" pattern=".*" required><br><br>
<input type="tel" class="form-control" id="phone" placeholder="Cell Phone Number" pattern=".*" required><br><br>
<button id="mainbutton" class="btn btn-lg btn-primary btn-block" type="button" onclick="registerButton()" >Sign Up</button>
</form>
</fieldset >
<script>
var username;
var password;
var firstname;
var lastname;
var jobtitle;
var organization;
var phonenumber;
var poolData;
function registerButton() {
username = document.getElementById("emailInputRegister").value;
password = document.getElementById("passwordInputRegister").value;
firstname = document.getElementById("personalnameRegister").value;
lastname = document.getElementById("personalnameRegister2").value;
organization = document.getElementById("organizationRegister").value;
jobtitle = document.getElementById("jobTitleRegister").value;
phonenumber = document.getElementById("phone").value;
poolData = {
UserPoolId :<userPoolId>,
'
ClientId : <client id>
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name : 'email',
Value : username, //get from form field
};
var dataFirstName = {
Name : 'name',
Value : firstname, //get from form field
};
/*var dataLastName ={
Name : 'family name',
Value : lastname,
};
var dataPhoneNumber ={
Name : 'family name',
Value : lastname,
};*/
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePersonalName = new AmazonCognitoIdentity.CognitoUserAttribute(dataFirstName);
attributeList.push(attributeEmail);
attributeList.push(attributePersonalName);
var temp;
userPool.signUp(username, password, attributeList, null, function(err, result){
if (err) {
alert(err.message || JSON.stringify(err));
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
//var cognitoUser = userPool.getCurrentUser();
//console.log('cognitoUser =',cognitoUser);
//change elements of page
//document.getElementById("titleheader").innerHTML = "Check your email for a verification link";
//});
//var userPool1 = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
//console.log('userPool',userPool1);
//var cognitoUser = userPool1.getCurrentUser();
//console.log("temp is ", cognitoUser);
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err);
return;
}
console.log('session validity: ' + session.isValid());
console.log('session token: ' + session.getIdToken().getJwtToken());
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : <Identity_Pool>,
Logins : {
// Change the key below according to the specific region your user pool is in.
'cognito-idp.us-east-1.amazonaws.com/${Identity_Pool}' : session.getIdToken().getJwtToken()
}
});
AWS.config.credentials.get(function(err) {
if (!err) {
var id = AWS.config.credentials.identityId;
console.log('Cognito Identity ID '+ id);
// Instantiate aws sdk service objects now that the credentials have been updated
var docClient = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var params = {
TableName: 'TestTable',
Item:{emailId:username, }
};
docClient.put(params, function(err, data) {
if (err)
console.error(err);
else
console.log(data);
});
}
});
});
} else {
console.log(err);
return;
}
});
}
</script>
</body>
</html>
You can use an API for Dynamodb operations with docClient.put()

Registering new login Information Angular JS

Hi I'd like to have new users register their name and password and have it pushed into the users array. It works in plain Javascript, but for some reason my Angular JS won't.
HERES THE ANGULAR JS
var users = [
{
username: 'Regie',
password: 'Tano'
},
{
username: 'Jacob',
password: 'Minshall'
},
{
username: 'Greg',
password: 'Mayer'
}
]
app.controller("logIn", function($scope){
$scope.log = function(){
//Get Values of Inputs for username and password
var username= document.getElementById('username').value
var password = document.getElementById('password').value
//Loop through users to check if username and password are correct.
for(i = 0; i < users.length; i++){
if(username == users[i].username && password == users[i].password){
alert('That Username or Password is already taken')
}
}
}
});
//REGISTER USER**********
app.controller("registerUser", function($scope){
$scope.place = function(){
var registerName = document.getElementById('registerName').value
var registerPass = document.getElementById('registerPass').value
var newUser = {
username: registerName,
password: registerPass
}
users.push(newUser)
console.log(users)
}
});
HERE'S THE HTML
<body ng-app='myApp'>
<form id='form' ng-controller='logIn'>
<h1>Log In</h1>
<input type="text" id="username" placeholder="Enter Username" />
<input type="password" id="password"placeholder="Enter Password" />
<button id="button" type="button" ng-click='log()'>Click This</button>
</form>
<form id='form2' ng-controller='registerUser'>
<h1>Register</h1>
<input type='text' id='registerName' placeholder='Enter Username'/>
<input type='password' id='registerPass' placeholder='Enter Password'/>
<button id='registerButton' type='button' ng-click='place()'>Register</button>
</form>
In angular you should not access to the DOM directly, instead use directives as ng-model.
So, you html should be something like this:
<body ng-app='myApp'>
<form id='form' ng-controller='logIn'>
<h1>Log In</h1>
<!-- Using ng-model is how you bind data from the view to the controller in AngularJS -->
<input type='text' ng-model='username' placeholder='Enter Username' />
<input type='password' ng-model='password' placeholder='Enter Password' />
<!-- we send the binded data to the function as parameters -->
<button id="button" type="button" ng-click='log(username, password)'>Click This</button>
</form>
<form id='form2' ng-controller='registerUser'>
<h1>Register</h1>
<!-- Using ng-model is how you bind data from the view to the controller in AngularJS -->
<input type='text' ng-model='registerName' placeholder='Enter Username'/>
<input type='password' ng-model='registerPass' placeholder='Enter Password'/>
<!-- we send the binded data to the function as parameters -->
<button id='registerButton' type='button' ng-click='place(registerName, registerPass)'>Register</button>
</form>
</body>
And your controllers:
var users = [
{
username: 'Regie',
password: 'Tano'
},
{
username: 'Jacob',
password: 'Minshall'
},
{
username: 'Greg',
password: 'Mayer'
}
]
app.controller("logIn", function($scope){
// This is the username and password in the html
$scope.username = ''; // ng-model="username"
$scope.password = ''; // ng-model="password"
$scope.log = function(username, password){
//Loop through users to check if username and password are correct.
for(i = 0; i < users.length; i++){
if(username == users[i].username && password == users[i].password){
alert('That Username or Password is already taken')
}
}
}
});
//REGISTER USER**********
app.controller("registerUser", function($scope){
// This is the registerName and registerPass in the html
$scope.registerName = ''; // ng-model="registerName"
$scope.registerPass = ''; // ng-model="registerPass"
// Instead of read the data in the model, we pass them as parameters. Doing this is better for testing.
$scope.place = function(registerName, registerPass){
var newUser = {
username: registerName,
password: registerPass
}
users.push(newUser)
console.log(users)
}
});

AngularJS 'Cannot read property 'then' of undefined'

I've this problem, when I click on login button, the chrome console log this:
angular.min.js:117 TypeError: Cannot read property 'then' of undefined
at m.$scope.logIn (loginModuleController.js:11)
Service:
angular.module('loginModule')
.factory('loginService', function($http){
return{
login: function(username, password){
var session;
$http.post('../server/php/auth/auth.php', {
username: username,
password: password
})
.then(function(res){
session = res;
});
return session;
},
isLogged: function(){
return $http.get('../angCMS/server/php/auth.php?is_logged=true');
},
logOut: function(){
return $http.get('../angCMS/server/php/auth.php?logout=true');
}
};
});
controller:
angular.module('loginModule')
.controller('LoginCtrl', ['$scope', 'loginService', function($scope, loginService){
$scope.auth = false;
$scope.username;
$scope.password;
$scope.logIn = function(){
loginService.login($scope.username, $scope.password).then(function(response){
}, function(res){
});
};
$scope.isLogged = function(){
loginService.isLogged()
.then(function(response){
if(response){
$scope.auth = true;
}
});
};
$scope.logOut = function(){
loginService.logOut()
.then(function(response){
if(response){
$scope.auth = false;
}
});
};
}]);
and this is the html template:
<div class="container" ng-if="auth==false">
<div class="col-md-4 col-md-offset-4">
<div class="row">
<br/><h2 align="center">Login</h2>
</div>
<div class="well">
<form class="form-horizontal">
<fieldset>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" ng-model="username" required>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" ng-model="password" required>
</div>
<div class="form-group">
<button class="btn btn-md btn-primary btn-block" type="submit" ng-click="logIn()">Sign in</button>
</div>
</fieldset>
</div>
</form>
</div>
</div>
PHP login method:
public function login($user, $pass){
$user = htmlspecialchars(trim($user));
$pass = md5(htmlspecialchars(trim($pass)));
$res = $this->DB->prepare("SELECT * FROM `admin` WHERE username = :user");
if(!$res->execute(Array(":user"=>$user)))
die(mysql_error());
$row = $res->fetch(PDO::FETCH_ASSOC);
if(!$row['password'] == $pass)
die("Errore: password errata!");
$_SESSION['logged'] = $row;
array_push($session, $_SESSION['logged'], true);
return $session;
}
This is more of a misuse of promises issue.
You might want to first take a look of how promises work:
https://docs.angularjs.org/api/ng/service/$q
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
From your service code:
login: function(username, password){
var session;
$http.post('../server/php/auth/auth.php', {
username: username,
password: password
})
.then(function(res){
session = res;
});
return session;
}
When login(username, password) is called, session is still undefined upon returning.
This is because $http.post() is an asynchronous function, the .then() clause does not get executed immediately.
As pointed out by Snixtor's answer,
you should "return the return value of $http.post()":
login: function(username, password){
return $http.post('../server/php/auth/auth.php', {
username: username,
password: password
});
}
Then referring to your controller's logIn method:
$scope.logIn = function(){
loginService.login($scope.username, $scope.password).then(function(response){
// response === 'session'
}, function(res){
});
};
the response parameter from loginService.login().then() is exactly the value of your intended session variable from your previous implementation.
You're returning an unassigned variable named "session". So what you are doing here in your logged in method is returning undefined. Undefined does not have a method called then.
login: function(username, password){
var session;
$http.post('../server/php/auth/auth.php', {
username: username,
password: password
})
.then(function(res){
session = res;
});
return session;
},
My guess is you actually want to return the $http.post method, which in turn returns a promise. That way you can use the session in the controller?
Your service function login is failing to return the promise created by the call to $http.post. Instead, you need this:
login: function(username, password){
return $http.post('../server/php/auth/auth.php', {
username: username,
password: password
});
}
Note too that I've removed the session variable from the function. It's the then function in your controller that needs to be dealing with the response.
Your isLogged and logOut functions look good already. Just repeat that pattern.

How do I return strings from an asynchronous POST request?

I'm trying to add a signup function, using a controller and a factory, to my Angular app, but I haven't been able to get several strings (tied conditionally to success or failure) to return from my factory to my controller.
The return statements below only return empty strings at first (I assume this has to do with the asynchronous http, but am not sure). In any case, how would I return the two strings I desire (_alertType and _alertMessage) with the updated values from .success or .error?
signup.html
<div class="col-md-6 container-fluid">
<div class="jumbotron text-center" ng-controller="SignupController as vm">
<p class="lead">
<h2>Account Creation</h2>
Welcome! Please make an account
</p>
<form ng-submit="vm.signup()">
<p><input type="text" name="username" value="" placeholder="Username or Email" ng-model="username"></p>
<p><input type="password" name="password" value="" placeholder="Password" ng-model="password"></p>
<p class="submit"><input type="submit" name="commit" value="Sign Up"></p>
<alert ng-show="vm.alertMessage" type="{{ vm.alertType }}">{{ vm.alertMessage }}</alert>
</form>
</div>
</div>
signup.factory.js
(function() {
angular
.module('app')
.factory('signupFactory', signupFactory);
signupFactory.$inject = ['$http'];
function signupFactory($http) {
var _alertType = '';
var _alertMessage = '';
var service = {
signup: signup,
getAlertType: getAlertType,
getAlertMessage: getAlertMessage
};
return service;
function signup(username, password) {
var request = $http({
method: 'POST',
url: 'http://localhost:8080/user',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: username,
password: password
}
});
request.success(function(){
_alertType = "success";
_alertMessage = "Signed Up";
});
request.error(function(){
_alertType = "danger";
_alertMessage = "Signup Failed";
});
}
function getAlertType() {
return _alertType;
}
function getAlertMessage() {
return _alertMessage;
}
}
})();
signup.controller.js
(function() {
'use strict';
angular
.module('app')
.controller('SignupController', SignupController);
SignupController.$inject = ['$scope', 'signupFactory'];
function SignupController($scope, signupFactory) {
var vm = this;
vm.signup = function() {
signupFactory.signup($scope.username, $scope.password);
vm.alertMessage = signupFactory.getAlertMessage();
vm.alertType = signupFactory.getAlertType();
}
}
})();
You should look for promises
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});

Roles - Parse.com Javascript

At the moment I have javascript that allows all users from the (_User) table to log in. I have set up a Role called (Admins) within the role table and assigned one user to this role. Would this be an if statement?
At the moment this is how the user logs in successfully
$scope.logIn = function(form) {
Parse.User.logIn(form.username, form.password, {
success: function(user) {
$scope.currentUser = user;
$scope.$apply();
window.location.href = "TEST.html";
},
It's easy to check whether any user belongs to a role. The only tricky part is to realize that the check includes a query, and is therefore an asynchronous operation. So first, a general purpose role checking function:
function userHasRole(user, roleName) {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", roleName);
query.equalTo("users", user);
return query.find().then(function(roles) {
return roles.length > 0;
});
}
This returns a promise that will be fulfilled with a boolean, so you can call it like this:
var currentUser = Parse.User.current();
// is the user an "admin"?
userHasRole(currentUser, "admin").then(function(isAdmin) {
console.log((isAdmin)? "user is admin" : "user is not admin");
});
Apply it like this in your code. In the view:
<form role="form" name="loginForm">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" ng-model="user.username" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" ng-model="user.password" />
</div>
<div class="form-group">
<button class="btn btn-ar btn-primary" ng-click="pressedLogIn()">Log in</button>
</div>
</form>
And in the controller:
(function() {
'use strict';
angular.module('myApp.controllers').controller('LogInController', LogInController);
LogInController.$inject = ['$scope'];
function LogInController($scope) {
$scope.user = { username:"", password:""};
function userHasRole(user, roleName) {
// defined exactly as above
// my real app has a user service, and this would be better placed there
}
$scope.pressedLogIn = function() {
if ($scope.loginForm.$valid) {
Parse.User.logIn($scope.user.username, $scope.user.password).then(function(user) {
$scope.user = user;
return userHasRole(user, "administrator");
}).then(function(isAdmin) {
alert("user is admin = " + isAdmin);
}, function(e) {
alert(error.message);
});
}
};
}
})();

Categories