webservice/library/WsScore/Account/v0.1/Service.php
Michael RICOIS b524fc01ae CS
2016-12-02 15:03:36 +01:00

1628 lines
52 KiB
PHP

<?php
require_once __DIR__ . '/Types.php';
class Account extends Scores_Ws_Server
{
/**
* Authentication
* @param string $app
* Application name (extranet | odea | starlinks)
* @param string $ip
* IPv4 ou IPv6
* @param string $browser
* User agent string
*/
public function loginAuthenticate($app, $ip = null, $browser = null)
{
switch ($app) {
case 'extranet':
$this->authApp = 'extranet';
$this->authIp = $ip;
break;
case 'odea':
$this->authApp = 'odea';
$this->authIp = $ip;
break;
case 'starlinks':
$this->authApp = 'starlinks';
$this->authIp = $ip;
break;
}
// --- Authentification des applications par login
$this->authenticate();
// --- Enregistrement authentification OK
try {
$this->conn->insert('sdv1.utilisateurs_auth_log', array(
'login' => $login,
'authenticate' => 'OK',
'ip' => $ip,
'dateInsert' => date('YmdHis'),
));
} catch (\Doctrine\DBAL\DBALException $e) {}
// --- Check App authorization - Find Service parameters
$sql = "SELECT * FROM sdv1.clients_services
WHERE IdClient = :clientId AND Code = :serviceCode";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $this->User->idClient);
$stmt->bindValue('serviceCode', $this->User->serviceCode);
$stmt->execute();
$serviceParams = $stmt->fetch(\PDO::FETCH_OBJ);
// --- Enregistrement informations navigateur uniquement si bien identifié
if ($browser !== null) {
try {
$this->conn->insert('sdv1.utilisateurs_browser_log', array(
'clientId' => $this->User->idClient,
'userId' => $this->User->id,
'service' => $this->User->serviceCode,
'login' => $this->User->login,
'userAgent' => $browser,
));
} catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
}
// Informations utiles
$auth = new LoginUser();
$auth->id = $this->User->id;
$auth->ClientId = $this->User->idClient;
$auth->ServiceCode = $this->User->serviceCode;
$auth->Login = $this->User->login;
$auth->Civilite = $this->User->civilite;
$auth->Nom = $this->User->nom;
$auth->Prenom = $this->User->prenom;
$auth->Email = $this->User->email;
$auth->Profil = $this->User->profil;
$auth->Access = $this->User->droits;
$auth->Pref = $this->User->pref;
$auth->ScoreType =$this->User->typeScore;
$auth->CguDate = $this->User->acceptationCGU;
$auth->Timeout = $this->User->timeout;
$auth->Lang = $this->User->lang;
return $auth;
}
/**
* Authentication by key
* @param string $app
*/
protected function keyAuthenticate($app)
{
//Authentification par clé - @define
$this->authApp = 'extranet';
//Reception du login
//Reception de la clé (key:md5(login + '|' + key))
//Vérification nécessaire : application - enable - date debut - date fin
}
/**
* Authentication by SSO
* @param int $client
* @param string $login
* @param string $token
* @param AuthParam[] $params
* @throws SoapFault
* @return mixed
* Retourne FALSE or HASH to connect
*/
public function ssoAuthenticate($client, $login, $token, $params)
{
/**
* login ?
* nom@mon.tld => extract nom
*/
$part = strstr($login, '@', true);
if ($part !== false) {
$login = $part;
}
/**
* Extract login from database
*/
try {
$sql = "SELECT u.id, u.login, u.idClient, u.actif, c.actif AS clientActif,
s.Service AS serviceCode FROM sdv1.utilisateurs u
JOIN sdv1.clients c ON u.idClient = c.id
LEFT JOIN sdv1.utilisateurs_service s ON u.login=s.login
WHERE u.login = :login AND c.id = :clientId";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('login', $login);
$stmt->bindValue('clientId', $client);
$stmt->execute();
$result = $stmt->fetch(\PDO::FETCH_OBJ);
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
/**
* Client disable
*/
if ( $result !== null && $result->clientActif == 'Non') {
throw new SoapFault('SSO', 'Compte client inactif'); //Client désactivé
}
/**
* No user
*/
if ( null === $result ) {
return false; //Utilisateur inexistant
}
/**
* User not activated
*/
if ( $result->actif == 0) {
throw new SoapFault('SSO', 'Utilisateur non activé'); //Utilisateur non activé
}
/**
* Process token - uniquement compatible In Extenso
*/
$key = 'rh5s4z';
$maxTime = time() + (15 * 60);
$time = 0;
$user = '';
if (count($params->item) > 0) {
foreach ($params->item as $k => $param) {
if ($param->label == 'time') {
$time = $param->value;
}
if ($param->label == 'mail') {
$user = $param->value;
}
}
}
/**
* Limite de temps
*/
if ($time > $maxTime) {
throw new SoapFault('SSO', 'Délai dépassé pour la connexion'); //Limite de temps dépassé pour la connexion
}
/**
* Check token
*/
$data = $user . '/' . $time . '/' . $key;
$internalToken = hash('sha256', $data);
//file_get_contents('inextenso.log', $internalToken .' = '. $token."\n", FILE_APPEND);
if ($internalToken == $token) {
//Generate random password
$hash = password_hash ( uniqid() , PASSWORD_BCRYPT );
try {
$this->conn->update('sdv1.utilisateurs',
array('password' => $hash), array('id' => $result->id));
}
catch (\Doctrine\DBAL\DBALException $e) {
throw new SoapFault('SSO', "Activation de l'utilisateur impossible");
}
return $hash;
}
throw new SoapFault('SSO', 'Token invalide'); //Token invalide
}
/**
* Liste des clients
* @throws SoapFault
* @return Client[]
*/
public function getClients()
{
$this->authenticate();
if ( $this->User->idClient != 1 ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
$sql = "SELECT nom AS Nom, LPAD(siren,9,0) AS Siren, LPAD(nic,5,0) AS Nic,
IF(actif='Oui',1,0) AS Actif, IF(test='Oui',1,0) AS Test
FROM sdv1.clients WHERE actif='Oui'";
$stmt = $this->conn->executeQuery($sql);
if ($stmt->rowCount() > 0) {
while ($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$client = new Client();
$client->Nom = $item->Nom;
$client->Siren = $item->Siren;
$client->Nic = $item->Nic;
$client->Actif = $item->Actif;
$client->Test = $item->Test;
$clients[] = $client;
}
}
return $clients;
}
/**
* Information client
* @param int $id
* ID du client
* @throws SoapFault
* @return Client
*/
public function getClient($id = null)
{
$this->authenticate();
if ( $id === null || $this->User->idClient != 1 ) {
$id = $this->User->idClient;
}
$sql = "SELECT nom AS Nom, LPAD(siren,9,0) AS Siren, LPAD(nic,5,0) AS Nic,
IF(actif='Oui',1,0) AS Actif, IF(test='Oui',1,0) AS Test
FROM sdv1.clients WHERE id= :id";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
if ($stmt->rowCount() == 0) {
throw new SoapFault('ERR', 'Information client introuvable.');
}
$result = $stmt->fetch(\PDO::FETCH_OBJ);
$client = new Client();
$client->Nom = $result->Nom;
$client->Siren = $result->Siren;
$client->Nic = $result->Nic;
$client->Actif = $result->Actif;
$client->Test = $result->Test;
return $client;
}
/**
* Information client avec la liste des services
* @param int $id
* ID du client
* @throws SoapFault
* @return ClientServices
*/
public function getClientServices($id = null)
{
$this->authenticate();
if ( $id === null || $this->User->idClient != 1 ) {
$id = $this->User->idClient;
}
$sql = "SELECT nom AS Nom, LPAD(siren,9,0) AS Siren, LPAD(nic,5,0) AS Nic,
IF(actif='Oui',1,0) AS Actif, IF(test='Oui',1,0) AS Test
FROM sdv1.clients WHERE id= :id";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
if ($stmt->rowCount() == 0) {
throw new SoapFault('ERR', 'Information client introuvable.');
}
$result = $stmt->fetch(\PDO::FETCH_OBJ);
$client = new ClientServices();
$client->Nom = $result->Nom;
$client->Siren = $result->Siren;
$client->Nic = $result->Nic;
$client->Actif = $result->Actif;
$client->Test = $result->Test;
//Get Services
$sql = "SELECT id, Code, Label, Editable, Active FROM sdv1.clients_services
WHERE Deleted = 0 AND Active = 1 AND IdClient = :clientId";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $id);
$stmt->execute();
$services = array();
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$clientService = new ClientServicesList();
$clientService->id = $item->id;
$clientService->Code = $item->Code;
$clientService->Label = $item->Label;
$clientService->Editable = $item->Editable;
$clientService->Active = $item->Active;
$services[] = $clientService;
}
}
$client->Services = $services;
return $client;
}
protected function getContratList()
{
//Liste des contrats, par service résumé
//Vérification des droits d'utilisation
if ( $this->User->profil != 'Administrateur' ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
}
protected function getContrat($id)
{
//Détail d'un contrat
//Vérification des droits d'utilisation
if ( $this->User->profil != 'Administrateur' ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
}
/**
* Liste des services
* @param string $client
* Id client
* @return ServiceList[]
*/
public function getServiceList($client = null)
{
//Liste des services
$this->authenticate();
if ( $client === null ) {
$client = $this->User->idClient;
}
// Uniquement si l'utilisateur est administrateur et dans le service DEFAULT
if ( !in_array($this->User->profil, array('Administrateur', 'SuperAdministrateur')) ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
try {
$sql = "SELECT * FROM sdv1.clients_services WHERE Deleted = 0 AND IdClient = :clientId";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $client);
$stmt->execute();
} catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
$services = array();
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$service = new ServiceList();
$service->id = $item->id;
$service->IdClient = $item->IdClient;
$service->Code = $item->Code;
$service->Label = $item->Label;
$service->TypeCompte = $item->TypeCompte;
$service->TypeAcces = $item->TypeAcces;
$service->TypeScore = $item->TypeScore;
$service->Timeout = $item->Timeout;
$service->Editable = $item->Editable;
$service->Active = $item->Active;
$service->DateInsert = $item->DateInsert;
$service->DateUpdate = $item->DateUpdate;
$services[] = $service;
}
}
return $services;
}
/**
* Détail d'un service
* @param string $code
* @throws SoapFault
* @return Service
*/
public function getService($code)
{
$this->authenticate();
$client = $this->User->idClient;
// Détail d'un service
try {
$sql = "SELECT * FROM sdv1.clients_services
WHERE Deleted = 0 AND IdClient = :clientId AND Code = :serviceCode";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $client);
$stmt->bindValue('serviceCode', $code);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() == 0) {
throw new SoapFault('ERR', 'Service introuvable.');
}
$result = $stmt->fetch(\PDO::FETCH_OBJ);
$output = new Service();
$output->id = $result->id;
$output->IdClient = $client;
$output->Code = $result->Code;
$output->Label = $result->Label;
$output->TypeCompte = $result->TypeCompte;
$output->TypeAcces = $result->TypeAcces;
$output->TypeScore = $result->TypeScore;
$output->Timeout = $result->Timeout;
$output->Editable = $result->Editable;
$output->Active = $result->Active;
$output->DateInsert = $result->DateInsert;
$output->DateUpdate = $result->DateUpdate;
$serviceCode = $result->Code;
// Droits
$output->Acces = array();
try {
$sql = "SELECT * FROM sdv1.clients_services_droits
WHERE IdClient = :clientId AND Service = :serviceCode";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $client);
$stmt->bindValue('serviceCode', $serviceCode);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$acces = new Acces();
$acces->Code = strtoupper($item->Acces);
$acces->Label = $this->listeDroits[strtoupper($item->Acces)];
$output->Acces[] = $acces;
}
}
// IP
$output->IP = array();
try {
$sql = "SELECT * FROM sdv1.clients_services_ip
WHERE IdClient = :clientId AND Service = :serviceCode";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $client);
$stmt->bindValue('serviceCode', $serviceCode);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$output->IP[] = $item->IP;
}
}
return $output;
}
protected function getServiceConso($id){}
protected function getServiceLogByFile(){}
/**
* Modification des éléments d'un service par un administrateur
* @param string $code Element à modifier (label | active | delete)
* @param mixed $value Valeur
* @param string $id Id du service
* @throws SoapFault
* @return boolean
*/
public function setService($code, $value, $id)
{
$this->authenticate();
// --- Vérification des droits d'utilisation
if ( !in_array($this->User->profil, array('Administrateur', 'SuperAdministrateur')) ) {
throw new SoapFault('ERR', "Accès non authorisé");
}
$client = $this->User->idClient;
// --- Définir les éléments du service
try {
$sql = "SELECT * FROM sdv1.clients_services
WHERE Deleted = 0 AND IdClient = :clientId AND id = :id";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $client);
$stmt->bindValue('id', $id);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() == 0) {
throw new SoapFault('ERR', "Service introuvable.");
}
$result = $stmt->fetch(\PDO::FETCH_OBJ);
if ( $result->Editable == 0) {
throw new SoapFault('MSG', "Impossible d'éditer le service");
}
$data = json_decode($data);
$dataToUpdate = array();
// --- Suppression d'un service
if ( $code == 'delete' && $value == 1 ) {
$dataToUpdate = array('Deleted' => 1);
}
if ( $code == 'active' && in_array($value, array(0,1)) ) {
$dataToUpdate = array('Active' => $value);
}
if ( $code == 'label' && is_string($value) ) {
$dataToUpdate = array('Label' => $value);
}
if (($dataToUpdate) > 0) {
$dataToUpdate['DateUpdate'] = date('YmdHis');
try {
$this->conn->update('sdv1.clients_services', $dataToUpdate, array('id' => $id));
return true;
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
}
return false;
}
/**
* Définit les paramètres d'un service
* @param string $type
* Type de ressource (acces, ip)
* @param string $value
* Valeur à ajouter
* @param string $id
* Id du service
* @param boolean $delete
* Marqueur de suppression
* @throws SoapFault
* @return boolean
*/
public function setServiceParam($type, $value, $id, $delete = false)
{
// --- Définir un paramètre du service
$this->authenticate();
// --- Vérification des droits d'utilisation
if ( !in_array($this->User->profil, array('Administrateur', 'SuperAdministrateur')) ) {
throw new SoapFault('ERR', "Accès non authorisé");
}
$client = $this->User->idClient;
try {
$sql = "SELECT * FROM sdv1.clients_services
WHERE Deleted = 0 AND IdClient = :clientId AND id = :id";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $client);
$stmt->bindValue('id', $id);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() == 0) {
throw new SoapFault('ERR', "Service introuvable.");
}
$result = $stmt->fetch(\PDO::FETCH_OBJ);
if ( $result->Editable == 0) {
throw new SoapFault('MSG', "Impossible d'éditer le service");
}
// --- Acces
if ($type == 'acces') {
if (array_key_exists($value, $this->listeDroits)) {
if ($delete === true) {
try {
$row = $this->conn->delete('sdv1.clients_services_droits', array(
'IdClient' => $result->IdClient,
'Service' => $result->Code,
'Acces' => $value,
));
if ($row > 0) {
return true;
}
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
}
else {
try {
$row = $this->conn->insert('sdv1.clients_services_droits', array(
'IdClient' => $result->IdClient,
'Service' => $result->Code,
'Acces' => $value,
'DateAdded' => date('YmdHis')
));
if ($row > 0 ) {
return true;
}
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
}
}
}
// --- IP
if ($type == 'ip') {
if ($delete) {
$row = $this->conn->delete('sdv1.clients_services_ip', array('id' => $id));
} else {
//Control de la plage IP ou de l'IP
$validate = new Zend_Validate_Ip();
if ( $validate->isValid($value) ) {
$this->conn->insert('sdv1.clients_services_ip', array(
'IdClient' => $result->IdClient,
'Service' => $result->Code,
'IP' => $value,
'DateAdded' => date('YmdHis'),
));
}
}
if ($row) {
return true;
}
}
return false;
}
/**
* Liste des utilisateurs
* @param int $actif (0|1)
* @param string $service Code du service
* @param string $client Id du client
* @return UserList[]
*/
public function getUserList($actif = null, $service = null, $client = null)
{
// Liste des utilisateurs - filtre au service
$this->authenticate();
if ( $client === null ) {
$client = $this->User->idClient;
}
// Administrateur
if ( !in_array($this->User->profil, array('Administrateur', 'SuperAdministrateur')) ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
// Administrateur d'un service
if ( $this->User->Service != '' && $this->User->Service !== null && $this->User->Service !== 'DEFAULT' ) {
$service = $this->User->Service;
}
try {
$qb = $this->conn->createQueryBuilder();
$qb->select(array('u.id', 'u.idClient', 'u.login', 'u.email', 'u.civilite', 'u.nom',
'u.prenom', 'u.actif', 'u.deleted', 's.Service', 'sd.Label'))
->leftJoin('u', 'sdv1.utilisateurs_service', 's', 'u.login=s.login')
->leftJoin('u', 'sdv1.clients_services', 'sd', 'sd.Code=s.Service')
->from('sdv1.utilisateurs', 'u')
->where('u.idClient = :clientId');
if ( $actif !== null && in_array($actif, array(0,1)) ) {
$qb->andWhere('u.actif = :actif')->setParameter('actif', $actif);
}
$qb->andWhere('u.deleted = 0');
if ($service == 'DEFAULT') {
$qb->andWhere("(s.Service IS NULL) OR (s.Service='DEFAULT' AND sd.idClient=:clientId)");
} else {
$qb->andWhere('sd.Code = :serviceCode')->setParameter('serviceCode', $service);
}
$qb->setParameter('clientId', $client);
$stmt = $qb->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
$users = array();
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$user = new UserList();
$user->id = $item->id;
$user->IdClient = $item->idClient;
$user->ServiceCode = $item->Service;
$user->ServiceLabel = $item->Label;
$user->Login = $item->login;
$user->Email = $item->email;
$user->Civilite = $item->civilite;
$user->Nom = $item->nom;
$user->Prenom = $item->prenom;
$user->Enable = $item->actif;
$user->Delete = $item->deleted;
$users[] = $user;
}
}
return $users;
}
protected function getUsersFile($actif = null, $service = null, $client = null)
{
}
/**
* Information Utilisateur
* @param string $id
* ID de l'utilisateur
* @throws SoapFault
* @return User
*/
public function getUser($id = null)
{
//Détail d'un utilisateur
$this->authenticate();
$idClient = $this->User->idClient;
if ( $id === null ) {
$id = $this->User->id;
}
// Get Data
try {
$qb = $this->conn->createQueryBuilder();
$qb->select('*')
->leftJoin('u', 'sdv1.utilisateurs_service', 's', 'u.login=s.login')
->leftJoin('u', 'sdv1.clients_services', 'sd', 'sd.Code=s.Service')
->from('sdv1.utilisateurs', 'u')
->where('u.id = :id');
$qb->setParameter('id', $id);
$stmt = $qb->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() == 0) {
throw new SoapFault('ERR', 'Utilisateur inexistant !');
}
$user = $stmt->fetch(\PDO::FETCH_OBJ);
// Service
$serviceCode = 'DEFAULT';
$serviceLabel = 'Standard';
if ( $user->Service !== null ) {
$serviceCode = $user->Service;
$serviceLabel = $user->ServiceLabel;
}
$output = new User();
$output->id = $user->id;
$output->IdClient = $user->idClient;
$output->ServiceCode = $serviceCode;
$output->ServiceLabel = $serviceLabel;
$output->Login = $user->login;
$output->Email = $user->email;
$output->Civilite = $user->civilite;
$output->Nom = $user->nom;
$output->Prenom = $user->prenom;
$output->Enable = $user->actif;
$output->Delete = $user->deleted;
// Droits utilisateurs surcharge les droits du service
if (strlen(trim($user->droits)) > 0) {
$droits = explode(' ', $user->droits);
foreach ($droits as $item) {
$acces = new Acces();
$acces->Code = strtoupper($item);
$acces->Label = $this->listeDroits[strtoupper($item)];
$output->Acces[] = $acces;
}
if (count($output->Acces) > 0) {
$output->AccesOverride = true;
}
}
// Service - Droits
if (count($output->Acces) == 0) {
try {
$sql = "SELECT * FROM sdv1.clients_services_droits
WHERE IdClient = :clientId AND Service = :serviceCode";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $idClient);
$stmt->bindValue('serviceCode', $serviceCode);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$acces = new Acces();
$acces->Code = strtoupper($item->Acces);
$acces->Label = $this->listeDroits[strtoupper($item->Acces)];
$output->Acces[] = $acces;
}
}
}
// Service - IP
try {
$sql = "SELECT * FROM sdv1.clients_services_ip
WHERE IdClient = :clientId AND Service = :serviceCode";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $idClient);
$stmt->bindValue('serviceCode', $serviceCode);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() > 0) {
while ($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$output->IP[] = $item;
}
}
return $output;
}
protected function getUserActivity($id = null)
{
//Retourner la liste des dernières connexions
}
/**
* Emails secondaires
* @param int $id
* @throws SoapFault
* @return string[]
*/
public function getUserEmail($id)
{
$this->authenticate();
$idClient = $this->User->idClient;
try {
$sql = "SELECT * FROM sdv1.utilisateurs_emails
WHERE IdClient = :clientId AND id = :id";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('clientId', $idClient);
$stmt->bindValue('id', $id);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
$emails = array();
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$email = new Email();
$email->id = $item->id;
$email->value = $item->email;
$email->valid = $item->valid;
$email->monitor = $item->monitor;
$emails[] = $email;
}
}
return $emails;
}
/**
* Log des consultations
* @param string $month AAAAMM
* @param string $item
* Code de l'élément
* @param integer $p
* @param integer $limit
* @throws SoapFault
* @return UserLog
*/
public function getUserLog($month, $item, $p=0, $limit=50)
{
$this->authenticate();
if (empty($p)) {
$p = 0;
}
if (empty($limit)) {
$limit = 50;
}
$selectedYear = date('Y');
$selectedMonth = date('m');
$item = 'identite';
// --- Get total
try {
$sql = "SELECT COUNT(*) AS NB FROM sdv1.logs
WHERE login = :login AND page = :page AND dateHeure BETWEEN :begin AND :end";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('login', $this->User->login);
$stmt->bindValue('page', $item);
$stmt->bindValue('begin', $selectedYear.'-'.$selectedMonth.'-00 00:00:00');
$stmt->bindValue('end', $selectedYear.'-'.$selectedMonth.'-31 23:59:59');
$stmt->execute();
$totalResult = $stmt->fetch(\PDO::FETCH_OBJ);
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
$output = new UserLog();
$output->Total = $totalResult->NB;
$output->List = array();
if ($totalResult->NB > 0) {
// --- Get Row
try {
$sql = "SELECT LPAD(siren,9,0) AS siren, LPAD(nic,5,0) AS nic, raisonSociale, dateHeure
FROM sdv1.logs
WHERE login = :login AND page = :page AND dateHeure BETWEEN :begin AND :end
ORDER BY dateHeure DESC LIMIT $p, $limit";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('login', $this->User->login);
$stmt->bindValue('page', $item);
$stmt->bindValue('begin', $selectedYear.'-'.$selectedMonth.'-00 00:00:00');
$stmt->bindValue('end', $selectedYear.'-'.$selectedMonth.'-31 23:59:59');
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() > 0) {
while($l = $stmt->fetch(\PDO::FETCH_OBJ)) {
$struct = new UserLogItem();
$companyId = $l->siren;
if (intval($l->nic) > 0) {
$companyId.= $l->nic;
}
$struct->CompanyId = $companyId;
$struct->CompanyType = 'SIREN';
$struct->CompanyName = $l->raisonSociale;
$struct->Date = $l->dateHeure;
$output->List[] = $struct;
}
}
}
return $output;
}
protected function getUserLogFile($id){}
/**
* Company User History (10 last)
* @param int $id
* @param int $limit
* @return UserLogItem[]
*/
public function getUserHistory($id = null, $limit = 10)
{
$this->authenticate();
$selectedYear = date('Y');
$selectedMonth = date('m');
$output = array();
// --- Generate SQL
try {
$logSubquery = "SELECT siren, MAX(dateHeure) AS MaxDateHeure FROM logs WHERE login='".$this->User->login."' AND page='identite' GROUP BY siren";
$logSql = "SELECT LPAD(x.siren,9,0) AS siren, LPAD(x.nic,5,0) AS nic, x.raisonSociale, x.dateHeure FROM logs x ".
"JOIN (".$logSubquery.") y ON y.siren = x.siren AND y.MaxDateHeure = x.dateHeure ".
"ORDER BY x.dateHeure DESC LIMIT 0,".$limit;
$stmt = $this->conn->executeQuery($logSql);
while ($l = $stmt->fetch(\PDO::FETCH_OBJ)) {
$struct = new UserLogItem();
$companyId = $l->siren;
if (intval($l->nic) > 0) {
$companyId.= $l->nic;
}
$struct->CompanyId = $companyId;
$struct->CompanyType = 'SIREN';
$struct->CompanyName = $l->raisonSociale;
$struct->Date = $l->dateHeure;
$output[] = $struct;
}
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
return $output;
}
/**
* Log d'authentification
* @param string $month Date (AAAAMM)
* @param string $type (OK, KO)
* @param integer $p
* @param integer $limit
* @return AuthLog
*/
public function getAuthLog($month, $type, $p=0, $limit=20)
{
$this->authenticate();
$limit = ($limit > 0) ? $limit : 20;
$p = ($p > 0) ? $p : 0;
if ($month === null) {
$month = date('Y-m');
}
$dateStart = $month.'-01 00:00:00';
$dateEnd = $month.'-31 23:59:59';
// --- Get total
try {
$sql = "SELECT COUNT(*) AS NB FROM sdv1.utilisateurs_auth_log
WHERE login = :login AND authenticate = 'OK' AND dateInsert BETWEEN :begin AND :end";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('login', $this->User->login);
$stmt->bindValue('begin', $dateStart);
$stmt->bindValue('end', $dateEnd);
$stmt->execute();
$totalResult = $stmt->fetch(\PDO::FETCH_OBJ);
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
$output = new AuthLog();
$output->Total = $totalResult->NB;
$output->List = array();
if ($totalResult->NB > 0) {
// --- Get Row
try {
$sql = "SELECT IP, dateInsert AS Date FROM sdv1.utilisateurs_auth_log
WHERE login = :login AND authenticate = 'OK' AND dateInsert BETWEEN :begin AND :end
ORDER BY dateInsert DESC";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('login', $this->User->login);
$stmt->bindValue('begin', $dateStart);
$stmt->bindValue('end', $dateEnd);
$stmt->execute();
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($stmt->rowCount() > 0) {
while($item = $stmt->fetch(\PDO::FETCH_OBJ)) {
$struct = new AuthLogItem();
$struct->IP = $item->IP;
$struct->Date = $item->Date;
$output->List[] = $struct;
}
}
}
return $output;
}
/**
* Paramétrage d'un utilisateur
* @param string $data
* @param int $id
* @throws SoapFault
* @return boolean
*/
public function setUser($data, $id = null)
{
$this->authenticate();
// --- Vérification des droits de création d'utilisateur
if ( /*$this->User->id != $id ||*/ !in_array($this->User->profil,
array('SuperAdministrateur', 'Administrateur')) ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
$values = json_decode($data);
// --- Création
if ( $id === null ) {
$userData = array(
'idClient' => $values->idClient,
'login' => trim($values->login),
'email' => strtolower(trim($values->email)),
'password' => '',
'actif' => 1,
'deleted' => 0,
'typeCompte' => 'PROD',
'civilite' => $values->civilite,
'nom' => trim($values->nom),
'prenom' => trim($values->prenom),
'profil' => 'Utilisateur',
'droits' => '',
'referenceParDefaut' => '',
'nbReponses' => 10,
'lang' => 'fr',
'formatMail' => 'txt2',
'lienExtranetMail' => 0,
'lienSurvFic' => 0,
'idSurvFic' => '',
'loginCptSurvFic' => '',
'listeEven' => '',
);
// --- Utilisateur existant
$sql = "SELECT id FROM sdv1.utilisateurs WHERE login = :login";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('login', $values->login);
$stmt->execute();
if ($stmt->rowCount() > 0) {
throw new SoapFault('ERR', "User exist");
}
// --- Prepare data to insert
foreach ($values as $key => $value) {
if (array_key_exists($key, $userData)) {
$userData[$key] = trim($value);
}
}
$userData['dateInsert'] = date('YmdHis');
try {
$this->conn->insert('sdv1.utilisateurs', $userData);
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
//Définition du service
try {
$this->conn->insert('sdv1.utilisateurs_service', array(
'login' => $infos->login,
'idClient'=> $infos->idClient,
'Service'=> $infos->Service
));
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
return true;
}
// --- Modification
else {
$userData = array();
$sql = "SELECT id FROM sdv1.utilisateurs WHERE id = :id";
$stmt = $this->conn->prepare($sql);
$stmt->bindValue('id', $id);
$stmt->execute();
if ($stmt->rowCount() == 0) {
throw new SoapFault('ERR', "User doesn't exist");
}
// --- Prepare data to update
foreach ($values as $key => $value) {
$userData[$key] = trim($value);
}
try {
$nb = $this->conn->update('sdv1.utilisateurs', $userData, array('id' => $id));
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ($nb > 0) {
return true;
}
return false;
}
}
/**
* Création de compte client partenaire
* @param string $data
* @return boolean
*/
public function setUserSSO ( $data )
{
//Check IP application
/*$ip = $_SERVER['REMOTE_ADDR'];
if ( !in_array($ip, $this->listApplicationIp) ) {
$this->sendError('0901');
}*/
//Decodage
$infos = json_decode($data);
$userData = array(
'idClient' => null,
'login' => null,
'email' => '',
'password' => '',
'actif' => 0,
'deleted' => 0,
'typeCompte' => 'PROD',
'filtre_ip' => '',
'civilite' => 'M',
'nom' => '',
'prenom' => '',
'raisonSociale' => '',
'siret' => '000000000',
'adrNum' => null,
'adrIndRep' => null,
'adrTypeVoie' => null,
'adrLibVoie' => '',
'adrCp' => null,
'adrVille' => null,
'adrComp' => '',
'tel' => '',
'fax' => null,
'mobile' => null,
'pref' => '',
'profil' => 'Utilisateur',
'dateInscription' => '0000-00-00 00:00:00',
'dateValidation' => '0000-00-00 00:00:00',
'nombreConnexions' => '0',
'dateDerniereConnexion' => '0000-00-00 00:00:00',
'droits' => '',
'referenceParDefaut' => '',
'nbReponses' => '020',
'lang' => null,
'formatMail' => 'txt1',
'lienExtranetMail' => 0,
'lienSurvFic' => 0,
'idSurvFic' => '',
'loginCptSurvFic' => '',
'listeEven' => '',
'dateDebutCompte' => null,
'dateFinCompte' => null,
'maxFicheId' => null,
'accesWS' => '0',
'rechRefType' => 'UTI',
'acceptationCGU' => null,
);
//Définition du service
try {
$this->conn->insert('sdv1.utilisateurs_service', array(
'login' => $infos->login,
'idClient'=> $infos->idClient,
'Service'=> $infos->Service
));
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
//Prepare data to insert
foreach ($infos as $key => $value) {
if (array_key_exists($key, $userData)) {
$userData[$key] = $value;
}
}
$userData['password'] = password_hash ( uniqid() , PASSWORD_BCRYPT );
$userData['dateInsert'] = date('YmdHis');
$userData['dateDebutCompte'] = date('YmdHis');
//Insertion dans la base de données
try {
$this->conn->insert('sdv1.utilisateurs', $userData);
}
catch (\Doctrine\DBAL\DBALException $e) {
return false;
}
return true;
}
protected function setUserService($service, $id)
{
//Déplacer un utilisateur de service - ne pas activer tout de suite
}
public function setUserEmail($id, $email, $op = null)
{
//Which operation
switch ( $op ) {
//Ajouter un email secondaire
case null:
case 'add':
break;
//Supprimer un email secondaire
case 'del':
break;
}
}
/**
* Change password
* @param string $password
* @param int $id
* @throws SoapFault
* @return boolean
*/
public function setUserPassword($password, $id = null)
{
$this->authenticate();
if ( $id === null ) {
$id = $this->User->id;
}
elseif ( $id !== null && $this->User->profil != 'Administrateur' ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
//@todo : Prise en compte de la version
//Changer le mot de passe
$result = $this->conn->update('sdv1.utilisateurs',
array('password'=>$password), array('id' => $id));
if ( $result == 1 ) {
return true;
}
return false;
}
/**
* Catégorie et Accès
* @return AccesCategory[]
*/
public function getCategory()
{
$output = array();
foreach ($this->listeCategory as $code => $desc) {
$c = new AccesCategory();
$c->Code = $code;
$c->Label = $desc['label'];
$c->Acces = $desc['droits'];
$output[] = $c;
}
return $output;
}
/**
* Liste des acces
* @return Acces[]
*/
public function getAccess()
{
$droits = $this->listeDroits;
$list = array();
foreach ($droits as $k => $v) {
$acces = new Acces();
$acces->Code = $k;
$acces->Label = $v;
$list[] = $acces;
}
return $list;
}
protected function getPref()
{
//Liste des préférences - Code, Label, Description, Values
}
protected function setPref(){}
/**
* Acceptation des CGUs
* @param string $app
* @throws SoapFault
* @return boolean
*/
public function setCGU($app = null)
{
$this->authenticate();
$id = $this->User->id;
try {
$result = $this->conn->update('sdv1.utilisateurs', $data, array('id' => $id));
}
catch (\Doctrine\DBAL\DBALException $e) {
if ($this->User->idClient == 1) {
throw new SoapFault('ERR', $e->getMessage());
} else {
throw new SoapFault('ERR', "Application error");
}
}
if ( 1 == $result ) {
return true;
}
return false;
}
protected function setUserEnable($id)
{
//Un administrateur force l'activation d'un utilisateur ?
//actif = 1
/**
* L'utilisateur n'a pas reçu ou a perdu l'email avec son mot de passe, vous pouvez activez sont compte
* (attention son email ne sera pas validé, et certaines prestations nécessitant un email valide ne peuvent fonctionner)
*/
}
protected function setLinkValidation()
{
//Génération d'un hash pour la validation email
//Database : utilisateurs_validationh [id, ]
//utilisateurs_email => dateValidation + surveillance
//Envoi email avec lien de validation
}
protected function setUserValidation($id)
{
//Un utilisateur valide son compte pour la première connexion et déclenche l'envoi de validation de l'email
//Doit-on demander un nouveau mot de passe ? Est ce que le mot de passe a été générer et envoyé par email .
//actif = 0
//dateValidation pour email
//Envoi email de validation
//lien + email + login + date + hash ('sha256', string ) => string {idClient}{login}{email}{AAAAMMJJ}
}
protected function setUserEmailValidation($id)
{
//Validation d'un email
//Email secondaire ajouté marqueur dateValidation
}
/**
* Un SuperAdministrateur devenir un utilisateur (pour les tests)
* @param int $id
* @throws SoapFault
*/
protected function setAdminAs($id)
{
$this->authenticate();
//Vérification des droits d'utilisation
if ( $this->User->profil != 'SuperAdministrateur' ) {
throw new SoapFault('ERR', 'Accès non authorisé');
}
// Pour les SuperAdministrateur, voir l'application comme un login (id)
}
}