Publish and Subscribe do not work correctly - javascript

Publish and Subscribe did not work. Please find the solution as an answer down below.
Initial question:
I am trying to publish the facebook first_name which is automatically retrieved when logging in with the accounts facebook package in Meteor (stored in the user collection under services.facebook). I have autopublish and insecure removed.
What I have tried so far looks like this:
Server side
Meteor.publish("facebook_name", function() {
return Meteor.users.find({_id: this.userId},
{fields: {'services.facebook.first_name' : true} });
});
Client side
Meteor.subscribe('facebook_name');
What I am using in my template to display it is this
<div class="Name"><p>{{currentUser.services.facebook.first_name}}</p></div>
Before removing autopublish the name showed up in the template.

Found the solution to my problem:
When setting up your meteor project in your client/main.js it will show import './main.html'; if you are working with routing and templates and not the main.html template this will prevent publish and subscribe to work correctly.

When user is logged in via facebook oauth API and the authentication was implemented using meteor accounts-facebook, then all needed data is stored in current user object ( Meteor.user() ).
So, the schema of user in your case looks similar to this:
{
"_id": "Ap85ac4r6Xe3paeAh",
"createdAt": "2015-12-10T22:29:46.854Z",
"services": {
"facebook": {
"accessToken": "XXX",
"expiresAt": 1454970581716,
"id": "XXX",
"email": "ada#lovelace.com",
"name": "Ada Lovelace",
"first_name": "Ada",
"last_name": "Lovelace",
"link": "https://www.facebook.com/app_scoped_user_id/XXX/",
"gender": "female",
"locale": "en_US",
"age_range": {
"min": 21
}
},
"resume": {
"loginTokens": [
{
"when": "2015-12-10T22:29:46.858Z",
"hashedToken": "XXX"
}
]
}
},
"profile": {
"name": "Sashko Stubailo"
}
}
Thus, if you want to retrieve a name of a user, all you need to do is to publish current user to a client and then get username from user object.
// server
Meteor.publish("userData", function () {
return Meteor.users.find({_id: this.userId});
});
// client
Meteor.subscribe("userData");
Template.templateName.helpers({
// this function returns username
Username : function(){
// if user is logged in using facebook; otherwise user is logged in using password
if (Meteor.user().profile.name)
return Meteor.user().profile.name;
else
return Meteor.user().username;
}
Now you can display a name of a user in your view: {{Username}}
Here is more info...

Related

Can't query by ID as second parameter with AWS DataStore

I am total noob to AWS, DataStore, and DynamoDB. I can't figure out why this isn't working.
If I attempt query an object related to my users ID from Cognito this seems to work. If I console log I get an array with one User.
let profile = await DataStore.query(User, (u) =>
u.id('eq', user.attributes.sub)
);
// Returns [Model]
console.log('[LOADING USER DATA]', profile);
If I attempt query an object related to my users ID like this. (as recommended by the docs). I get undefined.
let profile = await DataStore.query(User, user.attributes.sub);
// Returns undefined
console.log('[LOADING USER DATA]', profile);
Dynamo Data looks fine to me but am I using the wrong primary key ID field or something?
{
"id": "929e6e62-e3a0-4b84-b050-72c53eebda93",
"_lastChangedAt": 1644433699,
"status": "Active",
"createdAt": "2022-02-09T19:08:18.548Z",
"name": "Test",
"orgs": [
"b6508155-f5cf-49b7-88d6-0e605677c4e4"
],
"_version": 1,
"role": "User",
"updatedAt": "2022-02-09T19:08:18.548Z",
"orgID": "b6508155-f5cf-49b7-88d6-0e605677c4e4",
"title": ""
}
What am I doing wrong?

Getting username from GuildMember

When I was coding a guildMemberAdd and a guildMemberRemove I ran across an issue... So, I was wondering, how do you obtain the user's username and discriminator from when they join? as when I tried member.username and member.discriminator it logs as undefined and undefined
Code below, nothing was printed to console upon this issue:
exports.run = (client, member) => {
member.guild.channels.find(`name`, `mod-logs`).send({embed: {
"color": 8311585,
"footer": {
"text": "Bot made by: Pawxeric#0858"
},
"author": {
"name": "New Member",
"icon_url": member.avatarURL
},
"fields": [
{"name": `${member.username}#${member.discriminator}`, // logs as undefined#undefined
"value": "Joined"}
]
}});
}
Also, the code is having issues picking up anything that uses the member value. Like avatarURL, username, and discriminator. If there's something I'm missing, please share down below :3c
I think you want to get properties from a user object
<member>.user
User has username, discriminator and avatarurl.
The full object can be found on https://discord.js.org/

login page not working (javascript, firebase)

HELP!
I'm not sure what's going on, but my login page isn't working. It simply reloads even though I'm entering valid user/password.
I think the problem is it's getting stuck on issues with my data-structure, security-rules, and app.js, but I'm at a loss.
I was provided a sinatra/ruby simple api to work with users & groups (just a small project).
here's the site:
https://starter-vicks9985.firebaseapp.com/index.html
here's the code:
$.post/("https://starter-vicks9985.firebaseapp.com/main.rb",
{
"name": "admin",
"email": "admin#example.com",
"password": "secret",
"admin": true,
"role-value": 99,
}
), console.log("success");
{
"rules": {
".read": true,
"users": {
"$user": {
//can add a message if authenticated
".write": "auth.uid === $user"
}
},
"rooms": {
"$room": {
"users": {
// can write to the users list only if ADMINISTRATOR
"$user": {
"write":"newData.parent().child(auth.uid).val() === 99"
}
}
}
},
"messages": {
"$room": {
"$message": {
//can add a message if they are a MEMBER (if there was message/chat capability)
".write": "(!data.exists() && newData.exists() && root.child('rooms/' + $room + '/users/' + auth.uid).val() >= 10)"
}
}
}
}
}
$(document).ready(function() {
/**
*Set initial firebase ref. Use set to write in first admin user.
*/
var ref = new Firebase("https://starter-vicks9985.firebaseio.com/");
ref.set({
"name": "Admin",
"email": "admin#example.com",
"password": "secret",
"admin": true
});
/** Get email address from loginform, format email, get password
* Firebase keys cannot have a period (.) in them, so this converts the emails to valid keys
*/
var emailAddress = function emailToKey(emailAddress){
return btoa(emailAddress);
};
var password = document.getElementById('password');
/**
* Authorize user with email and password, passing in values from form.
*/
ref.authWithPassword({
email : emailAddress,
password : password,
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
return authData;
}
});
/**
* If user is logged in (valid), redirect to user profile
*/
ref.onAuth(function(authData) {
window.open="https://starter-vicks9985.firebaseio.com/userprofile/userprofile.html";
})
});
Like #Kato said, this is a code dump so please consider creating an mcve. Although, first check out my comments below.
The Code You Posted
After glancing at your code, I see some errors that I will point out:
1. Your jQuery post syntax is incorrect, and wouldn't work even if it was correct.
Most importantly, you are making a post request to a Ruby file. Firebase Hosting is not a server, it is hosting for static files.
See this answer by Frank. He says:
Firebase hosting is a product to serve so-called static application, which consist only of files that the client interprets. Firebase's servers will not interpret any code that you upload. So Firebase hosting is not suited to host your Ruby-on-Rails application.
To quote Firebase hosting's documentation:
We deliver all your static content (html, js, images, etc)
That being said, take a look at the jQuery documentation for $.post().
See my comments on your code:
$.post/("https://starter-vicks9985.firebaseapp.com/main.rb",
// ^ What is this '/'?
{
"name": "admin",
"email": "admin#example.com",
"password": "secret",
"admin": true,
"role-value": 99,
}
), console.log("success");
// ^ You are closing the function call, 'console.log' falls outside of it.
What it should look like:
$.post("https://starter-vicks9985.firebaseapp.com/main.rb", {
"name": "admin",
"email": "admin#example.com",
"password": "secret",
"admin": true,
"role-value": 99,
}, function() {
console.log("success");
});
2. What's even going on with the login functions?
Assuming you fix Uncaught SyntaxError: Unexpected token { in data-structure.js:14...
If you take a look at the console, you will see Uncaught Error: Firebase.authWithPassword failed: First argument must contain the key "email" with type "string".
That is because you are passing a function, emailAddress to .authWithPassword().
You declare emailAddress() like so:
var emailAddress = function emailToKey(emailAddress){
return btoa(emailAddress);
};
So the email parameter in the following is being passed emailAddress(), not a string that is an email address.
ref.authWithPassword({
email : emailAddress,
password : password,
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
return authData;
}
});
Most importantly, all of these login functions are being called immediately after the page loads. Nothing in your code (app.js) waits for, and responds to, the submission of the form.
The Code on Your Website
I also went on your page, looked at your source code, and found some more issues.
1. Error in form HTML in index.html
<section class="loginform cf">
<form id= "login" form name="login" form type= "submit" accept-charset="utf-8">
<!-- extra^space ^duplicate "form"^ ^again, space -->
...
</form>
</section>
2. Syntax Errors in data-structures.js
Again, you have the same errors here as I described above ('/' and closing parentheses), but the object that you're passing the post is incorrectly formatted
$.post/("https://starter-vicks9985.firebaseapp.com/main.rb",
{
"users" //missing ':' after users
//the following objects do not have keys - should be {"users":{"someUserKey1":{...},"someUserKey2":{...}}} etc.
{
"name": "admin",
"email": "...",
"password": "...",
"admin": true,
"role-value": 99,
},
{
"name": "aaa",
...
},
{
"name": "bbb",
...
}
},
), console.log("success");
And the same things apply for the post call for "groups".
I hope that provides some clarity.
I would suggest reading over other answers here on StackOverflow, like:
jQuery AJAX submit form
jQuery form submit
And search for more answers like:
https://stackoverflow.com/search?q=jquery+form+submit
In conclusion, I'd suggest doing some more research and reading documentation :)

Redirection after the login succeeds or fails in loopback framework

I have recently started with loopback framework and made a simple login functionality by creating a 'customer' model inheriting from base 'User' like this:
CUSTOMER.JSON
{
"name": "customer",
"base": "User",
"idInjection": true,
"properties": {
"email":{
"type":"string",
"required":false
},
"username":{
"type":"string",
"required":false
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
CUSTOMER.JS
module.exports = function(customer){
}
I then made a entry in model-config.json like this:
"customer": {
"dataSource": "mango-database",
"public": true
}
And yes I was able to login and logout easily. I have a login screen with fields username and password. I submit this form to customers/login and as soon as it gets the login, I get a screen:
{
id: "lvrTjKBKXCFPTMFej6AyegQUFYe5mSc1BiYbROZwCBM0jqae7kZ7v8ZfGujfDGgy",
ttl: 1209600,
created: "2014-12-07T08:12:17.572Z",
userId: "5483e88b5e9cf2fe0c64dd6c"
}
Now I want that instead of this screen, I should be able to redirect user to some other page (dashboard) and if the login fails, it should go back to the login screen.
I googled up a lot on this and all i found was the suggestions to use hooks. But hooks doesn't have such event. Where do I write the redirection functionality? My guess is CUSTOMER.JS
I found the documentation quiet confusing !
Use context.res provided in a remote hook. For example:
Customer.afterRemote('create', function(context, customer, next) {
var res = context.res; //this is the same response object you get in Express
res.send('hello world');
})
Basically, you have access to request and response objects, so just respond as you would in Express. See http://expressjs.com/4x/api.html for more info.

How to pass data form mongodb (using Mongous module) into nodejs view (using temp engine jade)?

Sorry to bother you folks. But i have a simple question. Ho can I pass data form model(database) into view. I use Express, Mongous(not Mongoose) to access MongoDB and Jade for my view-ing. I've tried Mongoose, but was not able to get even this far. The problem which I am having is how to actually pass data into view. Most examples that I've seen either have no mention of the views when database access is dicussed, or have manually created objects inside the views. I have not found any clear examples of data being fed into a view from the database. Please help, if you can...
This is what my model looks like:
//Model Mongo DB
var mgs = require('mongous').Mongous,
dbColl = 'test.personnel';
mgs(dbColl).find(function(data){
return data;
});
I require it in my app.js like so:
require(__dirname + '/model');
It seems to work because I do get connection messages and I can see my data in the terminal.
Here is DB info.
My DB name is "test", collection name "personnel" and here what my data looks like:
{
"_id": ObjectId("4ef82a27b238f02ed9000000"),
"cms": {
"0": "Druapl_1"
},
"first_name": "Name_1",
"last_name": "Lst_Name_1",
"skills": {
"0": "html_1",
"1": "css_1",
"2": "jQuery_1"
}
}
{
"_id": ObjectId("4ef81a0dcf163c7da3e5c964"),
"cms": {
"0": "Druapl_2"
},
"first_name": "Name_2",
"last_name": "Lst_Name_2",
"skills": {
"0": "html_2",
"1": "css_2",
"2": "jQuery_2"
}
}
Please help, if you do it will exponentially improve my understanding of how data is presented, not just in nodejs, but in general.Thanks.
app.get('/', function(req, res) {
mgs(dbColl).find(function(data){
res.render('yourview.jade', { data: data });
});
});

Categories

Resources