Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
i have project of login page for admin redirect to dashboard. it use expressjs as a server side and angularjs as a client side.
this client side login page use angularjs
//this is the angular controller that use for get the data from login form
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
$http.post('/admin/',{useremail:userEmail, userpassword:userPassword});
}
})
})();
this is the login page html
<!DOCTYPE html>
<html lang="en" >
<head>
<title>Awi Admin</title>
<meta charset="utf-8">
<meta name="description" content="Aplikasi AWI Realtime Lelang Menggunakan Framework ExpressJS dan Realtime Database Firebase">
<meta name="author" content="Muhammad Abubakar Siddiq - MAS Abbe">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel='stylesheet' href='/stylesheets/login.css'/>
<link rel="stylesheet" type="text/css" href="/stylesheets/font-awesome.min.css">>
</head>
<body ng-app="myAdmin">
<div class="container">
<div class="profile">
<button class="profile__avatar" id="btn_avatar">
<img src="/images/avatar.png" alt="Avatar" />
</button>
<div class="profile__form">
<div class="profile__fields">
<h3 class="text-center">Welcome Admin Lelang</h3>
<form name="login-form" role="form" ng-controller="loginCtrl" novalidate>
<div class="fields">
<input type="text" class="input" placeholder="Username" ng-model="user.email" required/>
<span style="color:red" ng-show="login-form.email.$dirty && login-form.user.$invalid">
<span ng-show="login-form.email.$error.required">Username is required.</span>
</span>
</div>
<div class="fields">
<input type="password" class="input" required-pattern=.*\S.* placeholder="password" ng-model="user.password"/>
<span style="color:red" ng-show="login-form.password.$dirty && login-form.user.$invalid">
<span ng-show="login-form.password.$error.required">Password is required.</span>
</span>
</div>
<div class="alert alert-warning" ng-show="login-form.email.$error.email">
<em class="fa fa-lg fa-warning"> </em>Peringatan, username atau password salah
</div>
<div class="profile__footer">
<center>
<button class="btn" id="btn-submit" ng-click="login()">LOG IN</button>
</center>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
document.getElementById('btn_avatar').addEventListener('click',
function () {
[].map.call(document.querySelectorAll('.profile'),
function(el) {
el.classList.toggle('profile--open');
});
}
);
</script>
<script type="text/javascript" src = "/javascripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src = "/javascripts/bootstraps/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular-resource.min.js"></script>
<script type="text/javascript" src = "/javascripts/login.js"></script>//==> this is the function for login that call the angular controller
</body>
</html>
and this index.js as server side expressjs
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');
const path = require('path');
const session = require('express-session');
const bodyParser = require('body-parser');
const app = express();
const firebaseApp = admin.initializeApp(
functions.config().admin
);
const HTTP_SERVER_ERROR = 500;
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing
app.get('/admin/', (req, res)=>{
res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
res.render('index')
});
//this is the functions post for server side express
app.post('/admin/', (req, res)=>{
console.log('post login'+req.body.userEmail, req.body.userPassword);
admin.auth().signInWithEmailAndPassword(req.body.userEmail, req.body.userPassword)
.then(function (user) {
res.render('/admin/home');
console.log("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.log("Error while executing firebase.auth() ",err);
});
});
exports.app = functions.https.onRequest(app);
this my project in github project
my issue for this project is the data from the post function of angular controller to the expressjs post rendering detected as unidentified.
can anyone enlight me what is the cause?? and how to solved this.
this function is naver get to run firebase auth() functions
Try as,
$http({
method: 'POST',
url: '//admin/',
data: {useremail:userEmail, userpassword:userPassword}
}).then(function(rsp){...});
this is the angular controller
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
var myObject = {useremail:userEmail, userpassword:userPassword}
$http({
method: 'POST',
url : '/admin/',
data : JSON.stringify(myObject)
});
}
})
})();
this is the expressjs functions
app.post('/admin/', (req, res)=>{
console.log("####Success");
console.log('post login '+req.body.useremail, req.body.userpassword);
admin.auth().signInWithEmailAndPassword(req.body.useremail, req.body.userpassword)
.then(function (user) {
res.render('/admin/home');
console.log("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.log("Error while executing firebase.auth() ",err);
});
});
after remote desktop consult, final fixed
Related
So I am getting this error: "GET http://localhost:8000/blogs/undefined net::ERR_EMPTY_RESPONSE angular.js:12587".
It happens when I go to my main blog page and when I go to a blog category page. Looking at the network tab I get:
1. blog-home.html 200 xhr angular.js 12587 4.6kb 21ms
2. all 200 xhr angular.js 12587 3.0kb 57ms
3. undefined pending xhr angular.js 12587 3.0kb 57ms 0kb
and the same when I go a blog category page. Ultimately they fail and kick the error above.
So before this gets voted down... I have read and tried here on stack:
No luck. Maybe I missed something or typed something wrong. I'm totally dumbfounded and I feel this is clearly above my skill level. So here is a bunch of code...
Server.js
var express = require('express');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var Mailgun = require('mailgun-js');
var path = require('path');
require('colors');
var app = express();
app.use(favicon(path.join(__dirname, 'client/assets/images', '*****')))
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({extended:true}))
app.use(express.static(path.join(__dirname, 'client')));
app.use(express.static("./bower_components"));
//app.all('/*', function(req, res, next) {
// res.sendFile('index.html', { root: 'client'});
//});
require('./server/config/mongoose.js');
var routes = require('./server/config/routes.js');
routes(app);
var api_key = '*********';
var domain = '*********';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: '********',
to: '********',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
app.listen(8000, function () {
console.log("I'm listening...".blue);
})
Index.html
<!DOCTYPE html>
<html lang="en" ng-app="Bridgeman">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<meta name="description" content="">
<meta name="author" content="">
<meta name="revisit-after" content="10 days">
<meta name="googlebot" content="noodp">
<meta name="msnbot" content="noodp">
<meta name="slurp" content="noodp, noydir">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ; connect-src 'self'; img-src * data:; style-src 'self' 'unsafe-inline'; font-src * data:; frame-src https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d44591.890384371676!2d-118.36723983279781!3d33.83006153459027!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2sus!4v1492366398808 ">
<meta content="/assets/images/******_BigBearSnowTrail.jpg" itemprop="image">
<link href="/assests/images/*******.ico" rel="shortcut icon">
<base href="/" />
<title></title>
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/modern-business.css" rel="stylesheet">
<link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="angular/angular.js"></script>
<script type="text/javascript" src="angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="/factories/ContactFactory.js"></script>
<script src="/factories/loginFactory.js"></script>
<script src="/factories/blogFactory.js"></script>
<script src="/controllers/contactController.js"></script>
<script src="/controllers/servicesController.js"></script>
<script src="/controllers/blogController.js"></script>
<script src="/controllers/blogViewController.js"></script>
<script src="/controllers/blogAWSController.js"></script>
<script src="/controllers/loginController.js"></script>
<base target="_blank">
</head>
<body>
<div ng-include='"templates/header.html"'></div>
<div ng-view=""></div>
<div ng-include='"templates/footer.html"'></div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
app.js (As you see I tried to seperate the AWS category into its own controller and both get's fired when that page loaded)
var Bridgeman = angular.module('Bridgeman', ['ngRoute']);
Bridgeman.config(['$routeProvider', '$httpProvider', '$locationProvider', '$qProvider', function($routeProvider, $httpProvider, $locationProvider, $qProvider){
$qProvider.errorOnUnhandledRejections(false);
$httpProvider.interceptors.push(function($q, $location){
return{
'responseError': function(rejection){
if(rejection.status == 401){
$location.url('/');
}
return $q.reject(rejection);
}
}
});
$routeProvider
.when('/', {
templateUrl:'partials/home.html',
}).when('/about', {
templateUrl:'partials/about.html',
}).when('/services', {
templateUrl: 'partials/services.html',
controller: 'servicesController'
}).when('/blog', {
templateUrl: 'partials/blog-home.html',
controller: 'blogViewController'
}).when('/blogAWS', {
templateUrl: 'partials/blog-aws.html',
controller: 'blogAWSController'
}).when('/blogSEO', {
templateUrl: 'partials/blog-SEO.html',
controller: 'blogViewController'
}).when('/blogSecurity', {
templateUrl: 'partials/blog-Security.html',
controller: 'blogViewController'
}).when('/blogBusiness', {
templateUrl: 'partials/blog-Business.html',
controller: 'blogViewController'
}).when('/blogSportsTech', {
templateUrl: 'partials/blog-SportsTech.html',
controller: 'blogViewController'
}).when('/blog-post/:id', {
templateUrl: 'partials/blog-post.html',
controller: 'blogViewController'
}).when('/contact', {
templateUrl: 'partials/contact.html',
controller: 'contactController'
}).when('/login', {
templateUrl:'partials/login.html',
controller: 'loginController'
}).when('/admin', {
templateUrl:'partials/admin.html',
controller: 'blogController'
}).otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
}])
Bridgeman.run(function($rootScope, $location, $anchorScroll, $routeParams) {
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
$location.hash($routeParams.scrollTo);
$anchorScroll();
});
})
blog-home.html (This is the main blog page which fires off both functions in my blogViewController)
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Blog Home
<small>My insights just for you</small>
</h1>
<ol class="breadcrumb">
<li>Home
</li>
<li class="active">Blog Home</li>
</ol>
</div>
</div>
<!-- /.row -->
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8">
<div class="blogs" ng-repeat="b in blogs | orderBy:'-createdAt' | filter:searchblogs">
<!-- Blog Post -->
<h2>
<p>{{b.title}}</p>
</h2>
<p class="lead">
by {{b._user.name}} in the {{b.category}} category
</p>
<p><i class="fa fa-clock-o"></i> Posted on {{b.createdAt | date: "MMM. dd, yyyy"}}</p>
<hr>
<p>{{b.snippet}}</p>
<hr>
<p>{{b.content}}</p>
<a class="btn btn-primary" ng-href="/blog-post/{{b._id}}">Read More <i class="fa fa-angle-right"></i></a>
<hr>
</div>
<hr>
</div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-4">
<!-- Blog Search Well -->
<div class="well">
<h4>Search my blogs</h4>
<div class="input-group">
<input type="text" class="form-control" ng-model="searchblogs">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-search"></i></button>
</span>
</div>
<!-- /.input-group -->
</div>
<!-- Blog Categories Well -->
<div class="well">
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-6">
<ul class="list-unstyled">
<li>AWS
</li>
<li>SEO
</li>
<li>Security
</li>
<li>Business Tips
</li>
</ul>
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<ul class="list-unstyled">
<li>Tech in Sports
</li>
<li>Coming Soon
</li>
<li>Coming Soon
</li>
<li>Coming Soon
</li>
</ul>
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>My Blog</h4>
<p>Here is a collection of my genius (ha!) and tech insights. I'm sure sooner than later I will discuss Formula 1 tech but be assured there will be plenty of SEO and various web development tips/tools/tricks. And lets not forget some general business savviness I've learned over the years.</p>
</div>
</div>
</div>
<!-- /.row -->
blogViewController (where the functions are. Again, I commented out the getOneBlog and the error didn't happen. So what is triggering this fire and before the button is clicked?)
Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams){
console.log("in the blog VIEW controller");
$scope.blogs = [];
$scope.one = [];
blogFactory.getAllBlogs(function(output){
$scope.blogs = output;
console.log(output);
})
blogFactory.getOneBlog($routeParams.id, function(output){
$scope.one = output;
console.log(output);
})
});
blogFactory (no issues here that I am aware of)
Bridgeman.factory('blogFactory', function($http){
var factory = {};
factory.submitNewBlog = function(input, callback){
$http.post('/blogs/new', input).then(function(output){
console.log("we just added a new blog");
callback(output.data);
});
}
//factory.submitNewComment = function(input, callback){
// $http.post('/comments/new', input).then(function(output){
// console.log("we just added a new comment");
// callback(output.data);
// });
//}
factory.getAllBlogs = function(callback){
$http.get('/blogs/all').then(function(output){
console.log("we just got all blogs");
callback(output.data);
});
}
factory.getOneBlog = function(blogID, callback){ //factory.getOneBlog = function(blogID, callback)
$http.get('/blogs/' + blogID).then(function (output){ //$http.get('blogs/' + blogID).then(function (output){
console.log(output.data); //callback(output.data);
console.log("we just got one blog");
callback(output.data);
});
}
return factory;
});
routes (a couple of different styles here just tying different formats to solve this)
var users = require('./../controllers/users.js');
var blogs = require('./../controllers/blogs.js');
module.exports = function(app){
app.post('/reg', function(req, res){
users.reg(req, res);
});
app.post('/login', function(req, res){
users.login(req, res);
});
app.get('/blogs/all', function(req, res) {
blogs.getAllBlogs(req, res);
});
app.get('/blogs/:id', blogs.getOneBlog); //app.get('/blogs/:id', blogs.getOneBlog)
app.post('/blogs/new', function(req, res) {
blogs.addBlog(req, res);
});
app.post('/contact', function(req,res){
var api_key = 'key-2451a2b90a87be616ab68b8f7c8f97ea';
var domain = 'sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'Website inquiry <postmaster#sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org>',
to: '*************com',
subject: req.body.full_name+" has sent you a message",
html:
req.body.full_name+" ..."+
req.body.phone+" ..."+
req.body.email+" ..."+
req.body.message
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
console.log("working...");
if(!error)
res.send("Your message has been sent");
else
res.send("Uh oh... something went wrong!");
});
});
}
blogs.js server side controller (no issue here... that I am aware of)
var Blog = mongoose.model('Blog');
module.exports = (function() {
return {
getAllBlogs: function(req, res){
Blog.find({}).populate([{path : '_user'}]).exec(function(err, b){
if(err){
console.log("there was an error when getting all blogs".red);
} else {
console.log(b);
console.log("successfully got all blogs".green);
res.json(b);
}
});
},
getOneBlog: function(req, res) {
console.log('Rich band aid');
if (req.params.id !== 'undefined') {
console.log('there was an id', req.params.id);
Blog.findOne({_id: req.params.id}).exec(function(err, b) { //({_id: req.params.id}, function(err,b){})
if(err){
console.log('error is', err);
console.log("there was an error when getting the blog".red);
} else {
console.log(b);
console.log("successfully got the blog".green);
res.json(b);
}
});
}else {
console.log('no id');
}
},
addBlog: function(req, res) {
console.log("===========================".yellow);
console.log(req.body);
console.log("===========================".yellow);
var b = new Blog({category: req.body.category, title: req.body.title, snippet: req.body.snippet, content: req.body.content, _user: req.body._user})
b.save(function(err){
if(err){
console.log("there was an error when saving a blog".red);
} else {
console.log(b);
console.log("successfully saved the above blog".green);
res.redirect('/blogs/all');
}
})
}
}
})();
and the mongoose db (no issue here... that I am aware of)
var mongoose = require('mongoose');
// Create the message schema
var BlogSchema = new mongoose.Schema({
category: {type: String, required: true, minlength: 3, enum:['Security', 'Business', 'SEO', 'AWS', 'Tech in Sports']},
title: {type: String, required: true, minlength: 3},
snippet: {type: String, required: true, minlength: 3},
content: {type: String, required: true, minlength: 3},
_user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
}, {timestamps: true});
mongoose.model('Blog', BlogSchema);
Any help is greatly appreciated. Thanks
PS... and yes I am aware of the CPS error for the frame-src and the font-src when you try to refresh the page. Super annoying.
Was able to figure it out with a friend. Problem solved by wrapping the 2 functions into an 'if' statement. It may not be the proper solution but it works perfectly.
Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams){
console.log("in the blog VIEW controller");
$scope.blogs = [];
$scope.one = [];
if ($routeParams.id) {
blogFactory.getOneBlog($routeParams.id, function(output) {
$scope.one = output;
console.log(output);
});
} else {
blogFactory.getAllBlogs(function(output) {
$scope.blogs = output;
console.log(output);
});
}
});
I have a node + angular project. I want to render a html page and init it with some values. I wan thoses values to be linked to the Angular scope.
So i have an input, I linked it with ng-model but this erase the EJS initialisation.
server.js:
var express = require('express');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/front/views');
app.set('view engine', 'html');
app.use('/front',express.static(__dirname + '/front'));
app.get('/signup',function(req,res){
res.render('view',{
user:{
email:"user mail",
}
})
});
var port = 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});
view.html:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="/front/controllers/app.js"></script>
<html ng-app="onboardingApp">
<form id="msform" novalidate ng-controller="onboardingController">
<input required type="text" name="email" ng-model="signup.user.email">
<label for="email">Email</label>
<input type="button" name="next" ng-click="displaySignup()" value="NEXT"/>
</form>
</html>
app.js:
var onboardingApp = angular.module('onboardingApp', []);
onboardingApp.controller('onboardingController',function OnboardingController($scope) {
$scope.signup = {
user:{
email:""
}
}
$scope.displaySignup = function(){
console.log($scope.signup)
}
});
So I am trying to set the value of: input required type="text" name="email" ng-model="signup.user.email"
with ejs and then that this value to be linked with the angular model signup.user.email.
Can someone help me with that?
you can add this piece of js at the end of your view.html
<script type="text/javascript">
angular.module('onboardingApp')
.value('userEmail', <%- JSON.stringify(user.email) %>);
</script>
and then inject the component wherever you need it like so:
onboardingApp.controller('onboardingController',
function OnboardingController($scope, userEmail) {
$scope.signup = {
user:{
email: userEmail
}
}
$scope.displaySignup = function(){
console.log($scope.signup)
}
});
Well, I'm building a simple login page using the MEAN stack. I'm using passport to authenticate, connect-flash to flash messages and Angular ngRoute to, well, route. I have the following code:
app.js
var app = angular.module("app", ["ngRoute"]);
app.factory("appFactory", function($http) {
return {
getData: function(path) {
return $http.get(path)
.then(function(response) {
return response.data;
}, function(response) {
console.log("Error...");
});
}
};
});
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "homeCtrl",
resolve: {
getMessage: function(appFactory) {
return appFactory.getData("/api/login");
}
}
})
.otherwise({
redirectTo: "/"
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
//to fix!
app.controller("homeCtrl", function($scope, getMessage) {
$scope.errors = getMessage.errors;
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>My Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.min.js"></script>
</head>
<body>
<!-- ngView -->
<div ng-view></div>
<!-- /ngView -->
<script src="/javascript/angular/app.js"></script>
</body>
</html>
home.html
<form action="/" method="post">
<label>E-mail:</label>
<br/>
<input type="email" name="email" />
<br/>
<label>Password:</label>
<br/>
<input type="password" name="password" />
<br/>
<input type="submit" name="submit" value="Log In" />
</form>
<!-- prints error messages (usually, only one) -->
<span ng-repeat="error in errors">{{errors[$index]}}</span>
login.js
var passport = require("passport");
module.exports = function(app) {
app.get("/api/login", function(req, res) {
var info = {
logged: false,
errors: req.flash("error")
};
if (!req.user) {
console.log(info.errors);
} else {
info.logged = true;
}
res.json(info);
});
}
index.js
var passport = require("passport");
var path = require("path");
module.exports = function(app) {
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "../views/index.html"));
});
app.post("/",
passport.authenticate("local-login", {
successRedirect: "/profile",
failureRedirect: "/",
failureFlash: true
}));
}
So, I'm testing wrong logins, expecting req.flash() to reset after a refresh on the homepage, but it takes some refreshs before resetting. As you can see, I've put a console check when the api is called falsely, and the console outputs:
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
[]
[]
[]
[]
See? It takes some refreshes before cleaning its value. It has nothing to do with my passport authentication strategy nor anything else but the resolve inside the routing. When I attempt to use it without routes (directly on the controller) it works perfectly. Please, help me enlighten my mind on this one and thank you for your time.
I am having hard time to pass this error:
Uncaught Error: [$injector:modulerr]
when I am trying to make an authentication app with AngularJS. I put the code in plunker.
Here are my codes:
1- app.js
"use strict";
(function() {
var app = angular.module('loginApp', ['AuthService', 'Session']);
app.constant('appSettings', {
title:'Authentication Application',
version:'1.0'
});
app.constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
loginFailed: 'auth-login-failed',
logoutSuccess: 'auth-logout-success',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
});
app.constant('USER_ROLES', {
all: '*',
admin: 'admin',
editor: 'editor',
guest: 'guest'
});
app.controller('footerController', function($scope, appSettings){
$scope.appSettings = appSettings;
});
}());
2 - applicationcontroller.js
"use strict";
(function() {
var applicationcontroller = function ($scope, USER_ROLES, AuthService) {
$scope.currentUser = null;
$scope.userRoles = USER_ROLES;
$scope.isAuthorized = AuthService.isAuthorized;
$scope.setCurrentUser = function (user) {
$scope.currentUser = user;
};
};
applicationcontroller.$inject = ['$scope', 'USER_ROLES', 'AuthService'];
angular.module('loginApp')
.controller('applicationcontroller', applicationcontroller);
}());
3- logincontroller.js
"use strict";
(function() {
var logincontroller = function ($scope, $rootScope, AUTH_EVENTS, AuthService) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function(credentials){
AuthService.login(credentials).then(function(user){
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.setCurrentUser(user);
}, function(error){
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
};
logincontroller.$inject = ['$scope', '$rootScope', 'AUTH_EVENTS', 'AuthService'];
angular.module('loginApp')
.controller('logincontroller', logincontroller);
}());
4- authservice.js
"use strict";
(function(){
var AuthService = function($http, Session){
var authService = {};
authService.login = function (credentials) {
return $http
.post('/login', credentials)
.then(function (res) {
Session.create(res.data.id, res.data.user.id,
res.data.user.role);
return res.data.user;
});
};
authService.isAuthenticated = function () {
return !!Session.userId;
};
authService.isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (authService.isAuthenticated() &&
authorizedRoles.indexOf(Session.userRole) !== -1);
};
return authService;
};
AuthService.$inject = ['$http', 'Session'];
angular.module('loginApp').factory('AuthService', AuthService);
}());
5- session.js
"use strict";
(function(){
var Session = function(){
this.create = function (sessionId, userId, userRole) {
this.id = sessionId;
this.userId = userId;
this.userRole = userRole;
};
this.destroy = function () {
this.id = null;
this.userId = null;
this.userRole = null;
};
};
angular.module('loginApp').service('Session', Session);
}());
6- index.html
<!DOCTYPE html>
<html data-ng-app="loginApp" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Authentication</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link href="css/main.css" rel="stylesheet">
</head>
<body ng-controller="applicationcontroller">
<div class="container">
<div class="jumbotron">
<form name="loginForm" ng-controller="logincontroller" ng-submit="login(credentials)" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" ng-model="credentials.username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" ng-model="credentials.password" class="form-control">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<hr class="color-violet">
<footer class="text-center" data-ng-controller="footerController"> MADE WITH <i class="fa fa-heart color-violet"></i> BY <span class="color-violet">ALAN SABERI</span>. FIND THIS ON <span class="color-violet">GITHUB</span><div>Version: {{appSettings.version}}</div></footer>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="vendor/bootstrap.min.js"></script>
<script src="vendor/angular.min.js"></script>
<script arc="js/services/authservice.js"></script>
<script arc="js/services/session.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/applicationcontroller.js"></script>
<script src="js/controllers/logincontroller.js"></script>
</body>
</html>
First of all you have a typo when referencing your script files
<script arc="js/services/authservice.js"></script>
<script arc="js/services/session.js"></script>
Should be
<script src="js/services/authservice.js"></script>
<script src="js/services/session.js"></script>
Second -> Your AuthService and Session are not new modules, they are being registered in the same loginApp module based on your code. So you don't inject them into your loginApp module.
Change
var app = angular.module('loginApp', ['AuthService', 'Session']);
to this
var app = angular.module('loginApp', []);
Third -> You are loading your service script files before loading your app.js, remember app.js is where you are first defining your loginApp module that you are using to assign your services, so change your script load order to be this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap.min.js"></script>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="session.js"></script>
<script src="authservice.js"></script>
<script src="applicationcontroller.js"></script>
<script src="logincontroller.js"></script>
Here's your plnkr that's forked and working : http://plnkr.co/edit/5BEIsVxwt8sKwr4HA8Eq?p=preview
I am working on ng-Cordova to build a project. I tried so many examples to get logging with google. My need is to login to my app using google account. I have login button. When I click the button, it needs to redirect to google account and sign in with the google account and need to come back to my app.
I have a google client id. I hereby post my index.html file and app.js file.
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
</ion-content>
</ion-pane>
</body>
</html>
my app.js file
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var exampleApp = angular.module('starter', ['ionic', 'ngCordova']);
//.run(function($ionicPlatform) {
// $ionicPlatform.ready(function() {
//// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
//// for form inputs)
// if(window.cordova && window.cordova.plugins.Keyboard) {
// cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// }
// if(window.StatusBar) {
// StatusBar.styleDefault();
// }
var requestToken = "";
var accessToken = "";
var clientId = "";
var clientSecret = "";
var exampleApp = angular.module('example', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('secure', {
url: '/secure',
templateUrl: 'templates/secure.html',
controller: 'SecureController'
});
$urlRouterProvider.otherwise('/login');
});
exampleApp.controller('LoginController', function($scope, $http, $location) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$scope.login = function() {
var ref = window.open('https://accounts.google.com/o/oauth2/auth?client_id=' + clientId + '&redirect_uri=http://localhost/callback&scope=https://www.googleapis.com/auth/urlshortener&approval_prompt=force&response_type=code&access_type=offline', '_blank', 'location=no');
ref.addEventListener('loadstart', function(event) {
if((event.url).startsWith("http://localhost/callback")) {
requestToken = (event.url).split("code=")[1];
$http({method: "post", url: "https://accounts.google.com/o/oauth2/token", data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=http://localhost/callback" + "&grant_type=authorization_code" + "&code=" + requestToken })
.success(function(data) {
accessToken = data.access_token;
$location.path("/secure");
})
.error(function(data, status) {
alert("ERROR: " + data);
});
ref.close();
}
});
}
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
});
exampleApp.controller('SecureController', function($scope, $http) {
$scope.accessToken = accessToken;
});
I created two html pages additionally after searching some examples.
login.html
<ion-view ng-controller="LoginController" title="Oauth Login">
<ion-content>
<div>
<div class="padding">
<button ng-click="login()" class="button button-block button-stable">
Sign In
</button>
</div>
</div>
</ion-content>
</ion-view>
and secure.html
<ion-view ng-controller="SecureController" title="Oauth Secure">
<ion-content>
<div>
<div class="padding">
{{accessToken}}
<button class="button button-block button-stable">
Do Something
</button>
</div>
</div>
</ion-content>
</ion-view>
When I run the app, only Index file with blank page is showing. I don't know what is the problem. Can somebody help me?
Hi in github i uploaded a sample project to login via google before you execute the project please follow the steps in README.md file of github