-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathazureb2c.php
More file actions
218 lines (202 loc) · 6.89 KB
/
azureb2c.php
File metadata and controls
218 lines (202 loc) · 6.89 KB
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
<?php
/**
* Azure B2C SSO Login Module for WHMCS
* Version: 1.0
*/
if (!defined('WHMCS')) {
die('Access Denied');
}
use WHMCS\Database\Capsule;
use WHMCS\Auth;
use WHMCS\Config\Setting;
function azureb2c_config() {
return [
'name' => 'Azure B2C SSO Login',
'description' => 'Replace client login with Azure AD B2C authentication.',
'version' => '1.0',
'author' => 'YourName',
'fields' => [
'TenantDomain' => [
'FriendlyName' => 'Tenant Domain',
'Type' => 'text',
'Size' => '50',
'Description' => 'e.g. yourtenant.onmicrosoft.com',
],
'PolicyName' => [
'FriendlyName' => 'B2C Policy',
'Type' => 'text',
'Size' => '30',
'Description' => 'e.g. B2C_1A_SignUpSignIn',
],
'ClientID' => [
'FriendlyName' => 'Azure App Client ID',
'Type' => 'text',
'Size' => '40',
],
'ClientSecret' => [
'FriendlyName' => 'Client Secret',
'Type' => 'password',
'Size' => '60',
],
'UsePKCE' => [
'FriendlyName' => 'Enable PKCE',
'Type' => 'yesno',
'Description' => 'Recommended for extra security.',
],
],
];
}
function azureb2c_activate() {
// Create a custom client field to store Azure B2C object ID
if (!Capsule::schema()->hasTable('tblcustomfields')) {
return ['status' => 'error', 'description' => 'Custom fields table missing'];
}
// Check if field exists
$exists = Capsule::table('tblcustomfields')
->where('fieldname', 'Azure B2C ID')
->where('type', 'client')
->exists();
if (!$exists) {
Capsule::table('tblcustomfields')->insert([
'type' => 'client',
'fieldname' => 'Azure B2C ID',
'fieldtype' => 'text',
'adminonly' => 1,
'required' => 0,
]);
}
return ['status' => 'success', 'description' => 'AzureB2C module activated'];
}
function azureb2c_deactivate() {
// Optionally remove custom field
Capsule::table('tblcustomfields')
->where('fieldname', 'Azure B2C ID')
->where('type', 'client')
->delete();
return ['status' => 'success', 'description' => 'AzureB2C module deactivated'];
}
function azureb2c_clientarea($vars) {
// Handle OAuth callback
if (!isset($_GET['code'])) {
// No code = nothing to do
return;
}
session_start();
$code = $_GET['code'];
$state = $_GET['state'] ?? '';
if (!$state || $state !== $_SESSION['azureb2c_state']) {
die('Invalid state parameter');
}
unset($_SESSION['azureb2c_state']);
// Load config
$cfg = AzureB2CConfig::get();
$tenant = $cfg['tenant'];
$policy = $cfg['policy'];
$clientId = $cfg['clientid'];
$clientSecret = $cfg['secret'];
$usePkce = $cfg['pkce'];
$redirectUri = AzureB2CConfig::callbackUrl();
// Exchange code for tokens
$tokenUrl = "https://{$tenant}/{$tenant}/{$policy}/oauth2/v2.0/token";
$postData = [
'grant_type' => 'authorization_code',
'client_id' => $clientId,
'code' => $code,
'redirect_uri' => $redirectUri,
'scope' => 'openid profile email',
];
if ($usePkce) {
$postData['code_verifier'] = $_SESSION['azureb2c_code_verifier'];
unset($_SESSION['azureb2c_code_verifier']);
} else {
$postData['client_secret'] = $clientSecret;
}
$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if (curl_errno($ch)) {
die('Token request error: ' . curl_error($ch));
}
curl_close($ch);
$tokenData = json_decode($resp, true);
if (empty($tokenData['id_token'])) {
die('Failed to get ID token');
}
$idToken = $tokenData['id_token'];
// Decode payload (no signature verification here—add JWT lib for prod)
$parts = explode('.', $idToken);
$payload = json_decode(base64_decode($parts[1]), true);
$email = $payload['email'] ?? ($payload['emails'][0] ?? null);
$first = $payload['given_name'] ?? '';
$last = $payload['family_name'] ?? '';
$oid = $payload['oid'] ?? $payload['sub'] ?? '';
if (!$email) {
die('Email claim not found');
}
// Find or create WHMCS client
$client = Capsule::table('tblclients')->where('email', $email)->first();
if ($client) {
$clientId = $client->id;
// Update name if changed
$update = [];
if ($first && $first !== $client->firstname) {
$update['firstname'] = $first;
}
if ($last && $last !== $client->lastname) {
$update['lastname'] = $last;
}
if ($update) {
$update['clientid'] = $clientId;
localAPI('UpdateClient', $update);
}
} else {
// JIT create
$pw = bin2hex(random_bytes(6));
$data = [
'firstname' => $first ?: 'Azure',
'lastname' => $last ?: 'User',
'email' => $email,
'password2' => $pw,
'noemail' => true,
];
$res = localAPI('AddClient', $data);
if ($res['result'] !== 'success') {
die('WHMCS AddClient error: ' . $res['message']);
}
$clientId = $res['clientid'];
}
// Save Azure B2C ID into custom field
Capsule::table('tblcustomfieldsvalues')
->updateOrInsert(
['fieldid' => Capsule::table('tblcustomfields')->where('fieldname','Azure B2C ID')->value('id'),
'relid' => $clientId],
['value' => $oid]
);
// Log them in
require_once __DIR__ . '/../../../init.php';
$auth = new Auth();
$auth->getInfobyID($clientId);
$auth->setSessionVars();
$auth->processLogin();
header('Location: clientarea.php');
exit;
}
// Helper for config and callback URL
class AzureB2CConfig {
public static function get() {
$settings = ModuleVars::getModuleParams('azureb2c'); // WHMCS helper
return [
'tenant' => $settings['TenantDomain'],
'policy' => $settings['PolicyName'],
'clientid' => $settings['ClientID'],
'secret' => $settings['ClientSecret'],
'pkce' => !empty($settings['UsePKCE']),
];
}
public static function callbackUrl() {
$base = Setting::getValue('SystemURL');
return $base . '/index.php?m=azureb2c';
}
}