File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.66: download - view: text, annotated - select for diffs
Thu Apr 7 06:56:21 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: version_1_99_1_tmcc, version_1_99_0_tmcc, HEAD
- ENV -> env

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

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