web/website/ops/oscommerce/DuneAccount.php
2026-11-27 23:43:05 +00:00

113 lines
10 KiB
PHP

<?php
namespace frontend\components;
use Yii;
final class DuneAccount {
private static function email(array $identity):string {
$email=$identity['email']??null;
return ($identity['emailVerified']??false)===true&&is_string($email)&&strlen($email)<=254&&filter_var($email,FILTER_VALIDATE_EMAIL)?$email:$identity['id'].'@accounts.dunerealms.invalid';
}
private static function token(): string { return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='); }
private static function cookie(string $name,string $value,int $expires):void { setcookie($name,$value,['expires'=>$expires,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']); }
private static function api(string $operation,array $payload):array {
$config=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true,8,JSON_THROW_ON_ERROR);
$curl=curl_init('http://127.0.0.1:3003/internal/integrations/'.$operation);
curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($payload),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$config['secret']],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>6]);
$body=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);curl_close($curl);
if($status!==200) throw new \yii\web\HttpException($status===401?401:503,'DuneRealms sign-in is unavailable. Please sign in again.');
return json_decode($body,true,32,JSON_THROW_ON_ERROR);
}
// DUNE SHOP DESIGN BOOTSTRAP START
public function bootstrap($app):void {
$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST,fn()=>self::handle($app));
$app->response->on(\yii\web\Response::EVENT_AFTER_PREPARE,static function($event):void {
$response=$event->sender;$path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH);$destination=$_SERVER['HTTP_SEC_FETCH_DEST']??null;
if(!is_string($path)||!str_starts_with($path,'/catalog/')||$response->statusCode<200||$response->statusCode>=300||$response->format!==\yii\web\Response::FORMAT_HTML||!is_string($response->content)||strtolower($_SERVER['HTTP_X_REQUESTED_WITH']??'')==='xmlhttprequest'||($destination!==null&&!in_array($destination,['document','iframe'],true)))return;
if(str_contains($response->content,'/oscommerce-inner.js')){
$response->content=preg_replace('~(/oscommerce-inner\.js)(?:\?[^"\']*)?(["\'])~','$1?v=realm-design-1$2',$response->content);return;
}
$script='<script src="/oscommerce-inner.js?v=realm-design-1" defer></script>';
// Native catalogue documents can omit their outer body tag.
$response->content=stripos($response->content,'</body')!==false?preg_replace('~</body\s*>~i',$script.'</body>',$response->content,1):$response->content.$script;
});
}
// DUNE SHOP DESIGN BOOTSTRAP END
private static function redirect($app,string $url):never { $app->response->redirect($url,303)->send();$app->end();exit; }
private static function start($app,string $next='/catalog/'):never {
$state=self::token();$nonce=self::token();
$app->db->createCommand()->delete('dune_sso_states','expires_at < :now',[':now'=>time()])->execute();
$app->db->createCommand()->insert('dune_sso_states',['state_hash'=>hash('sha256',$state),'nonce_hash'=>hash('sha256',$nonce),'next_path'=>$next,'expires_at'=>time()+300])->execute();
self::cookie('__Host-dune_osc_state',$nonce,time()+300);
$url='https://cp.dunerealms.com/sso/authorize?client=oscommerce&state='.rawurlencode($state);
if(($_SERVER['HTTP_SEC_FETCH_DEST']??'')==='iframe'){
$js=json_encode(['type'=>'dune-shop-signin','url'=>$url],JSON_HEX_TAG|JSON_HEX_AMP);
$app->response->format=\yii\web\Response::FORMAT_HTML;
$parent='https://shop.dunerealms.com';$ref=parse_url($_SERVER['HTTP_REFERER']??'');
if(($ref['scheme']??'')==='https'&&in_array($ref['host']??'',['www.dunerealms.com','dunerealms.com','cp.dunerealms.com','shop.dunerealms.com'],true))$parent='https://'.$ref['host'];
$app->response->content='<meta name="referrer" content="no-referrer"><script>parent.postMessage('.$js.','.json_encode($parent).');</script><p><a target="_top" href="'.htmlspecialchars($url,ENT_QUOTES).'">Continue with your DuneRealms account</a></p>';
$app->response->send();$app->end();exit;
}
self::redirect($app,$url);
}
private static function synchronize($app,array $identity):int {
if(!preg_match('/^[a-f0-9-]{36}$/i',$identity['id']??'')||!preg_match('/^[a-f0-9]{64}$/',$identity['sessionRef']??''))throw new \yii\web\ForbiddenHttpException('Invalid account identity');
$db=$app->db;$transaction=$db->beginTransaction();
try{
$id=$db->createCommand('SELECT customer_id FROM dune_account_links WHERE account_id=:id FOR UPDATE',[':id'=>$identity['id']])->queryScalar();
$email=self::email($identity);
$collision=$db->createCommand('SELECT customers_id FROM customers WHERE customers_email_address=:email AND customers_id<>:id',[':email'=>$email,':id'=>(int)$id])->queryScalar();
if($collision)throw new \yii\web\HttpException(409,'This email is linked to another shop customer. Please contact support to link the accounts.');
if(!$id){
$db->createCommand("SET SESSION sql_mode=''")->execute();
$db->createCommand()->insert('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_lastname'=>'','customers_email_address'=>$email,'customers_password'=>password_hash(bin2hex(random_bytes(32)),PASSWORD_BCRYPT),'customers_status'=>1,'platform_id'=>\common\classes\platform::currentId()])->execute();
$id=(int)$db->getLastInsertID();
$db->createCommand()->insert('dune_account_links',['account_id'=>$identity['id'],'customer_id'=>$id])->execute();
$db->createCommand()->insert('customers_info',['customers_info_id'=>$id,'customers_info_date_account_created'=>gmdate('Y-m-d H:i:s')])->execute();
}
$db->createCommand()->update('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_email_address'=>$email],['customers_id'=>$id])->execute();
$transaction->commit();return (int)$id;
}catch(\Throwable $e){$transaction->rollBack();throw $e;}
}
private static function handle($app):void {
$app->response->headers->set('Referrer-Policy','no-referrer');
$path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH);
if(empty($_GET['action'])&&preg_match('#^/catalog/(?:[A-Z]{3}/)?$#',$path)){
$currency=$_GET['currency']??'EUR';
if(!is_string($currency)||!in_array($currency,['EUR','GBP','USD'],true))$currency='EUR';
self::redirect($app,'/catalog/dune-shop?currency='.$currency);
}
if($path==='/dune-login.php'){
if(!isset($_GET['code']))self::start($app);
$state=$_GET['state']??'';$nonce=$_COOKIE['__Host-dune_osc_state']??'';
if(!is_string($state)||!is_string($nonce)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$state)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$nonce))throw new \yii\web\ForbiddenHttpException('Invalid sign-in state');
$row=$app->db->createCommand('SELECT * FROM dune_sso_states WHERE state_hash=:state AND nonce_hash=:nonce AND expires_at>=:now',[':state'=>hash('sha256',$state),':nonce'=>hash('sha256',$nonce),':now'=>time()])->queryOne();
if(!$row)throw new \yii\web\ForbiddenHttpException('Expired or already used sign-in state');
$removed=$app->db->createCommand()->delete('dune_sso_states',['state_hash'=>$row['state_hash'],'nonce_hash'=>$row['nonce_hash']])->execute();
if($removed!==1)throw new \yii\web\ForbiddenHttpException('Sign-in already used');
$identity=self::api('redeem',['client'=>'oscommerce','code'=>$_GET['code']]);
$id=self::synchronize($app,$identity);$token=self::token();
$app->db->createCommand()->insert('dune_sso_sessions',['token_hash'=>hash('sha256',$token),'account_id'=>$identity['id'],'session_ref'=>$identity['sessionRef'],'expires_at'=>time()+43200])->execute();
self::cookie('__Host-dune_oscommerce',$token,time()+43200);self::cookie('__Host-dune_osc_state','',time()-3600);
self::redirect($app,'https://shop.dunerealms.com/');
}
$token=$_COOKIE['__Host-dune_oscommerce']??'';$identity=null;
if(is_string($token)&&preg_match('/^[A-Za-z0-9_-]{43}$/',$token)){
$row=$app->db->createCommand('SELECT account_id,session_ref FROM dune_sso_sessions WHERE token_hash=:token AND expires_at>:now',[':token'=>hash('sha256',$token),':now'=>time()])->queryOne();
if($row){
try{$identity=self::api('identity',['sessionRef'=>$row['session_ref'],'client'=>'oscommerce']);}catch(\yii\web\HttpException $e){if($e->statusCode!==401)throw $e;}
if(($identity['id']??null)!==$row['account_id'])$identity=null;
}
}
if($identity){
$id=self::synchronize($app,$identity);
if((int)$app->user->id!==$id){
if(!$app->user->isGuest){$app->user->logout(false);global $cart;if(is_object($cart)&&is_callable([$cart,'reset']))$cart->reset();}
$app->session->regenerateID(true);
$customer=new \common\components\Customer(\common\components\Customer::LOGIN_WITHOUT_CHECK);
if(!$customer->loginCustomer(self::email($identity),$id))throw new \yii\web\ForbiddenHttpException('Account link failed');
}
}elseif(!$app->user->isGuest){$app->user->logout(false);self::cookie('__Host-dune_oscommerce','',time()-3600);}
if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/(login|create|password|password-forgotten)#',$path))self::start($app);
if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/?$#',$path))self::redirect($app,'https://cp.dunerealms.com/');
if(preg_match('#^/catalog/(?:[A-Z]{3}/)?checkout#',$path)&&!$identity)self::start($app,$path);
}
}