"Match error: Expected string, got undefined" Recover Password - meteor

Template.ResetPwd.events({
'submit #forgot-password': function(event, template) {
event.preventDefault();
var forgotPasswordForm = $(event.currentTarget),
email = forgotPasswordForm.find('#forgotPasswordEmail').val().toLowerCase();
if (email !== "") {
Accounts.forgotPassword({
email: email
}, function(err) {
if (err) {
if (err.message === 'User not found [403]') {
console.log('This email does not exist.');
FlashMessages.sendSuccess(err.message, {
autoHide: true,
hideDelay: 8000
});
} else {
console.log('We are sorry but something went wrong.');
FlashMessages.sendSuccess('We are sorry but something went wrong', {
autoHide: true,
hideDelay: 8000
});
}
} else {
console.log('Email Sent. Check your mailbox.');
FlashMessages.sendSuccess('Email Sent', {
autoHide: true,
hideDelay: 4000
});
}
});
} else {
template.find('#form-messages').html('Email Invalido');
}
return false;
}
});
if (Accounts._resetPasswordToken) {
Session.set('resetPassword', Accounts._resetPasswordToken);
};
Template.setNewPass.helpers({
resetPassword: function() {
return Session.get('resetPassword');
}
});
Template.setNewPass.events({
'submit #set-new-password': function(e, template) {
e.preventDefault();
// var target = event.target;
// var password = target.resetpass.value;
// var passwordConfirm = target.verificy.value;
var resetPasswordForm = $(e.currentTarget),
password = resetPasswordForm.find('#resetPasswordPassword').val(),
passwordConfirm = resetPasswordForm.find('#resetPasswordPasswordConfirm').val();
// if (isNotEmpty(password) && areValidPasswords(password, passwordConfirm)) {
if (password === passwordConfirm) {
Accounts.resetPassword(Session.get('resetPassword'), password, function(err) {
if (err) {
console.log('We are sorry but something went wrong.');
FlashMessages.sendSuccess(err, {
autoHide: true,
hideDelay: 8000
});
} else {
console.log('Your password has been changed. Welcome back!');
FlashMessages.sendSuccess('Your password has been changed. Welcome back', {
autoHide: true,
hideDelay: 8000
});
Session.set('resetPassword', null);
}
});
} else {
FlashMessages.sendSuccess('contraseñas no son iguales', {
autoHide: true,
hideDelay: 8000
});
}
return false;
}
});
<template name="ResetPwd">
<div class="container">
<p>
{{> flashMessages}}
</p>
<form id="forgot-password">
<div class="col-xs-12">
<input class="inputStyle" type="text" id="forgotPasswordEmail" name="email" placeholder="Email">
</div>
<div class="col-xs-12">
<input class="btn-main" type="submit" value="Recuperar Contraseña">
</div>
<p id="form-messages"></p>
</form>
</div>
</template>
<template name="setNewPass">
<div class="container">
<p>
{{> flashMessages}}
</p>
<div class="row">
<form id="set-new-password">
<div class="col-xs-12">
<input class="inputStyle" type="password" name="resetpass" id="resetPasswordPassword" placeholder="contraseña">
<input class="inputStyle" type="password" name="verificy" id="resetPasswordPasswordConfirm" placeholder="verificar contraseña">
</div>
<div class="col-xs-12">
<input class="btn-main" type="submit" name="some_name" value="Recuperar Contraseña">
</div>
<p id="form-messages"></p>
</form>
</div>
</div>
</template>
Hello, I'm having trouble retrieving the password when sending the email with the token to retrieve it I receive it successfully then I press that url
http://localhost:1999/reset/_M5swGv9Uwn--4_olB0itOuYBLGMYYgDMQB9es9Y0TM
And it directs me to the window to change the password and I enter the new password there is where I get the following error errorClass
errorType : "Match.Error" message : "Match error: Expected string, got
undefined" path : "" sanitizedError : errorClass
In my code I have the following.

Related

MeteorJS project with redis-livedata package not returning object from redisCollection.hgetall as expected

The MeteorJS method "get.jade" is not returning jade object to client as expected. I'm using redis-livedata and manuel:reactivearray packages, and Redis is functioning locally correctly. I have put console.log in the code where there is a problem is returning server side data to client
jades.html
<template name="jades">
{{#if jadeslength}}
<div class="row">
<div class="user-card" id="swipe">
<img src="{{jade.img}}" style="width:100%">
<div class="card-container">
<h5>{{jade.name}}, {{jade.gender}}</h5>
</div>
</div>
</div>
<div class="row">
<div class="one-half column">
<button class="no" type="button">no</button>
</div>
<div class="one-half column">
<button class="button-primary yes" type="button">yes</button>
</div>
</div>
{{else}}
<div class="row">
<button class="button-primary search-jades" type="button" id="search">search</button>
</div>
{{/if}}
</template>
jades.js
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import './jades.html';
Template.jades.onCreated(function () {
var jades = new ReactiveArray([]);
Session.set({'jadeId':""});
});
Template.jades.helpers({
jade: function() {
return jades.list();
},
jadeslength: function() {
var jades = jades.list();
return jades.length;
},
});
Template.jades.events({
...
'click .search-jades' () {
Template.instance.jades = [];
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var client_location = {"lat": position.coords.latitude, "lng": position.coords.longitude};
if (client_location) {
var lng = client_location.lng;
var lat = client_location.lat;
Meteor.call('client.profile', (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
} else {
var user_profile = result;
Session.set({'user_profile': user_profile});
var prefer = user_profile.prefer;
switch (prefer) {
case "cis women":
Meteor.call('search.cw', lng, lat, (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
return;
} else {
searched = result;
if (searched.length == 0) {
FlashMessages.sendWarning("no more providers found in your area", 3000);
} else {
for (var found of searched) {
var user_profile = Session.get('user_profile');
var right = user_profile.right;
if (!(found._id in right)) {
Template.instance.jades.push(found._id);
}
}
var jadeId = Template.instance.jades.pop();
console.log(jadeId); // returns ofQj98LBQWrSJ8gJs on client
if (jadeId) {
Meteor.call('get.jade', jadeId, (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
} else {
Session.set({'jadeId': jadeId});
Session.set({'jade': result});
console.log(result); // returns undefined on client
}
});
} else {
FlashMessages.sendWarning("no more providers found in your area", 3000);
}
}
}
});
break;
case "trans women":
...
methods.js
'get.jade': function(jadeId) {
var redisCollection = new Meteor.RedisCollection("redis");
redisCollection.hgetall(jadeId, function(error, object) {
if (error) {
console.log(error);
} else {
console.log(object); // returns { name: 'alex', img: 'null', gender: 'cis woman' } on server
return object;
}
});
},
I solved this by changing the method as follows:
'get.jade': function(jadeId) {
var redisCollection = new Meteor.RedisCollection("redis");
return redisCollection.hgetall(jadeId)
},

When I type something long with no spaces, it goes off screen

I have some issues with making a chatroom. For some reason whenever I type a long letter or something without spaces, it goes off screen. If I were to add some spaces, it would work.
As you can see here
, the first message has spaces and it worked fine, but the second message had no spaces and it went off the screen, how would I fix this?
server.js
var PORT = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var connectedUsers = {};
app.use(express.static(__dirname + '/public'));
io.on('connection', function(socket) {
/*var socketId = socket.id;
var clientIp = socket.request.connection.remoteAddress;
console.log('A user is connected. - IP: ' + clientIp + " | ID: " + socketId);*/
console.log('A user is connected.')
socket.on('disconnect', function() {
var userData = connectedUsers[socket.id];
if (typeof userData !== 'undefined') {
socket.leave(connectedUsers[socket.id]);
io.to(userData.room).emit('message', {
username: 'System',
text: userData.username + ' has left!',
timestamp: moment().valueOf()
});
delete connectedUsers[socket.id];
}
});
socket.on('joinRoom', function(req, callback) {
if (req.room.replace(/\s/g, "").length > 0 && req.username.replace(/\s/g, "").length > 0) {
var nameTaken = false;
Object.keys(connectedUsers).forEach(function(socketId) {
var userInfo = connectedUsers[socketId];
if (userInfo.username.toUpperCase() === req.username.toUpperCase()) {
nameTaken = true;
}
});
if (nameTaken) {
callback({
nameAvailable: false,
error: 'This username is taken, please choose another one.'
});
} else {
connectedUsers[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit('message', {
username: 'System',
text: req.username + ' has joined!',
timestamp: moment().valueOf()
});
callback({
nameAvailable: true
});
}
} else {
callback({
nameAvailable: false,
error: 'Please complete the forum.'
});
}
});
socket.on('message', function(message) {
message.timestamp = moment().valueOf();
io.to(connectedUsers[socket.id].room).emit('message', message);
});
socket.emit('message', {
username: 'System',
text: 'Ask someone to join this chat room to start talking.',
timestamp: moment().valueOf()
});
});
http.listen(PORT, function() {
console.log('Server started on port ' + PORT);
});
index.html body:
<body>
<div class="container">
<div id="login-area">
<div class="row">
<div class="large-7 medium-7 small-12 columns small-centered">
<form id="login-form">
<h2>Twintails🎀 Bot Chatroom</h2>
<p id="error-msg"></p>
<input
type="text"
name="username"
placeholder="Enter your username"
/>
<input
type="text"
name="room"
placeholder="Enter a chat room name"
/>
<input type="submit" value="Join Chat" />
</form>
</div>
</div>
</div>
<div class="row" id="message-area">
<div class="large-8 columns small-centered">
<h2>Twintails🎀 Bot Chatroom</h2>
<div class="chat-wrap">
<div class="top">
<h5 class="room-title"></h5>
</div>
<div id="messages"></div>
<form id="message-form">
<div class="input-group">
<input
type="text"
placeholder="Type message here"
class="input-group-field"
name="message"
/>
<div class="input-group-button">
<input type="submit" value="Send" />
</div>
</div>
</form>
</div>
</div>
</div>
<footer>
<p>
Add the
<a href="https://twintails-bot-dashboard.glitch.me/" target="_blank"
>Twintails🎀 bot!</a
>
</p>
<p>
Use the 'Mod' room to talk to mods!
</p>
</footer>
</div>
<script src="/js/jquery.js"></script>
<script src="/js/socket.io-1.7.3.min.js"></script>
<script src="/js/moment.min.js"></script>
<script src="/js/app.js"></script>
<script src="/js/foundation.min.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
</body>
If you need some info on the css, just comment and I'll edit this post.

Meteor: How can I restrict user on a chat?

Im working on a project and my last task is to implement publish and subscribe to prevent users seeing conversations they were not involved in. We were given an example code and I notice a filter on the router.
Router.route('/chat/:_id', function () {
// the user they want to chat to has id equal to
// the id sent in after /chat/...
var otherUserId = this.params._id;
// find a chat that has two users that match current user id
// and the requested user id
var filter = {$or:[
{user1Id:Meteor.userId(), user2Id:otherUserId},
{user2Id:Meteor.userId(), user1Id:otherUserId}
]};
var chat = Chats.findOne(filter);
if (!chat){// no chat matching the filter - need to insert a new one
chatId = Chats.insert({user1Id:Meteor.userId(), user2Id:otherUserId});
}
else {// there is a chat going already - use that.
chatId = chat._id;
}
if (chatId){// looking good, save the id to the session
Session.set("chatId",chatId);
}
this.render("navbar", {to:"header"});
this.render("chat_page", {to:"main"});
});
I thought the filter should be on publish and then subscribe. Here is what I have now.
My HTML
<template name="chat_page">
<h2>Type in the box below to send a message!</h2>
<div class="row">
<div class="col-md-12">
<div class="well well-lg">
{{#each recentMessages}}
{{> message}}
{{/each}}
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
{{#if currentUser}}
<form class="new-message">
<input class="input" type="text" name="text" placeholder="type a message here...">
<button class="btn btn-default">Send</button>
</form>
{{/if}}
</div>
</div>
</template>
<!-- simple template that displays a message -->
<template name="message">
<div class = "container">
<div class = "row">
<div class = "username">
<img src="/{{avatar}}" class="avatar_img" >
{{username}}
said: {{messageText}}
</div>
</div>
</div>
</template>
Server Side
Meteor.startup(function () {
if (!Meteor.users.findOne()){
for (var i=1;i<9;i++){
var email = "user"+i+"#test.com";
var username = "user"+i;
var avatar = "ava"+i+".png"
console.log("creating a user with password 'test123' and username/ email: "
+ email);
Meteor.users.insert({
profile:{username:username, avatar:avatar},
emails: [{address:email}],
services:{
password:{"bcrypt" : "PASSWORD REMOVED"}}});
}
}
});
Meteor.publish("messages", function (userId) {
return Messages.find();
});
Meteor.publish("userStatus", function() {
return Meteor.users.find({ "status.online": true });
});
Meteor.publish("userData", function(){
if(this.userId) {
return Meteor.users.find({_id: this.userId},{
fields: {'other':1, 'things': 1}});
} else {
this.ready();
}
return Meteor.users.find({ "status.online": true })
});
Client Side
Meteor.subscribe("messages");
Meteor.subscribe("userStatus");
Meteor.subscribe("userData");
// set up the main template the the router will use to build pages
Router.configure({
layoutTemplate: 'ApplicationLayout'
});
// specify the top level route, the page users see when they arrive at the site
Router.route('/', function () {
console.log("rendering root /");
this.render("navbar", {to:"header"});
this.render("lobby_page", {to:"main"});
});
Router.route('/chat/:_id', function () {
this.render("navbar", {to:"header"});
this.render("chat_page", {to:"main"});
});
///
// helper functions
///
Template.message.helpers({
userName: function() {
var userId = this.userId;
var user = Meteor.users.findOne(userId);
var username = user && user.profile && user.profile.username;
var avatar = user && user.profile && user.profile.avatar;
return {
username: username,
avatar: avatar
}
}
})
Template.available_user_list.helpers({
users:function(){
return Meteor.users.find();
}
})
Template.available_user.helpers({
getUsername:function(userId){
user = Meteor.users.findOne({_id:userId});
return user.profile.username;
},
isMyUser:function(userId){
if (userId == Meteor.userId()){
return true;
}
else {
return false;
}
}
})
Template.chat_page.helpers({
recentMessages: function () {
if (Session.get("hideCompleted")) {
return Messages.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
} else {
return Messages.find({}, {sort: {createdAt: 1}});
}
},
hideCompleted: function () {
return Session.get("hideCompleted");
},
incompleteCount: function () {
return Tasks.find({checked: {$ne: true}}).count();
}
});
Template.chat_page.events({
// this event fires when the user sends a message on the chat page
'submit .new-message':function(event){
console.log(event);
event.preventDefault();
var text = event.target.text.value;
// stop the form from triggering a page reload
event.target.text.value = "";
// see if we can find a chat object in the database
// to which we'll add the message
Meteor.call("sendMessage", text);
},
});
Collections
Messages = new Mongo.Collection("messages");
Shared-Methods
Meteor.methods({
sendMessage: function (messageText) {
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
Messages.insert({
messageText: messageText,
createdAt: new Date(),
username: Meteor.user().profile.username,
avatar: Meteor.user().profile.avatar,
});
}
});

jQuery UI mulitple dialog issue with showing

I'm seeing strange behavior with 2 dialogs in my master page. Basically I check to see if GeoLocation is enabled, if it's disabled I show a dialog telling that certain functions will not work in the site if it's disabled. If there is an error with GeoLocation I show a different dialog telling them there was a problem. One of the dialogs is working about 50% of the time, sometimes it shows and sometimes it is embedded in my page just showing the text. The other Dialog is always just embedded as text. I'm wondering if its the version of jQuery I am using or if there is another conflict.
Here is the script
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { $("#message").html("Geolocation is not supported by this browser."); }
function showPosition(position) {
var latlondata = position.coords.latitude + "," + position.coords.longitude;
var latlon = "Latitude" + position.coords.latitude + "," + "Longitude" + position.coords.longitude;
$("#message").html(latlon);
$("[id*=hdnLon]").val(position.coords.longitude);
$("[id*=hdnLat]").val(position.coords.latitude);
// var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//var geocoder = geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'latLng': latlng }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// if (results[1]) {
// alert("Location: " + results[1].formatted_address + "\r\nLatitude: " + position.coords.latitude + "\r\nLongitude: " + position.coords.latitude);
//}
}
function showError(error) {
if (error.code == 1) {
$("#message").html("User denied the request for Geolocation.");
$("#dialogGeoUserDenied").dialog({
autoOpen: true,
width: 400,
buttons: [
{
text: "Ok",
click: function () {
$(this).dialog("close");
}
},
{
text: "Cancel",
click: function () {
$(this).dialog("close");
}
}
]
});
}
else if (error.code == 2) {
$("#message").html("Location information is unavailable.");
$("#dialogGeoLocationUnavailable").dialog({
autoOpen: true,
width: 400,
buttons: [
{
text: "Ok",
click: function () {
$(this).dialog("close");
}
},
{
text: "Cancel",
click: function () {
$(this).dialog("close");
}
}
]
});
}
else if (error.code == 3) {
$("#message").html("The request to get user location timed out.");
$("#dialogGeoLocationUnavailable").dialog({
autoOpen: true,
width: 400,
buttons: [
{
text: "Ok",
click: function () {
$(this).dialog("close");
}
},
{
text: "Cancel",
click: function () {
$(this).dialog("close");
}
}
]
});
}
else {
$("#message").html("An unknown error occurred.");
$("#dialogGeoLocationUnavailable").dialog({
autoOpen: true,
width: 400,
buttons: [
{
text: "Ok",
click: function () {
$(this).dialog("close");
}
},
{
text: "Cancel",
click: function () {
$(this).dialog("close");
}
}
]
});
}
}
</script>
Here is the html
<div id="dialogGeoUserDenied" title="Dialog Title">
<p class="validateTips">Geolocation has been disabled on your browser, you will not be able to receive promimity alerts. Enter your zip code to enable them.</p>
<fieldset>
<label for="zipcode">Zip Code</label>
<input type="text" name="zipcode" id="zipcode" value="00000" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</div>
<div id="dialogGeoLocationUnavailable" title="Dialog Title">
<p class="validateTips">Geolocation is unavailable, you will not be able to receive promimity alerts. Enter your zip code to enable them.</p>
<fieldset>
<label for="zipcode">Zip Code</label>
<input type="text" name="zipcode" id="zipcodeGU" value="00000" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</div>

How to combine Meteor.publish/Subscirbe and collection.allow?

I tried to write some code for understanding Meteor.publish/subscribe and collection.allow
Now It's don't have any error However I can't insert data to my collection.
testing.html
<head>
<title>testing</title>
</head>
<body>
<div class="container">
<div class="col-xs-2">
{{> loginButtons}}
</div>
<div class="col-xs-10">
{{> gettingContent}}
</div>
</div>
</body>
<template name="gettingContent">
<h1>These are all my contents.</h1>
{{#each gettingAll}}
{{title}}
{{author}}
{{/each}}
{{#if currentUser}}
<h2 class="alert">{{denie}}</h2>
<p>Title: <input type="text" id="title"/></p>
<p>Author: <input type="text" id="author"/></p>
<p><input type="button" value="Click" id="action" /></p>
{{/if}}
</template>
model.js
Content = new Meteor.Collection("Content");
Meteor.methods({
creatingContent: function(options) {
check(options, {
title: String,
author: String,
date: new Date()
});
Content.insert({
title: options.title,
author: options.author,
date: options.date
});
}
});
Content.allow({
insert: function(userId) {
if(Meteor.userId() === true){
return true;
} else {
return false;
}
}
});
clientTesting.js
Template.gettingContent.helpers({
gettingAll : function(){
return Meteor.subscribe("getAll");
}
});
var options = {
title: $("#title").val(),
author: $("#author").val(),
date: new Date()
};
Template.gettingContent.events({
'click #action' : function(event,options) {
event.preventDefault();
if(Meteor.userId() === true) {
Meteor.call("creatingContent",options);
console.log("Content was created.");
$("#title").val("");
$("#author").val("");
}else{
Session.set("deny", "You must be login for creating content.");
}
}
});
serverTesting.js
Meteor.publish('getAll', function(){
if(Content.find().count() === 0){
return Session.set("noData", "Data not found'");
} else {
return Content.find({},{sort:{'date':-1}});
}
});
I believe your problem is here: Meteor.userId() === true
By default, a Meteor userId is an alphanumeric character string. Testing for equality to true is always going to be false if the userId exists.
Try this:
if (Meteor.userId()) {
return true;
} else {
return false;
}
Or even simpler:
return !!Meteor.userId();
i didnt test this code but date: new Date() line is incorrect. It Should be Date.
check(options, {
title: String,
author: String,
date: Date
});
Okay Everyone I have fixed some code problem and just two thing I don't understand 1.How to use Meteor.subscribe with Template? and 2. How to render for showing my data. I got error like this
Exception from Deps recompute function: Error: {{#each}} currently only accepts arrays, cursors or falsey values.
testing.html
<head>
<title>testing</title>
</head>
<body>
<div class="container">
<div class="col-xs-2">
{{> loginButtons}}
</div>
<div class="col-xs-10">
{{> gettingContent}}
</div>
</div>
</body>
<template name="gettingContent">
<h1>These are all my contents.</h1>
{{#each gettingAll}}
<p>Title: {{title}}, Author: {{author}}</p>
{{/each}}
<h2 class="alert">{{denies}}</h2>
{{#if currentUser}}
<p>Title: <input type="text" id="title"/></p>
<p>Author: <input type="text" id="author"/></p>
<p><input type="button" value="Click" id="action" /></p>
{{/if}}
</template>
clientTesting
Template.gettingContent.helpers({
gettingAll : function(){
return Meteor.subscribe('getAll') && Content.find().count() ;
},
denies: function(){
return Session.get("deny");
}
});
var options1 = function(title, author){
var title = $("#title").val();
var author = $("#author").val();
if(_.isString(title) && !_.isEmpty(title) && _.isString(author) && !_.isEmpty(author) ){
var result = {title: title, author: author};
return result;
}else{
console.log("Invalid Data")
}
};
Template.gettingContent.events({
'click #action' : function(event) {
event.preventDefault();
Session.set("options", options1());
var options = Session.get("options");
if(Meteor.userId() && !_.isEmpty(options)) {
Meteor.call('creatingContent',options, function(){
console.log("Content was created.");
});
$("#title").val("");
$("#author").val("");
return Session.set("deny", "Your Data was created.");
}else {
return Session.set("deny", "Invalid Data.");
}
}
});
model.js
Content = new Meteor.Collection("Content");
Meteor.methods({
creatingContent: function(options) {
check(options, {
title: String,
author: String
});
if(options.title.length === 0)
throw new Meteor.Error(413, "noData Passed");
if(options.author.length === 0)
throw new Meteor.Error(413, "noData Passed");
Content.insert({
title: options.title,
author: options.author,
date: new Date().getTime()
});
}
});
Content.allow({
insert: function(userId) {
if(Meteor.userId() === true){
return true;
} else {
return false;
}
}
});
serverTesting.js
Meteor.publish('getAll', function(){
return Content.find({},{sort:{'date':-1}});
});

Resources