Login page in Ajax popup box on home page load Magento - magento-1.5

How can we display login page in Ajax popup box on homepage load in Magento that to popup box need to come only one time until browser is closed and i also need to place FB connect to same popup box .can any reply me soon please

Hi you can use any lightbox plugin to display the code, and to show login in popup you can override the customer AccountController.php like this
protected $_validActions = array('create','login','logoutSuccess','forgotpassword','forgotpasswordpost','confirm','confirmation','resetpassword','resetpasswordpost');
protected $_customActions = array('signupformpopup','ajaxLogin','ajaxCreate');
public function preDispatch()
{
// a brute-force protection here would be nice
$action = $this->getRequest()->getActionName();
if (preg_match('/^('.$this->_getCustomActions().')/i', $action))
{
$this->getRequest()->setActionName($this->_validActions[1]);
}
parent::preDispatch();
if ($action != $this->getRequest()->getActionName())
{
$this->getRequest()->setActionName($action);
}
if (!$this->getRequest()->isDispatched()) {
return;
}
if (!preg_match('/^('.$this->_getValidActions().')/i', $action)) {
if (!$this->_getSession()->authenticate($this)) {
$this->setFlag('', 'no-dispatch', true);
}
} else {
$this->_getSession()->setNoReferer(true);
}
}
protected function _getValidActions()
{
return implode("|", array_merge($this->_validActions, $this->_customActions));
}
protected function _getCustomActions()
{
return implode("|", $this->_customActions);
}
/**
* Login post action
*/
public function ajaxLoginAction() {
if ($this->_getSession()->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session = $this->_getSession();
$result=array();
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$session->login($login['username'], $login['password']);
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
$result['success'] = true;
$result['redirecturl'] = Mage::getUrl('customer/account/edit');
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
/*$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', Mage::helper('customer')->getEmailConfirmationUrl($login['username']));*/
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('This account is not confirmed.');
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
break;
default:
$message = $e->getMessage();
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__($message);
}
//$session->addError($message);
$session->setUsername($login['username']);
} catch (Exception $e) {
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError($this->__('Login and password are required.'));
$result['success'] = false;
$result['message'] = Mage::helper('customer')->__('Login and password are required.');
}
}
$this->getResponse()->setBody(Zend_Json::encode($result));
//$this->_loginPostRedirect();
}
/**
* Login post action
*/
public function ajaxCreateAction()
{
$session = $this->_getSession();
if ($session->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session->setEscapeMessages(true); // prevent XSS injection in user input
if ($this->getRequest()->isPost()) {
$errors = array();
if (!$customer = Mage::registry('current_customer')) {
$customer = Mage::getModel('customer/customer')->setId(null);
}
/* #var $customerForm Mage_Customer_Model_Form */
$customerForm = Mage::getModel('customer/form');
$customerForm->setFormCode('customer_account_create')
->setEntity($customer);
$customerData = $customerForm->extractData($this->getRequest());
if ($this->getRequest()->getParam('is_subscribed', false)) {
$customer->setIsSubscribed(1);
}
/**
* Initialize customer group id
*/
$customer->getGroupId();
if ($this->getRequest()->getPost('create_address')) {
/* #var $address Mage_Customer_Model_Address */
$address = Mage::getModel('customer/address');
/* #var $addressForm Mage_Customer_Model_Form */
$addressForm = Mage::getModel('customer/form');
$addressForm->setFormCode('customer_register_address')
->setEntity($address);
$addressData = $addressForm->extractData($this->getRequest(), 'address', false);
$addressErrors = $addressForm->validateData($addressData);
if ($addressErrors === true) {
$address->setId(null)
->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
$addressForm->compactData($addressData);
$customer->addAddress($address);
$addressErrors = $address->validate();
if (is_array($addressErrors)) {
$errors = array_merge($errors, $addressErrors);
}
} else {
$errors = array_merge($errors, $addressErrors);
}
}
try {
$customerErrors = $customerForm->validateData($customerData);
if ($customerErrors !== true) {
$errors = array_merge($customerErrors, $errors);
} else {
$customerForm->compactData($customerData);
$customer->setPassword($this->getRequest()->getPost('password'));
$customer->setConfirmation($this->getRequest()->getPost('confirmation'));
$customerErrors = $customer->validate();
if (is_array($customerErrors)) {
$errors = array_merge($customerErrors, $errors);
}
}
$validationResult = count($errors) == 0;
$result = array();
if (true === $validationResult) {
$customer->save();
if ($customer->isConfirmationRequired()) {
$customer->sendNewAccountEmail('confirmation', $session->getBeforeAuthUrl());
// $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail())));
//$this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
//return;
$result['success'] = true;
$result['message'] = $this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail()));
} else {
$session->setCustomerAsLoggedIn($customer);
$url = $this->_welcomeCustomer($customer);
//$this->_redirectSuccess($url);
//return;
$result['success'] = true;
$result['message'] = $this->__('You are successfully registered');
}
} else {
$session->setCustomerFormData($this->getRequest()->getPost());
if (is_array($errors)) {
$result['success'] = false;
foreach ($errors as $errorMessage) {
//$session->addError($errorMessage);
$result['message'] .= $errorMessage;
}
} else {
//$session->addError($this->__('Invalid customer data'));
$result['success'] = false;
$result['message'] = $this->__('Invalid customer data');
}
}
} catch (Mage_Core_Exception $e) {
$session->setCustomerFormData($this->getRequest()->getPost());
if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
$url = Mage::getUrl('customer/account/forgotpassword');
$result['success'] = false;
$result['message'] = $this->__('There is already an account with this email address. If you are sure that it is your email address.');
} else {
$result['success'] = false;
$result['message'] = $e->getMessage();
}
//$session->addError($message);
} catch (Exception $e) {
// $session->setCustomerFormData($this->getRequest()->getPost())
// ->addException($e, $this->__('Cannot save the customer.'));
$result['success'] = false;
$result['message'] = $this->__('Cannot save the customer.');
}
}
//$this->_redirectError(Mage::getUrl('*/*/create', array('_secure' => true)));
$this->getResponse()->setBody(Zend_Json::encode($result));
}
}

Related

i want to pass header in login API using unity web request

public class Login : MonoBehaviour
{
[SerializeField] private string authenticationEndpoint = "http://146.190.226.27/api/login";
[SerializeField] private TMP_InputField usernameInputField;
[SerializeField] private TMP_InputField passwordInputField;
[SerializeField] private TextMeshProUGUI alertText;
[SerializeField] private Button loginButton;
public void OnLoginClick()
{
alertText.text = "Signing In...";
loginButton.interactable = false;
StartCoroutine(TryLogin());
}
private IEnumerator TryLogin()
{
string email = usernameInputField.text;
string password = passwordInputField.text;
if(email.Length < 15 || email.Length > 24)
{
alertText.text = "Invalid Username";
loginButton.interactable = true;
yield break;
}
if(password.Length < 3 || password.Length > 24)
{
alertText.text = "Invalid Password";
loginButton.interactable = true;
yield break;
}
else
{
alertText.text = "Locale is Required";
//Debug.Log("Locale is Required");
loginButton.interactable = true;
}
WWWForm form = new WWWForm();
form.AddField("email", email);
form.AddField("password", password);
UnityWebRequest request = UnityWebRequest.Post(authenticationEndpoint,form);
var handler = request.SendWebRequest();
float startTime = 0.0f;
while (!handler.isDone)
{
startTime += Time.deltaTime;
if(startTime > 10.0f)
{
break;
}
yield return null;
}
if(request.result == UnityWebRequest.Result.Success)
{
if (request.downloadHandler.text != "Invalid Credentials")
{
alertText.text = "Welcome";
loginButton.interactable = false;
}
else
{
alertText.text = "Invalid Credentials";
loginButton.interactable = true;
}
}
//Debug.Log($"{username}:{password}");
yield return null;
}
}
here is my code i have no idea how to call header or pass in unity here is API in json format
{
"msg": "Locale is required",
"data": {}
}

Can't send data to database when update data flutter

I'm a new Flutter user, here I want to explain my problem, I have a problem when I want to update data, the data can't be entered into the database, there is an error when I send data to the database.
Is there something wrong with my logic code on flutter ? Here's my source snippet
API.DART
updateData(apiURL, id, body ) async {
var fullUrl = _url + apiURL + '/' + id.toString();
await _getToken();
return await http.put(
fullUrl,
headers: _setHeaders(),
body: json.encode(body),
);
}
Nasabah_service.dart
static Future<List<Nasabah>> updateUser(id) async {
Map<String, String> data;
final response = await Network().updateData(baseUrl, id, data,);
List<Nasabah> list = parseResponse(response.body);
return list;
}
Here's the update function on the formfield
void _update() async {
setState(() {
_isLoading = true;
});
var data = {
"nama_debitur" : _nama_debiturController.text,
"alamat" : _alamatController.text,
"no_telp" : _no_telpController.text,
"no_ktp" : _no_ktpController.text,
"no_selular" : _no_selularController.text
};
print(data);
var res = await Network().updateData(NasabahService.baseUrl, 'mstdebitur' , data);
var body = json.decode(res.body);
if (res.statusCode == 200) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('mstdebitur', json.encode(body['mstdebitur']));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Berhasil Disimpan'),
duration: Duration(seconds: 2),
));
} else {
// if (body['message']['nama_debitur'] != null) {
// _showMsg(body['message']['nama_debitur'][0].toString());
// } else if (body['message']['alamat'] != null) {
// _showMsg(body['message']['alamat'][0].toString());
// } else if (body['message']['no_telp'] != null) {
// _showMsg(body['message']['no_telp'][0].toString());
// }
// else if (body['message']['no_ktp'] != null) {
// _showMsg(body['message']['no_ktp'][0].toString());
// }
// else if (body['message']['no_selular'] != null) {
// _showMsg(body['message']['no_selular'][0].toString());
// }
// ScaffoldMessenger.of(context)
// .showSnackBar(new SnackBar(content: Text("Gagal")));
}
setState(() {
_isLoading = false;
});
}
}

Session null jsf getExternalContext()

I generate a session in my code but then when using it in another file the session returns null, thx all!
this linux server primefaces,payara 5
public Usuarios loginUsuario(String usuario, String password) {
Usuarios user = null;
try {
UsuariosDAO us = new UsuariosDAO();
user = us.loginUsuario(usuario, password);
if (user != null) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuario", user); // here set user ok! not null
FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
} else {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion!", "User o Password Inconrrectos"));
}
} catch (Exception e) {
System.out.println(e);
}
return user;
}
public void probarSession() {
try {
FacesContext esta = FacesContext.getCurrentInstance();
System.err.println(esta.getExternalContext().getSessionMap().get("usuario")+"this is null!!!");
Usuarios us = (Usuarios) esta.getExternalContext().getSessionMap().get("usuario");
if (us == null) {
esta.getExternalContext().redirect("login.xhtml");
}
} catch (IOException e) {
System.err.println(e);
}
}

Unauthorized exception with SPSecurity.RunWithElevatedPrivileges?

I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}

How to Set User login Windows Phone 8 using sqlite database?

Hi i am using windows phone 8 app. i want to set existing user login, i can add user registration but i can't do user login my code is give below.
public partial class LoginPage : PhoneApplicationPage
{
public LoginPage()
{
InitializeComponent();
}
public static class dal
{
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Bestin.sqlite");
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Bestin.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
}
if (isDatabaseExisting)
{
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Bestin.sqlite"), true);
}
}
}
private void Click_Login(object sender, RoutedEventArgs e)
{
dal.ConnectToDB();
var query = dal.connection.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if (query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
}
I am using your code.I got error The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
ok so do this ....
public static class dal
{
public static SQLiteAsyncConnection connection;
public static bool isDatabaseExisting;
public static async void ConnectToDB()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Bestin.sqlite");
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
try
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Bestin.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
isDatabaseExisting = true;
}
catch (Exception ex)
{
isDatabaseExisting = false;
}
}
if (isDatabaseExisting)
{
connection = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Bestin.sqlite"), true);
}
}
}
make a class like above code for your database connection and call this at your application startup like this dal.ConnectToDB();
then in your loginpage do like this...
private void Click_Login(object sender, RoutedEventArgs e)
{
var query = dal.connection.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if(query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
you can try this ..
private void Click_Login(object sender, RoutedEventArgs e)
{
dbConn = new SQLiteConnection(DB_PATH);
var query = dbconn.QueryAsync<Task>("SELECT * FROM Task Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Password + "\'").Result;
if(query == null)
{
// invalid Login credentials
}
else
{
// do login
}
}
Hi i got solution in my question..,
using (var dbConn = new SQLiteConnection(DB_PATH))
{
var existing = dbConn.Query<Userlist>("select * from Userlist Where Email=" + "\'" + txtEmailaddress.Text + "\'" + "and Password=" + "\'" + txtPassword.Text + "\'").FirstOrDefault();
if (existing != null)
{
NavigationService.Navigate(new Uri("/Input.xaml?selectedItem=", UriKind.Relative));
}
else
{
MessageBox.Show("invalid login");
}
}

Resources