File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.68: download - view: text, annotated - select for diffs
Tue Jul 5 21:30:14 2005 UTC (18 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#2573 can't do randomlabel/imageresponse/reactionresponse/organicresponse etc as 'public' resources,
   - public users on first access get a Cookie and a skeleton of a session environment now

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

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