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

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

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