friendship ended with social-app. php is my new best friend
1<?php
2/**
3 * Class OAuthStorageAbstract
4 *
5 * @created 09.07.2017
6 * @author Smiley <smiley@chillerlan.net>
7 * @copyright 2017 Smiley
8 * @license MIT
9 */
10declare(strict_types=1);
11
12namespace chillerlan\OAuth\Storage;
13
14use chillerlan\OAuth\OAuthOptions;
15use chillerlan\OAuth\Core\AccessToken;
16use chillerlan\Settings\SettingsContainerInterface;
17use chillerlan\Utilities\Crypto;
18use Psr\Log\{LoggerInterface, NullLogger};
19use function trim;
20
21/**
22 * Implements an abstract OAuth storage adapter
23 */
24abstract class OAuthStorageAbstract implements OAuthStorageInterface{
25
26 final protected const KEY_TOKEN = 'TOKEN';
27 final protected const KEY_STATE = 'STATE';
28 final protected const KEY_VERIFIER = 'VERIFIER';
29
30 /**
31 * Output format for encrypted data
32 *
33 * @var int
34 */
35 protected const ENCRYPT_FORMAT = Crypto::ENCRYPT_FORMAT_HEX;
36
37 /**
38 * The options instance
39 */
40 protected OAuthOptions|SettingsContainerInterface $options;
41
42 /**
43 * A PSR-3 logger
44 */
45 protected LoggerInterface $logger;
46
47 /**
48 * OAuthStorageAbstract constructor.
49 */
50 public function __construct(
51 OAuthOptions|SettingsContainerInterface $options = new OAuthOptions,
52 LoggerInterface $logger = new NullLogger,
53 ){
54 $this->options = $options;
55 $this->logger = $logger;
56
57 if($this->options->useStorageEncryption === true && empty($this->options->storageEncryptionKey)){
58 throw new OAuthStorageException('no encryption key given');
59 }
60
61 }
62
63 /** @codeCoverageIgnore */
64 public function setLogger(LoggerInterface $logger):static{
65 $this->logger = $logger;
66
67 return $this;
68 }
69
70 /**
71 * Gets the current provider name
72 *
73 * @throws \chillerlan\OAuth\Storage\OAuthStorageException
74 */
75 protected function getProviderName(string $provider):string{
76 $name = trim($provider);
77
78 if($name === ''){
79 throw new OAuthStorageException('provider name must not be empty');
80 }
81
82 return $name;
83 }
84
85 public function toStorage(AccessToken $token):mixed{
86 $tokenJSON = $token->toJSON();
87
88 if($this->options->useStorageEncryption === true){
89 return $this->encrypt($tokenJSON);
90 }
91
92 return $tokenJSON;
93 }
94
95 public function fromStorage(mixed $data):AccessToken{
96
97 if($this->options->useStorageEncryption === true){
98 $data = $this->decrypt($data);
99 }
100
101 return (new AccessToken)->fromJSON($data);
102 }
103
104 /**
105 * encrypts the given $data
106 */
107 protected function encrypt(string $data):string{
108 return Crypto::encrypt($data, $this->options->storageEncryptionKey, $this::ENCRYPT_FORMAT);
109 }
110
111 /**
112 * decrypts the given $encrypted data
113 */
114 protected function decrypt(string $encrypted):string{
115 return Crypto::decrypt($encrypted, $this->options->storageEncryptionKey, $this::ENCRYPT_FORMAT);
116 }
117
118}