Annotation of loncom/auth/lonauth.pm, revision 1.73

1.1       albertel    1: # The LearningOnline Network
                      2: # User Authentication Module
1.27      www         3: #
1.73    ! albertel    4: # $Id: lonauth.pm,v 1.72 2005/11/15 17:55:03 www Exp $
1.27      www         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: #
1.1       albertel   28: 
                     29: package Apache::lonauth;
                     30: 
1.18      albertel   31: use strict;
1.1       albertel   32: use Apache::Constants qw(:common);
                     33: use Apache::File;
                     34: use CGI qw(:standard);
                     35: use CGI::Cookie();
1.26      harris41   36: use DynaLoader; # for Crypt::DES version
1.8       www        37: use Crypt::DES;
1.45      matthew    38: use Apache::loncommon();
1.66      albertel   39: use Apache::lonnet;
1.12      www        40: use Apache::lonmenu();
1.18      albertel   41: use Fcntl qw(:flock);
1.56      www        42: use Apache::lonlocal;
1.72      www        43: use POSIX qw(strftime);
1.37      www        44: 
                     45: my %FORM;
                     46: 
1.1       albertel   47: # ------------------------------------------------------------ Successful login
                     48: 
                     49: sub success {
1.6       www        50:     my ($r, $username, $domain, $authhost,$lowerurl) = @_;
1.1       albertel   51:     my $lonids=$r->dir_config('lonIDsDir');
1.4       www        52: 
1.69      albertel   53:     my $public=($username eq 'public' && $domain eq 'public');
                     54: 
1.4       www        55: # See if old ID present, if so, remove
1.17      www        56: 
1.69      albertel   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);
1.4       www        85: 
                     86: # Give them a new cookie
                     87: 
1.69      albertel   88: 	$cookie="$username\_$now\_$domain\_$authhost";
                     89:     
1.5       www        90: # Initialize roles
                     91: 
1.69      albertel   92: 	$userroles=Apache::lonnet::rolesinit($domain,$username,$authhost);
                     93:     }
1.7       www        94: # ------------------------------------ Check browser type and MathML capability
1.6       www        95: 
1.45      matthew    96:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                     97:         $clientunicode,$clientos) = &Apache::loncommon::decode_user_agent($r);
1.6       www        98: 
1.40      www        99: # -------------------------------------- Any accessibility options to remember?
                    100:     if (($FORM{'interface'}) && ($FORM{'remember'} eq 'true')) {
1.41      albertel  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:     }
1.11      www       111: # ------------------------------------------------------------- Get environment
                    112: 
1.32      albertel  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) {
1.73    ! albertel  117: 	# default remote control to off
        !           118: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
1.32      albertel  119: 	foreach my $key (keys(%userenv)) {
                    120: 	    $userenv.="environment.$key=$userenv{$key}\n";
                    121: 	}
1.11      www       122:     }
1.38      www       123:     if (($userenv{'interface'}) && (!$FORM{'interface'})) {
                    124: 	$FORM{'interface'}=$userenv{'interface'};
                    125:     }
1.66      albertel  126:     $env{'environment.remote'}=$userenv{'remote'};
1.65      albertel  127:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                    128: 
1.54      www       129: # --------------- Do not trust query string to be put directly into environment
                    130:     foreach ('imagesuppress','appletsuppress',
                    131: 	     'embedsuppress','fontenhance','blackwhite',
                    132: 	     'interface','localpath','localres') {
                    133: 	$FORM{$_}=~s/[\n\r\=]//gs;
                    134:     }
1.7       www       135: # --------------------------------------------------------- Write first profile
1.5       www       136: 
1.41      albertel  137:     {
                    138: 	my $idf=Apache::File->new(">$lonids/$cookie.id");
                    139: 	unless (flock($idf,LOCK_EX)) {
                    140: 	    &Apache::lonnet::logthis("<font color=blue>WARNING: ".
                    141: 			   'Could not obtain exclusive lock in lonauth: '.$!);
                    142: 	    $idf->close();
                    143: 	    return 'error: '.$!;
                    144: 	}
                    145: 	if ($userenv ne '') { print $idf "$userenv\n"; }
                    146: 	print $idf "user.name=$username\n";
                    147: 	print $idf "user.domain=$domain\n";
                    148: 	print $idf "user.home=$authhost\n";
                    149: 	print $idf "browser.type=$clientbrowser\n";
                    150: 	print $idf "browser.version=$clientversion\n";
                    151: 	print $idf "browser.mathml=$clientmathml\n";
                    152: 	print $idf "browser.unicode=$clientunicode\n";
                    153: 	print $idf "browser.os=$clientos\n";
1.53      www       154:         if ($FORM{'localpath'}) {
                    155:            print $idf "browser.localpath=$FORM{'localpath'}\n";
                    156:            print $idf "browser.localres=$FORM{'localres'}\n";
                    157:         }
1.71      www       158:         print $idf "server.domain=".$r->dir_config('lonDefDomain')."\n";
1.72      www       159:         my $timezone=POSIX::strftime("%Z",localtime(time));
1.71      www       160:         print $idf "server.timezone=$timezone\n";
1.41      albertel  161: 	print $idf "request.course.fn=\n";
                    162: 	print $idf "request.course.uri=\n";
                    163: 	print $idf "request.course.sec=\n";
                    164: 	print $idf "request.role=cm\n";
1.66      albertel  165:         print $idf "request.role.adv=$env{'user.adv'}\n";
1.42      www       166: 	print $idf "request.host=$ENV{'REMOTE_ADDR'}\n";
1.69      albertel  167: 	if ($public) {
1.68      albertel  168: 	    print $idf "environment.remote=off\n";
                    169: 	}
1.41      albertel  170: 	if ($FORM{'interface'}) {
                    171: 	    $FORM{'interface'}=~s/\W//gs;
                    172: 	    print $idf "browser.interface=$FORM{'interface'}\n";
1.66      albertel  173: 	    $env{'browser.interface'}=$FORM{'interface'};
1.41      albertel  174: 	    foreach ('imagesuppress','appletsuppress',
                    175: 		     'embedsuppress','fontenhance','blackwhite') {
                    176: 		if (($FORM{$_} eq 'true') ||
                    177: 		    ($userenv{$_} eq 'on')) {
                    178: 		    print $idf "browser.$_=on\n";
                    179: 		}
1.18      albertel  180: 	    }
1.41      albertel  181: 	}
                    182: 	if ($userroles ne '') { print $idf "$userroles"; }
                    183: 	$idf->close();
                    184:     }
1.66      albertel  185:     $env{'request.role'}='cm';
                    186:     $env{'request.role.adv'}=$env{'user.adv'};
                    187:     $env{'browser.type'}=$clientbrowser;
1.7       www       188: # -------------------------------------------------------------------- Log this
                    189: 
                    190:     &Apache::lonnet::log($domain,$username,$authhost,
                    191:                          "Login $ENV{'REMOTE_ADDR'}");
1.4       www       192: 
1.14      www       193: # ------------------------------------------------- Check for critical messages
                    194: 
1.21      www       195:     my @what=&Apache::lonnet::dump('critical',$domain,$username);
1.14      www       196:     if ($what[0]) {
1.22      www       197: 	if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
1.21      www       198: 	    $lowerurl='/adm/email?critical=display';
1.14      www       199:         }
                    200:     }
                    201: 
1.5       www       202: # ------------------------------------------------------------ Get cookie ready
                    203: 
1.70      albertel  204:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
                    205: 
1.1       albertel  206:     $cookie="lonID=$cookie; path=/";
1.12      www       207: # -------------------------------------------------------- Menu script and info
1.31      www       208:     my $windowinfo=&Apache::lonmenu::open($clientos);
1.35      www       209:     my $startupremote=&Apache::lonmenu::startupremote($lowerurl);
1.63      albertel  210:     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
1.35      www       211:     my $setflags=&Apache::lonmenu::setflags();
                    212:     my $maincall=&Apache::lonmenu::maincall();
1.52      www       213:     my $bodytag=&Apache::loncommon::bodytag('Successful Login');
1.60      www       214:     my $add=&addcontent();
1.64      albertel  215:     my $continuelink;
1.66      albertel  216:     if (($env{'browser.interface'} eq 'textual') ||
                    217:         ($env{'environment.remote'} eq 'off')) {
1.64      albertel  218: 	$continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";
                    219:     }
1.5       www       220: # ------------------------------------------------- Output for successful login
                    221: 
1.1       albertel  222:     $r->send_cgi_header(<<ENDHEADER);
1.60      www       223: Content-type: text/html$add
1.1       albertel  224: Set-cookie: $cookie
                    225: 
                    226: ENDHEADER
1.58      www       227:     my %lt=&Apache::lonlocal::texthash(
                    228: 				       'wel' => 'Welcome',
                    229: 				       'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up',
                    230: 				       'pro' => 'Problems',
                    231: 				       'log' => 'loginproblems.html',
                    232: 				       );
1.1       albertel  233:     $r->print(<<ENDSUCCESS);
                    234: <html>
                    235: <head>
1.4       www       236: <title>Successful Login to the LearningOnline Network with CAPA</title>
1.35      www       237: $startupremote
1.1       albertel  238: </head>
1.43      www       239: $bodytag
1.35      www       240: $setflags
1.19      www       241: $windowinfo
1.58      www       242: <h1>$lt{'wel'}</h1>
                    243: $lt{'mes'}.<p>
                    244: <a href="/adm/$lt{'log'}">$lt{'pro'}?</a></p>
1.63      albertel  245: $remoteinfo
1.35      www       246: $maincall
1.64      albertel  247: $continuelink
1.6       www       248: </body>
1.1       albertel  249: </html>
                    250: ENDSUCCESS
                    251: }
                    252: 
                    253: # --------------------------------------------------------------- Failed login!
                    254: 
                    255: sub failed {
                    256:     my ($r,$message) = @_;
1.52      www       257:     my $bodytag=&Apache::loncommon::bodytag('Unsuccessful Login');
1.60      www       258:     my $add=&addcontent();
1.1       albertel  259:     $r->send_cgi_header(<<ENDFHEADER);
1.60      www       260: Content-type: text/html$add
1.1       albertel  261: 
                    262: ENDFHEADER
                    263:     $r->print(<<ENDFAILED);
                    264: <html>
                    265: <head>
1.4       www       266: <title>Unsuccessful Login to the LearningOnline Network with CAPA</title>
1.1       albertel  267: </head>
1.43      www       268: $bodytag
1.1       albertel  269: <h1>Sorry ...</h1>
1.43      www       270: <p><b>$message</b></p>
1.46      matthew   271: <p>Please <a href="/adm/login?username=$FORM{'uname'}&domain=$FORM{'udom'}">log in again</a>.</p>
1.43      www       272: <p>
                    273: <a href="/adm/loginproblems.html">Problems?</a></p>
1.1       albertel  274: </body>
                    275: </html>
                    276: ENDFAILED
1.60      www       277: }
                    278: 
                    279: # --------------------------------------------------------------------- Charset
                    280: 
                    281: sub addcontent {
                    282:     my $encoding=&Apache::lonlocal::current_encoding;
                    283:     if ($encoding) {
                    284: 	return '; charset='.$encoding;
                    285:     } else {
                    286: 	return '';
                    287:     }
1.1       albertel  288: }
                    289: 
1.55      www       290: # ------------------------------------------------------------------ Rerouting!
                    291: 
                    292: sub reroute {
                    293:     my $r=shift;
                    294:     my $bodytag=&Apache::loncommon::bodytag('Rerouting');
                    295:     $r->send_cgi_header(<<ENDRFHEADER);
                    296: Content-type: text/html
                    297: 
                    298: ENDRFHEADER
                    299:     $r->print(<<ENDRFAILED);
                    300: <html>
                    301: <head>
                    302: <title>Rerouting Login to the LearningOnline Network with CAPA</title>
                    303: </head>
                    304: $bodytag
                    305: <h1>Sorry ...</h1>
                    306: Please <a href="/">log in again</a>.
                    307: </body>
                    308: </html>
                    309: ENDRFAILED
                    310: }
                    311: 
1.1       albertel  312: # ---------------------------------------------------------------- Main handler
                    313: 
                    314: sub handler {
                    315:     my $r = shift;
1.55      www       316: 
                    317: # Are we re-routing?
                    318:     if (-e '/home/httpd/html/lon-status/reroute.txt') {
                    319: 	&reroute($r);
                    320: 	return OK;
                    321:     }
1.56      www       322: 
1.57      www       323:     &Apache::lonlocal::get_language_handle($r);
1.1       albertel  324: 
1.59      www       325: # -------------------------------- Prevent users from attempting to login twice
                    326:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    327:     my $lonid=$cookies{'lonID'};
                    328:     my $cookie;
                    329:     if ($lonid) {
                    330: 	my $handle=$lonid->value;
                    331:         $handle=~s/\W//g;
                    332:         my $lonidsdir=$r->dir_config('lonIDsDir');
                    333:         if ((-e "$lonidsdir/$handle.id") && ($handle ne '')) {
                    334: # Indeed, a valid token is found
                    335: 	    $r->send_cgi_header(<<ENDFHEADER);
                    336: Content-type: text/html
                    337: 
                    338: ENDFHEADER
                    339: 	    my $bodytag=&Apache::loncommon::bodytag('Already logged in');
                    340: 	    $r->print(<<ENDFAILED);
                    341: <html>
                    342: <head>
                    343: <title>Already logged in</title>
                    344: </head>
                    345: $bodytag
                    346: <h1>You are already logged in</h1>
                    347: <p>Please either <a href="/adm/roles">continue the current session</a> or
                    348: <a href="/adm/logout">logout</a>.</p>
                    349: <p>
                    350: <a href="/adm/loginproblems.html">Problems?</a></p>
                    351: </body>
                    352: </html>
                    353: ENDFAILED
                    354:            return OK;
                    355: 	}
                    356:     }
                    357: 
                    358: # ---------------------------------------------------- No valid token, continue
                    359: 
                    360: 
1.1       albertel  361:     my $buffer;
1.49      albertel  362:     $r->read($buffer,$r->header_in('Content-length'),0);
1.1       albertel  363:     my @pairs=split(/&/,$buffer);
1.37      www       364:     my $pair; my $name; my $value;
                    365:     undef %FORM;
                    366:     %FORM=();
1.1       albertel  367:     foreach $pair (@pairs) {
                    368:        ($name,$value) = split(/=/,$pair);
1.7       www       369:        $value =~ tr/+/ /;
                    370:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.1       albertel  371:        $FORM{$name}=$value;
                    372:     } 
                    373: 
1.67      www       374:     if ((!$FORM{'uname'}) || (!$FORM{'upass0'}) || (!$FORM{'udom'})) {
1.43      www       375: 	failed($r,'Username, password and domain need to be specified.');
1.1       albertel  376:         return OK;
                    377:     }
1.61      www       378: 
                    379: # split user logging in and "su"-user
                    380: 
                    381:     ($FORM{'uname'},$FORM{'suname'})=split(/\:/,$FORM{'uname'});
1.1       albertel  382:     $FORM{'uname'} =~ s/\W//g;
1.61      www       383:     $FORM{'suname'} =~ s/\W//g;
1.1       albertel  384:     $FORM{'udom'}  =~ s/\W//g;
                    385: 
                    386:     my $role   = $r->dir_config('lonRole');
                    387:     my $domain = $r->dir_config('lonDefDomain');
                    388:     my $prodir = $r->dir_config('lonUsersDir');
                    389: 
1.8       www       390: # ---------------------------------------- Get the information from login token
                    391: 
                    392:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$FORM{'logtoken'},
                    393:                                       $FORM{'serverid'});
                    394: 
                    395:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
1.43      www       396: 	failed($r,'Information needed to verify your login information is missing, inaccessible or expired.');
1.8       www       397:         return OK;
1.44      www       398:     } else {
                    399:         unless (&Apache::lonnet::reply('tmpdel:'.$FORM{'logtoken'},
                    400:                                          $FORM{'serverid'}) eq 'ok') {
                    401:             &failed($r,'Session could not be opened.');
                    402: 	}
1.8       www       403:     }
1.9       www       404:     my ($key,$firsturl)=split(/&/,$tmpinfo);
1.8       www       405: 
                    406:     my $keybin=pack("H16",$key);
                    407: 
1.26      harris41  408:     my $cipher;
                    409:     if ($Crypt::DES::VERSION>=2.03) {
                    410: 	$cipher=new Crypt::DES $keybin;
                    411:     }
                    412:     else {
                    413: 	$cipher=new DES $keybin;
                    414:     }
1.67      www       415:     my $upass='';
                    416:     for (my $i=0;$i<=2;$i++) {
                    417: 	my $chunk=
                    418: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},0,16))));
1.8       www       419: 
1.67      www       420: 	$chunk.=
                    421: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},16,16))));
1.8       www       422: 
1.67      www       423: 	$chunk=substr($chunk,1,ord(substr($chunk,0,1)));
                    424: 	$upass.=$chunk;
                    425:     }
1.8       www       426: 
1.1       albertel  427: # ---------------------------------------------------------------- Authenticate
                    428:     my $authhost=Apache::lonnet::authenticate($FORM{'uname'},
1.8       www       429:                                               $upass,
1.1       albertel  430:                                               $FORM{'udom'});
                    431:     
                    432: # --------------------------------------------------------------------- Failed?
                    433: 
                    434:     if ($authhost eq 'no_host') {
1.43      www       435: 	failed($r,'Username and/or password could not be authenticated.');
1.1       albertel  436:         return OK;
                    437:     }
                    438: 
1.59      www       439:     if (($firsturl eq '') || 
                    440: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
1.24      www       441: 	$firsturl='/adm/roles';
1.7       www       442:     }
1.61      www       443: # --------------------------------- Are we attempting to login as somebody else?
                    444:     if ($FORM{'suname'}) {
                    445: # ------------ see if the original user has enough privileges to pull this stunt
                    446: 	if (&Apache::lonnet::privileged($FORM{'uname'},$FORM{'udom'})) {
                    447: # ---------------------------------------------------- see if the su-user exists
                    448: 	    unless (&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'})
                    449: 		eq 'no_host') {
                    450: 		&Apache::lonnet::logthis(&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'}));
                    451: # ------------------------------ see if the su-user is not too highly privileged
                    452: 		unless (&Apache::lonnet::privileged($FORM{'suname'},$FORM{'udom'})) {
                    453: # -------------------------------------------------------- actually switch users
                    454: 		    &Apache::lonnet::logperm('User '.$FORM{'uname'}.' at '.$FORM{'udom'}.
                    455: 			' logging in as '.$FORM{'suname'});
                    456: 		    $FORM{'uname'}=$FORM{'suname'};
                    457: 		} else {
                    458: 		    &Apache::lonnet::logthis('Attempted switch user to privileged user');
                    459: 		}
                    460: 	    }
                    461: 	} else {
                    462: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                    463: 	}
                    464:     }
                    465:     &success($r,$FORM{'uname'},$FORM{'udom'},$authhost,$firsturl);
1.1       albertel  466:     return OK;
                    467: }
                    468: 
                    469: 1;
                    470: __END__
1.7       www       471: 
                    472: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>