File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.70: download - view: text, annotated - select for diffs
Mon Oct 24 21:32:42 2005 UTC (18 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- 'switch server' now really does

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

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