Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class APIClient {
- function __construct() {
- $this->url = "http://apiserver.local/usuario/autenticar";
- }
- function auth() {}
- private function autenticar() {
- $ch = curl_init($this->url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
- curl_setopt($ch, CURLOPT_HEADER, True);
- $response = curl_exec($ch);
- curl_close($ch);
- return $response;
- }
- private function solicitar_autenticacion() {
- $response = $this->autenticar();
- $regex = "/WWW-Authenticate(.)+\n/";
- preg_match($regex, $response, $coincidencias);
- $auth_digest = str_replace("WWW-Authenticate: Digest ", "", $coincidencias[0]);
- $array_auth = explode(",", $auth_digest);
- return $array_auth;
- }
- private function parsear_respuesta_autenticacion($array_auth) {
- $this->terms_auth = array();
- foreach($array_auth as $term) {
- list($name, $value) = explode("=", $term);
- $this->terms_auth[$name] = str_replace(['"', "\r\n"], "", $value);
- }
- }
- private function solicitar_autorizacion($username, $password) {
- $A1 = hash('md5', "$username:{$this->terms_auth['realm']}:$password");
- $A2 = "POST:/usuario/autenticar";
- $info_extra_header= hash('md5', "$A1:{$this->terms_auth['nonce']}:$A2");
- $string = 'Authorization: Digest username="%s",realm="%s",nonce="%s",opaque="%s",uri="%s",response="%s"';
- $request = sprintf(
- $string,
- $username,
- $this->terms_auth['realm'],
- $this->terms_auth['nonce'],
- $this->terms_auth['opaque'],
- '/usuario/autenticar',
- $info_extra_header
- );
- # return $this->acceder_a_recurso_restringido($request); # ¿solucion? Agregada 5/9 carlos. fallo pantalla en blanco
- return $request;
- }
- private function acceder_a_recurso_restringido($request) {
- $ch = curl_init($this->url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [$request]);
- $response = curl_exec($ch);
- curl_close($ch);
- return $response;
- }
- function autorizar($url, $username, $password) {
- $this->url = $url;
- $array_auth = $this->solicitar_autenticacion();
- $this->parsear_respuesta_autenticacion($array_auth);
- $request = $this->solicitar_autorizacion($username, $password);
- }
- function get($url) {
- $str = "nonce=a1b2c3,opaque=abc123";
- $request = "SessionID: $str";
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [$request]);
- $response = curl_exec($ch);
- curl_close($ch);
- return $response;
- }
- # comentado: 6/9 eugenia: por si se llega a necesitar
- # function get_restricted($url) { $this->url = $url;
- # $string = 'SessionID: nonce="%s",opaque="%s"';
- # $request = sprintf(
- # $string,
- # $this->terms_auth['nonce'],
- # $this->terms_auth['opaque']
- # );
- # return $this->acceder_a_recurso_restringido($request);
- # }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement