Opecart - check if user in on a specific page (is_page command?) - opencart

I want to make sure only specific users can access my site content based on if they are logged in and part of a customer group. If not I kick them out of the wholesale site and into the regular site using this code.
if ($logged && !$this->customer->getCustomerGroupId() == '1') { /*Check if logged in and belong to wholesale group*/
$this->customer->logout();
$this->redirect("https://example.com/");
}
The problem is that if they aren't logged in and find a way they can still browse the site. I would like a way to check if they are logged in. I tried using this:
if (!$logged) { /*Check if user is logged in, not = redirect to login page*/
$this->redirect('https://wholesale.garrysun.com/index.php?route=account/login');
but then they get stuck in a redirect loop because the login page has this in the header. I would like to check for this on every page except for the login and logout pages:
http://example.com/index.php?route=account/login
http://example.com/index.php?route=account/logout
After thinking about it I tried using this code but to no avail:
<?php
/*Check if on wholesale site*/
if($this->config->get('config_store_id') == 1) {
/*Check if user is logged in, if not and not on login/logout/register page = redirect to login page*/
if(!$logged){
if(!$this->request->get['route'] == 'account/login' || !$this->request->get['route'] == 'account/logout' || !$this->request->get['route'] == 'account/register'){
$this->redirect('https://wholesale.garrysun.com/index.php?route=account/login');
}
}else if($logged && !$this->customer->getCustomerGroupId() == '1') { /* User is logged in and not a wholesale customer */
$this->customer->logout();
$this->redirect("https://garrysun.com/");
}
}
?>
What is the code in opencart to check if you are on a specific page?

This information isn't passed to any of the controllers. The best you can do is pretty much what you already have:
if (isset($this->request->get['route'])) {
$page = $this->request->get['route'];
} else {
$page = 'common/home';
}
if ($this->config->get('config_store_id') == 1) {
if (!$this->customer->isLogged() && !in_array($page, array('account/login', 'account/logout', 'account/register'))) {
... redirect
}
}

Related

Getting "This page isn’t working <url> redirected you too many times." error in production next.js middleware

So I'm trying to route my users to a sign in page if they don't have a cookie. My _middleware.js file looks like this:
import { NextResponse } from 'next/server'
export function middleware(req, res) {
const cookie = req.cookies['admin_cookie'];
if ((req.nextUrl.pathname.startsWith('/Submissions') || req.nextUrl.pathname.startsWith('/Batches')) && cookie !== 'cookie_password') {
return NextResponse.redirect(new URL('/Auth/', req.url));
}
}
It works fine in development, but when I push to production (using vercel) I get the redirected you too many times error. Also yes I know that's not great security, it doesn't really matter for this project.

How to require Sitecore user to change password on next login?

I am building a system using Sitecore 7.5 and I would like to figure out a way to require a Sitecore user to change their password on next login. We have a custom profile that all users have and I have added a checkbox called "Password Change Required". And I added the code below to the LoggingIn pipeline. That way when a user attempts to login I can just redirect them to the built in Sitecore change password page.
public class PasswordChange
{
public void Process(LoggingInArgs args)
{
var user = Sitecore.Security.Accounts.User.FromName(args.Username, true);
var myCustomUser = new CustomUser(user.Profile);
if (myCustomUser.PasswordChangeRequired)
{
HttpContext.Current.Response.Redirect("/sitecore/login/changepassword.aspx");
}
}
}
That works fine. If I go in to User Manager and check that checkbox for a given user, then the next time they try to login they are redirected to the built in Sitecore page for changing your password. However I can't seem to figure out when I can uncheck that checkbox in their user profile. Ideally I would like to have code that runs after the user has finished changing their password. That code should uncheck the checkbox so that the next time they login they are not required to change their password.
Does anyone know if it is possible to somehow tie in to the built in Sitecore change password page so that I can have some code run after the user successfully changes their password and uncheck that checkbox in their user profile?
Or is there a better way to accomplish this?
Thanks,
Corey
UPDATE: adding code that I used to solve the problem. I used the user:updated event as suggested by Anton below. I decided that if the user's password had been changed in the previous 30 seconds then that meant it was ok to uncheck the checkbox.
public class UserUpdatedHandler
{
protected void HandleUserUpdate(object sender, EventArgs args)
{
var user = (MembershipUserWrapper)Event.ExtractParameter(args, 0);
if (user != null)
{
// If this change was a password change and the Password Change Required checkbox is checked,
// then uncheck the Password Change Required checkbox
//First get a membership user object
var membershipUser = Membership.GetUser(user.UserName);
if (membershipUser != null)
{
//Now check the elapsed time since the last password change
var elapsedTimeSinceLastPasswordChange = DateTime.Now - membershipUser.LastPasswordChangedDate;
if (elapsedTimeSinceLastPasswordChange.TotalSeconds < 30)
{
//Get a Sitecore User
var sitecoreUser = User.FromName(user.UserName, true);
if (sitecoreUser != null)
{
//Create a custom user
var customUser = new CustomUser(sitecoreUser.Profile);
if (customUser.PasswordChangeRequired)
{
customUser.PasswordChangeRequired = false;
customUser.Save();
}
}
}
}
}
}
}
There is an event that should be triggered after user change(I believe that changing password will trigger this event): "user:updated". Within event handler you will be able to check "LastPasswordChangedDate" user property and determine was it password change or other change user action. If it is password change then you are able to uncheck that checkbox in user profile.
First step create a custom profile where you add a property named isFirstTime.
You add your own processor as a first processor of loggingin pipeline:
public void Process(LoggingInArgs args)
{
MembershipUser user = Membership.GetUser(args.Username);
if (user != null)
{
if (user.Profile["isFirstTime"].Equals("1"))
{
HttpContext.Current.Response.Redirect("/passwordchangepage");
}
}
}
This will redirect all the users that require password change to the /passwordchangepage url. On this page create a form for old password and new password and a submit button.
On submitting the form execute password change:
MembershipUser user = Membership.GetUser(username);
user.ChangePassword(oldPassword, newPassword);
user.Profile["isFirstTime"]=false;

Phantomjs cookie authentication failed to capture and print the web page

I am using phantomjs to print the webpage and create a pdf. As the UI needs the user's authentication before finding the data, I used persistent cookies to authenticate the user. But somehow I got login screen every time in the created PDF. I observed that the user authenticated successfully and also the result's webpage showing proper result (debug logs showing the proper data array) but while printing the web page or creating a PDF, it somehow gets the login screen. Sometimes I observed that I got two different cookies in my PHP code while getting the report data and in javascript 'document.cookies'.
Please let me know how can I fix this.
var page = require('webpage').create(),
system = require('system'), t, address;
page.settings.userName = 'myusername';
page.settings.password = 'mypassword';
if (system.args.length === 1) {
console.log('Usage: scrape.js ');
phantom.exit();
} else {
t = Date.now();
address = system.args[1];
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
t = Date.now() - t;
var title = page.evaluate(function() { return document.title;})
console.log('Page title is ' + title);
console.log('Loading time ' + t + ' msec');
}
phantom.exit();
});
}
Another piece of code of sending a cookie file
bin/phantomjs --cookies-file=/tmp/cookies.txt --disk-cache=yes --ignore-ssl-errors=yes /phantomjs/pdf.js 'username' 'params' '/tmp/phantomjs_file' /tmp/phantom_pdf.pdf
And
phantomjs --cookies-file=cookies.txt examples/rasterize.js localhost:7000/reports /tmp/report.pdf

Facebook realtime updates, no post update from facebook

I followed the guide realtime updates on facebook.
My application is a tab page.
I'm using the sandbox environment.
Initially set up by the signing of the dashboard.
The callback URL endpoint verify works fine.
I did an post on the page for only test.
But so far (after 24hrs), i received no update post from facebook.
On log apache server, there is no post from facebook too.
My callback script:
<?php
define('UPD_FILE', 'updates.log');
$method = $_SERVER['REQUEST_METHOD'];
global $log_file;
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == 'jogabonito') {
echo $_GET['hub_challenge'];
exit;
}
else if ($method == 'POST')
{
$log_file=UPD_FILE;
$updates = json_decode(file_get_contents("php://input"), true);
logToFile("updates =".print_r($updates));
}
function logToFile($message){
global $log_file;
$hdl = fopen($log_file, 'a') or die ("couldn't open log file");
fwrite($hdl,$message."\n");
fclose($hdl);
}
?>
Grateful for the attention
Your code works (somewhat) fine after some requirements have been met.
You have subscribed successfully for at least one field change.
The user you are testing with has granted your app some or all of the required permissions for the fields you are subscribed for.
If one of the above isn't properly handled you won't be notified about related changes.
On another note I wrote "somewhat" because you are dumping the array content using print_r without specifying that the function should return the data rather than print it. The way you have it right now will result in a "1" result.
What you need should look more like this:
logToFile("updates =".print_r($updates, true));
I was facing the same problem, below solution fixed my problem,
just make an POST request to the following URL
https://graph.facebook.com/PAGE_ID/tabs?app_id=APP_ID&access_token=PAGE_ACCESS_TOKEN
Please replace the values before making a request

getting the information if the user is a fan of a page

I have a problem with getting the information if the user is a fan of a page (fanpage) becouse sometimes this query
SELECT uid FROM page_fan WHERE uid=$mUserId AND page_id=$iPageId
gets me an empty result although the user is a fan of the page
I used this JavaScript method which returned me "resp.error_code" and "resp.error_msg" was "Invalid API key"
FB.api({
method: 'pages.isFan',
page_id: 'FB_FAN_PAGE_ID',
uid: $iUser
}, function (resp) {
if (resp == true) {
alert('fan');
} else if (resp.error_code) {
alert(resp.error_msg);
} else {
alert('no-fan');
}
});
but the code is correct as the application starts and what is strange it sometimes works and sometimes doesn't work.
I try to get the user is fan form request just like in this post How to check if a user likes my Facebook Page or URL using Facebook's API but it doesn't work.
Help pleace
With JS SDK you can check if the currently logged-in user has liked a page like this:
FB.api("me/likes/" + appPageId, function(response) {
if(response && response.data[0]) {
//user has liked the page
} else {
//user has not like the page
}
});