User Sessions Parse.com Cloud Code Hosting - parse-platform

My login form currently posts to itself on /
The post request is then picked up as follows...
app.post('/', userController.doLogin);
Then the controller is a follows..
exports.doLogin= function(req, res) {
Parse.User.logIn(req.body.username, req.body.password, {
success: function(user) {
console.log('login success');
res.render('loginSuccess');
},
error: function(user, error) {
console.log('login failed');
res.render('loginFailed');
}
});
}
This works correctly for a correct / incorrect login.
However, once logged in, the session is not stored no cookies are created / local storage etc..
Therefore when I test for login on one of my other routes it always displays as no-session, i am checking with the following code..
if(Parse.User.current()){
console.log('logged in and redirected');
res.redirect('/member/home');
}else{
console.log('not logged in, redirected to home/login page');
res.redirect('/');
}
Which always goes too home / again.
I read here https://parse.com/docs/hosting_guide#webapp-users that...
You just need to call Parse.User.logIn() in Cloud Code, and this middleware will automatically manage the user session for you.
Which would suggest it does the session for me?
Any help would be super useful! many thanks in advance!

Ok so after a lot of digging I have worked it out. First you need to add the module by doing the following..
var parseExpressCookieSession = require('parse-express-cookie-session');
Second you need to setup your own variables like this
app.use(express.cookieParser('YOUR_SIGNING_SECRET'));
app.use(parseExpressCookieSession({ cookie: { maxAge: 3600000 } }));
Third, you must do send the login/session all over HTTPS.
Boom, working - easy peasy when you know how.

Related

Laravel Sanctum Vue.js - How to check if session is expired

I'm starting up a learning project with Laravel, VueJS. I'm using Sanctum cookie based.
I have got the authentication working with the help of several tutorials, but none of the tutorials covers the piece of checking if your session is expired or not. The tutorials that where covering it where using LocalStorage, and what I red about is that you should avoid LocalStorage.
I'm looking for a simple possibility to check if a user is still authenticated and if not, then redirect them to the login page, or even better, show a modal to login and go further where they are.
22 jan 2021 Still haven't got he answer :(
I'm fairly new to VueJS, Vuex and so on :)
Thanks for the help !
Try this, its what I've been using so far. Its not very ideal but works out fine so far until I can make it better.
Put this in App.vue created method
// each call needs csrf token to work, so we call this on app load once.
axios.get(axios.rootURL + '/sanctum/csrf-cookie').catch(() => {
alert('Something went wrong, Contact admin <br> ErrorCode: csrf')
})
// this part is not necessary, you may adapt as required
// let isLoggedIn = localStorage.getItem('isLoggedIn') ? true : false
// this.setIsLoggedIn(isLoggedIn)
axios.interceptors.request.use(
config => {
return config
},
error => {
return Promise.reject(error)
}
)
// this is the actual part you need, here we check on each call
// if we get error 401 which is unauthenticated we redirect to login. That's it
axios.interceptors.response.use(
response => {
return response
},
error => {
if (error.response.status === 401) {
this.$router.push({ name: 'login' })
localStorage.removeItem('isLoggedIn')
this.setIsLoggedIn(false)
}
return Promise.reject(error)
}
)

How to use Auth::check or Auth::user between different domains?

I've got a question regarding Laravel framework (vers. 5.2) and the authentication. I have 2 domains which represent a software. let's call them https://azure.mydomain.com and https://azuresoftware.mydomain.com.
The Laravel application is hosted on the domain https://azuresoftware.mydomain.com. https://azure.mydomain.com is just a CMS framework which is providing some information about the website.
Now I want to display different menus, if the user is logged in or not on https://azure.mydomain.com. I thought, I can do a fetch request to https://azuresoftware.mydomain.com/ and use the Laravel methods Auth::check() to check if the user is already logged in or not. I know that this is a CORS fetch request, but this is not the issue. I've allowed in the IIS webserver requests from https://azure.mydomain.com. The request works fine and also just a simple request. But actually Auth::check() is always returning false, even when I'm logged in on the software side.
This is my code so far:
<script>
fetch('https://azuresoftware.mydomain.com/checkLogin', {
method: 'GET',
headers: {
'Content-Type': 'text/plain'
}
})
.then(function(res) {
return res.json()
})
.then(function(data) {
if(data.isLoggedIn) {
// do some stuff...
}
else
{
// do some other stuff...
}
});
</script>
routes.php:
Route::group(['middleware' => 'web'], function () {
...
Route::get('checkLogin', function() {
return json_encode(['isLoggedIn'=>\Auth::check()]);
});
...
I'm sure, I forgot something essential, why it is not working this way.
This is due to the fact that AJAX calls only send cookies if the url you're calling is on the same domain as your calling script.
See Cross domain POST request is not sending cookie Ajax Jquery for more information.

Parse: Session Not Created on Login

I'm having a slight issue when using the logIn class method. According to the docs, I should see a Session automatically created when a user logs in successfully.
Sessions are automatically created when users log in or sign up. They
are automatically deleted when users log out.
I'm logging in successfully, and am returning a success message to the console.
$("#login").submit(function(event) {
event.preventDefault();
var name = $("#login-name").val();
var pass = $("#login-password").val();
Parse.User.logIn(name, pass, {
success: function(user) {
console.log("Logged in successfully!");
}, error: function(user, error) {
console.log("Login error: " + error.message);
}
});
});
But when I jump into the Parse.com Data Browser, I can't see the Session under the Data Tab.
What am I doing wrong?
Any help is appreciated. Thanks in advance!
Seem to have fixed this by enabling "Require Revocable Sessions" in the Parse.com app settings page.

No callback when calling yam.platform.login

When using Yammer SDK and using yam.platform.login method, I don't get any callback when authentication fails or when the user closes dialog window. Is this a bug or something you have seen in your Yammer integration tasks?
My code
yam.platform.getLoginStatus(function (response) {
if (response.authResponse) {
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
console.dir(response);
}
else {
### CODE NEVER EXECUTED IF LOGIN FAILS OR USER CLOSE POPUP###
}
});
}
});
Make sure to add your web application url to "Javascript Origins" of your registered yammer app.
Make sure you added your web app url to "Trusted Sites" and other Yammer urls.
We get this problem (no callback on yam.platform.login) when the user is currently logged into a network other than the home network (network where app is registered). If your users use multiple networks, you may need to add your app to the global app register.
An alternative (hacky) way is to 'try' the approach below. This worked for us as it only needed to happen once (to get the auth token).
yam.getLoginStatus(function(resp){
if (resp.authResponse) {
//success
} else {
// not logged in
var yamLoginSuccess=0;
try {
yam.platform.login( function (response) { //prompt login
console.log('no response here if user in another network');
if (response.authResponse) {
//success
yamLoginSuccess=1;
}
});
}
catch(err) {
// does not throw an error so this bit is not helpful
}
finally{
if(yamLoginSuccess===0){
alert('Need to be logged into the home yammer first :-/ /n '
+ 'Redirecting now, hit back to come back');
window.location='https://www.yammer.com/YOURNETWORK/';
}
}
}
});

How to use Passport-Facebook login without redirection?

I'm building a phonegap application which will have nodejs at the server side. I wanted to implement login using passport-facebook strategy but their callbacks specify two routes, /successcallback and /failurecallback. Having a single page application, this makes it very confusing to have users redirected to so and so page.
I don't want to serve static files (index.html, login.html) from the server but rather have them on the client and ask the client to make ajax calls. So far, I'm able to make /auth/facebook call as an AJAX request but I can't receive any response on the same request because the login strategy requires the user to be redirected. I'd rather want to send a user_id or name back to the user on successful login or show him the login form (which is also on the www directory in phonegap) on failure. But the redirection and CORS errors are preventing me from doing this. Is there any way I can implement this? I've looked for this since a few weeks now, but no success. I'd really appreciate your help!
PS: I'd rather avoid having to send all html and static content from the node server.
EDIT: Adding login code for better understanding:
app.get('/userpage', utility.isLoggedIn, function(req, res)
{
res.send('User:'+req.user);
});
app.get('/', utility.isLoggedIn, function(req, res)
{
res.redirect('/userpage');
});
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',passport.authenticate('facebook',
{
successRedirect : '/',
failureRedirect : '/login'
}));
app.get('/logout', function(req, res)
{
req.logout();
res.redirect('/login');
});
utility.isLoggedIn:
function isLoggedIn(req, res, next)
{
if (req.isAuthenticated())
return next();
res.redirect('/login');
}
You can't do that with facebook oAuth, but Facebook provides another login solution where you can code your client app to request a token, that you can later validate on the server with passport-facebook-token.
This way you can use the advantages of passport for persistent sessions, without that annoying redirection.
Instead of using the standard redirections offered by passport, you can define your own function which will be executed instead of the redirection. Here's an example of what that code would look like
passport.authenticate('login', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.json({ status:"failed", "error": "Invalid credentials" }); }
// req / res held in closure
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.json({ "status":"success"});
})
})(req, res, next);

Resources