I have created an extension to creating md5 password and sync the email and md5 password with our 3rd party db to use in other tool. on the Resignation page works perfect but we have problem on the checkout Resignation, it is not getting the password and has no possibility to sync and save that in the db. here is the code:
in app/code/local/SyncUsers/config.xml
in the events global:
<customer_save_before>
<observers>
<md5password>
<class>membership/observer</class>
<method>storeMD5Password</method>
</md5password>
</observers>
</customer_save_before>
in app/code/local/SyncUsers/membership/Observer.php
public $_singletonFlag = false;
public function storeMD5Password($observer)
{
// Prevent the save_handler to call itself and end-up with infinite loops.
if($this->singletonFlag) {
return;
}
$this->singletonFlag = true;
$event = $observer->getEvent();
$customer = $event->getCustomer();
if ($customer instanceof Mage_Customer_Model_Customer) {
if ($new_password = Mage::app()->getRequest()->getPost('password', false) && strlen($new_password) > 0) {
$customer->setData('md5_password', md5($new_password));
$customer->save();
}
}
}
in the onpage checkout it is not passing the password and not convert them to md5!
Related
I've made an application with Blazor WebAssembly with a 5min timer in a BackgroundService into my SERVER.
Now, everytime a second change I would like to notify my client to update the timer on the CLIENT page. (it's a Component)
I was wondering if there was a solution to call a CLIENT C# Method from my SERVER by using a SERVICE between this two ?
Do you have any suggestion ?
I've already created the shared SERVICE but I don't know how I can call my CLIENT C# method from my Service automatically.
ps : I've already trying to pass my values from my SERVER to a SERVICE who call a JAVASCRIPT function (with IJSRuntime) who will call my C# function to update the timer. But actually my Js function seems to not working.
[My Background Task]
`
// A 5min timer who create a Draw every 5min and update it when count is at 0
public async Task ClockCountDownAsync()
{
if (secTime == 0 && minTime != 0)
{
if (minTime == 5)
{
Draw newDraw = new Draw();
_unitOfWork.Draws.Add(newDraw);
await _unitOfWork.Complete();
}
minTime = minTime - 1;
secTime = 59;
}
else if (secTime != 0)
{
secTime = secTime - 1;
}
else if(minTime == 0 && secTime == 0)
{
await DrawAndAddNumbers();
minTime = 5;
secTime = 0;
}
int[] timeTab = new int[] { minTime, secTime };
_timerService.GetTimeFromCounter(timeTab);
}
`
[My Client Function]
`
public async Task UpdateTimer(int[] timeTab)
{
minTime = timeTab[0];
secTime = timeTab[1];
await InvokeAsync(StateHasChanged);
}
`
[The function in a Service shared who is called by the SERVER who need to call the function from my CLIENT]
`
public void GetTimeFromCounter(int[] timeTab)
{
// UpdateTimer(timeTab);
}
`
I have been attempting to implement an OpenID log-in with Yii2 today, and for the most part it has worked. Below is code from my controller, with the action 'Register' running through, and outputting the user->identity->username, but when I, say, redirect this action back to any page on the site, the logged in user is essentially forgotten. I can return to my Register action and have the user logged in.
Help would be appreciated. Thank you.
public function actionRegister()
{
require ('../views/site/steamauth/userInfo.php');
$localId = $_SESSION['steam_steamid'];
$foundUser = User::findOne(['steamid' => $localId]);
if(isset($foundUser))
{
Yii::$app->user->login($foundUser);
var_dump($foundUser);
echo Yii::$app->user->identity->username;
} elseif(!isset($foundUser)) {
$db = new User();
$db->steamid = $_SESSION['steam_steamid'];
$db->username = $_SESSION['steam_personaname'];
$db->visstate = $_SESSION['steam_communityvisibilitystate'];
$db->profile = $_SESSION['steam_profileurl'];
$db->avs = $_SESSION['steam_avatar'];
$db->avm = $_SESSION['steam_avatarmedium'];
$db->avf = $_SESSION['steam_avatarfull'];
$db->persstate = $_SESSION['steam_personastate'];
$db->save();
$foundUser = User::findOne(['steamid' => $localId]);
Yii::$app->user->login($foundUser);
return $this->goHome();
}
}
/**
Ah. After scouring Stackoverflow I found it.
The standard model function findIdentity
return isset(self::$usrs[$id]) ? new static(self::$usrs[$id]) : null;
must be change to reflect the new table of
return User::findOne($id);
What I'm pretending to do is to include the LDAP for internal users in a Guard Authentication System configured by ddbb.
I already have build my Guard Authentication System and works really nice thanks to https://knpuniversity.com/screencast/symfony-security.
But I need also to try to log in previously via LDAP mode. More precisely, the functionality must be like this:
The user try to log in on the Guard System Authentication configured with a database from MySQL and:
1- Check if exist the user in the table User from MySQL. If exist, we go to step 2. If not exist return false to the authentication with the error message.
2-Check if the user exist in the LDAP mode. If exist go to the step 3. If not exist go to the step 4.
3-Try to log in via LDAP with the username and password. If the authentication is ok, it's logged in. If can't match the password via LDAP, return false to the authentication with the error message.
4-After checking the LDAP option, we will just try to log in via Guard Authentication System. If the authentication it's ok, the user is logged in. If can't match the password via Guard with the MySQL users table, return false to the authentication with the error message.
In the LoginFormAuthenticator file I finally could manage this behavior I want as shows the next code.
<?php
namespace AppBundle\Security;
use ...
use Zend\Ldap\Ldap;
use Zend\Ldap\Exception\LdapException;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
use TargetPathTrait;
private $em;
private $router;
private $passwordEncoder;
private $csrfTokenManager;
public function __construct(...
}
public function getCredentials(Request $request)
{
...
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
$ldapPassword = $credentials['password'];
$ldaphost = 'ldap.example.com'; // your ldap servers
$baseDn = 'dc=example,dc=es';
$options = [
'host' => $ldaphost,
'username' => $username,
'password' => $ldapPassword,
'bindRequiresDn' => false,
'accountDomainName' => 'example.es',
'baseDn' => $baseDn,
];
$userInterface = $this->em->getRepository('AppBundle:User')
->findOneBy(['email' => $username]);
$ldap = new Ldap($options);
try {
$ldap->bind();
$userInterface->setIsAuthenticationLDAP(true);
} catch (LdapException $zle){
$userInterface->setIsAuthenticationLDAP(false);
}
return $userInterface;
}
public function checkCredentials($credentials, UserInterface $user)
{
$password = $credentials['password'];
if($user->isAuthenticationLDAP()){
$user->setLoginAttempts(0);
$this->em->persist($user);
$this->em->flush();
return true;
} else {
if($this->passwordEncoder->isPasswordValid($user, $password)) {
$user->setLoginAttempts(0);
$this->em->persist($user);
$this->em->flush();
return true;
} else {
if($user->getLoginAttempts() == '0') $user->setFirstLoginAttempt(new \DateTime('now'));
$user->setLoginAttempts($user->getLoginAttempts() + 1);
if($user->getLoginAttempts() >= 5) {
$user->setLockedDateTime(new \DateTime('now'));
$user->setLoginAttempts(0);
}
$this->em->persist($user);
$this->em->flush();
}
}
return false;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
....
}
protected function getLoginUrl()
{
return $this->router->generate('fos_user_security_login');
}
}
I hope anyone can enjoy this answer.
Ok I am having real difficulty solving this. I'm trying to connect to a mysql database from a zend application and i receive the following error:
Message: No database adapter present
I have checked and double checked the connection credentials and they should be fine. The code should be fine too as it works ok in the development environment. If I deliberately change the password to be incorrect in the development environment, I get exactly the same error, which leads me to believe that maybe this is the case, despite my checking!
Any thoughts would be very welcome. If there's nothing obviously wrong here then maybe I need to look at the server/db/php settings?
Thanks!
Bootstrap code:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initPlaceholders(){
Zend_Session::start();
$this->bootstrap('View');
$view = $this->getResource('View');
$view->doctype('XHTML1_STRICT');
// Set the initial stylesheet:
$view->headLink()->appendStylesheet('/css/global.css');
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('Pog_');
Zend_Controller_Action_HelperBroker::addPath(
APPLICATION_PATH . '/controllers/helpers',
'Application_Controller_Action_Helper_');
}
}
Config file:
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.view.helperPath.View_Helper = APPLICATION_PATH "/views/helpers"
database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user
database.params.password = password
database.params.dbname = test
DB connection helper:
/**
* Constructor: initialize plugin loader
*
* #return void
*/
public function __construct()
{
try{
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
$dbAdapter = Zend_Db::factory($config->database);
$dbAdapter->getConnection();
$this->connection = $dbAdapter;
} catch (Zend_Db_Adapter_Exception $e) {
echo 'perhaps a failed login credential, or perhaps the RDBMS is not running';
} catch (Zend_Exception $e) {
echo 'perhaps factory() failed to load the specified Adapter class';
}
}
public function getDbConnection(){
return $this->connection;
}
}
Index:
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
->run();
Define your database as a resource
resources.db.adapter = pdo_mysql
resources.db.params.host = localhost
resources.db.params.username = user
resources.db.params.password = password
resources.db.params.dbname = test
In your main files you then need to do nothing but initiate a query without having to worry about assigning the database fvrom your config - its done in the inside, the DB resource is always chosen as the default adapter for your database transactions
I tried posting this on the Exchange Development forum and didnt get any replies, so I will try here. Link to forum
I have a windows services that fires every fifteen minutes to see if there is any subscriptions that need to be created or updated. I am using the Managed API v1.1 against Exchange 2007 SP1. I have a table that stores all the users that want there mailbox monitored. So that when a notifcation comes in to the "Listening Service" I am able to look up the user and access the message to log it into the application we are building. In the table I have the following columns that store the subscription information:
SubscriptionId - VARCHAR(MAX)
Watermark - VARCHAR(MAX)
LastStatusUpdate - DATETIME
My services calls a function that queries the data needed (based on which function it is doing). If the user doesn't have a subscription already the service will go and create one. I am using impersonation to access the mailboxes. Here is my "ActiveSubscription" method that is fired when a user needs the subscription either created or updated.
private void ActivateSubscription(User user)
{
if (user.ADGUID.HasValue)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Settings.ActiveDirectoryServerName, Settings.ActiveDirectoryRootContainer);
using (UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.Guid, user.ADGUID.Value.ToString()))
{
ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SID, up.Sid.Value);
}
}
else
{
ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user.EmailAddress);
}
PushSubscription pushSubscription = ewService.SubscribeToPushNotifications(
new FolderId[] { WellKnownFolderName.Inbox, WellKnownFolderName.SentItems },
Settings.ListenerService, 30, user.Watermark,
EventType.NewMail, EventType.Created);
user.Watermark = pushSubscription.Watermark;
user.SubscriptionID = pushSubscription.Id;
user.SubscriptionStatusDateTime = DateTime.Now.ToLocalTime();
_users.Update(user);
}
We have also ran the following cmdlet to give the user we are accessing the EWS with the ability to impersonate on the Exchange Server.
Get-ExchangeServer | where {$_.IsClientAccessServer -eq $TRUE} | ForEach-Object {Add-ADPermission -Identity $_.distinguishedname -User (Get-User -Identity mailmonitor | select-object).identity -extendedRight ms-Exch-EPI-Impersonation}
The "ActivateSubscription" code above works as expected. Or so I thought. When I was testing it I had it monitoring my mailbox and it worked great. The only problem I had to work around was that the subscription was firing twice when the item was a new mail in the inbox, I got a notification for the NewMail event and Created event. I implemented a work around that checks to make sure the message hasn't already been logged on my Listening service. It all worked great.
Today, we started testing two mailboxes being monitor at the same time. The two mailboxes were mine and another developers mailbox. We found the strangest behavior. My subscription worked as expected. But his didn't, the incoming part of his subscription work properly but any email he sent out the listening service never was sent a notification. Looking at the mailbox properties on Exchange I don't see any difference between his mailbox and mine. We even compared options/settings in Outlook. I can see no reasons why it works on my mailbox and not on his.
Is there something that I am missing when creating the subscription. I didn't think there was since my subscription works as expected.
My listening service code works perfectly well. I have placed the code below incase someone wants to see it to make sure it is not the issue.
Thanks in advance, Terry
Listening Service Code:
/// <summary>
/// Summary description for PushNotificationClient
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class PushNotificationClient : System.Web.Services.WebService, INotificationServiceBinding
{
ExchangeService ewService = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
public PushNotificationClient()
{
//todo: init the service.
SetupExchangeWebService();
}
private void SetupExchangeWebService()
{
ewService.Credentials = Settings.ServiceCreds;
try
{
ewService.AutodiscoverUrl(Settings.AutoDiscoverThisEmailAddress);
}
catch (AutodiscoverRemoteException e)
{
//log auto discovery failed
ewService.Url = Settings.ExchangeService;
}
}
public SendNotificationResultType SendNotification(SendNotificationResponseType SendNotification1)
{
using (var _users = new ExchangeUser(Settings.SqlConnectionString))
{
var result = new SendNotificationResultType();
var responseMessages = SendNotification1.ResponseMessages.Items;
foreach (var responseMessage in responseMessages)
{
if (responseMessage.ResponseCode != ResponseCodeType.NoError)
{
//log error and unsubscribe.
result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
return result;
}
var sendNoficationResponse = responseMessage as SendNotificationResponseMessageType;
if (sendNoficationResponse == null)
{
result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
return result;
}
var notificationType = sendNoficationResponse.Notification;
var subscriptionId = notificationType.SubscriptionId;
var previousWatermark = notificationType.PreviousWatermark;
User user = _users.GetById(subscriptionId);
if (user != null)
{
if (user.MonitorEmailYN == true)
{
BaseNotificationEventType[] baseNotifications = notificationType.Items;
for (int i = 0; i < notificationType.Items.Length; i++)
{
if (baseNotifications[i] is BaseObjectChangedEventType)
{
var bocet = baseNotifications[i] as BaseObjectChangedEventType;
AccessCreateDeleteNewMailEvent(bocet, ref user);
}
}
_PreviousItemId = null;
}
else
{
user.SubscriptionID = String.Empty;
user.SubscriptionStatusDateTime = null;
user.Watermark = String.Empty;
_users.Update(user);
result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
return result;
}
user.SubscriptionStatusDateTime = DateTime.Now.ToLocalTime();
_users.Update(user);
}
else
{
result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
return result;
}
}
result.SubscriptionStatus = SubscriptionStatusType.OK;
return result;
}
}
private string _PreviousItemId;
private void AccessCreateDeleteNewMailEvent(BaseObjectChangedEventType bocet, ref User user)
{
var watermark = bocet.Watermark;
var timestamp = bocet.TimeStamp.ToLocalTime();
var parentFolderId = bocet.ParentFolderId;
if (bocet.Item is ItemIdType)
{
var itemId = bocet.Item as ItemIdType;
if (itemId != null)
{
if (string.IsNullOrEmpty(_PreviousItemId) || (!string.IsNullOrEmpty(_PreviousItemId) && _PreviousItemId != itemId.Id))
{
ProcessItem(itemId, ref user);
_PreviousItemId = itemId.Id;
}
}
}
user.SubscriptionStatusDateTime = timestamp;
user.Watermark = watermark;
using (var _users = new ExchangeUser(Settings.SqlConnectionString))
{
_users.Update(user);
}
}
private void ProcessItem(ItemIdType itemId, ref User user)
{
try
{
ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user.EmailAddress);
EmailMessage email = EmailMessage.Bind(ewService, itemId.Id);
using (var _entity = new SalesAssistantEntityDataContext(Settings.SqlConnectionString))
{
var direction = EmailDirection.Incoming;
if (email.From.Address == user.EmailAddress)
{
direction = EmailDirection.Outgoing;
}
int? bodyType = (int)email.Body.BodyType;
var _HtmlToRtf = new HtmlToRtf();
var message = _HtmlToRtf.ConvertHtmlToText(email.Body.Text);
bool? IsIncoming = Convert.ToBoolean((int)direction);
if (IsIncoming.HasValue && IsIncoming.Value == false)
{
foreach (var emailTo in email.ToRecipients)
{
_entity.InsertMailMessage(email.From.Address, emailTo.Address, email.Subject, message, bodyType, IsIncoming);
}
}
else
{
if (email.ReceivedBy != null)
{
_entity.InsertMailMessage(email.From.Address, email.ReceivedBy.Address, email.Subject, message, bodyType, IsIncoming);
}
else
{
var emailToFind = user.EmailAddress;
if (email.ToRecipients.Any(x => x.Address == emailToFind))
{
_entity.InsertMailMessage(email.From.Address, emailToFind, email.Subject, message, bodyType, IsIncoming);
}
}
}
}
}
catch(Exception e)
{
//Log exception
using (var errorHandler = new ErrorHandler(Settings.SqlConnectionString))
{
errorHandler.LogException(e, user.UserID, user.SubscriptionID, user.Watermark, user.SubscriptionStatusDateTime);
}
throw e;
}
}
}
I have two answers for you.
At first you will have to create one instance of ExchangeService per user. Like I understand your Code you just create one instance and switch the impersonation, which is not supported. I developed a windowsservice which is pretty similar to yours. Mine is synchronising the mails between our CRM and Exchange. So at startup I create an instance per user and Cache it as long as the application runs.
Now about cache-mode. The diffrence between using cache-mode and not is just a timing gab. In cache-mode Outlook synchronizes from time to time. And non cached it's in time. When you use the cache-mode and want the Events immediatly on your Exchange-Server you can press the "send and receive"-button in Outlook to force the sync.
Hope that helps you...