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

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

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