Subversion Repositories Applications.wikini

Rev

Rev 65 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 65 Rev 66
1
<?php
1
<?php
-
 
2
 
-
 
3
// Remplacement de apache_request_headers pour les vieux serveurs
-
 
4
// http://stackoverflow.com/questions/2916232/call-to-undefined-function-apache-request-headers
-
 
5
if(!function_exists('apache_request_headers')) {
-
 
6
	function apache_request_headers() {
-
 
7
		// Based on: http://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers
-
 
8
		$arrCasedHeaders = array(
-
 
9
				// HTTP
-
 
10
				'Dasl'             => 'DASL',
-
 
11
				'Dav'              => 'DAV',
-
 
12
				'Etag'             => 'ETag',
-
 
13
				'Mime-Version'     => 'MIME-Version',
-
 
14
				'Slug'             => 'SLUG',
-
 
15
				'Te'               => 'TE',
-
 
16
				'Www-Authenticate' => 'WWW-Authenticate',
-
 
17
				// MIME
-
 
18
				'Content-Md5'      => 'Content-MD5',
-
 
19
				'Content-Id'       => 'Content-ID',
-
 
20
				'Content-Features' => 'Content-features',
-
 
21
		);
-
 
22
		$arrHttpHeaders = array();
-
 
23
 
-
 
24
		foreach($_SERVER as $strKey => $mixValue) {
-
 
25
			if('HTTP_' !== substr($strKey, 0, 5)) {
-
 
26
				continue;
-
 
27
			}
-
 
28
 
-
 
29
			$strHeaderKey = strtolower(substr($strKey, 5));
-
 
30
 
-
 
31
			if(0 < substr_count($strHeaderKey, '_')) {
-
 
32
				$arrHeaderKey = explode('_', $strHeaderKey);
-
 
33
				$arrHeaderKey = array_map('ucfirst', $arrHeaderKey);
-
 
34
				$strHeaderKey = implode('-', $arrHeaderKey);
-
 
35
			}
-
 
36
			else {
-
 
37
				$strHeaderKey = ucfirst($strHeaderKey);
-
 
38
			}
-
 
39
 
-
 
40
			if(array_key_exists($strHeaderKey, $arrCasedHeaders)) {
-
 
41
				$strHeaderKey = $arrCasedHeaders[$strHeaderKey];
-
 
42
			}
-
 
43
 
-
 
44
			$arrHttpHeaders[$strHeaderKey] = $mixValue;
-
 
45
		}
-
 
46
		return $arrHttpHeaders;
-
 
47
	}
-
 
48
}
-
 
49
 
2
class identificationSso {
50
class identificationSso {
3
 
51
 
4
	private $wiki = null;
52
	private $wiki = null;
5
	private $config = null;
53
	private $config = null;
6
 
54
 
7
	private $cookie_tentative_identification = "";
55
	private $cookie_tentative_identification = "";
8
	private $delai_tentative_identification = 60;
56
	private $delai_tentative_identification = 60;
9
	
57
	
10
	private $auth_header = 'Authorization';
58
	private $auth_header = 'Authorization';
11
 
59
 
12
	public function __construct($wiki) {
60
	public function __construct($wiki) {
13
		$this->wiki = $wiki;
61
		$this->wiki = $wiki;
14
		$this->config = $wiki->config;
62
		$this->config = $wiki->config;
15
		$this->auth_header = !empty($this->config['sso_auth_header']) ? $this->config['sso_auth_header'] : $this->auth_header;
63
		$this->auth_header = !empty($this->config['sso_auth_header']) ? $this->config['sso_auth_header'] : $this->auth_header;
16
		$this->cookie_tentative_identification = 'wikini_sso_tentative_identification';
64
		$this->cookie_tentative_identification = 'wikini_sso_tentative_identification';
17
	}
65
	}
18
 
66
 
19
	function getToken() {
67
	function getToken() {
20
		// Premier essai, dans le header
68
		// Premier essai, dans le header
21
		$headers = @apache_request_headers();
69
		$headers = @apache_request_headers();
22
		$token = !empty($headers['Authorization']) ? $headers['Authorization'] : null;
70
		$token = !empty($headers['Authorization']) ? $headers['Authorization'] : null;
23
		// Eventuellement, le jeton a pu être passé dans un header non standard, comme dans 
71
		// Eventuellement, le jeton a pu être passé dans un header non standard, comme dans 
24
		// le cas où le header Authorization est supprimé par le mod cgi d'apache
72
		// le cas où le header Authorization est supprimé par le mod cgi d'apache
25
		// Dans ce cas là on vérifie aussi dans un header alternatif si celui ci a été renseigné
73
		// Dans ce cas là on vérifie aussi dans un header alternatif si celui ci a été renseigné
26
		if($token == null && $this->auth_header != 'Authorization') {
74
		if($token == null && $this->auth_header != 'Authorization') {
27
			$token = !empty($headers[$this->auth_header]) ? $headers[$this->auth_header] : null;
75
			$token = !empty($headers[$this->auth_header]) ? $headers[$this->auth_header] : null;
28
		}
76
		}
29
 
77
 
30
		// Sinon dans $_REQUEST ?
78
		// Sinon dans $_REQUEST ?
31
		if($token == null) {
79
		if($token == null) {
32
			$token = !empty($_REQUEST['Authorization']) ? $_REQUEST['Authorization'] : null;
80
			$token = !empty($_REQUEST['Authorization']) ? $_REQUEST['Authorization'] : null;
33
		}
81
		}
34
		
82
		
35
		// Sinon dans $_COOKIE ?
83
		// Sinon dans $_COOKIE ?
36
		if($token == null) {
84
		if($token == null) {
37
			$token = !empty($_COOKIE['tb_auth']) ? $_COOKIE['tb_auth'] : null;
85
			$token = !empty($_COOKIE['tb_auth']) ? $_COOKIE['tb_auth'] : null;
38
		}
86
		}
39
 
87
 
40
		return $token;
88
		return $token;
41
	}
89
	}
42
 
90
 
43
	function decoderToken($token) {
91
	function decoderToken($token) {
44
		$token_parts = explode('.', $token);
92
		$token_parts = explode('.', $token);
45
		return json_decode(base64_decode($token_parts[1]), true);
93
		return json_decode(base64_decode($token_parts[1]), true);
46
	}
94
	}
47
 
95
 
48
	function getPage() {
96
	function getPage() {
49
		return !empty($this->wiki->page) ? $this->wiki->page['tag'] : 'PagePrincipale';
97
		return !empty($this->wiki->page) ? $this->wiki->page['tag'] : 'PagePrincipale';
50
	}
98
	}
51
 
99
 
52
	// http://stackoverflow.com/questions/1251582/beautiful-way-to-remove-get-variables-with-php?lq=1
100
	// http://stackoverflow.com/questions/1251582/beautiful-way-to-remove-get-variables-with-php?lq=1
53
	function supprimerUrlVar($url, $var) {
101
	function supprimerUrlVar($url, $var) {
54
		 return rtrim(preg_replace('/([?&])'.$var.'=[^&]+(&|$)/','$1',$url), '&?');
102
		 return rtrim(preg_replace('/([?&])'.$var.'=[^&]+(&|$)/','$1',$url), '&?');
55
	}
103
	}
56
 
104
 
57
	function getInfosCookie() {
105
	function getInfosCookie() {
58
		$infos = null;
106
		$infos = null;
59
		if(!empty($_COOKIE[$this->cookie_tentative_identification])) {
107
		if(!empty($_COOKIE[$this->cookie_tentative_identification])) {
60
			$infos = json_decode($_COOKIE[$this->cookie_tentative_identification], true);
108
			$infos = json_decode($_COOKIE[$this->cookie_tentative_identification], true);
61
		}
109
		}
62
		return $infos;
110
		return $infos;
63
	}
111
	}
64
 
112
 
65
	function setInfosCookie($infos) {
113
	function setInfosCookie($infos) {
66
		$infos['expire'] = !empty($infos['expire']) ? $infos['expire'] : 0;
114
		$infos['expire'] = !empty($infos['expire']) ? $infos['expire'] : 0;
67
		setcookie($this->cookie_tentative_identification, json_encode($infos), $infos['expire'], $this->wiki->CookiePath);
115
		setcookie($this->cookie_tentative_identification, json_encode($infos), $infos['expire'], $this->wiki->CookiePath);
68
	}
116
	}
69
 
117
 
70
	function verifierEtInsererUtilisateurParJeton($jeton_rafraichi) {
118
	function verifierEtInsererUtilisateurParJeton($jeton_rafraichi) {
71
		if(!empty($jeton_rafraichi['session']) && $jeton_rafraichi['session'] == true) {
119
		if(!empty($jeton_rafraichi['session']) && $jeton_rafraichi['session'] == true) {
72
			$token_decode = $this->decoderToken($jeton_rafraichi['token']);
120
			$token_decode = $this->decoderToken($jeton_rafraichi['token']);
73
			
121
			
74
			$nom_wiki = $token_decode['nomWiki'];
122
			$nom_wiki = $token_decode['nomWiki'];
75
			$courriel = $token_decode['sub'];
123
			$courriel = $token_decode['sub'];
76
			
124
			
77
			$utilisateur_wiki_existe = $this->wiki->LoadAll("SELECT * FROM  ".$this->wiki->config["table_prefix"]."users ".
125
			$utilisateur_wiki_existe = $this->wiki->LoadAll("SELECT * FROM  ".$this->wiki->config["table_prefix"]."users ".
78
					"WHERE ".
126
					"WHERE ".
79
					"name = '".mysql_escape_string($nom_wiki)."' OR ".
127
					"name = '".mysql_escape_string($nom_wiki)."' OR ".
80
					"email = '".mysql_escape_string($courriel)."'");
128
					"email = '".mysql_escape_string($courriel)."'");
81
			
129
			
82
			// pas inscrit ? on l'ajout à la base de données
130
			// pas inscrit ? on l'ajout à la base de données
83
			if(empty($utilisateur_wiki_existe)) {
131
			if(empty($utilisateur_wiki_existe)) {
84
				// mot de passe généré à l'arrache, le mieux serait de trouver celui de tela encodé
132
				// mot de passe généré à l'arrache, le mieux serait de trouver celui de tela encodé
85
				// mais en gérant bien le sso on peut s'en passer car l'utilisateur ne devrait jamais avoir 
133
				// mais en gérant bien le sso on peut s'en passer car l'utilisateur ne devrait jamais avoir 
86
				// à s'identifier par le wiki
134
				// à s'identifier par le wiki
87
				$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
135
				$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
88
				$pass = substr(str_shuffle(str_repeat($pool, 16)), 0, 16);
136
				$pass = substr(str_shuffle(str_repeat($pool, 16)), 0, 16);
89
				
137
				
90
				$this->wiki->Query("insert into ".$this->wiki->config["table_prefix"]."users set ".
138
				$this->wiki->Query("insert into ".$this->wiki->config["table_prefix"]."users set ".
91
						"signuptime = now(), ".
139
						"signuptime = now(), ".
92
						"name = '".mysql_escape_string($token_decode['nomWiki'])."', ".
140
						"name = '".mysql_escape_string($token_decode['nomWiki'])."', ".
93
						"email = '".mysql_escape_string($token_decode['sub'])."', ".
141
						"email = '".mysql_escape_string($token_decode['sub'])."', ".
94
						"password = md5('".mysql_escape_string($pass)."')");
142
						"password = md5('".mysql_escape_string($pass)."')");
95
			} else {
143
			} else {
96
				// Un utilisateur peut déjà s'être inscrit sur le wiki avec un autre nom que son pseudo
144
				// Un utilisateur peut déjà s'être inscrit sur le wiki avec un autre nom que son pseudo
97
				$nom_wiki = $utilisateur_wiki_existe[0]['name'];
145
				$nom_wiki = $utilisateur_wiki_existe[0]['name'];
98
				// s'il existe un enregistrement avec ce mail et un autre avec ce nomWiki on garde celui qui correspond au bon courriel
146
				// s'il existe un enregistrement avec ce mail et un autre avec ce nomWiki on garde celui qui correspond au bon courriel
99
				foreach($utilisateur_wiki_existe as $utilisateur_wiki) {
147
				foreach($utilisateur_wiki_existe as $utilisateur_wiki) {
100
					if($utilisateur_wiki['email'] == $courriel) {
148
					if($utilisateur_wiki['email'] == $courriel) {
101
						  $nom_wiki = $utilisateur_wiki['name'];
149
						  $nom_wiki = $utilisateur_wiki['name'];
102
					}
150
					}
103
				}
151
				}
104
			}
152
			}
105
		}
153
		}
106
 
154
 
107
		return $nom_wiki;
155
		return $nom_wiki;
108
	}
156
	}
109
 
157
 
110
	function recupererIdentiteConnectee() {
158
	function recupererIdentiteConnectee() {
111
		$infos_cookie = $this->getInfosCookie();
159
		$infos_cookie = $this->getInfosCookie();
112
		if($infos_cookie == null || $infos_cookie['tentative_identification'] == false) {	
160
		if($infos_cookie == null || $infos_cookie['tentative_identification'] == false) {	
113
			// peut importe si l'annuaire répond oui ou non, on a fait une tentative d'identification
161
			// peut importe si l'annuaire répond oui ou non, on a fait une tentative d'identification
114
			// et si on a trouvé quelqu'un on ne réésaiera pas jusqu'à la fermeture du navigateur
162
			// et si on a trouvé quelqu'un on ne réésaiera pas jusqu'à la fermeture du navigateur
115
			$infos_cookie = array('tentative_identification' => true, 'expire' => 0);
163
			$infos_cookie = array('tentative_identification' => true, 'expire' => 0);
116
 			$this->setInfosCookie($infos_cookie);
164
 			$this->setInfosCookie($infos_cookie);
117
 
165
 
118
			$annuaire_url = $this->wiki->config['sso_url'].'identite';
166
			$annuaire_url = $this->wiki->config['sso_url'].'identite';
119
			// Attention si le paramètre wiki de l'url est vide, la redirection de retour pose des problèmes
167
			// Attention si le paramètre wiki de l'url est vide, la redirection de retour pose des problèmes
120
			$url = $annuaire_url.'?redirect_url='.urlencode($this->wiki->config['base_url'].$this->getPage());
168
			$url = $annuaire_url.'?redirect_url='.urlencode($this->wiki->config['base_url'].$this->getPage());
121
 
169
 
122
			header('Location: '.$url);
170
			header('Location: '.$url);
123
			exit;
171
			exit;
124
		} else {
172
		} else {
125
			$token = $this->getToken();
173
			$token = $this->getToken();
126
 
174
 
127
			if($token != null) {
175
			if($token != null) {
128
				// On demande à l'annuaire si le jeton est bien valide
176
				// On demande à l'annuaire si le jeton est bien valide
129
				$jeton_rafraichi = json_decode(file_get_contents($this->wiki->config['sso_url'].'rafraichir?token='.$token), true);
177
				$jeton_rafraichi = json_decode(file_get_contents($this->wiki->config['sso_url'].'rafraichir?token='.$token), true);
130
				$nom_wiki = $this->verifierEtInsererUtilisateurParJeton($jeton_rafraichi);
178
				$nom_wiki = $this->verifierEtInsererUtilisateurParJeton($jeton_rafraichi);
131
				$token_decode = $this->decoderToken($jeton_rafraichi['token']);
179
				$token_decode = $this->decoderToken($jeton_rafraichi['token']);
132
 
180
 
133
				// dans le pire des cas, si on se déconnecte dans une autre application, on sera déconnecté 
181
				// dans le pire des cas, si on se déconnecte dans une autre application, on sera déconnecté 
134
				// lorsque le jeton expirera
182
				// lorsque le jeton expirera
135
				$infos_cookie = array('tentative_identification' => true, 'expire' => time()+$jeton_rafraichi['duration']);
183
				$infos_cookie = array('tentative_identification' => true, 'expire' => time()+$jeton_rafraichi['duration']);
136
				$this->setInfosCookie($infos_cookie);
184
				$this->setInfosCookie($infos_cookie);
137
 
185
 
138
				$this->wiki->SetUser($this->wiki->LoadUser($nom_wiki));
186
				$this->wiki->SetUser($this->wiki->LoadUser($nom_wiki));
139
			} else {
187
			} else {
140
				// personne n'a été trouvé ? on remplace le cookie par un de durée plus courte 
188
				// personne n'a été trouvé ? on remplace le cookie par un de durée plus courte 
141
				// pour rééssayer dans delai_tentative_identification si on en a pas déjà un
189
				// pour rééssayer dans delai_tentative_identification si on en a pas déjà un
142
				if($infos_cookie['expire'] == 0) { 
190
				if($infos_cookie['expire'] == 0) { 
143
					$infos_cookie['expire'] = time()+$this->delai_tentative_identification;
191
					$infos_cookie['expire'] = time()+$this->delai_tentative_identification;
144
					$this->setInfosCookie($infos_cookie);
192
					$this->setInfosCookie($infos_cookie);
145
				}
193
				}
146
			}
194
			}
147
		}
195
		}
148
	}
196
	}
149
 
197
 
150
	function recupererIdentiteConnecteePourApi() {		
198
	function recupererIdentiteConnecteePourApi() {		
151
		$token = $this->getToken();
199
		$token = $this->getToken();
152
		if($token != null) {
200
		if($token != null) {
153
			// On demande à l'annuaire si le jeton est bien valide
201
			// On demande à l'annuaire si le jeton est bien valide
154
			$jeton_rafraichi = json_decode(file_get_contents($this->wiki->config['sso_url'].'rafraichir?token='.$token), true);
202
			$jeton_rafraichi = json_decode(file_get_contents($this->wiki->config['sso_url'].'rafraichir?token='.$token), true);
155
			$nom_wiki = $this->verifierEtInsererUtilisateurParJeton($jeton_rafraichi);
203
			$nom_wiki = $this->verifierEtInsererUtilisateurParJeton($jeton_rafraichi);
156
			$token_decode = $this->decoderToken($jeton_rafraichi['token']);
204
			$token_decode = $this->decoderToken($jeton_rafraichi['token']);
157
			$this->wiki->SetUser($this->wiki->LoadUser($nom_wiki));
205
			$this->wiki->SetUser($this->wiki->LoadUser($nom_wiki));
158
		}
206
		}
159
	}
207
	}
160
 
208
 
161
	function connecterUtilisateur($login, $pass, $url_redirect = null) {
209
	function connecterUtilisateur($login, $pass, $url_redirect = null) {
162
		if(strpos($login, '@') === false) {
210
		if(strpos($login, '@') === false) {
163
			$utilisateur_wiki = $this->wiki->LoadSingle("SELECT email FROM  ".$this->wiki->config["table_prefix"]."users ".
211
			$utilisateur_wiki = $this->wiki->LoadSingle("SELECT email FROM  ".$this->wiki->config["table_prefix"]."users ".
164
			"WHERE name = '".mysql_escape_string($login)."'");
212
			"WHERE name = '".mysql_escape_string($login)."'");
165
 
213
 
166
			$login = !empty($utilisateur_wiki) ? $utilisateur_wiki['email'] : $login;
214
			$login = !empty($utilisateur_wiki) ? $utilisateur_wiki['email'] : $login;
167
			// TODO: si le courriel a changé dans l'annuaire, on devrait mettre à jour les informations 
215
			// TODO: si le courriel a changé dans l'annuaire, on devrait mettre à jour les informations 
168
			// si on a utilisé le nom wiki pour s'identifier mais le flow du programme rend cela complexe
216
			// si on a utilisé le nom wiki pour s'identifier mais le flow du programme rend cela complexe
169
		}
217
		}
170
 
218
 
171
		$url_redirect = ($url_redirect == null) ? $this->wiki->config['base_url'].'PagePrincipale' : $url_redirect;
219
		$url_redirect = ($url_redirect == null) ? $this->wiki->config['base_url'].'PagePrincipale' : $url_redirect;
172
 
220
 
173
		// le cookie de tentative d'identification est remis à zéro pour qu'au rechargement de la page il vérifie l'identité 
221
		// le cookie de tentative d'identification est remis à zéro pour qu'au rechargement de la page il vérifie l'identité 
174
		// connectée du nouvel utilisateur
222
		// connectée du nouvel utilisateur
175
		$infos_cookie = array('tentative_identification' => false, 'expire' => 0);
223
		$infos_cookie = array('tentative_identification' => false, 'expire' => 0);
176
		$this->setInfosCookie($infos_cookie);
224
		$this->setInfosCookie($infos_cookie);
177
		// On demande à l'annuaire si l'utilisateur est bien valide
225
		// On demande à l'annuaire si l'utilisateur est bien valide
178
		$annuaire_url = $this->wiki->config['sso_url'].'connexion?login='.$login.'&password='.$pass;
226
		$annuaire_url = $this->wiki->config['sso_url'].'connexion?login='.$login.'&password='.$pass;
179
		$url = $annuaire_url.'&redirect_url='.urlencode($url_redirect);
227
		$url = $annuaire_url.'&redirect_url='.urlencode($url_redirect);
180
 
228
 
181
		header('Location: '.$url);
229
		header('Location: '.$url);
182
		exit;
230
		exit;
183
	}
231
	}
184
 
232
 
185
	function deconnecterUtilisateur($url_redirect = null) {
233
	function deconnecterUtilisateur($url_redirect = null) {
186
		$url_redirect = ($url_redirect == null) ? $this->wiki->config['base_url'].'PagePrincipale' : $url_redirect;
234
		$url_redirect = ($url_redirect == null) ? $this->wiki->config['base_url'].'PagePrincipale' : $url_redirect;
187
		// Suppression d'un eventuel jeton contenu dans l'url
235
		// Suppression d'un eventuel jeton contenu dans l'url
188
		$url_redirect = $this->supprimerUrlVar($url_redirect, 'Authorization');
236
		$url_redirect = $this->supprimerUrlVar($url_redirect, 'Authorization');
189
		
237
		
190
		$infos_cookie = array('tentative_identification' => false, 'expire' => 0);
238
		$infos_cookie = array('tentative_identification' => false, 'expire' => 0);
191
 		$this->setInfosCookie($infos_cookie);
239
 		$this->setInfosCookie($infos_cookie);
192
		// On demande à l'annuaire si l'utilisateur est bien valide
240
		// On demande à l'annuaire si l'utilisateur est bien valide
193
		$annuaire_url = $this->wiki->config['sso_url'].'deconnexion';
241
		$annuaire_url = $this->wiki->config['sso_url'].'deconnexion';
194
		$url = $annuaire_url.'?redirect_url='.urlencode($url_redirect);
242
		$url = $annuaire_url.'?redirect_url='.urlencode($url_redirect);
195
		header('Location: '.$url);
243
		header('Location: '.$url);
196
		exit;
244
		exit;
197
	}
245
	}
198
}
246
}
199
?>
247
?>