File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.80: download - view: text, annotated - select for diffs
Tue Jun 27 14:09:46 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: version_2_2_0, version_2_1_99_3, version_2_1_99_2, version_2_1_99_1, version_2_1_99_0, HEAD
- migration wants to add in some env vars

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.80 2006/06/27 14:09:46 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 LONCAPA;
   33: use Apache::Constants qw(:common);
   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, $extra_env) = @_;
   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=Apache::lonnet::dump('environment',$domain,$username);
  113:     my ($tmp) = keys(%userenv);
  114:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
  115: 	# default remote control to off
  116: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
  117:     } else {
  118: 	undef(%userenv);
  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 %initial_env = 
  136: 	    ("user.name"          => $username,
  137: 	     "user.domain"        => $domain,
  138: 	     "user.home"          => $authhost,
  139: 	     "browser.type"       => $clientbrowser,
  140: 	     "browser.version"    => $clientversion,
  141: 	     "browser.mathml"     => $clientmathml,
  142: 	     "browser.unicode"    => $clientunicode,
  143: 	     "browser.os"         => $clientos,
  144: 	     "server.domain"      => $r->dir_config('lonDefDomain'),
  145: 	     "request.course.fn"  => '',
  146: 	     "request.course.uri" => '',
  147: 	     "request.course.sec" => '',
  148: 	     "request.role"       => 'cm',
  149: 	     "request.role.adv"   => $env{'user.adv'},
  150: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
  151: 
  152:         if ($FORM{'localpath'}) {
  153: 	    $initial_env{"browser.localpath"}  = $FORM{'localpath'};
  154: 	    $initial_env{"browser.localres"}   = $FORM{'localres'};
  155:         }
  156: 	
  157: 	if ($public) {
  158: 	    $initial_env{"environment.remote"} = "off";
  159: 	}
  160: 	if ($FORM{'interface'}) {
  161: 	    $FORM{'interface'}=~s/\W//gs;
  162: 	    $initial_env{"browser.interface"} = $FORM{'interface'};
  163: 	    $env{'browser.interface'}=$FORM{'interface'};
  164: 	    foreach my $option ('imagesuppress','appletsuppress',
  165: 				'embedsuppress','fontenhance','blackwhite') {
  166: 		if (($FORM{$option} eq 'true') ||
  167: 		    ($userenv{$option} eq 'on')) {
  168: 		    $initial_env{"browser.$option"} = "on";
  169: 		}
  170: 	    }
  171: 	}
  172: 
  173: 	open(my $idf,">$lonids/$cookie.id");
  174: 	unless (flock($idf,LOCK_EX)) {
  175: 	    &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  176: 			   'Could not obtain exclusive lock in lonauth: '.$!);
  177: 	    close($idf);
  178: 	    return 'error: '.$!;
  179: 	}
  180: 
  181: 	while (my ($key,$value) = each(%initial_env)) {
  182: 	    print $idf (&escape($key).'='.&escape($value)."\n");
  183: 	}
  184: 	while (my ($key,$value) = each(%userenv)) {
  185: 	    print $idf (&escape('environment.'.$key).'='.&escape($value)."\n");
  186: 	}
  187: 	while (my ($key,$value) = each(%{$userroles})) {
  188: 	    print $idf (&escape($key).'='.&escape($value)."\n");
  189: 	}
  190: 	while (my ($key,$value) = each(%{$extra_env})) {
  191: 	    print $idf (&escape($key).'='.&escape($value)."\n");
  192: 	}
  193: 	close($idf);
  194:     }
  195:     $env{'request.role'}='cm';
  196:     $env{'request.role.adv'}=$env{'user.adv'};
  197:     $env{'browser.type'}=$clientbrowser;
  198: # -------------------------------------------------------------------- Log this
  199: 
  200:     &Apache::lonnet::log($domain,$username,$authhost,
  201:                          "Login $ENV{'REMOTE_ADDR'}");
  202: 
  203: # ------------------------------------------------- Check for critical messages
  204: 
  205:     my @what=&Apache::lonnet::dump('critical',$domain,$username);
  206:     if ($what[0]) {
  207: 	if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
  208: 	    $lowerurl='/adm/email?critical=display';
  209:         }
  210:     }
  211: 
  212: # ------------------------------------------------------------ Get cookie ready
  213: 
  214:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
  215: 
  216:     $cookie="lonID=$cookie; path=/";
  217: # -------------------------------------------------------- Menu script and info
  218:     my $windowinfo=&Apache::lonmenu::open($clientos);
  219:     my $startupremote=&Apache::lonmenu::startupremote($lowerurl);
  220:     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
  221:     my $setflags=&Apache::lonmenu::setflags();
  222:     my $maincall=&Apache::lonmenu::maincall();
  223:     my $start_page=&Apache::loncommon::start_page('Successful Login',
  224: 						  $startupremote,
  225: 						  {'no_inline_link' => 1,});
  226:     my $end_page  =&Apache::loncommon::end_page();
  227: 
  228:     my $continuelink;
  229:     if (($env{'browser.interface'} eq 'textual') ||
  230:         ($env{'environment.remote'} eq 'off')) {
  231: 	$continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";
  232:     }
  233: # ------------------------------------------------- Output for successful login
  234: 
  235:     &Apache::loncommon::content_type($r,'text/html');
  236:     $r->header_out('Set-cookie' => $cookie);
  237:     $r->send_http_header;
  238: 
  239:     my %lt=&Apache::lonlocal::texthash(
  240: 				       'wel' => 'Welcome',
  241: 				       'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up',
  242: 				       'pro' => 'Problems',
  243: 				       'log' => 'loginproblems.html',
  244: 				       );
  245:     $r->print(<<ENDSUCCESS);
  246: $start_page
  247: $setflags
  248: $windowinfo
  249: <h1>$lt{'wel'}</h1>
  250: $lt{'mes'}.<p>
  251: <a href="/adm/$lt{'log'}">$lt{'pro'}?</a></p>
  252: $remoteinfo
  253: $maincall
  254: $continuelink
  255: $end_page
  256: ENDSUCCESS
  257: }
  258: 
  259: # --------------------------------------------------------------- Failed login!
  260: 
  261: sub failed {
  262:     my ($r,$message) = @_;
  263:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,
  264: 						    {'no_inline_link' => 1,});
  265:     my $end_page   = &Apache::loncommon::end_page();
  266: 
  267:     my %lt=('sorry'  => &mt('Sorry ...'),
  268: 	    'please' => 
  269: 	    &mt('Please [_1]log in again[_2].',
  270: 		"<a href=\"/adm/login?username=$FORM{'uname'}&domain=$FORM{'udom'}\">",
  271: 		'</a>'),
  272: 	    'problemspage' => &mt('loginproblems.html'),
  273: 	    'problems'     => 'Problems',
  274: 	    );
  275:     &Apache::loncommon::content_type($r,'text/html');
  276:     $r->send_http_header;
  277: 
  278:     $r->print(<<ENDFAILED);
  279: $start_page
  280: <h1>$lt{'sorry'}</h1>
  281: <p><b>$message</b></p>
  282: <p>$lt{'please'}</p>
  283: <p>
  284: <a href="/adm/$lt{'problemspage'}">$lt{'problems'}</a></p>
  285: $end_page
  286: ENDFAILED
  287: }
  288: 
  289: # ------------------------------------------------------------------ Rerouting!
  290: 
  291: sub reroute {
  292:     my ($r) = @_;
  293:     &Apache::loncommon::content_type($r,'text/html');
  294:     $r->send_http_header;
  295:     my $msg='<h1>Sorry ...</h1>
  296:              Please <a href="/">log in again</a>.';
  297:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg);
  298: }
  299: 
  300: # ---------------------------------------------------------------- Main handler
  301: 
  302: sub handler {
  303:     my $r = shift;
  304: 
  305: # Are we re-routing?
  306:     if (-e '/home/httpd/html/lon-status/reroute.txt') {
  307: 	&reroute($r);
  308: 	return OK;
  309:     }
  310: 
  311:     &Apache::lonlocal::get_language_handle($r);
  312: 
  313: # -------------------------------- Prevent users from attempting to login twice
  314:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  315:     my $lonid=$cookies{'lonID'};
  316:     my $cookie;
  317:     if ($lonid) {
  318: 	my $handle=$lonid->value;
  319:         $handle=~s/\W//g;
  320:         my $lonidsdir=$r->dir_config('lonIDsDir');
  321:         if ((-e "$lonidsdir/$handle.id") && ($handle ne '')) {
  322: # Indeed, a valid token is found
  323: 	    &Apache::loncommon::content_type($r,'text/html');
  324: 	    $r->send_http_header;
  325: 	    my $start_page = 
  326: 		&Apache::loncommon::start_page('Already logged in');
  327: 	    my $end_page = 
  328: 		&Apache::loncommon::end_page();
  329: 	    $r->print(<<ENDFAILED);
  330: $start_page
  331: <h1>You are already logged in</h1>
  332: <p>Please either <a href="/adm/roles">continue the current session</a> or
  333: <a href="/adm/logout">logout</a>.</p>
  334: <p>
  335: <a href="/adm/loginproblems.html">Problems?</a></p>
  336: $end_page
  337: ENDFAILED
  338:            return OK;
  339: 	}
  340:     }
  341: 
  342: # ---------------------------------------------------- No valid token, continue
  343: 
  344: 
  345:     my $buffer;
  346:     $r->read($buffer,$r->header_in('Content-length'),0);
  347:     my @pairs=split(/&/,$buffer);
  348:     my $pair; my $name; my $value;
  349:     undef %FORM;
  350:     %FORM=();
  351:     foreach $pair (@pairs) {
  352:        ($name,$value) = split(/=/,$pair);
  353:        $value =~ tr/+/ /;
  354:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  355:        $FORM{$name}=$value;
  356:     } 
  357: 
  358:     if ((!$FORM{'uname'}) || (!$FORM{'upass0'}) || (!$FORM{'udom'})) {
  359: 	failed($r,'Username, password and domain need to be specified.');
  360:         return OK;
  361:     }
  362: 
  363: # split user logging in and "su"-user
  364: 
  365:     ($FORM{'uname'},$FORM{'suname'})=split(/\:/,$FORM{'uname'});
  366:     $FORM{'uname'} =~ s/\W//g;
  367:     $FORM{'suname'} =~ s/\W//g;
  368:     $FORM{'udom'}  =~ s/\W//g;
  369: 
  370:     my $role   = $r->dir_config('lonRole');
  371:     my $domain = $r->dir_config('lonDefDomain');
  372:     my $prodir = $r->dir_config('lonUsersDir');
  373: 
  374: # ---------------------------------------- Get the information from login token
  375: 
  376:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$FORM{'logtoken'},
  377:                                       $FORM{'serverid'});
  378: 
  379:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
  380: 	failed($r,'Information needed to verify your login information is missing, inaccessible or expired.');
  381:         return OK;
  382:     } else {
  383: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$FORM{'logtoken'},
  384: 					   $FORM{'serverid'});
  385:         if ( $reply ne 'ok' ) {
  386:             &failed($r,'Session could not be opened.');
  387: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $FORM{'serverid'}." to get login token");
  388: 	    return OK;
  389: 	}
  390:     }
  391:     my ($key,$firsturl)=split(/&/,$tmpinfo);
  392: 
  393:     my $keybin=pack("H16",$key);
  394: 
  395:     my $cipher;
  396:     if ($Crypt::DES::VERSION>=2.03) {
  397: 	$cipher=new Crypt::DES $keybin;
  398:     }
  399:     else {
  400: 	$cipher=new DES $keybin;
  401:     }
  402:     my $upass='';
  403:     for (my $i=0;$i<=2;$i++) {
  404: 	my $chunk=
  405: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},0,16))));
  406: 
  407: 	$chunk.=
  408: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},16,16))));
  409: 
  410: 	$chunk=substr($chunk,1,ord(substr($chunk,0,1)));
  411: 	$upass.=$chunk;
  412:     }
  413: 
  414: # ---------------------------------------------------------------- Authenticate
  415:     my $authhost=Apache::lonnet::authenticate($FORM{'uname'},
  416:                                               $upass,
  417:                                               $FORM{'udom'});
  418:     
  419: # --------------------------------------------------------------------- Failed?
  420: 
  421:     if ($authhost eq 'no_host') {
  422: 	failed($r,'Username and/or password could not be authenticated.');
  423:         return OK;
  424:     }
  425: 
  426:     if (($firsturl eq '') || 
  427: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  428: 	$firsturl='/adm/roles';
  429:     }
  430: # --------------------------------- Are we attempting to login as somebody else?
  431:     if ($FORM{'suname'}) {
  432: # ------------ see if the original user has enough privileges to pull this stunt
  433: 	if (&Apache::lonnet::privileged($FORM{'uname'},$FORM{'udom'})) {
  434: # ---------------------------------------------------- see if the su-user exists
  435: 	    unless (&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'})
  436: 		eq 'no_host') {
  437: 		&Apache::lonnet::logthis(&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'}));
  438: # ------------------------------ see if the su-user is not too highly privileged
  439: 		unless (&Apache::lonnet::privileged($FORM{'suname'},$FORM{'udom'})) {
  440: # -------------------------------------------------------- actually switch users
  441: 		    &Apache::lonnet::logperm('User '.$FORM{'uname'}.' at '.$FORM{'udom'}.
  442: 			' logging in as '.$FORM{'suname'});
  443: 		    $FORM{'uname'}=$FORM{'suname'};
  444: 		} else {
  445: 		    &Apache::lonnet::logthis('Attempted switch user to privileged user');
  446: 		}
  447: 	    }
  448: 	} else {
  449: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  450: 	}
  451:     }
  452:     &success($r,$FORM{'uname'},$FORM{'udom'},$authhost,$firsturl);
  453:     return OK;
  454: }
  455: 
  456: 1;
  457: __END__
  458: 
  459: 

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