AngularJS + PHP. Login panel - javascript

I have very big problem with login panel. I am still learning AngularJS.
Can you help me with login panel? Here is my code guys. I don't know what I should do now:
api.php:
public function getLogin()
{
$sql = "SELECT login FROM users WHERE login='$username' AND password='$password'";
return $this->db->fetchAll();
}
$app->get('/login', function () use ($app, $DataProvider) {
$login = $DataProvider->getLogin();
return $app->json($login);
});
login.html:
<div class="row">
<div class="col-lg-10 col-sm-10 col-xs-12">
<div class="flat-panel">
<div class="flat-panel-header">
<h3 class="flat-panel-heading">Panel logowania</h3>
</div>
<div class="flat-panel-body">
<div class="form-group">
<input type="text" class="form-control" ng-model="loginInfo.username" placeholder="Podaj login">
</div>
<div class="form-group">
<input type="password" class="form-control" ng-model="loginInfo.password" placeholder="Podaj hasło">
</div>
<div class="form-group">
<button ng-click="loginUser()" class="btn btn-primary">Zaloguj</button>
</div>
</div>
</div>
</div>
</div>
services.js:
app.factory('login', ['$http', function($http){
var _getLogin = function (callback) {
callback = callback||function(){};
$http.get('/api.php/login')
.success(function (data) {
callback(data);
});
};
return {
getLogin: _getLogin
};
app.js:
app.controller("LoginController", function($scope, $http){
$scope.loginInfo = {
username: undefined,
password: undefined
}
$scope.loginUser = function(){
var data = {
username: $scope.loginInfo.username,
password: $scope.loginInfo.password
}
};
})

For angular you need token based authentication.
What is token based authentication?
I never use silex but I found this
https://gonzalo123.com/2014/05/05/token-based-authentication-with-silex-applications/
Another method is normal login form and when user login in see angular app, but this is bad when you try create mobile app.

Take a look at for example this:
https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps
I recommend jwt auth it's very nice!

Related

AngularJS User Login to Json file

I am currently trying to create a user login page where the user information is stored on a json file. I have created my GET method to the file but I cannot seem to redirect after the user has logged in successfully. Can you help me out?
I know that user login and validation done on the client side is A BAD IDEA but that is how I want to do it, without using a database.
Here is my HTML code:
<body ng-controller="myCtrl">
<form id="login-form">
<h3>User Login</h3>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button type="submit" class="btn btn-default" id="login-button" ng-click="LogOn()">Login</button>
</form>
</body>
My JavaScript code:
var app = angular.module('myApp', [ ]);
app.controller("myCtrl",['$scope', '$http', function($scope, $http){
$scope.LogOn = function(){
$http.get('data.json').then(function(data){
$scope.users = data;
});
if (data.email == email) && (data.password = password{
window.location.href = 'www.google.com';
}
};
}]);
My JSON File:
[
{
"email":"something#yahoo.com",
"Password":"password"
},
{
"email":"test#yahoo.com",
"password":"test999"
},
{
"email":"xxx#mail.xx",
"password":"xxx"
}
]
Please try to open the link and check and run the code which is deployed in w3 schools
https://www.w3schools.com/code/tryit.asp?filename=FDVZY3NXVYG6
Put redirection code inside then
$http.get('data.json').then(function(data){
$scope.users = data;
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
});
Obviously the if bellow has to be inside the .then( callback
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}

Clean way of posting form data with Angular?

I was wondering, what's the clean way of posting form data with angular?
I have this form setup
<div id="contact-form" class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
<form>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Firstname" name="firstname" ng-model="firstname">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Lastname" name="lastname" ng-model="lastname">
</div>
<div class="form-group">
<input type="email" class="form-control input-lg text-center" placeholder="Email" name="email"ng-model="email">
</div>
<!-- Submit Contact -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createContact()">Add</button>
</form>
</div>
</div>
and I'm posting this to a node.js backend "api".
How do I do this correctly? Do I write every api request in 1 core file? Do I make separate files for each page?
And then how I do I write a clean request?
$scope.createContact = function() {
$http.post('/contacts', ...)
.success(function(data) {
})
.error(function(data) {
});
};
I want to process 'lastname', 'firstname' and 'email' to add a new contact, but online I can't find a good, clean way to write this.
Here's my model in case it helps:
var mongoose = require('mongoose');
var ContactSchema = new mongoose.Schema({
firstname: { type: String, require: true },
lastname: { type: String, require: true },
email: { type: String, require: true }
});
module.exports = mongoose.model('Contact', ContactSchema);
Here's the code I used in the end.
$scope.createContact = function(contact) {
$scope.contact = { firstname: $scope.firstname, lastname: $scope.lastname, email: $scope.email };
$http.post('/contacts', $scope.contact)
.success(function(data) {
$scope.contact = {firstname:'',lastname: '', email:''}; // clear the form so our user is ready to enter another
$scope.contacts = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
How you structure your project is up to you. You could do it all in one file (but that's not very scalable), You could do one in each file (I wouldn't recommend it), or you could group them into semantic files like user_routes.js, social_media_routes.js, etc.
You are on the right track using $http.post() You'll want to create a JSON using your bound variables. You haven't included your entire controller so it's hard to tell you what to do. But a better way of doing this would probably just to create a JSON with empty values like this:
$scope.contact = {
firstname: '',
lastname: '',
email: '',
}
and then use something like ng-model="contact.firstname" for your data-binding. This will let you simply send $scope.contact to the back-end route.
The back-end route in Express would look something like:
var express = require('express');
var app = express();
app.post('/contacts', function (req, res) {
res.status(200).send(req)
}
This will send back what it receives - That should be enough to get you started - Handling POST requests in Express will depend on what version of Express you are using.
In the form tag add the attribute ng-submit to trigger directly in angular the post function.
<div id="contact-form" class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
<form ng-submit="createContact(user)">
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Firstname" name="firstname" ng-model="user.firstname">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg text-center" placeholder="Lastname" name="lastname" ng-model="user.lastname">
</div>
<div class="form-group">
<input type="email" class="form-control input-lg text-center" placeholder="Email" name="email"ng-model="user.email">
</div>
<!-- Submit Contact -->
<button type="submit" class="btn btn-primary btn-lg">Add</button>
</form>
</div>
Add an empty user object in the controller:
$scope.user = {firstname:'',lastname: '', email:''};
Let the $http service handle the call:
$scope.createContact = function(user) {
$http.post('/contacts', user)
.then(function(data) {
//in data.data is the result of the call
},function(error) {
//here is the error if your call dont succeed
});};

How to connect Mailchimp subscribers with Firebase using AngularJS

I have my database with Firebase and now I'm trying to do a newsletter subscription, but I want to save the subscribers in Mailchimp and Firebase.
Mailchimp connection works perfectly, but I don't know how to integrate the Firebase connection in the same js.
This is what I have in the <head> tag
<script type="text/javascript">
angular.module("productLaunch", ["mailchimp"])
</script>
This in the <body> tag
<body ng-app="productLaunch"><section class="container-fluid subscribe" ng-controller="MailchimpSubscriptionCtrl">
<div class="wrapper">
<!-- Let us your email -->
<div class="">
<h2 class="text-center">Subscribe to our news</h2>
<div class="col-lg-4 col-lg-offset-4 mt centered">
<h4 ng-hide="mailchimp.result ==='success'">LET ME KNOW WHEN YOU LAUNCH</h4>
<h4 ng-show="mailchimp.result ==='success'">THANKS FOR SIGNING UP!</h4>
</div>
<form class="form-inline" role="form" ng-hide="mailchimp.result === 'success'">
<input class="hidden" type="hidden" ng-model="mailchimp.username" ng-init="mailchimp.username='stopappweb'">
<input class="hidden" type="hidden" ng-model="mailchimp.dc" ng-init="mailchimp.dc='us12'">
<input class="hidden" type="hidden" ng-model="mailchimp.u" ng-init="mailchimp.u='3eb39be3ad857e60b357fdb5e'">
<input class="hidden" type="hidden" ng-model="mailchimp.id" ng-init="mailchimp.id='520ddfd981'">
<div class="form-group">
<label class="sr-only" for="mailchimp.email">Email address</label>
<input type="email" class="form-control" id="mailchimp.email" placeholder="Enter email" ng-model="mailchimp.email">
</div>
<button type="submit" class="btn btn-info" ng-disabled="MailchimpSubscriptionForm.$invalid" ng-click="addSubscription(mailchimp)" type="submit" value="SIGN UP" disabled="disabled">Submit</button>
<div ng-show="mailchimp.result === 'error'">
<p ng-bind-html="mailchimp.errorMessage" class="error"></p>
</div>
</form>
</div>
</div>
</section>
And this is my JS:
'use strict';
angular.module('mailchimp', ['ng', 'ngResource', 'ngSanitize'])
.controller('MailchimpSubscriptionCtrl', ['$log', '$resource', '$scope',
function ($log, $resource, $scope) {
$scope.myData = new Firebase("https://stopappwebpre.firebaseio.com/subscriptors");
// Handle clicks on the form submission.
$scope.addSubscription = function (mailchimp) {
var actions,
MailChimpSubscription,
params,
url;
$scope.myData.push({mailchimp.email:$scope.mailchimp.email});
// Create a resource for interacting with the MailChimp API
url = 'http://' + mailchimp.username + '.' + mailchimp.dc + '.list-manage.com/subscribe/post-json';
params = {
'EMAIL': mailchimp.email,
'FNAME': mailchimp.fname,
'LNAME': mailchimp.lname,
'c': 'JSON_CALLBACK',
'u': mailchimp.u,
'id': mailchimp.id
};
actions = {
'save': {
method: 'jsonp'
}
};
MailChimpSubscription = $resource(url, params, actions);
// Send subscriber data to MailChimp
MailChimpSubscription.save(
// Successfully sent data to MailChimp.
function (response) {
// Define message containers.
mailchimp.errorMessage = '';
mailchimp.successMessage = '';
// Store the result from MailChimp
mailchimp.result = response.result;
// Mailchimp returned an error.
if (response.result === 'error') {
if (response.msg) {
// Remove error numbers, if any.
var errorMessageParts = response.msg.split(' - ');
if (errorMessageParts.length > 1)
errorMessageParts.shift(); // Remove the error number
mailchimp.errorMessage = errorMessageParts.join(' ');
} else {
mailchimp.errorMessage = 'Sorry! An unknown error occured.';
}
}
// MailChimp returns a success.
else if (response.result === 'success') {
mailchimp.successMessage = response.msg;
}
},
// Error sending data to MailChimp
function (error) {
$log.error('MailChimp Error: %o', error);
}
);
}; }]);
Thank you so much for your help.

Can't create a new user on Angular Sign Up page

I am trying to create a new user in Angular. I'm attempting to send a POST request to my api through the client side to create a new user. Unfortunately I can't successfully send the post request. Sending the request through Postman is successful, but not through Angular. Any ideas on what could be the issue? Any help is appreciated.
userCtrl.js
//./public/app/controllers/userCtrl.js
angular.module('userCtrl',['userService'])
//SIGN UP CTRL ================================
//inject the User factory
.controller('userCreateController', function($location, User){
var vm = this;
//Function that creates a new user
vm.saveUser = function(){
//For spinner animation when signing up
vm.processing = true;
//Use the create funciton in the userService
User.create(vm.userData)
.then(function(data){
if(data.success){
$location.path('/login');
}else {
console.log('error');
vm.processing = false;
}
})
}//End saveUser
})//End userCreateController
userService.js
//userService.js
angular.module('userService', [])
.factory('User', function($http){
//create a user factory object
var userFactory = {};
//get a single user
userFactory.get = function(id){
return $http.get('/api/users/' + id);
};
//get all users
userFactory.all = function(){
return $http.get('/api/users/');
};
//create a user
userFactory.create = function(userData){
return $http.post('/api/users/', userData);
};
//update a user
userFactory.update = function(id, userData){
return $http.put('/api/users/' + id, userData);
};
//delete a user
userFactory.delete = function(id){
return $http.delete('/api/users' + id);
};
//return userFactory object
return userFactory;
});
routes.js
//./public/app/routes.js
angular.module('appRoutes', ['ngRoute'])
.config(function($routeProvider, $locationProvider){
$routeProvider
//homepage route
.when('/',{
templateUrl : 'app/views/pages/home.html'
})
.when('/login',{
templateUrl: 'app/views/pages/login.html',
controller: 'mainController',
controllerAs: 'login'
})
.when('/signup',{
templateUrl: 'app/views/pages/signup.html',
controller: 'userCreateController',
controllerAs: 'signup'
})
//Remove hash in the Url
$locationProvider.html5Mode(true);
})//End config
signup.html
<div class="row col-sm-6 col-sm-offset-3">
<div class="jumbtron">
<h1>Sign Up</h1>
<!-- Sign Up Form -->
<form ng-submit='signup.saveUser()'>
<!-- Name Input -->
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Enter Your Name" ng-model='signup.userData.name'>
</div>
<!-- Username Input -->
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Enter Username" ng-model='signup.userData.username'>
</div>
<!-- Password Input -->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Enter Password" ng-model='signup.userData.password'>
</div>
<!-- Signup Button -->
<button type="submit" class="btn btn-block btn-success">
<!-- Show SignUP -->
<span ng-if="!signup.processing">Sign Up</span>
<!-- Show spinner animation when signing up -->
<span ng-if="signup.processing" class="spinner">
<span class="glyphicon glyphicon-repeat"></span>
</span>
</button>
</form>
<!-- End Sign Up Form -->
</div>
</div>
It is difficult to say without more information like the browser console log, but if you are minifying the code, it could be due to the implicit annotation syntax used in the controller injection.
Try to write it with the preferred Inline Array Annotation like:
.controller('userCreateController',
['$location', 'User', function($location, User){
...
}]);
at signup.html you are modifying signup.userData.* but at userCtrl.js you are sending vm.userData instead of $scope.signup.userData.
The problem could be that you are sending an undefined object instead of the userData object.

AngularJs + php authentication

Hi i started learning AngularJs and now im trying to do my Login module using angular and php, but i have some issues. I have watched alot tutorials but none of them was helpful in my case, so here is what i have: controllers.js:
var controllers = angular.module('controllers', []);
controllers.controller('loginController', ['$scope', '$http', 'UserService', function(scope, $http, User) {
scope.main = [
{username: '', password: ''}
]
scope.login = function(){
var config = {
url: '../auth/login.php',
method: 'POST',
data: {
username: scope.main.username,
password: scope.main.password
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}
$http(config)
.success(function(data,status,headers,config){
if(data.status){
//succefull login
User.isLogged = true;
User.username = data.username;
}
else{
User.isLogged = false;
User.username = '';
}
})
.error(function(data,status,headers,config){
User.isLogged = false;
User.username = '';
});
}
}])
auth.js:
var services = angular.module('services', []);
services.factory('UserService', [function(){
var sdo = {
isLogged: false,
username: ''
};
return sdo;
}]);
login.php:
$username = $_POST['username'];
if($username){
return "Logged";
}else{
return false;
}
and the html:
<div class="col-xs-12" id="loginCol" ng-controller="loginController">
<form ng-submit='login()' name="form" novalidate>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" ng-model="scope.main.username" class="form-control" id="username" placeholder="Име..." />
<label for="password" class="sr-only">Password</label>
<input type="password" ng-model="scope.main.password" class="form-control" id="password" placeholder="Парола..." />
</div>
<div class="form-group pull-right">
<button type="button" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-default">Register</button>
</div>
</form>
</div>
In this case i want just if user type something in the username input and hit the login button and on successful call of login.php to return some message. The problem is that code written like that got error "'loginController' is not a function, got undefined" how to fix it?
(Disclosure: I'm one of the developers of UserApp)
You could try the third-party service UserApp, together with the AngularJS module.
Check out the getting started guide, or take the course on Codecademy. Here's some examples of how it works:
Login form with error handling:
<form ua-login ua-error="error-msg">
<input name="login" placeholder="Username"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Log in</button>
<p id="error-msg"></p>
</form>
Signup form with error handling:
<form ua-signup ua-error="error-msg">
<input name="first_name" placeholder="Your name"><br>
<input name="login" ua-is-email placeholder="Email"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Create account</button>
<p id="error-msg"></p>
</form>
ua-is-email means that the username is the same as the email.
How to specify which routes that should be public, and which route that is the login form:
$routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
$routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
The .otherwise() route should be set to where you want your users to be redirected after login. Example:
$routeProvider.otherwise({redirectTo: '/home'});
Log out link:
<a href="#" ua-logout>Log Out</a>
Access user properties:
User info is accessed using the user service, e.g: user.current.email
Or in the template: <span>{{ user.email }}</span>
Hide elements that should only be visible when logged in:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show an element based on permissions:
<div ua-has-permission="admin">You are an admin</div>
And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API with the PHP library to check if the token is valid or not.
If you need any help, just let me know :)
You have created the application
var controllers = angular.module('controllers', []);
but didn't use it in the html code, add ng-app attribute to the wrapper div
<div class="col-xs-12" ng-app="controllers" id="loginCol" ng-controller="loginController">
the second issue, that you try to catch submit event, but don't submit the form, use submit type instead button
<button type="submit" class="btn btn-primary">Login</button>
or add ng-click="login()" attribute to the button and remove ng-submit='login()' from the form

Categories