I have a function that deletes the current logged in user:
auth.currentUser.delete().then(logoutOfApp)
.catch((error) => alert(error)));
It works just fine, but I want to make someone an admin, so I would like him to have an option to delete other accounts, so is there a way to do something like this?
auth.something(UserID of the user that i want to delete).delete()
Use firebase-admin NPM package in your backend;
app.get('/delete', function (req, res) {
const sessionCookie = req.cookies.session || '';
res.clearCookie('session');
if (sessionCookie) {
// Verify user and then delete the user.
admin.auth().verifySessionCookie(sessionCookie, true).then(function(decodedClaims) {
return admin.auth().deleteUser(userIdToDelete);
})
.then(function() {
// Redirect to login page on success.
res.redirect('/');
})
.catch(function() {
// Redirect to login page on error.
res.redirect('/');
});
} else {
// Redirect to login page when no session cookie available.
res.redirect('/');
}
});
Related
I am using the library auth0/nextjs. I am trying to handle the email verification. I have access to the email_verification variable. If not verified, it will redirect to the page /please-verifiy-your-email.
At the moment I am using handleCallback method which is provided by auth0/nextjs.
Code:
const afterCallback = (req, res, session, state) => {
if (!session.user.email_verified) {
res.status(200).redirect('/please-verifiy-your-email')
}
return session;
};
export default auth0.handleAuth({
async login(req, res) {
try {
await auth0.handleLogin(req, res, {
authorizationParams: {
audience: 'https://dev-okz2bacx.us.auth0.com/api/v2/',
scope: 'openid profile email read:branding'
},
returnTo: "/dashboard"
});
} catch (error) {
res.status(error.status || 400).end(error.message);
}
},
async callback(req, res) {
try {
await auth0.handleCallback(req, res, { afterCallback });
} catch (error) {
res.status(error.status || 500).end(error.message);
}
}
});
How can I make sure, the user is still logged in, to get his email for a resend or the possibility to change his email.
He also needs the chance to do a new sign up , because when I will call api/auth/login after login with the unverified email, it will redirect automatically to /please-verifiy-your-email. I guess the session is not killed and auth0 goes back redirecting even tho I didn’t had the chance to sign up again.
Would be really cool if I get a few inputs.
It would solve the problem if I could log in the user and then it would redirect to /please-verifiy-your-email. I would be able to get his email address, name for further functions like resend verification. Right now I call api/auth/me I get:
{"error":"not_authenticated","description":"The user does not have an
active session or is not authenticated"}
Should i redirect or render the page? What is the best practice for authentication.
var User = require('models/user.js');
User.authenticate(req.body.email, req.body.password)
.then(function(error, user){
//IF SUCCES AND NO ERROR
res.redirect('/profile');
//OR
res.render('profile.pug');
})
.catch(error => console.log(error));
In your route you should do:
When everything is ok (no errors):
return res.render('view',{
param1:param2
});
When error appears:
req.flash('error', error.message); // If you are using flash
return res.redirect('back'); // It will redirect user back
// and display some error message
If you are going to write middleware for authentication:
middlewareObj.isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()){
return next();
} else {
return res.redirect('/signin'); // Or status code
}
};
I am trying to add SAML authentication using passport-saml for my application. I am using Angular for routing. On loading of the homepage, I check for a user through a GET request to my node server "/auth" to check req.user, if it's true, I send back logged in user data; if false, I send back an error message. I have data binding on this user data response so in the event of no user data, I still show "Log in" button.
On click of the "Log in" button, I perform a redirect to the node server "/login". This does passport.authenticate function which runs and then ties in with "/assert" when it's complete to perform a redirect.** It is at this point I am running into a problem.** My redirect always goes to "/" because I am performing a redirect and using angular routing so I dont know how to store this route say "/myPage1" or "/myPage2". NOTE: I do not want to always send back to "/myPage1", I want to be able to "Login" from any view in the SPA.
Am I going about this in the wrong way? Is this a limitation of using Angular routing?
Angular
$scope.login = function () {
window.location.href = 'http://example.com/login';
};
function getCreds() {
$http.get('http://example.com/auth', { withCredentials: true })
.then(function (response) {
$scope.creds = response.data;
});
}
Node.js
app.get('/login', passport.authenticate('saml', { failureRedirect: '/login' }));
app.post("/assert", passport.authenticate('saml', { failureRedirect: '/login' }), function (req, res) {
// console.log('session' + JSON.stringify(req.session));
// console.log("original url " + req.session.originalUrl);
if (req.session.originalUrl) {
res.redirect(req.session.originalUrl);
}
else {
res.redirect('/');
}
});
app.get('/auth', function (req, res) {
var authenticated = req.user;
if (authenticated) {
res.send(req.user);
} else {
res.send({statusCode: 401, message: 'User session is not alive'});
}
});
I have found a way to achieve the desired effect.
Before making the "Login" call, I make another api call to "/setSessionRedirectUrl" which passes the current window.location.href from angular to node server for session storage.
app.post('/setSessionRedirectUrl', function (req, res) {
req.session.samlLoginRedirectUrl = req.body.redirectUrl;
res.send();
});
Then when the assert function is being run after login, it is looking for the req.session.samlLoginRedirectUrl to redirect to. It works!
I am trying to set up a simple authentification system with Parse Server:
app.js
...
app.get('/login', (req, res) => {
res.render('login.ejs');
});
app.post('/login', (req, res) => {
console.log('POST /login\t' + util.inspect(req.body));
driver.login(req, (err, user) => {
//Here, user is defined
if(err) {
res.redirect('/login');
} else {
res.redirect('/user');
}
});
});
...
driver.js:
...
function login(req, callback) {
var username = req.body.username,
password = req.body.password;
Parse.User.logIn(username, password, {
success: (user) => {
callback();
},
error: (user, error) => {
callback(JSON.stringify(error));
}
});
}
function isLoggedIn(req, callback) {
console.log('isLoggedIn?');
console.log(util.inspect(req.user)); //undefined
if(req.user) {
callback();
} else {
callback('Not logged in');
}
}
...
When I access /login, I can login just fine, and get redirected to /user without any error, but on /user, which use isLoggedIn as a middleware, req.user is undefined.
I have seen others with the same problem when searching, but the post where either old (<2015), using another part of the JSSDK (react/browser), or just didn t get any answer.
I know I could use session, and recreate the user each time based on that, but it feels really hackish, is it really the supported way?
You have two routes to go, either have a REST-full server, which means users are not persistent between route calls, STATE-full and use sessions.
Luckily there is a really good nodejs authentication middleware already build that will handle all this session managment. This is called passportJS. Documentation can be found here: http://passportjs.org/docs
You can not only have authentication through local logins, but have support for authentication with google, facebook, github and many more. This is done through what are called Strategies. You use google-strategy for having google oauth, facebook-stradegy for facebook oauth, etc.
What you would be looking for is a local-strategy, which is called this because you want to authenticate with local user credentials. This strategy can be found here: https://www.npmjs.com/package/passport-local
you will need both passport and passport local and to install simply run
npm install passport passport-local
From there, just go through the documentation I have linked above for how to set everything up.
To develop my answer to blablabla comment, who asked what I ended up using.
In my case, I was develloping a REST API, and the session data wasn't expected to change once connected.
So what I did is delegate the session to the client, and go full stateless, by using JWT.
When the client is authentified, I encrypt his session data in a Json Web Token, and send him. When he try to access a protected page, he send me the JWT, which I can decrypt, and recreate req.user based on the information within.
My middleware look like this:
function isLoggedIn(req, res, next) {
//If there is a token
if(req.headers != null && req.headers.token != null) {
//Verify it and extract the user's data
verify(req.headers.token, (err, user) => {
if(err != null) {
res.status(401);
res.json({error: err});
} else {
//Recreate req.user
req.user = user;
next();
}
});
} else {
res.status(401);
res.json({error: 'No token'});
}
}
function verify(token, callback) {
//Verify the token
jwt.verify(token, jwtSecret, (error, user) => {
if(error != null) {
callback(error);
} else {
Separately check if logged into Parse
parse.isLoggedIn(user, (error, loggedIn) => {
if(error != null) {
callback(error);
} else if(!loggedIn) {
callback('Not logged in the Parse');
} else {
callback(null, user);
}
});
}
});
}
I am using the node-login module to login on my website. Ok, after the user logs in I render my dashboard.html website:
app.get('/', function(req, res){
// check if the user's credentials are saved in a cookie //
if (req.cookies.user == undefined || req.cookies.pass == undefined){
res.render(req.locale+'/login', { title: 'Hello - Please Login To Your Account' });
} else{
// attempt automatic login //
AM.autoLogin(req.cookies.user, req.cookies.pass, function(o){
if (o != null){
req.session.user = o;
res.redirect('/home');
} else{
res.render('/login', { title: 'Hello - Please Login To Your Account' });
}
});
}
});
After that, all other html websites are linked from within dashboard.html, so there are no other app.get methods called.
If a user tries to navigate to http://www.example.com/news.html (or any other html page that is not the login page ), if the user is not logged in, I need to redirect him to the login page.
I first thought somehting like this but I don't know if this is possible:
app.get('I-don't-know-what-to-insert-here', function(req, res) {
if (req.session.user == null){
// if user is not logged-in redirect back to login page //
res.redirect('/');
} else{
res.redirect('redirect-here-to-the-requested-html-page')
}
});
Regards,
You want to write middleware, not a route handler:
app.use(function(req, res, next) {
if (req.session.user == null){
// if user is not logged-in redirect back to login page //
res.redirect('/');
} else{
next();
}
});