<?php
/*************************************************************
 *
 * Copyright (c) 2024 ysrock Co., Ltd.	<info@ysrock.co.jp>
 * Copyright (c) 2024 Yasuo Sugano	<sugano@ysrock.co.jp>
 *
 * Version	: 1.0.0
 * Update 	: 2024.10.17
 *
 *************************************************************
 *
 *  Composerがインストールされているかを確認
 *
 *    [ ~]$ php composer.phar -V
 *
 *      インストール済み
 *        Composer version 2.8.1 2024-10-04 11:31:01
 *        PHP version 8.3.12 (/opt/remi/php83/root/usr/bin/php)
 *        Run the "diagnose" command to get more detailed diagnostics output.
 *
 *      未インストール
 *        Could not open input file: composer.phar
 *
 *************************************************************
 *
 *  Composerが未インストールの時
 *
 *    [ ~]$ curl -sS https://getcomposer.org/installer | php
 *
 *    [ ~]$ vi .bash_profile
 *      PATH=$PATH:$HOME/
 *
 *    [ ~]$ source ~/.bash_profile
 *
 *************************************************************
 *
 *  PHP-JWTのインストール
 *
 *    [ ~]$ cd public_html/nanairodo.com/public_html/ysrock/
 *    [ ysrock]$ composer.phar require firebase/php-jwt
 *      No composer.json in current directory, do you want to use the one at /home/union-241011/public_html/nanairodo.com/public_html[Y,n]? n
 *
 *************************************************************
 *
 *  サンプル：認証チェック
 *
 *    $class = new oAuth2();
 *    if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/^Bearer\s+(.+)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
 *      return $class->RS256_decode("<publicKeyFile>", $matches[1]);
 *    };
 *
 *
 *************************************************************/

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class oAuth2{
  public function __construct()
  {

  }

  public function makePayload()
  {
    return [
      'iss' => $_SERVER['REQUEST_URI'],
      'aud' => $_SERVER['REQUEST_URI'],
      'iat' => time(),
      'nbf' => time(),
    ];
  }

  public function RS256_encode(String $privateKeyFile, Array $payload=null)
  {
    $privateKey = file_get_contents($privateKeyFile);
    if ($payload === null) $payload = $this->makePayload();
    return JWT::encode($payload, $privateKey, 'RS256');
  } 

  public function RS256_decode(String $publicKeyFile, String $jwt)
  {
    $publicKey = file_get_contents($publicKeyFile);
    return JWT::decode($jwt, new Key($publicKey, 'RS256'));
  } 
}
?>