How to keep the session with angular-http-auth? - session

I use angular-http-auth for authentication in an angular-js app.
here is the login function inside the login controller :
$scope.login = function() {
var credentials = Base64.encode($scope.username + ':' + $scope.password);
var config = { headers: { 'Authorization': 'Basic ' + credentials } };
$http.get('url/to/json/user', config)
.success(function() {
$http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;
authService.loginConfirmed();
console.log('login success');
})
.error(function() {
console.log('login failed');
});
}
(base64 is an encrypting service coming from here)
the problem: If the user is already logged-in and he opens a new tab or if he reloads the page, he has to log-in again.
How can is it possible to avoid that and to keep the session open if the user reloads the page or comes from an external link ?

You can use either cookies or the html5 datastore to save the credentials or the base64 string with the credentials. You can then load them from there and parse them to $http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;
Hope it helps.

Related

Accessing ProcessMaker BPM framework's APIs from external apllication

I have followed the tutorial from the PM docs (http://wiki.processmaker.com/3.1/OAuth_2.0) and have not success accessing the access token.
Currently I am using the trial version of PM and I would like to access the APIs in my java application js file, but the browser returns the following error "XMLHttpRequest cannot load 'myPMServerAddress' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.".
Any help??
I registered my apps server (http://localhost:8100) within the Website box of the (User Applications -> +New) form and my code looks as followed:
var restServer = 'https://trial.processmaker.com/';
var workspace = 'sysmyWorkspace/';
var jqxhr = $.ajax({
type: "POST",
url: restServer + workspace + 'oauth2/token',
data: {
grant_type : 'password',
scope : '*',
client_id : 'myClientId',
client_secret: 'myClientSecret',
username : 'admin',
password : 'myPassword'
}
})
.done( function(data) {
if (data.error) {
alert("Error in login!\nError: " + data.error + "\nDescription: " + data.error_description);
}
else if (data.access_token) {
alert("data access token received!");
var d = new Date();
d.setTime(d.getTime() + 60*60*1000);
document.cookie = "access_token=" + data.access_token + "; expires=" + d.toUTCString();
document.cookie = "refresh_token=" + data.refresh_token; //refresh token doesn't expire
}
else {
alert(JSON.stringify(data, null, 4));
}
})
.fail(function(data, statusText, xhr) {
alert("Failed to connect.\nHTTP status code: " + xhr.status + ' ' + statusText);
});
});
You need to disable CORS in client side
for Ubuntu:
google-chrome --disable-web-security --user-data-dir
for Ms Windows:
Go into the command prompt and go into the folder where Chrome.exe is and type
chrome.exe --disable-web-security
I can test that with no errors.

Parse server twitter authentication: Twitter auth integrated but unable to create session to use on client side

Parse Cloud code:
Parse.Cloud.define("twitter", function(req, res) {
/*
|--------------------------------------------------------------------------
| Login with Twitter
| Note: Make sure "Request email addresses from users" is enabled
| under Permissions tab in your Twitter app. (https://apps.twitter.com)
|--------------------------------------------------------------------------
*/
var requestTokenUrl = 'htt****/oauth/request_token';
var accessTokenUrl = 'http***itter.com/oauth/access_token';
var profileUrl = 'https://api.twitter.com/1.1/account/verify_credentials.json';
// Part 1 of 2: Initial request from Satellizer.
if (!req.params.oauth_token || !req.params.oauth_verifier) {
var requestTokenOauth = {
consumer_key: 'EVJCRJfgcKSyNUQgOhr02aPC2',
consumer_secret: 'UsunEtBnEaQRMiq5yi4ijnjijnjijnijnjEjkjYzHNaaaSbQCe',
oauth_callback: req.params.redirectUri
};
// Step 1. Obtain request token for the authorization popup.
request.post({
url: requestTokenUrl,
oauth: requestTokenOauth
}, function(err, response, body) {
var oauthToken = qs.parse(body);
// console.log(body);
// Step 2. Send OAuth token back to open the authorization screen.
console.log(oauthToken);
res.success(oauthToken);
});
} else {
// Part 2 of 2: Second request after Authorize app is clicked.
var accessTokenOauth = {
consumer_key: 'EVJCRJfgcKSyNUQgOhr02aPC2',
consumer_secret: 'UsunEtBnEaQRMiq5yi4ijnjijnjijnijnjEjkjYzHNaaaSbQCe',
token: req.params.oauth_token,
verifier: req.params.oauth_verifier
};
// Step 3. Exchange oauth token and oauth verifier for access token.
request.post({
url: accessTokenUrl,
oauth: accessTokenOauth
}, function(err, response, accessToken) {
accessToken = qs.parse(accessToken);
var profileOauth = {
consumer_key: 'EVJCRJfgcKSyNUQgOhr02aPC2',
consumer_secret: 'UsunEtBnEaQRMiq5yi4ijnjijnjijnijnjEjkjYzHNaaaSbQCe',
token: accessToken.oauth_token,
token_secret: accessToken.oauth_token_secret,
};
console.log(profileOauth);
// Step 4. Retrieve user's profile information and email address.
request.get({
url: profileUrl,
qs: {
include_email: true
},
oauth: profileOauth,
json: true
}, function(err, response, profile, USER) {
console.log(profile);
//console.log(response.email);
Parse.Cloud.useMasterKey();
var UserPrivateInfo = Parse.Object.extend("UserPrivateInfo");
var query = new Parse.Query(UserPrivateInfo);
query.equalTo("email", profile.email);
query.first({
success: function(privateInfo) {
if (privateInfo) {
res.success(privateInfo.get('user'));
} else {
response.success();
}
},
error: function(error) {
response.error("Error : " + error.code + " : " + error.message);
}
});
});
});
}
});
For client side using Sendgrid twitter authentication:
loginCtrl.twitterLogin = function() {
$auth.authenticate("twitter").then(function(response) {
console.log(response.data.result);
var user = response.data.result;
if (!user.existed()) {
var promise = authFactory.saveUserStreamDetails(user, response.email);
promise.then(function(response) {
signInSuccess(response);
}, function(error) {
console.log("error while saving user details.");
});
} else {
signInSuccess(user);
}
}).catch(function(error) {
console.log(error);
});;
};
Issue:
Step 1: Called cloud function Parse.Cloud.define("twitter", function(req, res) using loginCtrl.twitterLogin
Step 2: Twitter popup opens and user logs in to twitter
Step 3: Got verification keys and again cloud function Parse.Cloud.define("twitter", function(req, res) is called and user is verified
Step 4: Got the user email using the twitter API.
Step 5: I can get the existing Parse User Object using the email or can signUp using that email.
Step 6: Returns the parse user object to client but there is no session attached to it so **How can I create user session?
Without parse session we can not log in to parse application. Every clound code api/ function call will fail as no session is attached to them. So how can I create and manage a session using twitter authentication.

Facebook Login + Drupal 8 custom module. POST variable not being allowed/detected in db_select

I have created a custom module in Drupal 8 that allows a user to authenticate using facebook login. Their access token is checked against one stored in the database and if it matches authenticates the user and if it doesn't then redirects them to a page that allows them to link their Facebook account to a Drupal user.
The button for login is:
<button id="login_fb" onclick="logIt()">Log in with Facebook</button>
The "logit" function with the ajax request to the Drupal controller is:
function logIt()
{
FB.login(function(response) {
if (response.authResponse) {
if(response.authResponse.accessToken)
{
var request = $.ajax({
url: "/user/token",
method: "POST",
data: { access_token : response.authResponse.accessToken},
dataType: "json"
});
request.done(function( msg ) {
window.location.replace(msg['redirect_url']);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
}
}
And the controller code that handles this ajax call is:
public function token() {
$fb_token = $_POST['access_token'];
$query = db_select('user__field_fb_token', 'u');
$query
->fields('u')
->condition('u.field_fb_token_value', $fb_token,'=');
$res = $query->execute();
$res->allowRowCount = TRUE;
$count = $res->rowCount();
//See if anybody has this access token
if($count > 0)
{
$user = $res->fetchAssoc();
//TODO: Refresh access token and update
$login_id = $user['entity_id'];
//Redirect the user to topics
user_login_finalize(user_load($login_id));
$response_arr = array("status" => "authorised","redirect_url" => "/topics");
}
else
{
$_SESSION['access_token'] = $fb_token;
$response_arr = array("status" => "unauthorised","redirect_url" => "/user/auth","token" => $fb_token);
}
$response = new Response();
$response->setContent(json_encode($response_arr));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
The weird thing is that the db_select query always returns 0 and therefore does not authenticate the user account that has this token. However replacing
$fb_token = $_POST['access_token'];
with
$fb_token = '** hard coded access token **';
yields the correct result. I have checked that the post variable being passed in and it is present (that's why I pass it back with the unauthorised response to check that it's not blank).
I think it may have something to do with the async nature of FB.Login method but not sure.
Any help on this matter would be greatly appreciated!

How to make dojo.request.xhr GET request with basic authentication

I look at the documentation for Dojo v.1.9 request/xhr
and I cannot find example that includes basic authentication.
How and where do I include the User name and Password in the Dojo XHR options?
require(["dojo/request/xhr"], function(xhr){
xhr("example.json", {
// Include User and Password options here ?
user: "userLogin"
password: "userPassword"
handleAs: "json"
}).then(function(data){
// Do something with the handled data
}, function(err){
// Handle the error condition
}, function(evt){
// Handle a progress event from the request if the
// browser supports XHR2
});
});
Thanks.
Indeed, you should be able to pass the user and password with the user and password property in the options object.
In previous versions of Dojo this was documented, but it seems that now they aren't. However, I just tested it and it seems to add the username and password to the URL, like:
http://user:password#myUrl/example.json
Normally the browser should be capable of translating this URL so the request headers are set.
You could also set these headers manually, for example by using:
xhr("example.json", {
headers: {
"Authorization": "Basic " + base64.encode(toByteArray(user + ":" + pass))
}
}).then(function(data) {
// Do something
});
However, this requires the dojox/encoding/base64 module and the following function:
var toByteArray = function(str) {
var bytes = [];
for (var i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
};

Session access issue in nodejs?

I have modify https://github.com/jimpick/everyauth-example-password/blob/master/server.js for making login with mysql.
I want to access the session in
authenticate(function(login, password) {
var errors = [];
var user = [];
userModule.CheckUserLogin(login, password, function(err, results) {
if(results.length > 0) {
req.session.login = login;
return user;
}
else {
if(!user) return ['Login failed'];
}
});
return user;
})
I have this code in bottom
var app = express.createServer(
express.bodyParser()
, express.static(__dirname + "/public")
, express.cookieParser()
, express.session({ secret: 'htuayreve' })
, everyauth.middleware()
);
app.configure(function() {
app.set('view engine', 'jade');
});
app.get('/', function(req, res) {
res.render('home', { users: JSON.stringify(usersByLogin, null, 2) });
});
If I paste app code from bottom to top then everyayth's routing not worked.I want to simple know how I can access the req.session.login inside everyauth function.
You can't access the session from your authenticate function. The everyauth way of supporting access the authenticated user's information is for you to provide a findUserById function to everyauth that will look up a user record given the user's id that gets stored in the session during authentication. Once you do that you can access all the user's attributes in your route handlers via req.user.
See the 'Accessing the User' section on the everyauth website.

Resources