Facebook provider is not authenticating users in my ionic app - using angularfire - ionic-framework

I am trying to implement (social & email-password) login in my ionic app..
It was working well for email-pass. When i tried adding google and facebook, i have faced a lot of problems, then a very dirty code. Now my code is working for googleauthentication, but for facebook, the app is redirecting, but returned result is {user: null}, and no thing changes.
What is the error? Why facebook authentication is not changing this.afAuth.authState?
Functionality is implemented in my auth.service.ts file.
A function for Facebook login is as so:
loginWithFacebook() {
this.store.dispatch(new UIActions.StartLoading());
alert('facebook login');
try {
let provider = new auth.FacebookAuthProvider();
console.log(provider);
const credential = this.afAuth.auth.signInWithRedirect(provider);
console.log('accomplished sign in with redirect');
} catch (error) {
console.log(error);
alert(error);
}
}
LoginWithGoogle (working as expected):
webGoogleLogin() {
try {
const provider = new firebase.auth.GoogleAuthProvider();
console.log(provider);
const credential = this.afAuth.auth.signInWithRedirect(provider);
console.log('accomplished sign in with redirect');
} catch (error) {
console.log(error);
alert(error);
}
}
I listen to auth changes in initAthListener(), which is fired on app initialization (it worked as expected for email-pass login - logout):
initAuthListener() {
// this.store.dispatch(new UIActions.StartLoading());
this.afAuth.authState.subscribe(user => {
// if( user && !user.emailVerified) {
// this.store.dispatch(new UIActions.StopLoading());
// this.alertService.presentToast(this.translateService.instant("Auth.PLEASE_VALIDATE_YOUR_EMAIL_ADDRESS"), 3000);
// }
console.log(user);
alert(user);
if (user) {
if(user.emailVerified) {
this.isAuthenticated = true;
this.store.dispatch(new AuthActions.SetAuthenticated());
this.afStore.collection('profiles').doc<FullUserProfile>(user.uid).valueChanges().pipe(take(1)).subscribe(
(profile: FullUserProfile) => {
if (profile != null) {
this.store.dispatch(new AuthActions.SetUserProfile(profile));
// this.functionsGeneralDataService.initialize(profile);
this.generalDataService.initialize(profile);
this.store.dispatch(new UIActions.StopLoading());
// this.router.navigate(['/groups']);
this.goToMainPage();
} else {
return;
}
}
);
}
} else {
this.isAuthenticated = false;
this.generalDataService.unsubscribeFromAll();
this.store.dispatch(new AuthActions.SetUnauthenticated());
this.store.dispatch(new AuthActions.RemoveUserProfile());
this.store.dispatch(new GroupsActions.ClearState());
// this.router.navigate(['/login']);
}
this.store.dispatch(new UIActions.StopLoading());
});
// this.listenToRedirectResults();
}
I have tried adding the following functionality at the end of inmitAuthListener(), but without solving the problem:
listenToRedirectResults() {
firebase.auth().getRedirectResult().then((result) => {
console.log(result);
console.log(firebase.auth().currentUser);
alert("THIS IS RESULT");
this.store.dispatch(new UIActions.StartLoading());
if (result.credential) {
alert('result.credentials is not null');
var token = result.user.getIdToken();
var user = result.user;
// if(result == null || result.user == null) {
// alert('result or user null');
// this.isAuthenticated = false;
// this.generalDataService.unsubscribeFromAll();
// this.store.dispatch(new AuthActions.SetUnauthenticated());
// this.store.dispatch(new AuthActions.RemoveUserProfile());
// this.store.dispatch(new GroupsActions.ClearState());
// }
alert('will get data');
this.store.dispatch(new AuthActions.SetAuthenticated());
this.afStore.collection('profiles').doc(user.uid).valueChanges().pipe(take(1)).subscribe(
(profile: FullUserProfile) => {
this.store.dispatch(new UIActions.StartLoading());
this.isAuthenticated = true;
if (profile != null) {
this.store.dispatch(new AuthActions.SetUserProfile(profile));
// this.functionsGeneralDataService.initialize(profile);
this.generalDataService.initialize(profile);
this.store.dispatch(new UIActions.StopLoading());
this.goToMainPage();
} else {
let profile = {} as FullUserProfile;
profile.id = user.uid;
profile.email = user.email;
profile.name = user.displayName;
profile.image = { name: '', url: user.photoURL}
profile.type = 0;
profile.numberOfGroupsAllowed = 2;
this.afStore.collection('profiles').doc(user.uid).set(profile);
this.store.dispatch(new AuthActions.SetUserProfile(profile));
// this.functionsGeneralDataService.initialize(profile);
this.generalDataService.initialize(profile);
this.store.dispatch(new UIActions.StopLoading());
this.goToMainPage();
// this.router.navigate(['/groups']);
}
}
);
// this.router.navigate(['groups'])
} else {
alert('no creadential');
}
})
.catch(function(error) {
console.log(error.message);
this.store.dispatch(new UIActions.StopLoading());
this.alertService.presentToast(error.message);
});
}
Notice: If the user is deleted from users of firebase console, and tried to sign in with facebook, then user is added there, but no changes in my app.
Sorry for my dirty code, i have cleaned a lot before asking the question..
Yesterday, before adding google authentication, facebook authentication was working, but logout was not.
Sorry, but i am new to the ionic framework.

The error: I am checking if email verified for a facebook account where email is not verified. I have restructured my code.

Related

Append firebase JWT in Ember-simple-auth

I am trying to do authorization in my Ember App(2.10). My workflow is
user hit the button of Facebook login then
i'm using torii to get the access token /my user database is on firebase/
Then i send token to firebase.auth with facebook provider. It returns JWT token.
Problem is i got the JWT token and now i have to login to my emberapp. I am trying to customize torii authenticator here. How can i implement this in ember app. Below is my authenticator:
authenticate() {
return this._super(...arguments).then((torii) => {
const serverTokenEndpoint = this.get('serverTokenEndpoint');
return this.get('ajax').request(serverTokenEndpoint, {
type: 'POST',
data: {
'type': torii.provider,
'client_id': this.client,
'token': torii.authorizationCode
}
}).then((token) => {
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives Facebook Access Token.
// JWT-token=result.user.Cd
// JWT-token.iat at=result.user.ea.Sa
// JWT-token-refresh = result.user.refreshToken
console.log(result)
// token = result.user.Cd;
// const expiresAt = this._absolutizeExpirationTime(result.user.ea.Sa);
token = Ember.assign(token, { 'expires_at': result.user.ea.Sa });
// this._scheduleAccessTokenRefresh(result.user.ea.Sa, expiresAt, result.user.refreshToken, torii);
return Ember.assign(token, {'torii': torii});
});
});
});
}
Check out this guide in the ESA repo. It covers torii and Github auth but the general concepts are the same for your use case.
#marcoow I did try this and it authenticate but when token is expired i can not refresh token.Seems it is not the right approach, How can i refresh token using firebase
export default ToriiAuthenticator.extend({
torii: Ember.inject.service(),
ajax: Ember.inject.service(),
refreshAccessTokens: true,
rejectWithResponse: false,
restore(data) {
return new RSVP.Promise((resolve, reject) => {
const now = (new Date()).getTime();
const refreshAccessTokens = this.get('refreshAccessTokens');
if (!isEmpty(data['expires_at']) && data['expires_at'] < now) {
// if (refreshAccessTokens) {
this._refreshAccessToken(data['expires_in'], data['refresh_token']).then(() => {
resolve();
}).catch(function(error) {
reject();
});
// } else {
// reject();
// }
} else {
if (!this._validate(data)) {
reject();
} else {
this._scheduleAccessTokenRefresh(data['expires_in'], data['expires_at'], data['refresh_token']);
resolve(data);
}
}
});
},
authenticate() {
return new Ember.RSVP.Promise((resolve, reject) => {
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then((result) => {
var expires_in = this._absolutizeExpirationTime(result.user.ea.Sa);
var expiresAt = result.user.ea.Sa;
result = Ember.assign(result, { 'expires_at': expiresAt, 'expires_in': expires_in, 'access_token': result.user.Cd, 'refresh_token': result.refresh_token });
resolve(result)
});
// const useResponse = this.get('rejectWithResponse');
// const provider = new firebase.auth.FacebookAuthProvider();
// firebase.auth().signInWithPopup(provider).then((result) => {
// let expires_in = result.user.ea.Sa;
// const expiresAt = this._absolutizeExpirationTime(expires_in);
// this._scheduleAccessTokenRefresh(expires_in, expiresAt, result.refresh_token);
// if (!isEmpty(expiresAt)) {
// result = Ember.assign(result, { 'expires_at': expiresAt, 'expires_in': expires_in, 'access_token': result.user.Cd, 'refresh_token': result.refresh_token });
// }
// // resolve(result);
// }, (response) => {
// Ember.run(null, reject, useResponse ? response : response.responseJSON);
// }).catch(function(error) {
// console.log(error);
// });
});
},
invalidate(data) {
const serverTokenRevocationEndpoint = this.get('serverTokenRevocationEndpoint');
return new RSVP.Promise((resolve) => {
if (isEmpty(serverTokenRevocationEndpoint)) {
resolve();
} else {
if (!Ember.isEmpty(data.access_token)) {
delete data.access_token;
firebase.auth().signOut();
resolve();
}
}
});
},
_scheduleAccessTokenRefresh(expiresIn, expiresAt, refreshToken) {
console.log('sched')
const refreshAccessTokens = this.get('_refreshAccessTokens');
if (refreshAccessTokens) {
const now = (new Date()).getTime();
if (isEmpty(expiresAt) && !isEmpty(expiresIn)) {
expiresAt = new Date(now + expiresIn * 1000).getTime();
}
const offset = this.get('tokenRefreshOffset');
if (!isEmpty(refreshToken) && !isEmpty(expiresAt) && expiresAt > now - offset) {
run.cancel(this._refreshTokenTimeout);
delete this._refreshTokenTimeout;
if (!testing) {
this._refreshTokenTimeout = run.later(this, this._refreshAccessToken, expiresIn, refreshToken, expiresAt - now - offset);
}
}
}
},
_refreshAccessToken(expiresIn, refreshToken) {
console.log('refresh');
const data = { 'grant_type': 'refresh_token', 'refresh_token': refreshToken };
firebase.auth().currentUser.getToken(/ forceRefresh / true).then((response) => {
return new RSVP.Promise((resolve, reject) => {
// firebase.auth().currentUser.getToken(true).then((response) => {
expiresIn = response.user.ea.Sa || expiresIn;
refreshToken = response.refresh_token || refreshToken;
const expiresAt = this._absolutizeExpirationTime(expiresIn);
const data = assign(response, { 'expires_in': expiresIn, 'expires_at': expiresAt, 'refresh_token': refreshToken });
this._scheduleAccessTokenRefresh(expiresIn, null, refreshToken);
this.trigger('sessionDataUpdated', data);
resolve(data);
}, (response) => {
warn(`Access token could not be refreshed - server responded with ${response.responseJSON}.`);
reject();
});
});
},
_absolutizeExpirationTime(expiresIn) {
if (!isEmpty(expiresIn)) {
return new Date((new Date().getTime()) + expiresIn * 1000).getTime();
}
},
_validate(data) {
return !isEmpty(data['access_token']);
}
});

What does this `checkSession` function do?

I have included the firebase and angularfire libraries to my ionic framework project.
I am following the below link for my sample project.
https://www.sitepoint.com/creating-firebase-powered-end-end-ionic-application/
I am not able to understand how the 'checkSession' function in the below 'app.js' works. Could someone please explain?
How can we call the 'auth' function which is inside 'checkSession' function?
app.js
angular.module('bucketList', ['ionic', 'firebase', 'bucketList.controllers'])
.run(function($ionicPlatform, $rootScope, $firebaseAuth, $firebase, $window, $ionicLoading) {
$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();
}
$rootScope.userEmail = null;
$rootScope.baseUrl = 'https://bucketlist-app.firebaseio.com/';
var authRef = new Firebase($rootScope.baseUrl);
$rootScope.auth = $firebaseAuth(authRef);
$rootScope.show = function(text) {
$rootScope.loading = $ionicLoading.show({
content: text ? text : 'Loading..',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
};
$rootScope.hide = function() {
$ionicLoading.hide();
};
$rootScope.notify = function(text) {
$rootScope.show(text);
$window.setTimeout(function() {
$rootScope.hide();
}, 1999);
};
$rootScope.logout = function() {
$rootScope.auth.$logout();
$rootScope.checkSession();
};
$rootScope.checkSession = function() {
var auth = new FirebaseSimpleLogin(authRef, function(error, user) {
if (error) {
// no action yet.. redirect to default route
$rootScope.userEmail = null;
$window.location.href = '#/auth/signin';
} else if (user) {
// user authenticated with Firebase
$rootScope.userEmail = user.email;
$window.location.href = ('#/bucket/list');
} else {
// user is logged out
$rootScope.userEmail = null;
$window.location.href = '#/auth/signin';
}
});
}
});
})

How to set up profiles and sessions in Firebase and Ionic using Facebook Auth

I am very new to Firebase and struggling to set up a system where a user logs in via Facebook, and his/her profile picture is saved in a database.
I have a users and also a uids array in Firebase. What I want the flow to be is:
Login via Facebook
Store some memory of the user so they don't have to login again on the app, or perhaps store into the uids and users array
Get the existing name, location to fill into a profile section of the app
Update any of these to then fill into the Firebase users database, as well as add new fields e.g. location
Here is my current setup:
Login Controller:
.controller('LoginCtrl', ['Auth', '$state', '$location', '$scope', '$rootScope', '$firebaseAuth', '$window',
function (Auth, $state, $location, $scope, $rootScope, $firebaseAuth, $window) {
// check session
//$rootScope.checkSession;
// Create a callback to handle the result of the authentication
$scope.user = {
email: this.email,
password: this.password
};
$scope.validateUser = function (user) {
$rootScope.show('Please wait.. Authenticating');
console.log('Please wait.. Authenticating');
var email = this.user.email;
var password = this.user.password;
/* Check user fields*/
if (!email || !password) {
$rootScope.hide();
$rootScope.notify('Error', 'Email or Password is incorrect!');
return;
}
/* All good, let's authentify */
Auth.$authWithPassword({
email: email,
password: password
}).then(function (authData) {
console.log(authData);
//$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
$rootScope.hide();
}).catch(function (error) {
console.log("Login Failed!", error);
if (error.code == 'INVALID_EMAIL') {
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'INVALID_PASSWORD') {
$rootScope.notify('Invalid Password');
}
else if (error.code == 'INVALID_USER') {
$rootScope.notify('Invalid User');
}
else {
$rootScope.notify('Oops something went wrong. Please try again later');
}
$rootScope.hide();
//$rootScope.notify('Error', 'Email or Password is incorrect!');
});
};
$scope.loginWithGoogle = function () {
Auth.$authWithOAuthPopup('google')
.then(function (authData) {
$state.go($location.path('app/meals'));
});
};
$scope.loginWithFacebook = function () {
Auth.$authWithOAuthPopup('facebook')
.then(function (authData) {
console.log(authData);
$state.go($location.path('app/meals'));
})
.catch(function(error){
if (error.code === "TRANSPORT_UNAVAILABLE") {
Auth.$authWithOAuthRedirect("facebook").then(function (authData) {
// User successfully logged in. We can log to the console
// since we’re using a popup here
console.log(authData);
$state.go($location.path('app/meals'));
});
} else {
// Another error occurred
console.log(error);
}
});
};
}
])
Key functions like get session I want in $rootScope:
.run(function ($ionicPlatform, $rootScope, $firebaseAuth, $firebase, $window, $ionicLoading) {
$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);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
$rootScope.userEmail = null;
$rootScope.baseUrl = 'https://[myappurl.firebaseio.com/';
var authRef = new Firebase($rootScope.baseUrl);
$rootScope.auth = $firebaseAuth(authRef);
$rootScope.authData = authRef.getAuth();
$rootScope.show = function(text) {
$rootScope.loading = $ionicLoading.show({
content: text ? text : 'Loading..',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
};
$rootScope.hide = function() {
$ionicLoading.hide();
};
$rootScope.notify = function(text) {
$rootScope.show(text);
$window.setTimeout(function() {
$rootScope.hide();
}, 1999);
};
$rootScope.logout = function() {
authRef.unauth();
$rootScope.authDataCallBack;
};
$rootScope.checkSession = function() {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
} else {
console.log("No session so logout");
$rootScope.userEmail = null;
$window.location.href = '#/auth/signin';
}
}
$rootScope.authDataCallBack = function(authData) {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
$window.location.href = '#/auth/signin';
}
};
});
})
The profile page:
<ion-view view-title="Profile">
<ion-content class="has-header">
<div class="list card">
<div class="item">
<h2>{{user.name}}</h2>
<p>{{user.city}}</p>
</div>
<!--https://github.com/israelidanny/ion-profile-picture-->
<!--<div class="item item-body">-->
<!--<img src="http://graph.facebook.com/{{user.id}}/picture?width=270&height=270"/>-->
<!--</div>-->
</div>
</ion-content>
</ion-view>
Auth factory:
app.factory('Auth', ['rootRef', '$firebaseAuth', function (rootRef, $firebaseAuth) {
return $firebaseAuth(rootRef);
}]);
If it helps, here is my SignUpCtrl which pushes items into the users array and also stores an array of uids of users already set up in the app.
.controller('SignUpCtrl', [
'$scope', '$rootScope', '$firebaseAuth', '$window', 'Auth',
function ($scope, $rootScope, $firebaseAuth, $window, Auth) {
$scope.user = {
firstname: this.firstname,
lastname: this.lastname,
email: "",
password: ""
};
$scope.createUser = function () {
var firstname = this.user.firstname;
var lastname = this.user.lastname;
var email = this.user.email;
var password = this.user.password;
if (!email || !password) {
$rootScope.notify("Please enter valid credentials");
return false;
}
$rootScope.show('Please wait.. Registering');
$rootScope.auth.$createUser(
{email: email, password: password})
.then(function (user) {
console.log('user is created');
$rootScope.hide();
$rootScope.userEmail = user.email;
var usersRef = new Firebase('https://foodsharingapp.firebaseio.com/users');
var keyRef = usersRef.push({
'uid': user.uid,
'email': email,
'firstname': firstname,
'lastname': lastname
});
var uidRef = new Firebase('https://[myapp].firebaseio.com/uids/' + user.uid + '/' + keyRef.key());
uidRef.set({'registered': true});
$window.location.href = ('#/app/meals');
}, function (error) {
console.log('error unfortunately');
$rootScope.hide();
if (error.code == 'INVALID_EMAIL') {
console.log('invalid email');
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'EMAIL_TAKEN') {
console.log('email taken');
$rootScope.notify('Email Address already taken');
}
else {
console.log('not sure what happened');
$rootScope.notify('Oops something went wrong. Please try again later');
}
});
}
Questions:
I want to call $rootScope.authDataCallBack(authData) on any controller to get the name and any details of the user_id logged in, however this is not working. Am I thinking about this right? How can I use my $rootScope functions as ways to obtain global information?
When I log in I see the Facebook object appearing fine, should I use the Facebook ID as a uid to store in my array?
On any view, how can I use the session uid or authData to then match against my list of users in the user array and pull out more detailed user info? Is there some pseudocode I can use and would this be in every function in my controller, or would it be split between factory and controller?

react-native-fbsdk - how to get user profile?

onLoginFinished's result just tells me the granted permissions. From the repo, not clear how to get the user profile. Seems like react-native-fbsdkcore should wrap FBSDKProfile.h but don't see where it does.
var FBSDKLogin = require('react-native-fbsdklogin');
var {
FBSDKLoginButton,
} = FBSDKLogin;
var Login = React.createClass({
render: function() {
return (
<View>
<FBSDKLoginButton
onLoginFinished={(error, result) => {
if (error) {
alert('Error logging in.');
} else {
if (result.isCanceled) {
alert('Login cancelled.');
} else {
alert('Logged in.');
}
}
}}
onLogoutFinished={() => alert('Logged out.')}
readPermissions={[]}
publishPermissions={['publish_actions']}/>
</View>
);
}
});
Found out you can get logged in user's profile with Graph API.
// Create a graph request asking for user's profile
var fetchProfileRequest = new FBSDKGraphRequest((error, result) => {
if (error) {
alert('Error making request.');
} else {
// Data from request is in result
}
}, '/me');
// Start the graph request.
fetchProfileRequest.start();
There is an easier way to do it. Rather than manually making the graph request yourself, 'react-native-fbsdkcore' package to get the data associated with the logged in user (if there is one)
var
FBSDKCore = require('react-native-fbsdkcore');
var {
FBSDKAccessToken,
} = FBSDKCore;
FBSDKAccessToken.getCurrentAccessToken((token) => {
// token will be null if no user is logged in,
// or will contain the data associated with the logged in user
});
cphackm address is that in this issue #2
Using #flow, here is a full example:
FbLogin.js
// #flow
import * as React from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken } from 'react-native-fbsdk';
import { FbService } from '#services';
import { toast } from '#libs/helpers';
type LoginResult = {
isCancelled: boolean,
grantedPermissions?: Array<string>,
declinedPermissions?: Array<string>
};
type Props = {
store: {
Account: Object
}
};
type State = {
token?: string
};
export default class Login extends React.Component<Props, State> {
componentDidMount() {
AccessToken.getCurrentAccessToken().then(tokenData => {
if (tokenData) {
console.log('[-- tokenData --]', tokenData);
const { accessToken, userID } = tokenData;
if (accessToken) {
console.log('[-- accessToken, userID --]', accessToken, userID);
this.setState({ token: accessToken });
// this._getUserInformation();
}
}
});
}
_getUserInformation = () => {
const { token } = this.state;
const { Account } = this.props.store;
if (token) {
FbService.getFbUserData(token, (error, result) => {
if (error) {
console.log('[-- error --]', error);
} else {
Account.provider = 'facebook';
Account.authorized = true;
Account.current = { password: '', token, ...result };
console.log('[-- responseFbUserData --]', result);
}
});
}
};
render() {
return (
<View>
<LoginButton
readPermissions={['public_profile']}
onLoginFinished={(error: Object, result: LoginResult) => {
if (error) {
alert('Login failed with error: ' + error.toString());
} else if (result.isCancelled) {
alert('Login was cancelled');
} else {
if (result) {
this._getUserInformation();
}
}
}}
onLogoutFinished={() => toast('User logged out', 'info')}
/>
</View>
);
}
}
/* AccessToken
accessToken: string,
applicationID: string,
userID: string,
permissions: Array<string>,
declinedPermissions: Array<string>,
accessTokenSource?: string,
expirationTime: number,
lastRefreshTime: number,
*/
FbService.js
// #flow
import * as React from 'react';
import { GraphRequestManager, GraphRequest, AccessToken } from 'react-native-fbsdk';
export function getFbUserData(token: string, callBack: Function) {
const profileRequestConfig = {
httpMethod: 'GET',
version: 'v2.12',
parameters: {
fields: {
string: 'id, name, email'
}
},
accessToken: token
};
const profileRequest = new GraphRequest('/me', profileRequestConfig, callBack);
new GraphRequestManager().addRequest(profileRequest).start();
}

Combining koa-passport with koa-router (getting user data)

I have created a login which is able to login a user and store the user if they are new in the database.
The user is then redirected to / and then is checked if they are authenticated or not, see below (app.js):
.get('/', function* () {
if (this.isAuthenticated()) {
yield this.render('homeSecure', {}); // <-- need user data here
} else {
yield this.render('homePublic', {});
}
As I commented in the code, I would like to send the user object of which is logged in. I have no idea how to get a hold of the id of the person logged in as the documentation for koa in general is not as complete as that of express.
I am using koa-generic-session-mongo to handle my sessions. Here is my GoogleStrategy (auth.js):
var user = null;
// ...
var GoogleStrategy = require('passport-google').Strategy;
passport.use(new GoogleStrategy({
returnURL: 'http://localhost:' + (process.env.PORT || 3000) + '/auth/google/callback',
realm: 'http://localhost:' + (process.env.PORT || 3000)
},
function (identifier, profile, done) {
var emails = new Array();
for (var i = 0; i < profile.emails.length; i++) {
emails.push(profile.emails[i].value);
}
co(function* () {
yield users.findOne({
emails: emails
});
});
if (user === null) { // first time signin, create account
co(function* () {
user = {
id: 1,
name: profile.displayName,
emails: emails
};
yield users.insert(user);
});
}
console.log(user);
done(null, user);
}));
publicRouter
.get('/', function* () {
if (this.isAuthenticated()) {
yield this.render('homeSecure', {
user: this.req.user
});
} else {
yield this.render('homePublic', {});
}
})...
Disclaimer: I've not used koa-passport, I've just looked at the code.
According to the source code of the koa-passport library, the property you're looking for is passport.user, and is used like so:
app.use( function*(){
var user = this.passport.user
})
Thus, your code sample would become
.get('/', function* () {
if (this.isAuthenticated()) {
yield this.render('homeSecure', this.passport.user );
} else {
yield this.render('homePublic', {});
}
If that does not work, this file leads me to suspect that koa-passport follows the standard passport interface and provides this.user to the request.