haw load user information after login SPA koa.js - mongodb

I realized the authorization of the user through the passport (Koa, Mongodb, React, Redux).
router.post('/login', function(ctx, next) {
return passport.authenticate('local', async function(err, user, info) {
if (err) throw err;
if (user === false) {
ctx.status = 401;
ctx.body = { error: info };
} else {
ctx.body = {
success: true
};
await ctx.login(user);
}
})(ctx, next);
})
If the user logged in, he redirects to the profile page(main page).
router.get('/login', function(ctx, next) {
if (ctx.isAuthenticated()) {
ctx.redirect('/');
} else {
ctx.body = fs.readFileSync(path.resolve(path.join('build', 'index.html')), 'utf8')
}
});
Since I have a spa I always pass a static file (routing on the client via a react-router)
The problem is that I can not understand how I get information about the user when the profile page is loaded
If I send a ajax-request (feth) from the React-component, then the request for another session id and it is not associated with the user.
Or, I need to do this on the server, but how I might to use the store storage on the server?
How best to solve this problem?

Well, while it might not be the best way, the easiest way to do this would be to have a section in your html file like..
<script type="text/javascript">
window.currentUser = $$USER$$
</script>
And then do a replace on the body.
let content = fs.readFileSync(path.resolve(path.join('build', 'index.html')), 'utf8')
content = content.replace('$$USER$$', JSON.stringify(user))
ctx.body = content
In your React app, you can use window.currentUser.

Related

Javascript injection goes wrong

In our Android project (download manager) we need to show built-in web browser so we able to catch downloads there with the all data (headers, cookies, post data) so we can handle them properly.
Unfortunately, WebView control we use does not provide any way to access POST data of the requests it makes.
So we use a hacky way to get this data. We inject this javascript code in the each html code the browser loads:
<script language="JavaScript">
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = formSubmitMonitor;
window.addEventListener('submit', function(e) {
formSubmitMonitor(e);
}, true);
function formSubmitMonitor(e) {
var frm = e ? e.target : this;
formSubmitMonitor_onsubmit(frm);
frm._submit();
}
function formSubmitMonitor_onsubmit(f) {
var data = "";
for (i = 0; i < f.elements.length; i++) {
var name = f.elements[i].name;
var value = f.elements[i].value;
//var type = f.elements[i].type;
if (name)
{
if (data !== "")
data += '&';
data += encodeURIComponent(name) + '=' + encodeURIComponent(value);
}
}
postDataMonitor.onBeforeSendPostData(
f.attributes['method'] === undefined ? null : f.attributes['method'].nodeValue,
new URL(f.action, document.baseURI).href,
data,
f.attributes['enctype'] === undefined ? null : f.attributes['enctype'].nodeValue);
}
XMLHttpRequest.prototype.origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
// these will be the key to retrieve the payload
this.recordedMethod = method;
this.recordedUrl = url;
this.origOpen(method, url, async, user, password);
};
XMLHttpRequest.prototype.origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
if (body)
{
postDataMonitor.onBeforeSendPostData(
this.recordedMethod,
this.recordedUrl,
body,
null);
}
this.origSend(body);
};
const origFetch = window.fetch;
window.fetch = function()
{
postDataMonitor.onBeforeSendPostData(
"POST",
"test",
"TEST",
null);
return origFetch.apply(this, arguments);
}
</script>
Generally, it works fine.
But in Google Mail web interface, it's not working for some unknown reason. E.g. when the user enters his login name and presses Next. I thought it's using Fetch API, so I've added interception for it too. But this did not help. Please note, that we do not need to intercept the user credentials, but we need to be able to intercept all, or nothing. Unfortunately, this is the way the whole system works there...
Addition #1.
I've found another way: don't override shouldInterceptRequest, but override onPageStarted instead and call evaluateJavascript there. That way it works even on Google Mail web site! But why the first method is not working then? We break HTML code somehow?

Add a user manually on server side and set their session

I can't seem to understand the relation between Accounts.createUser() and Accounts.onCreateUser(). I have an external api that validates the users' login credentials. Once the api sends me a positive response, I need to add the user in MongoDB and start its session so it can be considered as a logged in user. Accounts.createUser() is creating a user on server side, but I need Accounts.onCreateUser() because I need to add custom fields like user's token that is being generated from the external api.
This is the code I have right now (which doesn't add a user at all):
server-side code:
var request = {
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
'params': user
};
try {
var response = HTTP.call('POST', url, request); //send call to the external api
var token = response.data.token;
//decode the token and add the user in the database
var userInfo = Base64.decode(token.split('.')[1]);
var options = {
email: user._username,
profile: {
name: user._username
},
token: token
};
var user = Accounts.onCreateUser(function(options, user) {
if (options.token)
user.token = options.token;
if (options.profile)
user.profile = options.profile;
return user;
});
console.log(user); //this returns undefined
return JSON.stringify({
'code': 200,
'token': userInfo
});
} catch (error) {
console.log(error);
//console.log(error.response);
var body = error.response.content;
return body;
}
Okay. So I finally found what I had been looking for. The relation between Accounts.createUser and Accounts.onCreateUser is that Accounts.onCreateUser is a hook and adds extended functionality to the original Accounts.createUser function. What is the extended functionality? It lets you create additional fields prior to actually inserting your user in the database. You have to write this hook in your main.js (server side) in the startup code snippet:
Meteor.startup(() => {
Accounts.onCreateUser(function(options, user) {
if (options.token)
user.token = options.token;
if (options.profile)
user.profile = options.profile;
return user;
});
})
And wherever you want to add the user, simply call Accounts.createUser() and this hook will be called automatically prior to the createUser call

No 'Access-Control-Allow-Origin', only errors on first call but works subsequently

I have an AngularJS app which is trying to auth with my Web Api. I receive the below error during the first call to my server if the user does not exist in my database, but does not happen on subsequent calls to the same method once the user exists in my db. (relevant code at the bottom)
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1378' is therefore not allowed access. The response had HTTP status code 500.
The flow of the logic is:
AngularJS auths with Facebook when the user clicks login
App does an $http.post to my server for auth/login passing their credentials
Server polls Facebook API for user details
If user exists, update their profile and auth 'em
Else, create new membership user, update with FB details, and auth 'em
The only thing that's different if they don't exist in the database (which is when the defect occurs) is that the login method asynchronously calls a createUser method then returns data. No additional external calls are made.
API startup method enabling CORS:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
ConfigureOAuth(app);
app_start.WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
API Controller:
[Route("Login")]
[HttpPost]
[AllowAnonymous]
public async Task<FacebookUserModel> Login(FacebookUserRequest user)
{
FacebookUserModel fbUser = new FacebookUserModel();
// Build FacebookUser object
try {
// Grab basic user details
string profileRequestUri = "https://graph.facebook.com/" + user.fbID + "?access_token=" + user.access_token;
HttpWebRequest profileRequest = (HttpWebRequest)WebRequest.Create(profileRequestUri);
profileRequest.Method = WebRequestMethods.Http.Get;
profileRequest.Accept = "application/json";
HttpWebResponse profileResponse = (HttpWebResponse)profileRequest.GetResponse();
Stream profileResponseStream = profileResponse.GetResponseStream();
StreamReader profileStreamReader = new StreamReader(profileResponseStream);
fbUser = JsonConvert.DeserializeObject<FacebookUserModel>(profileStreamReader.ReadToEnd());
} catch (Exception) ...
try {
// Grab profile picture
string pictureRequestUri = "https://graph.facebook.com/" + user.fbID + "/picture";
HttpWebRequest pictureRequest = (HttpWebRequest)WebRequest.Create(pictureRequestUri);
pictureRequest.Method = WebRequestMethods.Http.Get;
HttpWebResponse pictureResponse = (HttpWebResponse)pictureRequest.GetResponse();
fbUser.profilePictureUri = pictureResponse.ResponseUri.ToString();
} catch (Exception) ...
// If user exists, change password to new token and return)
if(userExists)
{
try {
IdentityUser identityUser = _repo.FindUser(ID, pass).Result;
FacebookUserModel dbUser = db.FacebookUserObjects.First(u => u.identityUserID == identityUser.Id);
db.Entry(dbUser).CurrentValues.SetValues(fbUser);
db.SaveChangesAsync();
fbUser.identityUserID = identityUser.Id;
return fbUser;
}
catch (Exception e)
{ return null; }
}
// Else, create the new user using same scheme
else
{
UserModel newUser = new UserModel
{
UserName = ID,
Password = pass,
ConfirmPassword = pass
};
// Create user in Identity & linked Facebook record
createUser(newUser, fbUser);
return fbUser;
}
}
private async void createUser(UserModel newUser, FacebookUserModel fbUser)
{
IdentityResult result = await _repo.RegisterUser(newUser);
var identityUser = await _repo.FindUser(newUser.UserName, newUser.Password);
fbUser.identityUserID = identityUser.Id;
db.FacebookUserObjects.Add(fbUser);
db.SaveChangesAsync();
}
AngularJS calls to my server:
var _login = function (fbID, fbToken) {
$http.post(serviceBase + 'auth/login', { "fbID": fbID, "access_token": fbToken }).then(function (response) {
var data = "grant_type=password&username=" + fbID + "&password=" + pass;
$http.post(serviceBase + 'auth/token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.success(function (tokenResponse) {
authServiceFactory.bearerToken = tokenResponse.access_token;
})
.error(function (err) {
console.log("token error:", err);
});
authServiceFactory.userObject = response.data;
window.localStorage['userObject'] = JSON.stringify(authServiceFactory.userObject);
})
};
Why would I get the No 'Access-Control-Allow-Origin' error only on the first call, but not subsequent ones?
Update
I have a workaround in place that works, but I don't really like. The issue only arose when calling a second method from my login controller, so if I moved that code up into the login controller instead of a secondary method it works without the CORS error. This really bothers me though and is inefficient, I'd love to know a better way around it.
if you're working with angularjs you might want to check out satellizer. It makes the auth process really simple and has some awesome built in window popup control.
As far as the Access-Control-Allow-Origin calls it could be happening because you explicitly set headers on the one call and the other ones are falling back to the default http provider? Check out $http and see if providing those defaults might work around it.

Change the route for a Restangular object

I'm using Restangular to login my currentUser like this:
this.login = function (credentials) {
var loginURL = Restangular.all('logins');
return loginURL.customPOST({ user: credentials.user, password: credentials.password })
.then(function (res) {
$scope.currentUser = res;
console.log("User successfully logged in.");
};
};
At some point the currentUser might need to update his preferences with a customPUT() . . .
this.updateUser = function(currentUser){
return currentUser.customPUT({ user: currentUser })
.then(function(response){
if (typeof response.errors === 'undefined') {
$rootScope.$broadcast(AUTH_EVENTS.updateAccount, response.data );
console.log("Account successfully updated.");
currentUser = response.data
} else {
$q.reject(response);
}
}, function(response){
$q.reject(response);
});
My problem is that my server api has a one route for logins/outs (/api/logins/) and a different route for user updates (/api/users/).
Is there a way to easily change the route on my currentUser object after login so that it uses the /api/users route?
I assume
that you have set the baseUrl (via Restangular.setBaseUrl) to your API
and that the route 'users' is needed most of the time.
If this is true, one solution would be to take the plain object returned by the login and re-restangularize it. This can look similar to following code:
$scope.currentUser = res.plain();
Restangular.restangularizeElement('', $scope.currentUser, 'users');
Try this in the then-part of your login POST. Afterwards $scope.currentUser should be your user object, but all set up like you've retrieved it from /users. Subsequent REST-operations will then use the new URL.

Baasbox and Javascript

I'm trying BaaSbox, a free Backend as a Service. But it has no out-of-the-box Javascript support I can use right away (yet, only iOS and Android)
I'm having trouble sending the right curl command from javascript, anyone happen to know a good resource or a simple working $.ajax template? I've tried a few examples from stackoverflow, but none of them specifically aimed at BaaSbox.
I've tried following the Java instructions on their site here. Just making a simple login work, but I keep getting the wrong responses from the server.
Or on the other hand, anyone know a good, free alternative to BaaSbox? I just want to be able to install it on my own server, no paid plans or whatever.
in the download page there is a preliminary version of the JS SDK (added few days ago).
The documentation is on the way, however in the zip file you can find a simple example.
For example to perform a signup:
//set the BaasBox parameters: these operations initialize the SDK
BaasBox.setEndPoint("http://localhost:9000"); //this is the address of your BaasBox instance
BaasBox.appcode = "1234567890"; //this is your instance AppCode
//register a new user
BaasBox.createUser("user", "pass", function (res, error) {
if (res) console.log("res is ", res);
else console.log("err is ", error);
});
Now you can login into BaasBox
//perform a login
$("#login").click(function() {
BaasBox.login("user", "pass", function (res, error) {
if (res) {
console.log("res is ", res);
//login ok, do something here.....
} else {
console.log("err is ", error);
//login ko, do something else here....
}
});
Once the user is logged in he can load the Documents belonging to a Collection (the SDK automatically manages the Session Token for you):
BaasBox.loadCollection("catalogue", function (res, error) { //catalogue is the name of the Collection
if (res) {
$.each (res, function (i, item) {
console.log("item " + item.id); //.id is a field of the Document
});
} else {
console.log("error: " + error);
}
});
However under the hood the SDK uses JQuery. So you can inspect it to know how to user $.ajax to call BaasBox.
For example the creatUser() method (signup) is:
createUser: function (user, pass, cb) {
var url = BaasBox.endPoint + '/user'
var req = $.ajax({
url: url,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
username: user,
password: pass
}),
success: function (res) {
var roles = [];
$(res.data.user.roles).each(function(idx,r){
roles.push(r.name);
})
setCurrentUser({"username" : res.data.user.name,
"token" : res.data['X-BB-SESSION'],
"roles": roles});
var u = getCurrentUser()
cb(u,null);
},
error: function (e) {
cb(null,JSON.parse(e.responseText))
}
});
}