1: # The LearningOnline Network
2: # User Authentication Module
3: #
4: # $Id: lonauth.pm,v 1.71 2005/11/10 19:19:08 www Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::lonauth;
30:
31: use strict;
32: use Apache::Constants qw(:common);
33: use Apache::File;
34: use CGI qw(:standard);
35: use CGI::Cookie();
36: use DynaLoader; # for Crypt::DES version
37: use Crypt::DES;
38: use Apache::loncommon();
39: use Apache::lonnet;
40: use Apache::lonmenu();
41: use Fcntl qw(:flock);
42: use Apache::lonlocal;
43: use POSIX qw(mktime);
44:
45: my %FORM;
46:
47: # ------------------------------------------------------------ Successful login
48:
49: sub success {
50: my ($r, $username, $domain, $authhost,$lowerurl) = @_;
51: my $lonids=$r->dir_config('lonIDsDir');
52:
53: my $public=($username eq 'public' && $domain eq 'public');
54:
55: # See if old ID present, if so, remove
56:
57: my ($filename,$cookie,$userroles);
58: my $now=time;
59:
60: if ($public) {
61: my $max_public=100;
62: my $oldest;
63: my $oldest_time=0;
64: for(my $next=1;$next<=$max_public;$next++) {
65: if (-e $lonids."/publicuser_$next.id") {
66: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
67: if ($mtime<$oldest_time || !$oldest_time) {
68: $oldest_time=$mtime;
69: $oldest=$next;
70: }
71: } else {
72: $cookie="publicuser_$next";
73: last;
74: }
75: }
76: if (!$cookie) { $cookie="publicuser_$oldest"; }
77: } else {
78: opendir(DIR,$lonids);
79: while ($filename=readdir(DIR)) {
80: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
81: unlink($lonids.'/'.$filename);
82: }
83: }
84: closedir(DIR);
85:
86: # Give them a new cookie
87:
88: $cookie="$username\_$now\_$domain\_$authhost";
89:
90: # Initialize roles
91:
92: $userroles=Apache::lonnet::rolesinit($domain,$username,$authhost);
93: }
94: # ------------------------------------ Check browser type and MathML capability
95:
96: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
97: $clientunicode,$clientos) = &Apache::loncommon::decode_user_agent($r);
98:
99: # -------------------------------------- Any accessibility options to remember?
100: if (($FORM{'interface'}) && ($FORM{'remember'} eq 'true')) {
101: foreach ('imagesuppress','appletsuppress',
102: 'embedsuppress','fontenhance','blackwhite') {
103: if ($FORM{$_} eq 'true') {
104: &Apache::lonnet::put('environment',{$_ => 'on'},
105: $domain,$username);
106: } else {
107: &Apache::lonnet::del('environment',[$_],$domain,$username);
108: }
109: }
110: }
111: # ------------------------------------------------------------- Get environment
112:
113: my $userenv;
114: my %userenv=Apache::lonnet::dump('environment',$domain,$username);
115: my ($tmp) = keys(%userenv);
116: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
117: foreach my $key (keys(%userenv)) {
118: $userenv.="environment.$key=$userenv{$key}\n";
119: }
120: }
121: if (($userenv{'interface'}) && (!$FORM{'interface'})) {
122: $FORM{'interface'}=$userenv{'interface'};
123: }
124: $env{'environment.remote'}=$userenv{'remote'};
125: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
126:
127: # --------------- Do not trust query string to be put directly into environment
128: foreach ('imagesuppress','appletsuppress',
129: 'embedsuppress','fontenhance','blackwhite',
130: 'interface','localpath','localres') {
131: $FORM{$_}=~s/[\n\r\=]//gs;
132: }
133: # --------------------------------------------------------- Write first profile
134:
135: {
136: my $idf=Apache::File->new(">$lonids/$cookie.id");
137: unless (flock($idf,LOCK_EX)) {
138: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
139: 'Could not obtain exclusive lock in lonauth: '.$!);
140: $idf->close();
141: return 'error: '.$!;
142: }
143: if ($userenv ne '') { print $idf "$userenv\n"; }
144: print $idf "user.name=$username\n";
145: print $idf "user.domain=$domain\n";
146: print $idf "user.home=$authhost\n";
147: print $idf "browser.type=$clientbrowser\n";
148: print $idf "browser.version=$clientversion\n";
149: print $idf "browser.mathml=$clientmathml\n";
150: print $idf "browser.unicode=$clientunicode\n";
151: print $idf "browser.os=$clientos\n";
152: if ($FORM{'localpath'}) {
153: print $idf "browser.localpath=$FORM{'localpath'}\n";
154: print $idf "browser.localres=$FORM{'localres'}\n";
155: }
156: print $idf "server.domain=".$r->dir_config('lonDefDomain')."\n";
157: my $timezone='UTC';
158: my $timediff=POSIX::mktime(localtime())-POSIX::mktime(gmtime());
159: if ($timediff) {
160: my $hours=int($timediff/3600);
161: my $minutes=abs(int(($timediff-$hours*3600)/60));
162: my $sign="+";
163: if ($timediff<0) {
164: $sign="-";
165: }
166: $timezone.=$sign.abs($hours).':'.substr("0$minutes",-2);
167: }
168: print $idf "server.timezone=$timezone\n";
169: print $idf "request.course.fn=\n";
170: print $idf "request.course.uri=\n";
171: print $idf "request.course.sec=\n";
172: print $idf "request.role=cm\n";
173: print $idf "request.role.adv=$env{'user.adv'}\n";
174: print $idf "request.host=$ENV{'REMOTE_ADDR'}\n";
175: if ($public) {
176: print $idf "environment.remote=off\n";
177: }
178: if ($FORM{'interface'}) {
179: $FORM{'interface'}=~s/\W//gs;
180: print $idf "browser.interface=$FORM{'interface'}\n";
181: $env{'browser.interface'}=$FORM{'interface'};
182: foreach ('imagesuppress','appletsuppress',
183: 'embedsuppress','fontenhance','blackwhite') {
184: if (($FORM{$_} eq 'true') ||
185: ($userenv{$_} eq 'on')) {
186: print $idf "browser.$_=on\n";
187: }
188: }
189: }
190: if ($userroles ne '') { print $idf "$userroles"; }
191: $idf->close();
192: }
193: $env{'request.role'}='cm';
194: $env{'request.role.adv'}=$env{'user.adv'};
195: $env{'browser.type'}=$clientbrowser;
196: # -------------------------------------------------------------------- Log this
197:
198: &Apache::lonnet::log($domain,$username,$authhost,
199: "Login $ENV{'REMOTE_ADDR'}");
200:
201: # ------------------------------------------------- Check for critical messages
202:
203: my @what=&Apache::lonnet::dump('critical',$domain,$username);
204: if ($what[0]) {
205: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
206: $lowerurl='/adm/email?critical=display';
207: }
208: }
209:
210: # ------------------------------------------------------------ Get cookie ready
211:
212: if ($public or $lowerurl eq 'noredirect') { return $cookie; }
213:
214: $cookie="lonID=$cookie; path=/";
215: # -------------------------------------------------------- Menu script and info
216: my $windowinfo=&Apache::lonmenu::open($clientos);
217: my $startupremote=&Apache::lonmenu::startupremote($lowerurl);
218: my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
219: my $setflags=&Apache::lonmenu::setflags();
220: my $maincall=&Apache::lonmenu::maincall();
221: my $bodytag=&Apache::loncommon::bodytag('Successful Login');
222: my $add=&addcontent();
223: my $continuelink;
224: if (($env{'browser.interface'} eq 'textual') ||
225: ($env{'environment.remote'} eq 'off')) {
226: $continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";
227: }
228: # ------------------------------------------------- Output for successful login
229:
230: $r->send_cgi_header(<<ENDHEADER);
231: Content-type: text/html$add
232: Set-cookie: $cookie
233:
234: ENDHEADER
235: my %lt=&Apache::lonlocal::texthash(
236: 'wel' => 'Welcome',
237: 'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up',
238: 'pro' => 'Problems',
239: 'log' => 'loginproblems.html',
240: );
241: $r->print(<<ENDSUCCESS);
242: <html>
243: <head>
244: <title>Successful Login to the LearningOnline Network with CAPA</title>
245: $startupremote
246: </head>
247: $bodytag
248: $setflags
249: $windowinfo
250: <h1>$lt{'wel'}</h1>
251: $lt{'mes'}.<p>
252: <a href="/adm/$lt{'log'}">$lt{'pro'}?</a></p>
253: $remoteinfo
254: $maincall
255: $continuelink
256: </body>
257: </html>
258: ENDSUCCESS
259: }
260:
261: # --------------------------------------------------------------- Failed login!
262:
263: sub failed {
264: my ($r,$message) = @_;
265: my $bodytag=&Apache::loncommon::bodytag('Unsuccessful Login');
266: my $add=&addcontent();
267: $r->send_cgi_header(<<ENDFHEADER);
268: Content-type: text/html$add
269:
270: ENDFHEADER
271: $r->print(<<ENDFAILED);
272: <html>
273: <head>
274: <title>Unsuccessful Login to the LearningOnline Network with CAPA</title>
275: </head>
276: $bodytag
277: <h1>Sorry ...</h1>
278: <p><b>$message</b></p>
279: <p>Please <a href="/adm/login?username=$FORM{'uname'}&domain=$FORM{'udom'}">log in again</a>.</p>
280: <p>
281: <a href="/adm/loginproblems.html">Problems?</a></p>
282: </body>
283: </html>
284: ENDFAILED
285: }
286:
287: # --------------------------------------------------------------------- Charset
288:
289: sub addcontent {
290: my $encoding=&Apache::lonlocal::current_encoding;
291: if ($encoding) {
292: return '; charset='.$encoding;
293: } else {
294: return '';
295: }
296: }
297:
298: # ------------------------------------------------------------------ Rerouting!
299:
300: sub reroute {
301: my $r=shift;
302: my $bodytag=&Apache::loncommon::bodytag('Rerouting');
303: $r->send_cgi_header(<<ENDRFHEADER);
304: Content-type: text/html
305:
306: ENDRFHEADER
307: $r->print(<<ENDRFAILED);
308: <html>
309: <head>
310: <title>Rerouting Login to the LearningOnline Network with CAPA</title>
311: </head>
312: $bodytag
313: <h1>Sorry ...</h1>
314: Please <a href="/">log in again</a>.
315: </body>
316: </html>
317: ENDRFAILED
318: }
319:
320: # ---------------------------------------------------------------- Main handler
321:
322: sub handler {
323: my $r = shift;
324:
325: # Are we re-routing?
326: if (-e '/home/httpd/html/lon-status/reroute.txt') {
327: &reroute($r);
328: return OK;
329: }
330:
331: &Apache::lonlocal::get_language_handle($r);
332:
333: # -------------------------------- Prevent users from attempting to login twice
334: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
335: my $lonid=$cookies{'lonID'};
336: my $cookie;
337: if ($lonid) {
338: my $handle=$lonid->value;
339: $handle=~s/\W//g;
340: my $lonidsdir=$r->dir_config('lonIDsDir');
341: if ((-e "$lonidsdir/$handle.id") && ($handle ne '')) {
342: # Indeed, a valid token is found
343: $r->send_cgi_header(<<ENDFHEADER);
344: Content-type: text/html
345:
346: ENDFHEADER
347: my $bodytag=&Apache::loncommon::bodytag('Already logged in');
348: $r->print(<<ENDFAILED);
349: <html>
350: <head>
351: <title>Already logged in</title>
352: </head>
353: $bodytag
354: <h1>You are already logged in</h1>
355: <p>Please either <a href="/adm/roles">continue the current session</a> or
356: <a href="/adm/logout">logout</a>.</p>
357: <p>
358: <a href="/adm/loginproblems.html">Problems?</a></p>
359: </body>
360: </html>
361: ENDFAILED
362: return OK;
363: }
364: }
365:
366: # ---------------------------------------------------- No valid token, continue
367:
368:
369: my $buffer;
370: $r->read($buffer,$r->header_in('Content-length'),0);
371: my @pairs=split(/&/,$buffer);
372: my $pair; my $name; my $value;
373: undef %FORM;
374: %FORM=();
375: foreach $pair (@pairs) {
376: ($name,$value) = split(/=/,$pair);
377: $value =~ tr/+/ /;
378: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
379: $FORM{$name}=$value;
380: }
381:
382: if ((!$FORM{'uname'}) || (!$FORM{'upass0'}) || (!$FORM{'udom'})) {
383: failed($r,'Username, password and domain need to be specified.');
384: return OK;
385: }
386:
387: # split user logging in and "su"-user
388:
389: ($FORM{'uname'},$FORM{'suname'})=split(/\:/,$FORM{'uname'});
390: $FORM{'uname'} =~ s/\W//g;
391: $FORM{'suname'} =~ s/\W//g;
392: $FORM{'udom'} =~ s/\W//g;
393:
394: my $role = $r->dir_config('lonRole');
395: my $domain = $r->dir_config('lonDefDomain');
396: my $prodir = $r->dir_config('lonUsersDir');
397:
398: # ---------------------------------------- Get the information from login token
399:
400: my $tmpinfo=Apache::lonnet::reply('tmpget:'.$FORM{'logtoken'},
401: $FORM{'serverid'});
402:
403: if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
404: failed($r,'Information needed to verify your login information is missing, inaccessible or expired.');
405: return OK;
406: } else {
407: unless (&Apache::lonnet::reply('tmpdel:'.$FORM{'logtoken'},
408: $FORM{'serverid'}) eq 'ok') {
409: &failed($r,'Session could not be opened.');
410: }
411: }
412: my ($key,$firsturl)=split(/&/,$tmpinfo);
413:
414: my $keybin=pack("H16",$key);
415:
416: my $cipher;
417: if ($Crypt::DES::VERSION>=2.03) {
418: $cipher=new Crypt::DES $keybin;
419: }
420: else {
421: $cipher=new DES $keybin;
422: }
423: my $upass='';
424: for (my $i=0;$i<=2;$i++) {
425: my $chunk=
426: $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},0,16))));
427:
428: $chunk.=
429: $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},16,16))));
430:
431: $chunk=substr($chunk,1,ord(substr($chunk,0,1)));
432: $upass.=$chunk;
433: }
434:
435: # ---------------------------------------------------------------- Authenticate
436: my $authhost=Apache::lonnet::authenticate($FORM{'uname'},
437: $upass,
438: $FORM{'udom'});
439:
440: # --------------------------------------------------------------------- Failed?
441:
442: if ($authhost eq 'no_host') {
443: failed($r,'Username and/or password could not be authenticated.');
444: return OK;
445: }
446:
447: if (($firsturl eq '') ||
448: ($firsturl=~/^\/adm\/(logout|remote)/)) {
449: $firsturl='/adm/roles';
450: }
451: # --------------------------------- Are we attempting to login as somebody else?
452: if ($FORM{'suname'}) {
453: # ------------ see if the original user has enough privileges to pull this stunt
454: if (&Apache::lonnet::privileged($FORM{'uname'},$FORM{'udom'})) {
455: # ---------------------------------------------------- see if the su-user exists
456: unless (&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'})
457: eq 'no_host') {
458: &Apache::lonnet::logthis(&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'}));
459: # ------------------------------ see if the su-user is not too highly privileged
460: unless (&Apache::lonnet::privileged($FORM{'suname'},$FORM{'udom'})) {
461: # -------------------------------------------------------- actually switch users
462: &Apache::lonnet::logperm('User '.$FORM{'uname'}.' at '.$FORM{'udom'}.
463: ' logging in as '.$FORM{'suname'});
464: $FORM{'uname'}=$FORM{'suname'};
465: } else {
466: &Apache::lonnet::logthis('Attempted switch user to privileged user');
467: }
468: }
469: } else {
470: &Apache::lonnet::logthis('Non-privileged user attempting switch user');
471: }
472: }
473: &success($r,$FORM{'uname'},$FORM{'udom'},$authhost,$firsturl);
474: return OK;
475: }
476:
477: 1;
478: __END__
479:
480:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>