FlowRouter and email verification token - javascript

If I change the verify-email so it wouldn't have the # in it , My user is not getting verified , once they landed on the page i want them to , and keeps asking for email verification .shown in code below
this is how i change the verify email link
Accounts.urls.verifyEmail = function(token){
return Meteor.absoluteUrl("verify-email/" + token);
};
and here is my router ( I am using FlowRouter not iron-router )
FlowRouter.route('/verify-email/:token',{
name: 'verifyEmail',
action: function(){
BlazeLayout.render('MainLayout', {content: 'VerifyEmail'});
}
});
and here is how I verify the user
Template.VerifyEmail.created = function() {
if (Accounts._verifyEmailToken) {
Accounts.verifyEmail(Accounts._verifyEmailToken, function(err) {
if (err != null) {
if (err.message = 'Verify email link expired [403]') {
console.log('Sorry this verification link has expired.')
}
} else {
console.log('You account is active now !')
}
});
}
};
If I do not change the sent verify link and let the original verification token sent , once its clicked it goes to the home page of and i need to change the Template.VerifyEmail.created = function() to
Template.Home.created = function() it works which is not what i want
thanks

Related

Angular 12: reload header after login/ any navigation

I have angular application. In header I need to show notifications after user login like facebook , the notification unread count and on click notifications messages. Also after login need to redirect to timeline. onSubmit function in header ts file calls on login form submit.
header TS
ngOnInit() {
if (this.isLoggedIn) {
this.GetNotifications();
}
}
get isLoggedIn() {
return this.authService.isLoggedIn();
}
onSubmit() {
this.authService
.login(this.f.email.value, this.f.password.value)
.subscribe(
(data) => {
if (data["status"] === true || data["count"] === true) {
window.localStorage.setItem(
"myUser",
JSON.stringify(data["data"])
);
window.localStorage.setItem("isLoggedIn", "true");
this.router.navigate(["timeline"]).then(() => {
window.location.reload();
});
} else {
window.localStorage.setItem("isLoggedIn", "false");
}
},
(error) => {
window.localStorage.setItem("isLoggedIn", "false");
}
);
}
Auth service Ts
login(email: string, password: string) {
let input = new FormData();
const headers = { 'APP-TOKEN': 'xxxx' };
input.append('email', email);
input.append('password', password);
return this.http
.post<any>(`${this.serverUrl}api/v1/login`, input, { headers: headers })
.pipe(
map((user) => {
if (user && user.token) {
localStorage.setItem('myUser', JSON.stringify(user));
}
return user;
}),
catchError(this.handleError)
);
}
isLoggedIn() {
if (localStorage.getItem('myUser')) {
return true;
}
return false;
}
The problem is without window.location.reload(); the count/notification data not shows in header. After login, it needs reload after navigation to timeline. But window.location.reload(); gives me problem on production so I have used useHash: true in app-rounting.module.ts. Again that giving me problem in SSR implementation. So I need alternate way for reloading header after every navigation. As if I go to another header menu there also I need to use window.location.reload(); to show notification data in header.
I have tried this way. But not works as expected in above flow.
How I can get rid of window.location.reload(); and get same functionality/get notification data after navigation in angular without using window?
Please help and guide.

Is it possible to retrieve user attributes from aws cognito in javascript on page load (Before login)?

I am using AWS cognito and successfully fulfilling all my requirements. However, there is a scenario is which I am struggling. I have an Auth code field along with username and password on login page and my requirement is to populate that auth code field before logging in.
I am successfully retrieving user attributes after login but in this case, I need to retrieve a user attribute before login to populate the input field.
My question is that is it possible to fetch a specific user attribute (Auth Code) before even login?
Below is the code for your reference that I am using to retrieve user attributes on clicking login button. Please have a look.
function signInButton() {
var authcode = document.getElementById("authcode").value;
var authenticationData = {
Username : document.getElementById("inputUsername").value,
Password : document.getElementById("inputPassword").value,
Authcode : document.getElementById("authcode").value,
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : _config.cognito.userPoolId, // Your user pool id here
ClientId : _config.cognito.clientId, // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : document.getElementById("inputUsername").value,
Pool : userPool,
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
var userid = document.getElementById("inputUsername").value;
console.log('userid: ',userid)
if(authcode=='1234'){
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/////Getting User Attributes//////
AWS.config.update({region:'us-east-1'});
var params = {
AccessToken: accessToken
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.getUser(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} // an error occurred
else{
console.log(data);
} // successful response
})
/////// End /////////
if(accessToken!=null || accessToken!=''){
$.post("testapi.php", {userid: userid}, function(result){
console.log('result: ',result);
if(result.includes("accept")){
window.open("landing.php?status=Logged In","_self");
}else{
alert('Unauthorized User ID. Please try again with correct ID!')
}
});
}
console.log(accessToken);
},
onFailure: function(err) {
alert(err.message || JSON.stringify(err));
window.open("landing.php?status=Not Logged In","_self");
},
});
}else{
alert('Incorrect Authentication Code. Please try again');
}
}
Please suggest a possible solution.
Thank you

Resent email verification link not changing verified to true

I'm setting up a custom authentication system in my meteor app.
When a user signs up, they are sent an email verification link. If they click on this, it changes the verification boolean to true as expected.
I have a button in the users account setting page that allows them to resend a verification email if needed. Clicking on this works ok and they receive another email with a different link.
When this new link is clicked, it redirects to the home page but it doesn't verify the email address.
My guess is that the users account isn't aware of the new token.
//server code
Meteor.methods({
'sendVerificationEmail' : function(userId, primaryEmail){
var userId = Meteor.user();
Accounts.sendVerificationEmail(userId, primaryEmail, function (error) {
if (! error) {
return alert('Verfication email sent');
} else {
return alert(error);
};
});
}
});
//Client code
Accounts.onEmailVerificationLink(function (token, done) {
Accounts.verifyEmail(token, function (error) {
if (! error) {
console.log('Account verified');
alert('Account verified');
}
done();
// show something if there was an error.
});
});
// Email verification route
Router.route('/verify-email/:token', {
name: 'verifyEmail'
});

How to handle Callback/Redirects from dpd-passport via Google strategy?

I am building a project using Deployd for assistance with my API, and dpd-passport for authentication.
I seem to have everything authenticating, with session keys behind handed out and users authentication through Google, but I am having trouble with my redirectURLs, as well as translating the callback page I am returned with.
I have dug into the dpd-passport/index.js file, and I believe this is the relevant information:
var sendResponse = function(ctx, err, config) {
var sessionData = ctx.session.data;
var returnUrl = (ctx.req.cookies && ctx.req.cookies.get('_passportReturnUrl')) || null;
if(returnUrl) {
var redirectURL = url.parse(returnUrl, true);
// only append if not disabled
if(!config.disableReturnParams) {
// delete search so that query is used
delete redirectURL.search;
// make sure query is inited
redirectURL.query = redirectURL.query || {};
if(err) {
redirectURL.query.success = false;
redirectURL.query.error = err;
} else {
// append user + session id to the redirect url
redirectURL.query.success = true;
if(!config.disableSessionId) {
redirectURL.query.sid = sessionData.id;
redirectURL.query.uid = sessionData.uid;
}
}
}
var redirectURLString = '';
try {
redirectURLString = url.format(redirectURL);
} catch(ex) {
console.warn('An error happened while formatting the redirectURL', ex);
}
// redirect the user
ctx.res.setHeader("Location", redirectURLString);
ctx.res.statusCode = 302;
ctx.done(null, 'This page has moved to ' + redirectURLString);
} else {
if(err) {
ctx.res.statusCode = 401;
console.error(err);
return ctx.done('bad credentials');
} else {
ctx.done(err, { path: sessionData.path, id: sessionData.id, uid: sessionData.uid });
}
}
};
After successfully authenticating, I am given a returnUrl of:
http://localhost:3000/auth/google/callback?code=4/l4o-H2F4QKJ5tdKbVbGfWygTGRvhHgr9zrHWImFFKdM#
with an body of:
{"path":"/users","id":"d03c0faccfe41134c193266afef979c5af33adf935aeff45844b0f9473dee4ab1fbd1114240e13ea9a542785da3845cfec984e3a5b8cb188d6c595b6fc39a726","uid":"747f97a9bcfa9811"}
which seems to me like my results are hitting the final else statement in the topmost code block.
If this is true, then my returnUrl is NULL.
Tracing back the returnUrl code in the dpd-passport file, it looks like it should be grabbing this from cookies in the follow snippet:
if(ctx.query.redirectURL && this.config.allowedRedirectURLs) {
try {
this.regEx = this.regEx || new RegExp(this.config.allowedRedirectURLs, 'i');
if(ctx.query.redirectURL.match(this.regEx)) {
// save this info into the users session, so that we can access it later (even if the user was redirected to facebook)
if (ctx.res.cookies) ctx.res.cookies.set('_passportReturnUrl', ctx.query.redirectURL);
} else {
debug(ctx.query.redirectURL, 'did not match', this.config.allowedRedirectURLs);
}
} catch(ex) {
debug('Error parsing RedirectURL Regex!', ex);
}
}
To add to this, I have my allowedRedirectUrls in the config as:
^http://localhost:3000/.*$
I am at a loss and am hoping there is something obvious that I am missing.
I have seen the passport routes and authentication strategies similar to the following, but have been unsuccessful in implementing this into dpd-passport:
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
To add to this all, I am using ui-router/AngularJS.
You have to supply the redirectURL to dpd-passport through the link that starts the oauth procedure:
http://localhost:2403/auth/google?redirectURL=http://localhost

Facebook on PhoneGap/Cordova -- File protocol?

Have searched everywhere for this without luck. I'm getting this error when running PhoneGap app on device (works fine in browser):
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
This is because I haven't added the host to the facebook app configuration. BUT, PhoneGap/Cordova accesses the app through the file:/// protocol, so there's no domain for me to add to Facebook.
Potential options: 1) Figure out how to use a cordova native plugin (this is hard because we're using Parse), 2) Switch Cordova to use localhost instead of file:// (not sure how to do this).
I've been down this road and ultimately went with option #1. Since we're not really dealing with a website there is no domain to add. Cordova needs to use file:// I don't think there is any way around it. The trick with using the plugin is keeping the login status in sync with Parse (use Parse.FacebookUtils.logIn). He's some code that should help you out. This is how I check the login status:
try {
console.log("Trying to get FB login status");
return FB.getLoginStatus(function(response) {
var accessToken, currentView, expDate, facebookAuthData, uid, user;
console.log(response);
if (response.status === "connected") {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log("Logged in!");
user = Parse.User.current();
if (user != null) {
console.log("we have a user");
} else {
console.log("we don't have a user... need to login with parse");
expDate = new Date(response.authResponse.expirationTime);
facebookAuthData = {
id: response.authResponse.userID + "",
access_token: response.authResponse.accessToken,
expiration_date: expDate.toISOString()
};
Parse.FacebookUtils.logIn(facebookAuthData, {
success: function(_user) {
return console.log("Logged in with Parse!");
},
error: function(error1, error2) {
return console.log("Unable to create/login as Facebook user");
}
});
}
} else {
// not logged in to fb...
}
});
} catch (e) {
return console.log(e);
}
Here's how I handle logins:
return FB.Event.subscribe("auth.authResponseChange", function(response) {
var expDate, facebookAuthData;
if (response.status === "connected") {
console.log(response.status);
try {
expDate = new Date(response.authResponse.expirationTime);
facebookAuthData = {
id: response.authResponse.userID + "",
access_token: response.authResponse.accessToken,
expiration_date: expDate.toISOString()
};
return Parse.FacebookUtils.logIn(facebookAuthData, {
success: function(_user) {
//return window.location.hash = "loginsuccess";
},
error: function(error1, error2) {
console.log("Unable to create/login to as Facebook user");
}
});
} catch (ex) {
return console.log("parse login error " + ex);
}
} else if (response.status === "not_authorized") {
// handle not auth event
} else {
// take them home?
}
});
}

Categories

Resources