-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.php
249 lines (219 loc) · 9.56 KB
/
auth.php
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
<?php
/**
* Authentication class for suap is defined here.
*
* @package auth_suap
* @copyright 2020 Kelson Medeiros <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->dirroot/user/lib.php");
require_once("$CFG->dirroot/user/profile/lib.php");
require_once("$CFG->dirroot/lib/authlib.php");
require_once("$CFG->dirroot/lib/classes/user.php");
require_once("$CFG->dirroot/auth/suap/classes/Httpful/Bootstrap.php");
\Httpful\Bootstrap::init();
class auth_plugin_suap extends auth_oauth2\auth
{
public $authtype;
public $roleauth;
public $errorlogtag;
public $config;
public $usuario;
public function __construct()
{
$this->authtype = 'suap';
$this->roleauth = 'auth_suap';
$this->errorlogtag = '[AUTH SUAP] ';
$this->config = get_config('auth_suap');
$this->usuario = null;
}
public function user_login($username, $password)
{
return false;
}
public function can_change_password()
{
return false;
}
public function is_internal()
{
return false;
}
function postlogout_hook($user)
{
global $CFG;
if ($user->auth != 'suap') {
return 0;
}
$config = get_config('auth/suap');
redirect($CFG->wwwroot . '/auth/suap/logout.php');
}
public function login()
{
global $CFG, $USER, $SESSION;
if (isset($_GET['next'])) {
$next = $_GET['next'];
} elseif (property_exists($SESSION, 'wantsurl')) {
$next = $SESSION->wantsurl;
} else {
$next = $CFG->wwwroot;
}
if ($USER->id) {
header("Location: $next", true, 302);
} else {
$SESSION->next_after_next = $next;
$redirect_uri = "$CFG->wwwroot/auth/suap/authenticate.php";
header("Location: {$this->config->base_url}/o/authorize/?response_type=code&client_id={$this->config->client_id}&redirect_uri=$redirect_uri", true, 302);
}
}
public function authenticate()
{
global $CFG, $USER;
if ($USER->id) {
header("Location: /", true, 302);
die();
}
$conf = get_config('auth_suap');
if (!isset($_GET['code'])) {
throw new Exception("O código de autenticação não foi informado.");
}
$user_data_response = "";
try {
$auth = json_decode(
\Httpful\Request::post(
"$conf->base_url/o/token/",
[
'grant_type' => 'authorization_code',
'code' => $_GET['code'],
'redirect_uri' => "{$CFG->wwwroot}/auth/suap/authenticate.php",
'client_id' => $conf->client_id,
'client_secret' => $conf->client_secret
],
\Httpful\Mime::FORM
)->send()->raw_body
);
try {
// Tenta o SUAP Monolítico
$$user_data_response = \Httpful\Request::get("$conf->base_url/api/eu/?scope=" . urlencode('identificacao documentos_pessoais'))
->addHeaders(["Authorization" => "Bearer {$auth->access_token}", 'x-api-key' => $conf->client_secret, 'Accept' => 'application/json'])
->send()->raw_body;
if (strpos($$user_data_response, '"identificacao"') === false) {
throw new Exception("Erro ao tentar obter dados do SUAP Monolítico.");
}
} catch (Exception $e) {
// Tenta o SUAP Login
$$user_data_response = \Httpful\Request::get("$conf->base_url/api/v1/userinfo/?scope=" . urlencode('read'))
->addHeaders(["Authorization" => "Bearer {$auth->access_token}", 'x-api-key' => $conf->client_secret, 'Accept' => 'application/json'])
->send()->raw_body;
if (strpos($$user_data_response, '"identificacao"') === false) {
throw new Exception("Erro ao tentar obter dados do SUAP Login.");
}
}
$userdata = json_decode($$user_data_response);
$this->create_or_update_user($userdata);
} catch (Exception $e) {
echo "<p>Erro ao tentar integrar com o SUAP. Aguarde alguns minutos e <a href='{$CFG->wwwroot}/auth/suap/login.php'>tente novamente</a>.";
echo "<div style='display: None'>$user_data_response</div>.";
die();
}
echo "<p>Erro ao tentar integrar com o SUAP. Não foi possível obter seus dados da API.</a>.";
die();
}
function create_or_update_user($userdata)
{
/*
{
"identificacao": "123456789",
"nome_social": "",
"nome_usual": "Nome Outros",
"nome_registro": "Nome Outros Nomes Sobrenome",
"nome": "Nome Sobrenome",
"primeiro_nome": "Nome",
"ultimo_nome": "Sobrenome",
"email": "[email protected]",
"email_secundario": "[email protected]",
"email_google_classroom": "[email protected]",
"email_academico": "[email protected]",
"campus": "RE",
"foto":"https://cdn.suap.ifrn.edu.br/media/fotos/75x100/159574.4t54kAqLqyPB.jpg?X-Amz-Algorithm=...&X-Amz-Credential=...&X-Amz-Date=...&X-Amz-Expires=...&X-Amz-SignedHeaders=...&X-Amz-Signature=...",
"tipo_usuario": "Servidor (Técnico-Administrativo)",
"email_preferencial": "[email protected]"
}
// Antes a foto era relativa ao baseurl do SUAP, agora é absoluta e temporária
*/
global $DB, $SESSION, $CFG;
if (!property_exists($userdata, 'identificacao')) {
echo "<p>Erro ao integrar com o SUAP.</p>";
echo "<pre style='display: None'>";
var_dump($userdata);
echo "</pre>";
die();
}
$usuario = $DB->get_record("user", ["username" => $userdata->identificacao]);
if (!$usuario) {
$usuario = (object)[
'username' => $userdata->identificacao,
'firstname' => $userdata->primeiro_nome,
'lastname' => $userdata->ultimo_nome,
'email' => $userdata->email_preferencial,
'auth' => 'suap',
'suspended' => 0,
'password' => '!aA1' . uniqid(),
'timezone' => '99',
// 'lang'=>'pt_br',
'confirmed' => 1,
'mnethostid' => 1,
'policyagreed' => 0,
'deleted' => 0,
'firstaccess' => time(),
'currentlogin' => time(),
'lastip' => $_SERVER['REMOTE_ADDR'],
'firstnamephonetic' => null,
'lastnamephonetic' => null,
'middlename' => null,
'alternatename' => null,
];
$usuario->id = \user_create_user($usuario);
}
$usuario->firstname = $userdata->primeiro_nome;
$usuario->lastname = $userdata->ultimo_nome;
$usuario->email = $userdata->email_preferencial;
$usuario->auth = 'suap';
$usuario->suspended = 0;
$usuario->profile_field_nome_apresentacao = $userdata->nome_usuaal;
$usuario->profile_field_nome_completo = property_exists($userdata, 'nome_registro') ? $userdata->nome_registro : null;
$usuario->profile_field_nome_social = property_exists($userdata, 'nome_social') ? $userdata->nome_social : null;
$usuario->profile_field_email_secundario = property_exists($userdata, 'email_secundario') ? $userdata->email_secundario : null;
$usuario->profile_field_email_google_classroom = property_exists($userdata, 'email_google_classroom') ? $userdata->email_google_classroom : null;
$usuario->profile_field_email_academico = property_exists($userdata, 'email_academico') ? $userdata->email_academico : null;
$usuario->profile_field_campus_sigla = property_exists($userdata, 'campus') ? $userdata->campus : null;
$usuario->profile_field_last_login = \json_encode($userdata);
$usuario->profile_field_tipo_usuario = property_exists($userdata, 'tipo_usuario') ? $userdata->tipo_usuario : null;
$this->usuario = $usuario;
$next = $SESSION->next_after_next;
$this->update_user_record($this->usuario->username);
if (property_exists($userdata, 'foto') && $userdata->foto) {
$this->update_picture($usuario, $userdata->foto);
}
$usuario = $DB->get_record("user", ["username" => $userdata->identificacao]);
complete_user_login($usuario);
header("Location: $next", true, 302);
}
function update_picture($usuario, $foto)
{
global $CFG, $DB;
require_once($CFG->libdir . '/gdlib.php');
$conf = get_config('auth_suap');
$tmp_filename = $CFG->tempdir . '/suapfoto' . $usuario->id;
file_put_contents($tmp_filename, file_get_contents($foto));
$usuario->imagefile = process_new_icon(context_user::instance($usuario->id, MUST_EXIST), 'user', 'icon', 0, $tmp_filename);
if ($usuario->imagefile) {
$DB->set_field('user', 'picture', $usuario->imagefile, ['id' => $usuario->id]);
}
}
function get_userinfo($username)
{
return get_object_vars($this->usuario);
}
}