File: Facebook.php

package info (click to toggle)
simplesamlphp 1.19.7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,920 kB
  • sloc: php: 202,044; javascript: 14,867; xml: 2,700; sh: 225; perl: 82; makefile: 70; python: 5
file content (223 lines) | stat: -rw-r--r-- 6,475 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php

namespace SimpleSAML\Module\authfacebook;

require_once(dirname(dirname(__FILE__)) . '/extlibinc/base_facebook.php');

/**
 * Extends the BaseFacebook class with the intent of using
 * PHP sessions to store user ids and access tokens.
 */

class Facebook extends \BaseFacebook
{
    const FBSS_COOKIE_NAME = 'fbss';

    // We can set this to a high number because the main session
    // expiration will trump this
    const FBSS_COOKIE_EXPIRE = 31556926; // 1 year

    /**
     * Stores the shared session ID if one is set
     * @var string
     */
    protected $sharedSessionID = '';

    /**
     * SimpleSAMLphp state array
     * @var array
     */
    protected $ssp_state = [];

    /** @var string|null */
    protected $state = null;

    /** @var array */
    protected static $kSupportedKeys = ['state', 'code', 'access_token', 'user_id'];


    /**
     * Identical to the parent constructor, except that
     * we start a PHP session to store the user ID and
     * access token if during the course of execution
     * we discover them.
     *
     * @param array $config the application configuration. Additionally
     * @param array &$ssp_state
     * accepts "sharedSession" as a boolean to turn on a secondary
     * cookie for environments with a shared session (that is, your app
     * shares the domain with other apps).
     * @see BaseFacebook::__construct in base_facebook.php
     */
    public function __construct(array $config, &$ssp_state)
    {
        $this->ssp_state = &$ssp_state;

        parent::__construct($config);
        if (!empty($config['sharedSession'])) {
            $this->initSharedSession();
        }
    }


    /**
     * @return void
     */
    protected function initSharedSession()
    {
        $cookie_name = $this->getSharedSessionCookieName();
        if (isset($_COOKIE[$cookie_name])) {
            $data = $this->parseSignedRequest($_COOKIE[$cookie_name]);
            if (
                !empty($data)
                && !empty($data['domain'])
                && self::isAllowedDomain($this->getHttpHost(), $data['domain'])
            ) {
                // good case
                $this->sharedSessionID = $data['id'];
                return;
            }
            // ignoring potentially unreachable data
        }
        // evil/corrupt/missing case
        $base_domain = $this->getBaseDomain();
        $this->sharedSessionID = md5(uniqid(strval(mt_rand()), true));
        $cookie_value = $this->makeSignedRequest(
            [
                'domain' => $base_domain,
                'id' => $this->sharedSessionID,
            ]
        );
        $_COOKIE[$cookie_name] = $cookie_value;
        if (!headers_sent()) {
            $expire = time() + self::FBSS_COOKIE_EXPIRE;
            setcookie($cookie_name, $cookie_value, $expire, '/', '.' . $base_domain);
        } else {
            // @codeCoverageIgnoreStart
            \SimpleSAML\Logger::debug(
                'Shared session ID cookie could not be set! You must ensure you ' .
                'create the Facebook instance before headers have been sent. This ' .
                'will cause authentication issues after the first request.'
            );
            // @codeCoverageIgnoreEnd
        }
    }


    /**
     * Provides the implementations of the inherited abstract
     * methods.  The implementation uses PHP sessions to maintain
     * a store for authorization codes, user ids, CSRF states, and
     * access tokens.
     *
     * @param string $key
     * @param mixed $value
     * @return void
     */
    protected function setPersistentData($key, $value)
    {
        if (!in_array($key, self::$kSupportedKeys)) {
            \SimpleSAML\Logger::debug("Unsupported key passed to setPersistentData: " . var_export($key, true));
            return;
        }

        $session_var_name = $this->constructSessionVariableName($key);
        $this->ssp_state[$session_var_name] = $value;
    }


    /**
     * @param string $key
     * @param bool $default
     * @return mixed
     */
    protected function getPersistentData($key, $default = false)
    {
        if (!in_array($key, self::$kSupportedKeys)) {
            \SimpleSAML\Logger::debug("Unsupported key passed to getPersistentData: " . var_export($key, true));
            return $default;
        }

        $session_var_name = $this->constructSessionVariableName($key);
        return isset($this->ssp_state[$session_var_name]) ? $this->ssp_state[$session_var_name] : $default;
    }


    /**
     * @param string $key
     * @return void
     */
    protected function clearPersistentData($key)
    {
        if (!in_array($key, self::$kSupportedKeys)) {
            \SimpleSAML\Logger::debug("Unsupported key passed to clearPersistentData: " . var_export($key, true));
            return;
        }

        $session_var_name = $this->constructSessionVariableName($key);
        if (isset($this->ssp_state[$session_var_name])) {
            unset($this->ssp_state[$session_var_name]);
        }
    }


    /**
     * @return void
     */
    protected function clearAllPersistentData()
    {
        foreach (self::$kSupportedKeys as $key) {
            $this->clearPersistentData($key);
        }
        if ($this->sharedSessionID) {
            $this->deleteSharedSessionCookie();
        }
    }


    /**
     * @return void
     */
    protected function deleteSharedSessionCookie()
    {
        $cookie_name = $this->getSharedSessionCookieName();
        unset($_COOKIE[$cookie_name]);
        $base_domain = $this->getBaseDomain();
        setcookie($cookie_name, '', 1, '/', '.' . $base_domain);
    }


    /**
     * @return string
     */
    protected function getSharedSessionCookieName()
    {
        return self::FBSS_COOKIE_NAME . '_' . $this->getAppId();
    }


    /**
     * @param string $key
     * @return string
     */
    protected function constructSessionVariableName($key)
    {
        $parts = ['authfacebook:authdata:fb', $this->getAppId(), $key];
        if ($this->sharedSessionID) {
            array_unshift($parts, $this->sharedSessionID);
        }
        return implode('_', $parts);
    }


    /**
     * @return void
     */
    protected function establishCSRFTokenState()
    {
        if ($this->state === null) {
            $this->state = \SimpleSAML\Auth\State::getStateId($this->ssp_state);
            $this->setPersistentData('state', $this->state);
        }
    }
}