summaryrefslogtreecommitdiff
path: root/snippets/oidc-woocommerce.php
blob: 2731728061f7f49576370061a64333c9b613a8ac (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
/**
 * License: Public domain.
 *
 * Description: This snippet integrates the OIDC connect button with WooCommerce
 *              to allow importing the customer's shopping details via OIDC.
 * Author Christian Grothoff <grothoff@taler.net>
 */

// Add OIDC login form to checkout page.
add_action(
	'openid-connect-generic-register-login-form',
	function ( $login_form ) {

		// If WooCommerce is inactive, do nothing.
		if ( ! in_array(
			'woocommerce/woocommerce.php',
			apply_filters(
				'active_plugins',
				get_option( 'active_plugins' )
			),
			true
		) ) {
			return;
		}

		// Show login form at the shopping cart (if not logged in).
		add_action(
			'woocommerce_before_checkout_billing_form',
			function ( $checkout ) use ( $login_form ) {
				$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 ( $login_form->handle_login_page( '' ) );
				}
			}
		);

		// Add action to set cookie to redirect back to current
		// (checkout) page after OIDC provided the data.
		add_action(
			'woocommerce_before_checkout_billing_form',
			function ( $checkout ) use ( $login_form ) {
                                 $login_form->handle_redirect_cookie ( );
                        }
		);

	}
);


// Hook to convert OIDC fields to WC checkout fields if logged in.
add_filter(
	'woocommerce_checkout_fields',
	'filter_checkout_get_value'
);


/**
 * Checks if $claimname is in the body or _claim_names of the userinfo.
 * If yes, returns the claim value. Otherwise, returns false.
 *
 * @param string $claimname the claim name to look for
 * @param array $userinfo the JSON to look in
 * @param string $claimvalue the source claim value ( from the body of the JWT of the claim source)
 * @return True if a reference was found
 */
function get_claim( $claimname, $userinfo, &$claimvalue ) {
  if ( ! isset( $token_response ) ) {
    return False;
  }
  /**
   * If we find a simple claim, return it.
   */
  if ( array_keys_exists( $claimname, $token_response ) ) {
    $claimvalue = $token_response[$claimname];
    return True;
  }
  /**
   * If there are not aggregated claims, it is over.
   */
  if  ( ! array_key_exists( '_claim_names', $token_response ) ||
        ! array_key_exists( '_claim_sources', $token_response ) ) {
    return False;
  }
  $claim_src_ptr = $token_response['_claim_names'];
  if ( ! isset( $claim_src_ptr ) ) {
    return False;
  }
  /**
   * No reference found
   */
  if ( ! array_key_exists( $claimname, $claim_src_ptr ) ) {
    return False;
  }
  $src = $claim_src_ptr[$claimname];
  //Reference found, but no corresponding JWT. This is a malformed userinfo
  if ( ! array_key_exists( $src, $token_response['_claim_sources']) ) {
    return False;
  }
  //Source claim is not a JWT. Abort.
  if ( ! array_key_exists( 'JWT',  $src ) ) {
    return False;
  }
  /**
   * Extract claim from JWT.
   * FIXME: We probably want to verify the JWT signature/issuer here!
   */
  $jwt = $src['JWT'];
  list ($header, $body, $rest) = split('.', $jwt, 3);
  $body_decoded = base64_decode ( $body, false );
  if ( ( isset ( $body_decoded ) ) &&
    ( array_key_exists( $claimname, $body_decoded ) ) ) {
    $claimvalue = $body_decoded[$claimname];
    return True;
  }
  return False;
}

/**
 * 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.
 *
 * @param array $in Data structure with shipping details to extend and return.
 *
 * @return array Enhanced shipping details.
 */
function filter_checkout_get_value( $in = array() ) {
	$user = wp_get_current_user();
	if ( 0 !== $user->ID ) {
    $token_response = $user->get( 'openid-connect-generic-last-user-claim' );
    $src = '';
    if ( get_claim( 'given_name', $token_response, $given_name ) ) {
			$in['billing']['billing_first_name']['default']   = $given_name;
			$in['shipping']['shipping_first_name']['default'] = $given_name;
		}
		if ( get_claim( 'family_name', $token_response, $family_name ) ) {
			$in['billing']['billing_last_name']['default']   = $family_name;
			$in['shipping']['shipping_last_name']['default'] = $family_name;
		}
		if ( get_claim( 'phone_number', $token_response, $phone_number ) ) {
			$in['billing']['billing_phone']['default']   = $phone_number;
			$in['shipping']['shipping_phone']['default'] = $phone_number;
    }
    if ( get_claim( 'address', $token_response, $address ) ) {
			if ( array_key_exists( 'postal_code', $address ) ) {
				$postal_code                                    = $address ['postal_code'];
				$in['billing']['billing_postcode']['default']   = $postal_code;
				$in['shipping']['shipping_postcode']['default'] = $postal_code;
			}
			if ( array_key_exists( 'country', $address ) ) {
				$country                                       = $address ['country'];
				$in['billing']['billing_country']['default']   = $country;
				$in['shipping']['shipping_country']['default'] = $country;
			}
			if ( array_key_exists( 'locality', $address ) ) {
				$locality                                   = $address ['locality'];
				$in['billing']['billing_city']['default']   = $locality;
				$in['shipping']['shipping_city']['default'] = $locality;
			}
			if ( array_key_exists( 'region', $address ) ) {
				$region                                      = $address ['region'];
				$in['billing']['billing_state']['default']   = $region;
				$in['shipping']['shipping_state']['default'] = $region;
			}
			if ( array_key_exists( '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 ( array_key_exists( 'street_address', $address ) ) {
				$street_address = $address ['street_address'];
				if ( ! array_key_exists( 'formatted', $address ) ) {
					$in['billing']['billing_address_1']['default']   = $street_address;
					$in['shipping']['shipping_address_1']['default'] = $street_address;
				}
			}
		}
	}
	return $in;
}