Alloy MVC Framework Titanium Network (Model) - javascript

I'm trying to authenticate using the Model in Alloy. I have been trying to figure this problem out since yesterday. If anybody could help me, I'd really appreciate it.
So, I have a view login.xml, then a controller login.js. The login.js contains the following function:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
if(user.login($.username.value, $.password.value)){
Alloy.createController('home').getView().open();
$.login.close();
}
}else{
alert('Username and/or Password required!');
}
}
Then in my user.js model, it's like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
alert(_this.get('email')); //alert email
},
});
When I click on login in login.xml it calls the function login in index.js. So, now my problem is that, when I click the button for the first time, I get an empty alert from alert(_this.get('email')), but then when I click the button the second time, everything works fine, it alerts the email. I have no idea what's going on. Thank you for the help.

I think I figured it out, for people that might stumble upon the same problem. I used callback function to do it.
Refer to this Titanium HTTP Request
Now my user.js looks like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password, callback) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
callback(foo); //whatever you want to send
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
},
});
And my login.js looks like this:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
var logged_in = user.login($.username.value, $.password.value, function(foo){
if(foo == bar)
call_another_function();
});
}else{
alert('Username and/or Password required!');
}
}
Thanks. I hope this helps.

Related

How to write test cases in Jest for login page

The following code is what I have written in order for the Admin to log in to the system. I am now trying to carry out unit testing and have to test the ValidateLogin for admin in particular. I have chosen jest to do that.
I created a test file:
const LoginController = reqire('./LoginController')
test('login to the system', () => {
expect(true).toBe(true);
})
Instead of checking for true to be true. I want to check for the username and password to be true. Please explain how should I do it.
Following is the code for login:
class User {
username;
password;
email;
firstName;
lastName;
roleName;
constructor(username,password,email,firstName, lastName, roleName){
this.username = username;
this.password = password;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.roleName = roleName;
}
getlogininfo(username, password, callback) {
var sql = "SELECT * FROM User Where username = '" + username +
"' AND password = '" + password + "'";
var Username;
var dataRes;
con.query(sql, function(err, results){
if (err){
throw err;
}
if(results.length>0) { //result is not empty
Username = results[0].username; // Scope is larger than function
dataRes = {
username: results[0].username,
firstName: results[0].firstName,
lastName: results[0].lastName,
roleName: results[0].roleName
}
return callback(dataRes);
} else {
return callback(false);
}
})
}
}
exports.User = User
class LoginController {
ValidateLogin(req, res) {
let user = new User();
var dataRes;
var username = req.body.username
var password = req.body.password
console.log(username + "kekw" + password);
user.getlogininfo(username, password, function(result){
if(result) {
dataRes = result;
var session;
// Login endpoint
if(dataRes.roleName == "useradmin") {
console.log("Call User Admin Dashboard");
res.redirect("/UserAdmin");
}
else if(dataRes.roleName == "manager") {
console.log("Call Manager Dashboard");
res.redirect("/Manager");
}
else if(dataRes.roleName == "staff") {
console.log("Called Staff Dashboard");
res.redirect('/Staff');
}
else if(dataRes.roleName == "customer") {
console.log("Called Customer Dashboard");
res.redirect('/Customer');
}
/*
else if(dataRes.role == "Pharmacist") {
console.log("Called Pharmacist home");
res.redirect('/PharmacistHome');
}
else if(dataRes.role == "Patient") {
console.log("Called Patient home");
res.redirect('/PatientHome');
}*/
}
else {
req.flash('message', 'Wrong Username or Password!')
res.redirect("/?error=true");
return false;
}
});
}
}
//module.exports = LoginController;
exports.LoginController = LoginController;
I want to write test cases for username and password for the useradmin login. How do I do so? Thanks.
Could you please send your complete error code? It would be very helpful to get a solution. Although i think it could be an error with ES6 modules. Check if you have "type": "module" in your package.json. If that's the case you have to import your LoginController with import * from './LoginController'
You wrote „require“ wrong:
Like this: const LoginController = reqire('./LoginController');

How to fix nodemailer "object object" error in node.js website?

I am creating a node.js website for a business and would like to be able to notify through email, everytime someone applies. I am using nodemailer and mailgun to send an email every time the job application form is submitted. The emails are being sent, however, it does not contain the key value pairs of the applicant object I've created. Any help would be greatly appreciated!
Here is an image of the email I receive when submitting and application
Here is the nodemailer code I'm running
const nodemailer = require('nodemailer');
const mailgun = require('nodemailer-mailgun-transport');
const debug = require('debug')('app:mail');
const auth = {
auth: {
api_key: '**************',
domain: '***************'
}
};
const transporter = nodemailer.createTransport(mailgun(auth));
function sendOrderEmail(applicant) {
let html = '<ul>';
Object.entries(applicant).forEach(([key, value]) => {
html += `<li>${key}: ${value}</li>`;
});
html += '</ul>';
const mailOptions = {
from: '*************',
to: '*********, *************',
subject: '*****************',
html
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
debug(`Error: ${err}`);
} else {
debug(`Info: ${info}`);
}
});
}
module.exports = sendOrderEmail;
Here is my post route where I create the applicant object
app.post('/employment', function(req, res){
var firstName = req.body.firstName;
var middleInitial = req.body.middleInitial;
var lastName = req.body.lastName;
var address = req.body.address;
var city = req.body.city;
var state = req.body.state;
var zipCode = req.body.zipCode;
var phoneNumber = req.body.phoneNumber;
var doYouRecieveText = req.body.doYouRecieveText;
var newApplicant = {
firstName: firstName,
middleInitial: middleInitial,
lastName: lastName,
address: address,
city: city,
state: state,
zipCode: zipCode,
phoneNumber: phoneNumber,
doYouRecieveText: doYouRecieveText
};
Applicant.create(newApplicant, function(err, newlyCreated){
if(err) {
console.log(err);
} else {
console.log(newlyCreated);
sendOrderEmail(newlyCreated);
res.redirect('/');
}
});
});
It looks like the value you are attempting to insert in your html is an Object but the html is expecting a value of type String.
Try stringifying your value before inserting it in your html.
html += `<li>${key}: ${ typeof value === 'string' ? value : JSON.stringify(value)}</li>`;
I was passing through the newlyCreated parameter to the sendOrderEmail function when I should have been passing through the newApplicant variable
Applicant.create(newApplicant, function(err, newlyCreated){
if(err) {
console.log(err);
} else {
console.log(newlyCreated);
sendOrderEmail(newApplicant);
res.redirect('/');
}
});

How to check if there's no errors in authentication process in Firebase Web?

I'm new to Web Development, especially to Firebase.
I'm trying to check if there are no errors while creating a user in Firebase Authentication system, so I can put this user into Database.
Here's my code:
function register() {
var firebaseRef = firebase.database().ref();
var shaObj = new jsSHA("SHA-256", "TEXT")
shaObj.update(passwordField.value)
//console.log(hash)
var email = emailField.value
var password = shaObj.getHash("HEX")
if (isBarber != null) {
if (email != "" && password != "") {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
$('#errorMsg').show();
$('#errorMsg').text(error.message);
if (error === null) {
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}
});
} else {
alert('Email or password fields are empty')
}
} else {
alert('Select your role')
}
}
createUserWithEmailAndPassword works properly and creates a user, but I don't know how to check if there are no errors so I could add this user to database.
Thanks a lot
You can use then() to action on a successful registration as follows:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Registration is successful
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}).catch(error) {
//Registration unsuccessful
$('#errorMsg').show();
$('#errorMsg').text(error.message);
});

How do I access the user UID in my firebase database

I am working on a fantasy soccer web app based on a local league. So far, when a user is created using firebase auth, there is a respective node created in my firebase using the user uid as follows:
$scope.signUp = function (){
var username = $scope.user.email;
var password = $scope.user.password;
var teamname = $scope.user.teamname;
var fullname = $scope.user.fullname;
var ref = firebase.database().ref().child('users');
if(username && password){
var auth = $firebaseAuth();
auth.$createUserWithEmailAndPassword(username,
password).then(function(user){
console.log("User Successfully Created");
let usersRef = firebase.database().ref("users");
//child is created under users node with a user's user id as
child name
usersRef.child(user.uid).set({
email: user.email,
userName: username,
teamname: teamname,
fullname: fullname,
total: 0,
week:0
});
$location.path('/home');
}).catch(function(error){
$scope.errMsg = true;
$scope.errorMessage = error.message;
});
}
};
That part works fine. In the database, the JSON tree looks something like this:
users:{
user UID: {
email:
teamname:
fullname:
week:
}
}
I have a service I use for all my views :
.service('CommonProp',['$location','$firebaseAuth', function($location,$firebaseAuth){
var user = "";
var auth = $firebaseAuth();
return {
getUser:function(){
if(user == ""){
user = localStorage.getItem("userEmail");
}
return user;
},
setUser: function(value){
localStorage.setItem("userEmail", value);
user = value;
},
logoutUser: function(){
auth.$signOut();
console.log("Logged Out Successfully");
user = "";
localStorage.removeItem("userEmail");
$location.path('/home');
}
};
}]);
PROBLEM
My problem is that when I go to my 'select player' view, I do not know how to access the user UID so that I can set each user's selection for each week.This is what I tried to do :`
$scope.saveTeam = function(user){
$scope.history = [];
var uid = user.uid;
var ref2 = firebase.database().ref("users/" + auth.uid + "/week");
ref2.set($scope.history);
};
Is there a way that I can access each user's respective "week" child node under their respective user uid?

Sails.js - creating empty models

This is the controller that I am using to create a new instance of my human model:
newh: function(req, res) {
var firstName = req.param('firstName');
var lastName = req.param('lastName');
var contact = req.param('contact');
var email = req.param('email');
var home = 'http://localhost:1337/humans';
Human.create({
firstName: firstName,
lastName: lastName,
contact: contact,
email: email
}).done(function(err, user) {
if(err) {
return console.log('Could not create user. Error: ' + err);
}else{
res.redirect('/humans');
}
});
This is the script that I am using to post the data to the controller:
$(document).ready(function() {
var firstName = $('#first').val();
var lastName = $('#last').val();
var contact = $('#contact').val();
var email = $('#email').val();
$('#add').on('click', function() {
$.ajax({
type: 'POST',
url: '/humans/new',
data: {
firstName: firstName,
lastName: lastName,
contact: contact,
email: email
},
success: function() {
console.log('Successfully passed data.');
}
});
});
});
Whenever I post the information, the success function gets executed. Still, my controller doesn't seem to make use of that res.redirect() call and it simply generates empty instances of the human model.
What's the problem?
Thank you!

Categories

Resources