summaryrefslogtreecommitdiff
path: root/daggerhart-openid-connect-generic/includes/openid-connect-generic-login-form.php
blob: 76107b036e7789da31620ab969ae349c043bcb0d (plain)
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
<?php

class OpenID_Connect_Generic_Login_Form {

	private $settings;
	private $client_wrapper;

	/**
	 * @param $settings
	 * @param $client_wrapper
	 */
	function __construct( $settings, $client_wrapper ){
		$this->settings = $settings;
		$this->client_wrapper = $client_wrapper;

		// maybe set redirect cookie on formular page
		add_action('login_form_login', [$this, 'handle_redirect_cookie']);
	}

	/**
	 * @param $settings
	 * @param $client_wrapper
	 *
	 * @return \OpenID_Connect_Generic_Login_Form
	 */
	static public function register( $settings, $client_wrapper ){
		$login_form = new self( $settings, $client_wrapper );

		// alter the login form as dictated by settings
		add_filter( 'login_message', array( $login_form, 'handle_login_page' ), 99 );

		// if WooCommerce is active, also insert logic for the shopping cart
	        if ( in_array( 'woocommerce/woocommerce.php',
                               apply_filters( 'active_plugins',
                                              get_option( 'active_plugins' ) ) ) ) {
			// show login form at the shopping cart (if not logged in)
			add_action( 'woocommerce_before_checkout_billing_form',
                                    array( $login_form, 'action_login_page' ) );
                        // Add action to set cookie to redirect back to current
                        // (checkout) page after OIDC provided the data
                        // (see similar add_action()
                        //  above for the 'login_form_login' - we must do the
                        //  same on the 'Billing details' page!)
                        add_action('woocommerce_before_checkout_billing_form',
                                    array( $login_form, 'handle_redirect_cookie' ) );
			// hook to convert OIDC fields to WC checkout fields if logged in
			add_filter( 'woocommerce_checkout_fields',
 			            array( $login_form,
                                           'filter_checkout_get_value' ) );
		}

		// add a shortcode for the login button
		add_shortcode( 'openid_connect_generic_login_button', array( $login_form, 'make_login_button' ) );

		$login_form->handle_redirect_login_type_auto();

		return $login_form;
	}

	/**
	 * Auto Login redirect
	 */
	function handle_redirect_login_type_auto(){
		if ( $GLOBALS['pagenow'] == 'wp-login.php'
			&& ( $this->settings->login_type == 'auto' || ! empty( $_GET['force_redirect'] ) )
			&& ( ! isset( $_GET[ 'action' ] ) || $_GET[ 'action' ] !== 'logout' )
			&& ! isset( $_POST['wp-submit'] ) ) {
			if (  ! isset( $_GET['login-error'] ) ) {
			    $this->handle_redirect_cookie();
				wp_redirect( $this->client_wrapper->get_authentication_url() );
				exit;
			}
			else {
				add_action( 'login_footer', array( $this, 'remove_login_form' ), 99 );
			}
		}
	}

	/**
	 * Handle login related redirects
	 */
	function handle_redirect_cookie() {
		if ( $GLOBALS['pagenow'] == 'wp-login.php' && isset( $_GET[ 'action' ] ) && $_GET[ 'action' ] === 'logout' ) {
			return;
		}

		// record the URL of this page if set to redirect back to origin page
		if ( $this->settings->redirect_user_back ){
			$redirect_expiry = current_time('timestamp') + DAY_IN_SECONDS;

			// default redirect to the homepage
			$redirect_url = home_url( esc_url( add_query_arg( null, null ) ) );

			if ( $GLOBALS['pagenow'] == 'wp-login.php' ){
				// if using the login form, default redirect to the admin dashboard
				$redirect_url = admin_url();

				if ( isset( $_REQUEST['redirect_to'] ) ){
					$redirect_url = esc_url_raw( $_REQUEST[ 'redirect_to' ] );
				}
			}

			$redirect_url = apply_filters( 'openid-connect-generic-cookie-redirect-url', $redirect_url );

			setcookie( $this->client_wrapper->cookie_redirect_key, $redirect_url, $redirect_expiry, COOKIEPATH, COOKIE_DOMAIN, is_ssl() );
		}
	}

	/**
	 * WooCommerce integration.
         * Action to output the login button inside the "Billing details" form
	 * just before the user would otherwise manually enter their details.
         */
	function action_login_page () {
		$user = wp_get_current_user ();
	   	if (0 == $user->ID) {
			// ID 0 is used to indicate user is not logged in.
			// Re-use filter logic to generate login page
	        	print ( $this->handle_login_page ('') );
		}
        }

	/**
	 * WooCommerce integration.
	 * Filter to transform (defaults) for the Billing details according to
	 * the information obtained from OpenID Connect (OIDC).  WooCommerce
         * already grabs many of the values properly, but there are some fields
	 * which we have to convert manually.
	 */
	function filter_checkout_get_value ($in=array())
	{
                echo "<pre>"; // DEBUG
 		echo "FCG for" . json_encode ($in) . "<br>\n"; // DEBUG
		$user = wp_get_current_user ();
	   	if (0 != $user->ID) {
			$token_response = $user->get ('openid-connect-generic-last-user-claim');
			echo "OIDC has: " . json_encode ( $token_response ); // DEBUG
                        echo "SET: " . (isset( $token_response)) . " AND " .
                             is_array ($token_response) . " AND " .
                             (array_key_exists ('address', $token_response));
			if ( (isset( $token_response)) &&
                             (array_key_exists ('address', $token_response)) ){
				$address = $token_response [ 'address' ];
                           	echo "OIDC has address: " . json_encode ( $address ); // DEBUG
				if ( in_array( 'postal_code', $address ) ){
					$postal_code = $address [ 'postal_code' ];
					$in['billing']['billing_postcode']['default'] = $postal_code;
					$in['shipping']['shipping_postcode']['default'] = $postal_code;
				}
				if ( in_array( 'country', $address ) ){
					$country = $address [ 'country' ];
					$in['billing']['billing_country']['default'] = $country;
					$in['shipping']['shipping_country']['default'] = $country;
				}
				if ( in_array( 'locality', $address ) ){
					$locality = $address [ 'locality' ];
					$in['billing']['billing_city']['default'] = $locality;
					$in['shipping']['shipping_city']['default'] = $locality;
				}
				if ( in_array ( 'region', $address ) ){
					$region = $address [ 'region' ];
					$in['billing']['billing_state']['default'] = $region;
					$in['shipping']['shipping_state']['default'] = $region;
				}
				if ( in_array ( 'formatted', $address ) ){
					$formatted = $address [ 'formatted' ];
					$lines = explode ( '\r\n', $formatted );
					if ( count($lines) > 0 ){
						$in['billing']['billing_address_1']['default'] = $lines[0];
						$in['shipping']['shipping_address_1']['default'] = $lines[0];
					}
					if ( count($lines) > 1 ){
						$in['billing']['billing_address_2']['default'] = $lines[1];
						$in['shipping']['shipping_address_2']['default'] = $lines[1];
					}
				}
				if ( in_array ( 'street_address', $address ) ){
					$street_address = $address [ 'street_address' ];
					if ( ! in_array ( 'formatted', $address ) ){
						$in['billing']['billing_address_1']['default'] = $street_address;
						$in['shipping']['shipping_address_1']['default'] = $street_address;
					}
				}
			}
		}
                echo "</pre>"; // DEBUG
		return $in;
	}

	/**
	 * Implements filter login_message
	 *
	 * @param $message
	 * @return string
	 */
	function handle_login_page( $message ) {

		if ( isset( $_GET['login-error'] ) ) {
			$message .= $this->make_error_output( $_GET['login-error'], $_GET['message'] );
		}

		// login button is appended to existing messages in case of error
		$message .= $this->make_login_button();
		return $message;
	}

	/**
	 * Display an error message to the user
	 *
	 * @param $error_code
	 *
	 * @return string
	 */
	function make_error_output( $error_code, $error_message ) {

		ob_start();
		?>
		<div id="login_error">
			<strong><?php _e( 'ERROR'); ?>: </strong>
			<?php print esc_html($error_message); ?>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Create a login button (link)
	 *
	 * @return string
	 */
	function make_login_button() {
		$text = apply_filters( 'openid-connect-generic-login-button-text', __( 'Login with OpenID Connect' ) );
		$href = apply_filters( 'openid-connect-generic-login-button-url', $this->client_wrapper->get_authentication_url() );

		ob_start();
		?>
		<div class="openid-connect-login-button" style="margin: 1em 0; text-align: center;">
			<a class="button button-large" href="<?php print esc_url( $href ); ?>"><?php print $text; ?></a>
		</div>
		<?php
		return ob_get_clean();
	}

	/*
	 * Removes the login form from the HTML DOM
	 */
	function remove_login_form() {
		?>
		<script type="text/javascript">
			(function() {
				var loginForm = document.getElementById("user_login").form;
				var parent = loginForm.parentNode;
				parent.removeChild(loginForm);
			})();
		</script>
		<?php
	}
}