ExtJS4 & Symfony 2 - extjs

I have to mix up Symfony2 and ExtJS4. All views need to be render with ExtJS, no twig.
All the application is in a secured area, only members will be able to access it.
When an user launch the application, main viewport is displayed with login form. After connecting, the entire app is displayed.
In facts, the / route need to display viewport. It will call an ajax request to check if user is connected.
if yes, launch the app
if not, show the login form
And I don't know how to do that, the / action in my controller wait for response and I only want to launch javascript.
EDIT : the login form must be made with ExtJS.
security.yml
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login$
security: false
secured_area:
pattern: ^/
form_login:
check_path: /login_check
login_path: /login
logout:
path: /logout
target: /
and the loginAction
public function loginAction()
{
if ($this->get('request')->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $this->get('request')->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $this->get('request')->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
}
$json = json_encode(array(
'username' => $this->get('request')->getSession()->get(SecurityContext::LAST_USERNAME),
'error' => $error,
));
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
}

Process should be -
Make an ajax call to login_check
Read the json response into an object and check whatever variable is set to denote success or failure
If the user isn't logged in, show the login window
In the click event of the login button, make another ajax call to log them in
If they authenticate, return a variable to notify via json, and show the app, if not give them a hint as to what went wrong in a message.
-
var login = Ext.create('Ext.window.Window', {
id: 'login',
height: 200,
width: 350,
layout: 'anchor',
modal: true,
title: 'Welcome, Please Login',
items: [
this.username = Ext.create('Ext.form.field.Text', {
fieldLabel: 'Username'
}),
this.password = Ext.create('Ext.form.field.Text', {
fieldLabel: 'Password'
}),
this.submit = Ext.create('Ext.button.Button', {
text: 'Login'
})
]
});
login.submit.on('click', function (btn, e, eOpts) {
Ext.Ajax.request({
scope: this,
params: {
username: login.username.getValue(),
password: login.password.getValue()
},
url: 'yoursite/login',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
if (obj.logged_in === true) {
//Show App
} else {
//Display error message
}
}
});
});
Ext.Ajax.request({
scope: this,
url: 'yoursite/login_check',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
if (obj.username === null) {
//Show Login window
login.show();
} else {
//Logic to show app if logged in
}
}
});

Related

cookie NOT setting in browser with hapi-auth-cookie plugin

I've used hapi js for my backend and react for my frontend. The front end server is running on localhost port 3000, and the backend on 8000. So i have 2 routes like this -
let userDetails = {
method: "GET",
path: "/api/user/userdata",
config: {
description: 'Get userdata',
notes: 'Returns a todo item by the id passed in the path',
tags: ['api', 'User Data'],
cors: corsHeaders,
auth: {
strategy: 'restricted',
}
},
handler: (request, h) => {
return h.response(userData)
}
}
and
let createUser = {
method: "POST",
path: "/api/user/userdata",
config: {
tags: ['api', 'User Data'],
description: 'Upload User data to the db',
cors: corsHeaders,
},
handler: async (request, h) => {
const { username, emailId, password } = request.payload
request.cookieAuth.set({ username })
return h.response('cookie created!')
}
}
now the 'post' route sets the cookie by request.cookieAuth.set({ username }),
so when i posted through postman application, it's setting the cookie in postman and the get route sends the data without any problem. But in browser, the cookie is'nt being set.
i'm using hapi-auth-cookie plugin and the registration is done like this -
await server.register(HapiAuthCookie)
server.auth.strategy('restricted', 'cookie',{
password: 'AudhASp342SID3acdh83CDASHciAS93rashdiva34a',
cookie: 'session',
isSecure: false,
ttl: 7 * 24 * 60 * 60 * 1000,
})
someone please help

How to detect redirect from external URI opened from Electron desktop application

I am building a react / electron desktop application with manual facebook login (https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#dialogresponse).
With the click of a button, I open using shell.openExternal method the login dialog, but I need to detect this redirect and then read the access token out of the URI. I don't know how to do that (react newbee here).
Which should be the best approach?
Thanks in advance.
The right answer is to follow this tutorial: https://competenepal.com/lets-make-a-facebook-login-system-in-electron-that-actually-works/
I only had to implement this part:
var options = {
client_id: '',
scopes: "public_profile",
redirect_uri: "https://www.facebook.com/connect/login_success.html"
};
var authWindow = new BrowserWindow({ width: 450, height: 300, show: false,
parent: mainWindow, modal: true, webPreferences: {nodeIntegration:false} });
var facebookAuthURL = "https://www.facebook.com/v2.8/dialog/oauth?client_id=" + options.client_id + "&redirect_uri=" + options.redirect_uri + "&response_type=token,granted_scopes&scope=" + options.scopes + "&display=popup";
authWindow.loadURL(facebookAuthURL);
authWindow.show();
authWindow.webContents.on('did-get-redirect-request', function (event, oldUrl, newUrl) {
var raw_code = /access_token=([^&]*)/.exec(newUrl) || null;
var access_token = (raw_code && raw_code.length > 1) ? raw_code[1] : null;
var error = /\?error=(.+)$/.exec(newUrl);
if(access_token) {
FB.setAccessToken(access_token);
FB.api('/me', { fields: ['id', 'name', 'picture.width(800).height(800)'] }, function (res) {
console.log('response is:', res);
});
authWindow.close();
}
});

ExtJS MessageBox does not block like alert(..) does

ExtJS MessageBox does not seem to block like Javascript alert(..) does. I want to show a popup, and then call and AJAX call, upon which it will close the window.
If I call the show method like this then...
//Alert Box :
var alertBox = Ext.create('Ext.window.MessageBox');
var config = {
title : 'Title',
closable: true,
msg: 'Message',
buttons: Ext.Msg.OK,
buttonText: { ok: EML.lang.buttons.ok },
modal: true
};
alertBox.show(config);
//callback
Ext.Ajax.request({
url: someURL,
method: 'POST',
callback: function (options, success, response) {
//do some stuff
self.up('window').destroy();
}
})
..no popup is shown, however the parent window is closes.
If I use a standard Javascript alert then the alert will block. After clicking the OK button, then the callback is executed after which the window closes.
//Alert Box :
alert('asdf')
//callback
Ext.Ajax.request({
url: someURL,
method: 'POST',
callback: function (options, success, response) {
//do some stuff
self.up('window').destroy();
}
})
why does MessageBox not block?
what can I do to get around this problem?
does the MessageBox somehow need to know about the parent window to block?
It does not block because blocks are not supported in custom javascript code. As chrome console tells us,
window.alert
function alert() { [native code] }
and native code can block execution.
In ExtJS, you would write a callback for a message box like this:
//Alert Box :
var alertBox = Ext.create('Ext.window.MessageBox');
var config = {
title : 'Title',
closable: true,
msg: 'Message',
buttons: Ext.Msg.OK,
buttonText: { ok: EML.lang.buttons.ok },
modal: true,
callback:function(btn) {
//callback
Ext.Ajax.request({
url: someURL,
method: 'POST',
callback: function (options, success, response) {
//do some stuff
self.up('window').destroy();
}
})
}
};
alertBox.show(config);
If such callbacks are deeply nested, I tend to flatten the callbacks like this:
var store = me.down('grid').getStore();
var callback3 = function(btn) {
if(btn=="yes") store.sync();
};
var callback2 = function() {
Ext.Msg.prompt('A','Third', callback3);
};
var callback1 = function() {
Ext.Msg.alert('A','Second', callback2);
};
Ext.Msg.alert('A','First', callback1);
In newer versions of ExtJS, you can check out Ext.Promise, but not in ExtJS 4.1.

Need captcha field in registration form using ExtJS

I am using ExtJS 4.2 and I am not able to get the captcha field in my registration form. Can
anybody suggest a solution?
I use google recpatcha. I'll paste my client side code below here. you'll need to do the server side yourself. you need to include the google recaptcha library and have a panel on your form like what is below. then, when you submit, the google values to up and need to be verified.
ExtJS:
{
xtype: 'panel',
border: false,
height: 150,
html: '<div id="recaptcha">Captcha Control From Google. This should be replaced by image by google</div>',
itemId: 'reCaptcha',
margin: '0 0 0 105'
}
JavaScript Submit Click Event
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Creating New Account..."});
myMask.show();
localValues.recaptchaChallengeField = Recaptcha.get_challenge();
localValues.recaptchaResponseField =Recaptcha.get_response();
Ext.Ajax.on('requestexception', function (conn, response, options) {
myMask.hide();
if (response.status != 200) {
var errorData = Ext.JSON.decode(response.responseText);
Ext.MessageBox.show({
title: 'Error Message',
msg: errorData.message,
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
Ext.Msg.alert('Creating User Failed',errorData.message);
}
});
Ext.Ajax.request({
url:'/rpc/Account/CreateUser',
actionMethods:'POST',
scope:this,
params: localValues,
success: function(r, o) {
myMask.hide();
var retData = Ext.JSON.decode(r.responseText);
} else {
tabPanel.setActiveTab(tabPanel.getTabIdByName('AttendeeAfterLoginConf'));
}
},
failure: function(r,o) {
myMask.hide();
// handled in exception now
//debugger;
//Ext.Msg.alert('Creating User Failed','');
}
});

Backbone.js: Dynamic model/collection url based on user input

I'm total new to Backbone so please pointing me the right way to do it. Here is what I have:
A Backbone login View with 3 inputs: serverIP, username, password. I am doing all the validation and send jquery ajax() request to my backend host based on the serverIP that the user has to enter earlier.
My backend is js PHP using Slim restful framework, check user, password like usual basic stuff.
On the callback of successful ajax() call, I want to set the urlRoot for latter use of all models and collections as I'm using Slim for all database interactions and this PHP file located on the server.
I tried to set it on the global app variable like this in app.js:
var app = {
api_url: '',
views: {},
models: {},
routers: {},
utils: {},
adapters: {}
};
In the callback of login view I set:
app.api_url = "http://"+serverIP;
And try to use app.api_url in backbone model url but it's apparently undefined.
May be this is not the correct approach I'm trying and I messed up with the variable scope? Then how can I set model.url from the view? Please, any suggestions are much appreciated.
Thanks,
Hungnd
EDIT: Ok, I will try to elaborate my problem again:
Here is the login function in my LoginView.js, basically it take user inputs and send to my model to interact with the server, if success navigate to home view:
var user = new app.models.Login();
var userDetails = {
serverIP: $('#serverIP').val(),
username: $('#username').val(),
password: $('#password').val()
};
user.save(userDetails, {
success: function(data) {
/* update the view now */
if(data.error) { // If there is an error, show the error messages
}
else { // If not, send them back to the home page
app.router = new app.routers.AppRouter();
app.router.navigate('home',true);
}
},
error: function() {
/* handle the error code here */
}
Here is my LoginModel.js, get the serverIP from user input on login form and send to the server to process
app.models.Login = Backbone.Model.extend({
urlRoot: function(){
var serverIP = this.get('serverIP');
return "http://"+serverIP+"/api/login";
},
defaults: {
'serverIP': '',
'username': '',
'password': '',
}
});
Now, after successful login, navigate to HomeView.js, on initialize it calls to EmployeeCollection, so far so good
initialize: function () {
//Search result
this.searchResults = new app.models.EmployeeCollection();
this.searchResults.fetch({data: {name: ''}});
this.searchresultsView = new app.views.EmployeeListView({model: this.searchResults});
}
Here is my EmployeeModel.js where I have the problem, I dont know how to access the serverIP variable.
app.models.Employee = Backbone.Model.extend({
urlRoot:"api/employees",
//urlRoot: app.api_url+"/api/employees",
initialize:function () {
this.reports = new app.models.EmployeeCollection();
this.reports.url = app.api_url+'/api/employees/' + this.id + '/reports';
}
});
app.models.EmployeeCollection = Backbone.Collection.extend({
model: app.models.Employee,
//url: "api/employees",
url: function() {
//How to get serverIP?
},
});
All models in backbone already have an url property which will be used to fetch data. In your case you could define it as a function to generate url dynamically.
Here is an example :
//we are inside the definition of the loginModel
data: {
serverIP : null,
username : null,
password : null
},
url: function() {
var url = "rootUrl",
data = this.get("data");
return function() {
return url + '?' + $.param(data);
};
}
url is then defined as a closure, and object being references in javascript, the url generated will use the current values in the data object.

Resources