create user method error in `meteor Js`? - meteor

I am new to meteor Js, i had develop the meteor app the below error is came in server console please verify my code and suggest me how to solve the error.HERE IS MY SERVER JS AND CLIENT JS IS THERE WHERE I DID A MISTAKE PLEASE VERIFY AND GIVE ME SUGGESTION.
eRROR:
TypeError: Object #<Object> has no method 'createUser'
SERVER JS:
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
if ( Meteor.users.find().count() === 0 )
{
Accounts.createUser
({
username: 'admin',
email: 'admin#hcare.com',
password: '000000',
profile:
{
first_name: 'admin',
last_name: 'admin',
company: '3CubeTech',
}
}) //Added close parenthesis.
}
});
}
cLIENT js:
Template.body.events
({
'submit #login-form' : function (e,t)
{
/* template data, if any, is available in 'this'*/
if (typeof console !== 'undefined')
console.log("You pressed Login the button");
e.preventDefault();
/*retrieve the input field values*/
var username = t.find('#username').value
, password = t.find('#password').value;
console.log(password);
Meteor.loginWithPassword(username, password, function (err)
{
if (err)
{
console.log(err);
alert(err.reason);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
console.log( ">>>>>>>>>>>>>>>>>>>>>>> userid="+Meteor.userId() );
var adminUser = Meteor.users.findOne({username:"admin"});
console.log( ">>>>>>>>>>>>>>>>>>>>>>> adminUser()="+adminUser +" AND "+adminUser._id);
}
});
}
});

Run mrt test-packages For me it turned out, that I had to run mrt add accounts-password

Related

Login page lets user get inside the app even if the authentication failed

I've made a simple app with phone authentication (sms).
My problem splits to two, the first part is that the verification code (sms) is always wrong somehow (I do get it, however it doesn't pass the confirmation), and the second part (as stated in the title) is that the user can still access the main activities even if authentication failed.
the function is invoked via a button.
the function is :
signIn(){
const appVerifier = this.recaptchaVerifier;
const phoneNumberString = "+972" + this.phoneNumber.substring(1,10);
firebase.auth().signInWithPhoneNumber(phoneNumberString, appVerifier)
.then( confirmationResult => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
let prompt = this.alertCtrl.create({
title: 'Enter the Confirmation code',
inputs: [{ name: 'confirmationCode', placeholder: 'Confirmation Code' }],
buttons: [
{ text: 'Cancel',
handler: data => { console.log('Cancel clicked'); }
},
{ text: 'Send',
handler: data => {
confirmationResult.confirm(data.confirmationCode)
.then(function (result) {
// User signed in successfully.
this.uid = result.user.uid
this.addUser(this.fullName, this.uid);
console.log(result.user);
// ...
}).catch(function (error) {
console.log("Invalid code") // always getting here
});
}
}
]
});
prompt.present();
}).catch(function (error) {
console.log("SMS not sent")
});
}
UPDATE (app.component)
the decision is made in the constructor of app.component.ts
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
var that = this
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
that.rootPage = TabsPage; // even though auth failed, he comes here
} else {
that.rootPage = LoginPage;
}
});
});
}
I dont see it in your code but anywhere you call a method to push the main App-Page. You only should show the main App-Page after User successfully logged in. If this dont work maybe the user comes inside of your app, because the Firebase function is asynchron.

Nativescript with Firebase : Works login in offline mode

I use nativescript-plugin-firebase to connect with Firebase. It does work when create new user / login / CRUD operations when app is online mode.
When the app is offline mode, Login authentication / Create new user is not working rest of the above mentioned things are working.
My code base:
app.component.ts
ngOnInit(): void {
firebase.init({
persist: true,
storageBucket: 'gs://**************/',
onAuthStateChanged: (data: any) => {
console.log(JSON.stringify(data))
if (data.loggedIn) {
BackendService.token = data.user.uid;
}
else {
BackendService.token = "";
}
}
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
firebase.keepInSync(
"/users", // which path in your Firebase needs to be kept in sync?
true // set to false to disable this feature again
).then(
function () {
console.log("firebase.keepInSync is ON for /users");
},
function (error) {
console.log("firebase.keepInSync error: " + error);
}
);
in service file
login(user: User) {
return firebase.login({
type: firebase.LoginType.PASSWORD,
email: user.email,
password: user.password
}).then((result: any) => {
BackendService.token = result.uid;
return JSON.stringify(result);
}, (errorMessage: any) => {
// alert(errorMessage);
alert('Email address / Password is wrong!!!');
});
}
Anyone help me how login will work in when offline mode.

Prevent Firebase auth from remembering Google account?

So I'm using Firebase-UI to authenticate and sign in users, I need to use the account chooser in order for them to sign in to a different Google account (not using the account chooser results in it auto-signing them in), however, I want to either prevent it from displaying + saving accounts, or remove them on sign out.
And this is the Firebase-UI web I'm using: Firebase UI web
This isn't a huge issue when the application is running on a user's machine, however, it will also be running on a public machine with many users signing in an out, and we can't have them saved as an easy one-click sign in. The biggest security issue is the fact that I can also log into their emails once they've authenticated with Google. We want it to forget them once they sign out.
My sign-in flow:
<script type="text/javascript">
// FirebaseUI config.
var uiConfig = {
callbacks: {
signInSuccess: function (user, credential, redirectUrl) {
var userSignIn = {
displayName: user.displayName,
email: user.email,
emailVerified: user.emailVerified,
photoURL: user.photoURL,
uid: user.uid,
phoneNumber: user.phoneNumber
};
/* POST signed in user to Login Controller*/
var csrfToken = $('input[name="csrfToken"]').attr('value');
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', csrfToken);
}
});
$.ajax({
url: '/signedIn',
type: 'POST',
data: JSON.stringify(userSignIn),
contentType: 'application/json',
error: function(err) {
console.log(err);
}
});
return true;
}
},
signInSuccessUrl: '/Dashboard',
signInOptions: [{
provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
scopes: ['https://www.googleapis.com/auth/calendar']
}],
// Terms of service url.
tosUrl: '/Terms'
};
// Initialize the FirebaseUI Widget using FirestoreDB.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);
</script>
Sign-out flow:
initApp = function () {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// User is signed in.
if (window.location.pathname === "/Login" || window.location.pathname === "/") {
window.location.href = '/Dashboard';
}
$('#sign-out').show();
} else {
// User is signed out.
$('#sign-out').hide();
disableLinks();
switch(window.location.pathname){
case "/Login":
case "/Terms":
case "/Help":
break;
default:
window.location.href = '/Login';
}
}
}, function (error) {
console.log(error);
});
};
window.addEventListener('load', function () {
initApp();
document.getElementById('sign-out').addEventListener('click', function () {
firebase.auth().signOut().then(function() {
sessionStorage.clear();
localStorage.clear();
window.location = "/Logout";
}).catch(function(error) {
console.log(error);
});
});
});
On sign out from Firebase Auth, redirect to Google single sign out URL:
firebase.auth().signOut()
.then(function() {
window.location.assign('https://accounts.google.com/Logout');
})
.catch(function(error) {
console.log(error);
});

Firebase - no displayName for user

I can add users in Firebase console -> Auth but I can't do anything more than setting an email and password for them.
Could I in some way set for them displayName?
I guess if you just want to update users profile:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
user.updateProfile({
displayName: "Random Name"
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
} else {
// No user is signed in.
}
});
Additionally: https://firebase.google.com/docs/auth/web/manage-users
When you create a user you create it only with email and password but you can and the displayName in the promise, then inside the .then() method you call the updateProfile method and you are ready, right down is the code:
onSubmit(formData) {
if(formData.valid) {
console.log(formData.value);
this.af.auth.createUserWithEmailAndPassword(
formData.value.email,
formData.value.password
).then(
(success) => {
console.log(success);
success.updateProfile({
displayName: "Example User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).catch(
(err) => {
this.error = err;
});
this.router.navigate(['/login'])
}).catch(
(err) => {
this.error = err;
})
}
}
Note that in my example the displayName is set to "Example User", in the real app you just add the parameter as in my case it should be -> displayName:formData.value.name

Evothings and ddp

We are trying to connect our evothings app up to a meteor server.
To do this we are using a lib called asteroid. However we are unable to connect and run methods. We are absolutly sure this is not a server issue since we have some separate client code for testing that works flawlessly with it.
Evothings says it should work with websockets, and we aren't getting any error output, but all our method calls are returning nothing.
Here is the code:
var _asteroid = require('asteroid');
var Asteroid = (0, _asteroid.createClass)('password-login');
var asteroid = new Asteroid({ endpoint: 'wss://[url]/websocket' });
var currentLogin = null;
$('#login').submit(function(event) {
event.preventDefault();
login($('#login_username').val(), $('#login_password').val());
});
$('#create').submit(function(event) {
event.preventDefault();
newUser($('#create_username').val(), $('#create_password').val(), $('#create_id').val());
});
$('#occupy').click(function(event) {
setStatus(0);
});
$('#vacant').click(function(event) {
setStatus(1);
});
$('#refreash').click(function() {
getEmptyRooms();
});
window.newUser = function (username, password, roomId) {
$('#create_error').text('');
asteroid.call("accounts.newUser", username, password, roomId).then(function (result) {
console.log("Success");
login(username, password);
}).catch(function (error) {
console.log("Error");
console.error(error);
$('#create_error').text(error.message);
});
}
window.login = function (username, password) {
$('#login_error').text('');
asteroid.loginWithPassword({ username: username, password: password }).then(function (result) {
console.log(result);
currentLogin = result;
$('#current').html('Current User: ' + username);
}).catch(function (error) {
console.log("Error");
console.error(error);
$('#login_error').text(error.message);
});;
}
window.getEmptyRooms = function () {
asteroid.call("rooms.getAvailable").then(function (result) {
console.log(result);
$('#room_list').empty();
for(i = 0; i < result.length; i++) {
$('#room_list').append('<li>' + result[i] + '</li>');
}
}).catch(function (error) {
console.log("Error");
console.error(error);
});
}
window.setStatus = function (status) {
$('#status_error').text('');
if (currentLogin != null) {
asteroid.call("rooms.setStatus", status).then(function (result) {
console.log(result);
}).catch(function (error) {
console.log("Error");
console.error(error);
$('#status_error').text(error.message);
});
} else {
console.log('please login first');
$('#status_error').text('please login first');
}
}
As far as I know, the require() function works only in node.js, not in browser environment such as Evothings Viewer or Cordova, so you'll need some alternative means of loading the "asteroid" lib. Browserify?
How did you look for error output? The Evothings Tools window? If so, did you add this snippet to your index.html file?
<script>
// Redirect console.log to Evothings Workbench.
if (window.hyper && window.hyper.log) { console.log = hyper.log }
</script>
Perhaps this error isn't exclusive to the Evothings environment. Have you tested the app in a regular web browser?
Are you using proper certs?
Self signed will not work. The Evothings app is served via wss and since it runs "headless" so to speak (not a normal browser) it can't ask the user about allowing a self signed cert, so it will fail. Note that AFAIK ANY issue with the cert will make it fail.

Resources