I have an app i'm programming in Javascript/JQuery. I'm using PhoneGap and want to use localStorage to store the users credentials the first time they open the app and then autofill next time the user opens the app. I want to call the checkPreAuth() right when the page loads. But It's not calling my function. Can anybody help me?
Calling the function from login.html:
<script>
$(document).ready(function() {
checkPreAuth();
});
</script>
And the function in my digest_auth.js:
function checkPreAuth() {
var form = $("#loginForm");
var values = new Array();
var username = $('#username').val();
var password = $('#password').val();
if(window.localStorage["username"] == undefined && window.localStorage["password"] == undefined) {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
alert('Saved username and password');
} else {
alert(username + ', ' + password);
}
}
Maybe this is the answer to your problem. I faced this problem and instead of using document ready of jquery, i used this:
JQuery document.ready vs Phonegap deviceready
Related
Im facing a problem reading the already set data from previous login after user abruptly switches from my App into another or restarts the phone. The data I've set after successful login does get saved in the SQLite database.
.controller('LoginCtrl', function($scope, $ionicPopup, $state,$http,ServerEndPoint,localStorageService,$cordovaGeolocation,$ionicActionSheet,dataShare,$ionicPush,loading,$rootScope,$cordovaSQLite) {
$scope.data = {};
//Does not work
$scope.init = function()
{
$scope.load();
};
if(localStorageService.get("tradie_id") !== null && localStorageService.get("phone_no") !== null) {
$state.go('menu.map');
}
//This is called from login form submit button click
$scope.authenticateUser = function(loginForm){
//Authenticating user from the server, after successful login
//This one works
$scope.addInfo(res.data.user_id,res.data.first_name,res.data.phone_no,status);
$state.go('menu.map');
}
$scope.addInfo = function(user_id,first_name,phone_no,status){
var query = "INSERT INTO user_data(user_id,first_name,phone_no,status) VALUES(?,?,?,?)";
$cordovaSQLite.execute(db,query,[user_id,first_name,phone_no,status]);
$scope.load();
}
$scope.load = function(){
$scope.alldata = [];
$cordovaSQLite.execute(db,"SELECT * FROM user_data").then(function(result){
if(result.rows.length)
{
for(var i=0;i<result.rows.length;i++)
{
$scope.alldata.push(result.rows.item(i));
}
localStorageService.set("user_id", $scope.alldata[0].tradie_id);
localStorageService.set("first_name", $scope.alldata[0].first_name);
localStorageService.set("phone_no", $scope.alldata[0].phone_no);
}else
{
console.log("No data found");
}
},function(error){
console.log("error "+err);
})
}
})
Any suggestions or pointers to a sample source code is highly appreciated. I'm using ionic version 1.
I think you didn't create or open the db when app ready first:
var db = $cordovaSQLite.openDB({ name: "my.db" });
I am trying to login from my Phonegap App using Angularjs (using the Ionic Framework) through Google OAuth2. Currently I am using the http://phonegap-tips.com/articles/google-api-oauth-with-phonegaps-inappbrowser.html for logging in. But it is creating really ugly looking code and quite a hard to understand code when I am using Angular-UI-Router for Ionic.
This issue seems to be spiralling around without any proper answers. I hope it should be solved now. The Google Angular Guys should help.
How to implement Google Auth in phonegap?
The closest topic is How to use Google Login API with Cordova/Phonegap, but this is not a solution for angularjs.
I had to transfer the javascript variable values using the following code:
var el = document.getElementById('test');
var scopeTest = angular.element(el).scope();
scopeTest.$apply(function(){
scopeTest.user = user;
scopeTest.logged_in = true;
scopeTest.name = user.name;
scopeTest.email = user.email;
});
I did the solution like this, where TestCtrl is the Controller where the Login Button resides. There is a mix of jquery based $.ajax calls, which I am going to change to the angualar way. The google_call function basically calls the google_api which is mentioned in the link mentioned above in phonegap-tips.
.controller('TestCtrl', function($scope,$ionicPopup) {
$scope.logged_in = false;
$scope.getMember = function(id) {
console.log(id);
};
$scope.test = function(){
$ionicPopup.alert({"title":"Clicked"});
}
$scope.call_google = function(){
googleapi.authorize({
client_id: 'CLIENT_ID',
client_secret: 'CLIENT_SECRET',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function(data) {
accessToken=data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
//$ionicPopup.alert({"title":JSON.stringify(data)});
$scope.getDataProfile();
});
};
$scope.getDataProfile = function(){
var term=null;
// alert("getting user data="+accessToken);
$.ajax({
url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken,
type:'GET',
data:term,
dataType:'json',
error:function(jqXHR,text_status,strError){
},
success:function(data)
{
var item;
console.log(JSON.stringify(data));
// Save the userprofile data in your localStorage.
window.localStorage.gmailLogin="true";
window.localStorage.gmailID=data.id;
window.localStorage.gmailEmail=data.email;
window.localStorage.gmailFirstName=data.given_name;
window.localStorage.gmailLastName=data.family_name;
window.localStorage.gmailProfilePicture=data.picture;
window.localStorage.gmailGender=data.gender;
window.localStorage.gmailName=data.name;
$scope.email = data.email;
$scope.name = data.name;
}
});
//$scope.disconnectUser(); //This call can be done later.
};
$scope.disconnectUser = function() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='+accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken=null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----"+accessToken);
},
error: function(e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
}
});
};
})
I am providing this answer for the newbies who faced similar problems like mine while trying to login using Google OAuth2. So asking for Upvotes shamelessly as I am new here too!
Is it possible to communicate an android Application with cakePhp website and share data? If it is possible, I want to create an application that can login into the website; my doubt is:
How to pass user name and password from our application to cakephp websites login page? Can anybody show me an example program?
How cakephp controller handle this request and respond to this request? Please show me an example program?
(I am a beginner in android and cakephp.)
Quick answer -- YES!
We just finished pushing an Android app to the market place that does this exact thing. Here's how we did it:
1) Download and learn to use Cordova PhoneGap (2.2.0 is the latest version) within Eclipse. This makes the whole thing so much easier with just some HTML and a lot of Javascript.
2) In your JS, create methods that push the login information using AJAX parameters. Example:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
$("#login").click(function() {
$email = $("#UserEmail").val();
$pass = $("#UserPassword").val();
$.ajax({
url : yourURL + 'api/users/login',
async : false,
data : {
'email' : $email,
'password' : $pass
},
dataType : 'json',
type : 'post',
success : function(result) {
/**
* do your login redirects or
* use localStorage to store your data
* on the phone. Keep in mind the limitations of
* per domain localStorage of 5MB
*/
// you are officially "logged in"
window.location.href = "yourUrl.html";
return;
},
error : function(xhr, status, err) {
// do your stuff when the login fails
}
});
}
}
3) In Cake / PHP, your Users controller here will take the username and password data in the AJAX call and use that for its authentication.
<?php
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('api_login');
}
public function api_login() {
$this->autoRender = false;
if ($this->request->data && isset($this->request->data['email']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('all',array(
'conditions'=>array(
'email'=> $this->request->data['email'],
'password' => $this->Auth->password($this->request->data['password']),
)
)
);
if (count($arrUser) > 0) {
$this->Session->write('Auth.User',$arrUser[0]['User']);
// Do your login functions
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array( 'loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
echo json_encode($arrReturn);
}
}
?>
That's pretty much it. You are now authenticated to CakePHP.
You do not need to use "api_", you can use any function name you want, but this helped us keep a handle on what we allowed mobile users to do versus web users.
Now, these are just the building blocks. You basically have to create a whole version of your site on the phone using HTML and Javascript, so depending on your application it may be easier just to create a responsive design to your site and allow mobile browsing.
HTH!
Use Admad JWT Auth Plugin
If you use cakephp3 change your login function with this one :
public function token() {
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid username (email) or password');
}
$this->set([
'success' => true,
'data' => [
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
You can read this tutorial about REST Api and JWT Auth Implementation
http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/
if rebuild most of the view pages in cakephp into ajax will seem defeat the purposes of using cakephp as it is.
I'm trying to find the best way to send my users a real-time status update of a process that's running on my server - this process is broken up into five parts. Right now I'm just 'pulling' the status using an Ajax call every few seconds to a PHP file that connects to MySQL and reads the status, but as you can imagine, this is extremely hard on my database and doesn't work so well with users that don't have a strong internet connection.
So I'm looking for a solution that will 'push' data to my client. I have APE push-engine running on my server now, but I'm guessing Socket.IO is better for this? What if they're on 3G and they miss a status update?
Thanks in advance :)
I guess my answer may match what you need.
1st: You Have to Get Node.js to run the socket.io
BELOW IS SAMPLE CODE FOR SERVER:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8800); //<---------Port Number
//If No Connection / Page Error
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
//If there is connection
io.sockets.on('connection', function (socket) {
//Set Varible
var UserID;
var Old_FieldContent = "";
socket.on('userid', function (data) {
if(data.id){
UserID = data.id;
StartGetting_FileName(UserID)
}
});
//Checking New Status
function StartGetting_FileName(UserID){
//Create Interval for continues checking from MYSQL database
var myInterval = setInterval(function() {
//clearInterval(myInterval);
//MySQL Connection
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : '3306',
user : 'root',
password : 'ABCD1234',
database : 'test',
});
//Setup SQL Query
var SQL_Query = "SELECT FileName FROM status WHERE UserID = '"+UserID+"'";
connection.connect();
connection.query(SQL_Query, function(err, rows, fields) {
//Do if old result is, different with new result.
if(Old_FieldContent !== rows[0].FileName){
if (err) throw err;
//Display at Server Console
console.log('------------------------------------------');
console.log('');
console.log('Fields: ', fields[0].name);
console.log('Result: ', rows[0].FileName);
console.log('');
console.log('------------------------------------------');
//Send Data To Client
socket.emit('news', { FieldName: fields[0].name });
socket.emit('news', { FieldContent: rows[0].FileName });
//Reset Old Data Variable
Old_FieldContent = rows[0].FileName;
}
});
connection.end();
}, 500 );
}
});
BELOW IS CLIENT HTML & JS:
<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
<!-- URL PATH TO LOAD socket.io script -->
<script src="http://15.17.100.165:8800/socket.io/socket.io.js"></script>
<script>
//Set Variable
var UserID = "U00001";
var socket = io.connect('http://15.17.100.165:8800');
var Field_Name = "No Data";
var Field_Content = "No Data";
// Add a disconnect listener
socket.on('connecting',function() {
msgArea.innerHTML ='Connecting to client...';
console.log('Connecting to client...');
//Once Connected Send UserID to server
//for checking data inside MYSQL
socket.emit('userid', { id: UserID });
});
// Get data that push from server
socket.on('news', function (data) {
console.log(data);
writeMessage(data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
msgArea.innerHTML ='The client has disconnected!';
console.log('The client has disconnected!');
});
//Function to display message on webpage
function writeMessage(msg) {
var msgArea = document.getElementById("msgArea");
if (typeof msg == "object") {
// msgArea.innerHTML = msg.hello;
if(msg.FieldName !== undefined){
Field_Name = msg.FieldName;
}
if(msg.FieldContent !== undefined){
Field_Content = msg.FieldContent;
}
}else {
msgArea.innerHTML = msg;
}
msgArea.innerHTML = Field_Name +" = "+ Field_Content;
}
</script>
</head>
<body>
<div id="msgArea">
</div>
</body>
</html>
You should consider using push notifications, with the service provided for Android by Google as C2DM: https://developers.google.com/android/c2dm/
You will need to implement a PhoneGap plugin to handle the native notifications, and communicate them to your PhoneGap project that will then (and only then) query your server .
As K-ballo above points out, using a push notification plugin would be best.
Luckily, some good citizen on GitHub has done this already!
https://github.com/awysocki/C2DM-PhoneGap
Please note: the above C2DM plugin was built for PhoneGap v1.2, so if you are running a more up-to-date version you will have to tweak the native code a bit to get it working better.
I have a really weird scenario that I'm stuck on. I have a ASP.Net MVC 4 app where I'm authenticating a user and creating an authCookie and adding it to the response's cookies then redirecting them to the target page:
if (ModelState.IsValid)
{
var userAuthenticated = UserInfo.AuthenticateUser(model.UserName, model.Password);
if (userAuthenticated)
{
var userInfo = UserInfo.FindByUserName(model.UserName);
//SERIALIZE AUTHENTICATED USER
var serializer = new JavaScriptSerializer();
var serializedUser = serializer.Serialize(userInfo);
var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, serializedUser);
var hash = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash) {Expires = ticket.Expiration};
Response.Cookies.Add(authCookie);
if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/") && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\"))
{
return Redirect(model.ReturnUrl);
}
var url = Url.Action("Index", "Course");
return Redirect(url);
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
This is working just fine in all browsers. I can login and access the secure pages in my app.
My client is requesting an android version of this app. So, I'm trying to figure out how to convert this app into an APK file. My first attempt is to create a simple index.html page with an iframe that targets the application. This works just fine in Firefox and IE 9. However, when accessing the index.html page that contains the iframe that points to the app via Chrome, I get past the login code above and the user gets redirected to the secure controller, but the secure controller has a custom attribute to make sure the user is authenticated:
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated) return;
if (filterContext.HttpContext.Request.Url == null) return;
var returnUrl = filterContext.HttpContext.Request.Url.AbsolutePath;
if (!filterContext.HttpContext.Request.Browser.IsMobileDevice)
{
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + string.Format("?ReturnUrl={0}", returnUrl), true);
}
else
{
filterContext.HttpContext.Response.Redirect("/Home/Home", true);
}
}
}
My app is failing on: filterContext.HttpContext.User.Identity.IsAuthenticated. IsAuthenticated is always false, even though the user was authenticated in the code above.
Keep in mind this only happens when accessing the app via iframe in Chrome. If I access the app directly instead of via iframe, then everything works just fine.
Any ideas?
UPDATE:
My controller extends SecureController. In the constructor of SecureController I have the code that deserializes the user:
public SecureController()
{
var context = new HttpContextWrapper(System.Web.HttpContext.Current);
if (context.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
var serializer = new JavaScriptSerializer();
var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
var ticket = FormsAuthentication.Decrypt(cookie);
CurrentUser = serializer.Deserialize<UserInfo>(ticket.UserData);
}
else
{
CurrentUser = new UserInfo();
}
//if ajax request and session has expired, then force re-login
if (context.Request.IsAjaxRequest() && context.Request.IsAuthenticated == false)
{
context.Response.Clear();
context.Response.StatusCode = 401;
context.Response.Flush();
}
}
First, you should be deriving from AuthorizeAttribute, not an ActionFilterAttribute. Authorization attributes execute before the method is even called at a higher level of the pipeline, while ActionFilters execute much further down, and other attributes can execute before yours.
Secondly, you aren't showing the code you use to decrypt the ticket and set the IPrincipal and IIdentity. Since that's where the problem is, it's odd that you didn't include it.