Firebase - Angularjs handle email verification - angularjs

I use firebase and Angularjs on my web app. I have a factory below serving to all my app modules:
.factory('Auth', ["$firebaseAuth",
function($firebaseAuth) {
return $firebaseAuth();
}
]);
It is critical for me (in fact it is the easiest and only way I know) to check pages if auth required or not. So I put this code on each module config in $stateProvider :
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireSignIn();
}]
I want to use firebase email verification and according to documents I need to do so:
var app = firebase.initializeApp(config);
var auth = app.auth();
...
function handleVerifyEmail(auth, actionCode, continueUrl) {
auth.applyActionCode(actionCode).then(function(resp) {
...
}).catch(function(error) {
...
});
}
But then it returns error:
{code: "app/duplicate-app", message: "Firebase: Firebase App named
'[DEFAULT]' already exists (app/duplicate-app).",
I wanted to try with the factory Auth.applyActionCode but there is no such method. How can I solve this problem?

make sure you're not calling the initialize method more than once. see: github.com/Polymer/polycasts/issues/16 for more details.

Related

AngularJS - IdentityServer4.Quickstart.UI - 'AuthenticationProperties' is an ambiguous reference

I'm implementing an AngularJS app that will use IdentityServer4 for Authorization.
I have a stand alone Angular app within a .Net Core 2.0 app that calls the api controller in the .net core app. if I browse to http://localhost:5050/.well-known/openid-configuration I am getting the json returned.
I have used this example as a basis for my auth service:
function authService() {
var config = {
authority: "http://localhost:5050",
client_id: "js",
redirect_uri: "http://localhost:5050/LocalizationAdmin/callback.html",
response_type: "id_token token",
scope: "openid profile api1",
post_logout_redirect_uri: "http://localhost:5050/LocalizationAdmin/index.html"
};
var mgr = new Oidc.UserManager(config);
mgr.getUser().then(function (user) {
if (user) {
log("User logged in", user.profile);
} else {
log("User not logged in");
}
});
var service = {
login: login,
logout: logout,
};
return service;
function login() {
mgr.signinRedirect();
}
In callback.html I have added:
<body>
<script src="scripts/oidc-client.js"></script>
<script>
new Oidc.UserManager().signinRedirectCallback().then(function () {
window.location = "index.html";
}).catch(function (e) {
console.error(e);
});
</script>
</body>
It is trying to redirect to:
http://localhost:5050/account/login?returnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Djs%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A5050%252FLocalizationAdmin%252Fcallback.html%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520api1%26state%3Dd526351a26f74202badb7685022a6549%26nonce%3D6c858921378645ca8fcad973eb26cc72
However I just want it to redirect to the IdentityServer4 login screen. How can I achieve this? Any help appreciated.
Edit:
I have added the UI templates from here:
https://github.com/IdentityServer/IdentityServer4.Quickstart.UI
But I am getting a number of errors, could this be because I am using .Net Core 2.0 version: assemblyref://IdentityServer4 (2.0.0-rc1-update1)
Error CS0104 'AuthenticationProperties' is an ambiguous reference between 'Microsoft.AspNetCore.Authentication.AuthenticationProperties' and 'Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties'
Demo Project showing issue added to github here.
I have no idea how stable this is but I just used the powershell command pointing to the dev branch and it seems to be working.
iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/dev/get.ps1'))
you might want to look instead at the quickstarts relating to 2.0.0-rc1-update1 which can be found here on the dev branch:
https://github.com/IdentityServer/IdentityServer4/tree/dev/docs/quickstarts
as they have been also updated.

Firebase V3 and Social Login with Ionic

I am just trying to create a simple social login (e.g.: google, Facebook,...) inside a Ionic App and using Firebase V3 as backend. Unfortunately all the example and tutorial that I found on the internet seems to be broken and do not work with the new API v3.
For example I tried to follow this tutorial (https://firebase.googleblog.com/2016/01/social-login-with-ionic_77.html?showComment=1465144743780#c7688518627861813273)
but apparently I am not able to access the global variable Firebase that was previously available and therefore from this snippet of my app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'firebase'])
.constant('FirebaseUrl', 'https://ionicle.firebaseio.com/')
.service('rootRef', ['FirebaseUrl', Firebase])
I get the following error
ReferenceError: Can't find variable: Firebase, http://localhost:8103/js/app.js, Line: 12
facebookAuth: function () {
ngFB.login({ scope: 'email' }).then(
function (response) {
if (response.status === 'connected') {
console.log('Facebook login succeeded', response);
var credential = firebase.auth.FacebookAuthProvider.credential(
response.authResponse.accessToken);
firebase.auth().signInWithCredential(credential).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
} else {
alert('Facebook login failed');
}
});
},
more details here: http://www.clearlyinnovative.com/firebase-3-0-ionic-facebook-login

How to save the google login as an app user?

So I have some code that authenticates the user to my app using google which works out fine. What I want to do is then save that user info to the firebase and then have that user be able add data specifically under their account that will then reload the next time they log in. What's the best way to do that? I'm getting very lost.
(function() {
'use strict';
angular.module('life-of-a-story')
.controller('UserController', function($scope, $firebaseAuth) {
var ref = new Firebase('https://life-of-a-story.firebaseio.com/');
// create an instance of the authentication service
var auth = $firebaseAuth(ref);
// login with Google
this.login = function() {
auth.$authWithOAuthPopup("google").then(function(authData) {
console.log(authData);
console.log("Logged in as:", authData.uid);
var user = {
'name': authData.google.displayName,
'image': authData.google.profileImageURL,
'uid': authData.uid
}
console.log(user);
}).catch(function(error) {
console.log("Authentication failed:", error);
});
};
});
})();
AngularFire is a (relatively) thin UI binding library on top of Firebase's regular JavaScript SDK. So when something is not explicitly documented in the AngularFire documentation, you can sometimes find the answer in the documentation for the regular Firebase JavaScript SDK.
Most Firebase Authentication developers store each user's data under a /users node. If that is what you're trying to do, you can read how to accomplish it in the section called Storing user data in the Firebase documentation for JavaScript.
The relevant code from there:
// we would probably save a profile when we register new users on our site
// we could also read the profile to see if it's null
// here we will just simulate this with an isNewUser boolean
var isNewUser = true;
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData && isNewUser) {
// save the user's profile into the database so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData)
});
}
});
// find a suitable name based on the meta info given by each provider
function getName(authData) {
switch(authData.provider) {
case 'password':
return authData.password.email.replace(/#.*/, '');
case 'twitter':
return authData.twitter.displayName;
case 'facebook':
return authData.facebook.displayName;
}
}

I am using MEAN.IO stack, why can't I hit my data-access layer using require?

So, I am using mean.io and for some reason, my routes.js never hits my 'index.all' method, or the 'exports.all' function, even though I require the functions from the server-side controller. Also, my routing is done using angular-ui-router. Does anybody know how to call a backend method from routing in MEAN.IO? I keep using:
'use strict';
module.exports = function(System, app, auth, database) {
// Home route
var index = require('../controllers/index');
app.route('/test').get(index.all);
app.route('/')
.get(index.render);
};
I would like to hit 'index.all' but even if I navigate to /test, it still gets
index.render. Does anybody know why?
Here is the controllers file:
'use strict';
var mean = require('meanio');
var mongoose = require('mongoose');
var Composition = mongoose.model('Composition');
exports.render = function(req, res) {
console.log(req.user);
var modules = [];
// Preparing angular modules list with dependencies
for (var name in mean.modules) {
modules.push({
name: name,
module: 'mean.' + name,
angularDependencies: mean.modules[name].angularDependencies
});
}
function isAdmin() {
return req.user && req.user.roles.indexOf('admin') !== -1;
}
// Send some basic starting info to the view
res.render('index', {
user: req.user ? {
name: req.user.name,
_id: req.user._id,
username: req.user.username,
roles: req.user.roles
} : {},
modules: modules,
isAdmin: isAdmin,
adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin')
});
};
exports.all = function(req, res) {
console.log(req.user);
Composition.find({user: req.user}, 'title description').sort('-created').populate('user', 'name username').exec(function(err, compositions) {
if (err) {
return res.jsonp(500, {
error: 'Cannot list the compositions'
});
}
res.jsonp(compositions);
});
};
Is this a front-end or backend problem? Thanks for any advice that might be helpful.
You are navigating. So are you hitting the link in the browser url? Then you should try localhost:3000/test instead of localhost:3000/#!/test.
The urls of the form localhost:3000:/#!/<something> are angular routes. Look up angular routing and views. It is better to use angular views than server side rendering. Do angular routing for test and add a view corresponding to it. Fetch the dynamic data in the view using the regular $http.get calls.
Check this tutorial for routing and adding views in angular

angularfire login with a previously issued firebase token

I am using a separate server that authenticates my angular app. As part of that process the server has already authenticated the user with firebase and has received an auth_token back. Once the angular app is served, I re-request the token from my server and now I want to issue an angularFireAuth.login().
I have tried this but get a "Reference Error unrecognized auth". Am I missing something very fundamental? Shouldn't I be able to login with a pre-existing firebase auth_token??
Here is the code:
var profileController = function ($rootScope, $scope, $log, $location, angularFire, angularFireAuth, profileService) {
init();
function init() {
$scope.profile = {};
profileService.getFirebaseToken(function success(data) {
$scope.auths = data;$
$scope.auth = $rootScope.auth;
var id = {'id': data['_id']};
auth=angularFireAuth.login(data['access_token'],id);
$scope.auth = auth;
}, function error(err) {
console.log('error', err);
});
** Note: data['_id'] = string id that is the userid in my firebase and used as auth.id in my security rules
data['access_token'] = string token. this is not a dictionary or object. just the string token returned from: token = create_token(SECRET, custom_data, options). Which runs successfully on my python tornado server using the: firebase_token_generator module.
Ok. I figured it out. The error I was receiving because the login request is asynchronous. So the "Reference Error: auth" was because the variable auth was referenced before assigned.
I did not ultimately use this exact code above. So I do not know if it was/would work. Instead I switched to the construct that is on the firebase site:
fbLoginService.getFirebaseToken(function success(data) {
var dataRef = new Firebase('xxxxxx.firebaseio.com')
dataRef.auth(data['firebase']['access_token'], function(error) {
if(error) {
console.log("Login Failed!", error);
alert("Login Failure. Unable to login to database(firebase)");
} else {
console.log("Firebase Login Succeeded!");
$rootScope.firebaseAuth=true;
}
});
}, function error(err) {
console.log('error', err);
alert('error', err);
});
I have now created a loginController and loginService that I fire on initial load of index.html with the inclusion of the ng-controller="fbLoginController". All looks good so far.

Resources