How to set expiration of newsletter confirmation link in magento 2 - magento2

I have newsletter in my magento website. I have enable confirmation before subscription from admin configuration. User are getting confirmation link in mail.
But I want to set expiry of that link. Is magento provide default config ?
How can I set expiry of that link ?

I found the solution. I just did two things.
1) Add created_at field in newsletter_subscriber table.
2) Overwrite the following file
vendor/magento/module-newsletter/Model/Subscriber.php
to
Company/name/Model/Subscriber.php
Overited Subscriber.php file code
public function confirm($code) // existing function
{
$id = $this->getId();
if ($this->validateConfirmLinkToken($id, $code)) {
if ($this->getCode() == $code) {
$this->setStatus(self::STATUS_SUBSCRIBED)
->setStatusChanged(true)
->save();
$this->sendConfirmationSuccessEmail();
return true;
}
return false;
}
}
private function validateConfirmLinkToken($customerId, $code) //check validation for token
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$messageManager = $objectManager->get('Magento\Framework\Message\ManagerInterface');
if (empty($customerId) || $customerId < 0) {
$this->_messageManager->addError('Sorry you have not rigts to access this page');
return false;
}
if (!is_string($code) || empty($code)) {
$params = ['fieldName' => 'code'];
//$messageManager->addError('Sorry Your subscription confirmation code is not valid.');
return false;
}
$dcode = $this->getCode();
$dcreated_at = $this->getCreatedAt();
if (trim($dcode) != trim($code)) {
//$messageManager->addError('Sorry Your subscription confirmation code is mismatch.');
return false;
} elseif ($this->isConfirmationLinkTokenExpired($dcode, $dcreated_at)) {
//$messageManager->addError('Sorry Your subscription confirmation code is expired.');
return false;
}
return true;
}
public function isConfirmationLinkTokenExpired($dcode, $dcreated_at) // check expiration token
{
if (empty($dcode) || empty($dcreated_at)) {
return true;
}
$expirationPeriod = '720';
$currentTimestamp = (new \DateTime())->getTimestamp();
$tokenTimestamp = (new \DateTime($dcreated_at))->getTimestamp();
if ($tokenTimestamp > $currentTimestamp) {
return true;
}
$hourDifference = floor(($currentTimestamp - $tokenTimestamp) / (60 * 60));
if ($hourDifference >= $expirationPeriod) {
return true;
}
return false;
}
Hope it will helps to many.
Thanks.

Related

Discourse plugin to restrict users from mentioning each other is failing

I have inherited a plugin used to restrict #mentions in discourse. Users are restricted to specific categories and are unable to view blocked categories, but when using the #mention in a topic the users in the restricted categories are showing up.
So user A works at company 1 and has access to the category associated to company 1. User B has access to the company 2 category. When user A #mentions someone on the company 1 category the autocomplete is displaying the users associated with the company 2 category.
I'm receiving no errors and the plugin supposedly worked before my arrival.
import { withPluginApi } from "discourse/lib/plugin-api";
import discourseComputed from "discourse-common/utils/decorators";
import userSearch from "discourse/lib/user-search";
function initWithApi(api) {
if (!Discourse.SiteSettings.restrict_mentions_enabled) return;
api.modifyClass("component:groups-form-interaction-fields", {
pluginId: 'groups-form-interaction-fields-plugin',
#discourseComputed(
"siteSettings.restrict_mentions_enabled",
"currentUser.admin",
"model.c_all_groups",
"model.name"
)
isShowRestrictMentions(enabled, admin, allGroups, name) {
return enabled && admin && allGroups && name && allGroups.includes(name);
},
#discourseComputed("model.c_all_groups", "model.name")
cSelectableGroups(allGroups, name) {
return (allGroups || []).filter(g => g !== name);
},
actions: {
setCAllowedMentionGroups(val) {
console.log(val);
let newVal;
if (val.includes("any")) {
newVal = "any";
} else {
newVal = val.filter(x => !Ember.isBlank(x)).join("|");
}
console.log(newVal)
this.model.set("c_allowed_mention_groups", newVal);
}
}
});
api.modifyClass("model:group", {
pluginId: 'group-plugin',
asJSON() {
const attrs = this._super(...arguments);
attrs["c_allowed_mention_groups"] = this.c_allowed_mention_groups;
return attrs;
},
#discourseComputed("c_allowed_mention_groups")
cAllowedMentionGroups(groups) {
return (groups || "").split("|");
}
});
api.modifyClass("component:composer-editor", {
pluginId: 'composer-editor-plugin',
userSearchTerm(term) {
if (!this.siteSettings.restrict_mentions_enabled) {
return this._super(...arguments);
}
let viewGroups = true;
const allowed =
this.get("topic.c_allowed_mention_groups") ||
this.currentUser.get("c_allowed_mention_groups");
console.log([this, allowed]);
if (Ember.isBlank(allowed)) {
return;
}
//REMOVING CUSTOMER GROUP FROM SEARCHABLE ARRAY OF STANDARD USERS
if(!this.currentUser.admin && !this.currentUser.moderator){
viewGroups = false;
const index = allowed.indexOf('All_Customers');
if (index > -1) {
allowed.splice(index, 1);
}
console.log(allowed)
}
const opts = {
term,
includeGroups: viewGroups,
groupMembersOf: allowed
};
return userSearch(opts);
}
});
}
export default {
name: "restrict-mentions",
initialize() {
withPluginApi("0.8", initWithApi);
}
};

Why user comment is not in email order confirmation html opencart 2?

I noticed that in opencart 2.3.0.2 the order confirmation for admin contains the comments from the user, and the email that the user gets doesn't.
The user gets only the text version with the comment, not the HTML version with the comment.
In 2012 2013 the problem was that the comment wasn't passed at all into the emails.
https://github.com/opencart/opencart/pull/94
https://github.com/opencart-ce/opencart-ce/issues/12
It seems the problem was solved only partially.
The solution is:
Edit:
catalog/model/checkout/order.php
Put this code:
$data['ip'] = $order_info['ip'];
$data['order_status'] = $order_status;
if ($comment && $notify) {
$data['comment'] = nl2br($comment);
} else {
$data['comment'] = '';
}
if ($comment) {
if ($order_info['comment']) {
$data['comment'] = nl2br($comment) . '<br/><br/><strong>Comment:</strong><br/>' . $order_info['comment'];
} else {
$data['comment'] = nl2br($comment);
}
} else {
if ($order_info['comment']) {
$data['comment'] = $order_info['comment'];
} else {
$data['comment'] = '';
}
}
instead of:
$data['ip'] = $order_info['ip'];
$data['order_status'] = $order_status;
if ($comment && $notify) {
$data['comment'] = nl2br($comment);
} else {
$data['comment'] = '';
}
Or you can install this mod https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=32499&filter_search=add%20comment&filter_category_id=8&filter_license=0

Login Page Hash issue UPDATE

I am having a issue with my login page reading a function to login
on my register page which I'm proud to say works perfect
this is my password hash code
$password = password_hash($password, PASSWORD_BCRYPT);
my login page has 2 fields
email &
password
I have re cleaned my code and solved the issue some what
functions are working
when I enter email and password it triggers
Warning! Email or Password Incorrect
plus an error at the top
Notice: Undefined index: password in C:\Program Files (x86)\Zend\Apache2\htdocs\CMS\functions\functions.php on line 249
this is line 249
$db_password = $row['password'];
/* Validate Login */
function validate_login()
{
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$email = clean($_POST['email']);
$password = clean($_POST['password']);
if (empty($email)) {
$errors[] = "Email Required";
}
if (empty($password)) {
$errors[] = "Password Required";
}
if (! empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
if (login_user($email, $password)) {
redirect("../account/profile.php");
} else {
echo validation_errors("Email or Password Incorrect");
}
}
}
} // End Function
/* User Login */
function login_user($email, $password)
{
$sql = "SELECT user_pwd, uid FROM userss WHERE user_email = '" . escape($email) . "'";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['password'];
if (hash_algos($password) == $db_password) {
return true;
} else {
return false;
}
}
}// End Function
It looks like you are missing a closing bracket for your validate_login() function so it is defining the login_user() function only after the first function is called. Therefore as you progress through your validate_login() function you call the login_user() function before it is created since it is created after the if statement completes.
OK I just figured out the issue
if (hash_algos($password) == $db_password) {
return true;
} else {
return false;
}
changed it to this
if(password_verify($password, $db_password)){
return true;
} else {
return false;
}

set user id based on pk when logged in through facebook

I am able to login/logout on my web app using facebook. But the problem is when the user needs to update his profile on my application, he can't. It would say that he is restricted to view his own page. The only way for this to happen is that user identity is probably not set. But I am not sure how to correct this. When I tried Yii::app()->user->user_id the Id is actually correct id, which is the pk in user model. So how is it that he cannot get to update his own page?
in my facebookUserIdentity:
public function authenticate()
{
if($this->getIsAccessTokenValid() && $this->setFBUser())
{
$this->_user = $this->getUserFromDatabase();
if($this->_user === false)
return false;
$this->setState('isUser', false);
$this->setState('isAdmin', false);
$this->setState('isShop', false);
$this->setState('isSuper', false);
$this->setState('user',$this->_user);
$this->_id = $this->_FBUser['id'];
//I've tried doing something like $this->_id = Yii::app()->user->user_id; or like $this->_user->user_id; ?
$this->_name = $this->_FBUser['name'];
return true;
}
else {
return false;
}
}
getting user from db:
protected function getUserFromDatabase()
{
$FBUser = $this->_FBUser;
if($FBUser)
{
$user = User::model()->findByAttributes (array('oauth_uid'=>$FBUser['id']));
if(!$user)
{
$user = new User;
$user->oauth_uid = $FBUser['id'];
$user->username = $FBUser['id'];
$user->first_name = $FBUser['first_name'];
//other info etc
$user->image = "https://graph.facebook.com/" . $FBUser['id'] . "/picture?type=large";
}
else
{
if ($user->oauth_permission == 'n')
{
$this->errorMessage = self::ERROR_LOGIN_DISABLE;
return false;
}
$user->last_login_date = date('Y-m-d H:i:s');
}
if($user->save())
{
return $user;
}
else
$this->errorMessage = CJSON::encode ( $user->getErrors());
return false;
}
else {
$this->errorMessage = "Failed getting facebook user data";
return false;
}
}
and lastly, the controller page rules:
public function accessRules()
{
$params=array();
$id=Yii::app()->request->getParam('id');
$params['model']=$this->loadModel($id);
return array(
//stuff
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','RemoveImage'),
'roles'=>array('admin','super','owner'=>$params),
),
//stuff

Zend Gdata Calendar Event Update Not Sending Email Notification

Although the following code snippet does successfully add additional guests to a google calendar event, it is not sending them email notifications of the event. Can someone tell me if it's possible to also send an email to the new guests?
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // predefined service name for calendar
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
function sendInvite($eventId, $email)
{
$gdataCal = new Zend_Gdata_Calendar($client);
if($eventOld = $this->getEvent($eventId))
{
$who = $gdataCal->newwho();
$who->setEmail($email);
$eventOld->setWho(array_merge(array($who), $eventOld->getWho()));
try
{
$eventOld->save();
} catch(Zend_Gdata_App_Exception $e)
{
return false;
}
return true;
} else
return false;
}
function getEvent($eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('full');
$query->setEvent($eventId);
try
{
$eventEntry = $gdataCal->getCalendarEventEntry($query);
return $eventEntry;
} catch(Zend_Gdata_App_Exception $e)
{
return null;
}
}
Finally figured it out.
public function sendInvite($eventId, $email)
{
$gdataCal = new Zend_Gdata_Calendar($this->client);
if($eventOld = $this->getEvent($eventId))
{
$SendEventNotifications = new Zend_Gdata_Calendar_Extension_SendEventNotifications();
$SendEventNotifications->setValue(true);
$eventOld->SendEventNotifications = $SendEventNotifications;
$who = $gdataCal->newwho();
$who->setEmail($email);
$eventOld->setWho(array_merge(array($who), $eventOld->getWho()));
try
{
$eventOld->save();
} catch(Zend_Gdata_App_Exception $e)
{
return false;
}
return true;
} else
return false;
}