File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.105: download - view: text, annotated - select for diffs
Sat Jul 17 20:02:02 2010 UTC (13 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Following the switch to 2.10, domains may prefer that their users do not have sessions hosted on older versions of LON-CAPA.
- Domain Coordinators can control:
  (a) where their users may have sessions hosted (by domain and/or LON-CAPA version).
  (b) which other domains will have user sessions hosted on servers in the domain.

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.105 2010/07/17 20:02:02 raeburn 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 DynaLoader; # for Crypt::DES version
   36: use Crypt::DES;
   37: use Apache::loncommon();
   38: use Apache::lonnet;
   39: use Apache::lonmenu();
   40: use Apache::createaccount;
   41: use Fcntl qw(:flock);
   42: use Apache::lonlocal;
   43: use HTML::Entities;
   44:  
   45: # ------------------------------------------------------------ Successful login
   46: sub success {
   47:     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
   48: 	$form) = @_;
   49: 
   50: # ------------------------------------------------------------ Get cookie ready
   51:     my $cookie =
   52: 	&Apache::loncommon::init_user_environment($r, $username, $domain,
   53: 						  $authhost, $form,
   54: 						  {'extra_env' => $extra_env,});
   55: 
   56:     my $public=($username eq 'public' && $domain eq 'public');
   57: 
   58:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   59: 
   60: # -------------------------------------------------------------------- Log this
   61: 
   62:     &Apache::lonnet::log($domain,$username,$authhost,
   63:                          "Login $ENV{'REMOTE_ADDR'}");
   64: 
   65: # ------------------------------------------------- Check for critical messages
   66: 
   67:     my @what=&Apache::lonnet::dump('critical',$domain,$username);
   68:     if ($what[0]) {
   69: 	if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
   70: 	    $lowerurl='/adm/email?critical=display';
   71:         }
   72:     }
   73: 
   74: # ------------------------------------------------------------ Get cookie ready
   75:     $cookie="lonID=$cookie; path=/";
   76: # -------------------------------------------------------- Menu script and info
   77:     my $destination = $lowerurl;
   78: 
   79:     if (defined($form->{role})) {
   80:         my $envkey = 'user.role.'.$form->{role};
   81:         my $now=time;
   82:         my $then=$env{'user.login.time'};
   83:         my $refresh=$env{'user.refresh.time'};
   84:         if (exists($env{$envkey})) {
   85:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
   86:             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,
   87:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
   88:             if ($tstatus eq 'is') {
   89:                 $destination  .= ($destination =~ /\?/) ? '&' : '?';
   90:                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
   91:                 $destination .= 'selectrole=1&'.$newrole.'=1';
   92:             }
   93:         }
   94:     }
   95:     if (defined($form->{symb})) {
   96:         my $destsymb = $form->{symb};
   97:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
   98:         if ($destsymb =~ /___/) {
   99:             # FIXME Need to deal with encrypted symbs and urls as needed.
  100:             my ($map,$resid,$desturl)=split(/___/,$destsymb);
  101:             unless ($desturl=~/^(adm|uploaded|editupload|public)/) {
  102:                 $desturl = &Apache::lonnet::clutter($desturl);
  103:             }
  104:             $desturl = &HTML::Entities::encode($desturl,'"<>&');
  105:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  106:             $destination .= '&destinationurl='.$desturl.
  107:                             '&destsymb='.$destsymb;
  108:         } else {
  109:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  110:             $destination .= '&destinationurl='.$destsymb;
  111:         }
  112:     }
  113: 
  114:     my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="loncapaclient";');
  115:     my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';
  116:     my $brcrum = [{'href' => '',
  117:                    'text' => 'Successful Login'},];
  118:     my $start_page=&Apache::loncommon::start_page('Successful Login',
  119:                                                   $header,
  120:                                                   {'bread_crumbs' => $brcrum,});
  121:     my $end_page  =&Apache::loncommon::end_page();
  122: 
  123: 	my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
  124: # ------------------------------------------------- Output for successful login
  125: 
  126:     &Apache::loncommon::content_type($r,'text/html');
  127:     $r->header_out('Set-cookie' => $cookie);
  128:     $r->send_http_header;
  129: 
  130:     my %lt=&Apache::lonlocal::texthash(
  131: 				       'wel' => 'Welcome',
  132: 				       'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up.',
  133: 				       'pro' => 'Login problems?',
  134: 				       'log' => 'loginproblems.html',
  135: 				       );
  136:     $r->print(<<ENDSUCCESS);
  137: $start_page
  138: $windowinfo
  139: <h1>$lt{'wel'}</h1>
  140: $lt{'mes'}<p>
  141: <a href="/adm/$lt{'log'}">$lt{'pro'}</a></p>
  142: $continuelink
  143: $end_page
  144: ENDSUCCESS
  145: }
  146: 
  147: # --------------------------------------------------------------- Failed login!
  148: 
  149: sub failed {
  150:     my ($r,$message,$form) = @_;
  151:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef);
  152:     my $retry = '/adm/login?username='.$form->{'uname'}.
  153:                 '&domain='.$form->{'udom'};
  154:     if (exists($form->{role})) {
  155:         $retry .= '&role='.$form->{role};
  156:     }
  157:     if (exists($form->{symb})) {
  158:         $retry .= '&symb='.$form->{symb};
  159:     }
  160:     my $end_page   = &Apache::loncommon::end_page();
  161:     &Apache::loncommon::content_type($r,'text/html');
  162:     $r->send_http_header;
  163:     $r->print(
  164:        $start_page
  165:       .'<h1>'.&mt('Sorry ...').'</h1>'
  166:       .'<p class="LC_warning">'.&mt($message).'</p>'
  167:       .'<p>'.&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>')
  168:       .'</p>'
  169:       .'<p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'
  170:       .$end_page
  171:     );
  172:  }
  173: 
  174: # ------------------------------------------------------------------ Rerouting!
  175: 
  176: sub reroute {
  177:     my ($r) = @_;
  178:     &Apache::loncommon::content_type($r,'text/html');
  179:     $r->send_http_header;
  180:     my $msg='<h1>'.&mt('Sorry ...').'</h1>'
  181:            .&mt('Please [_1]log in again[_2].');
  182:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg);
  183: }
  184: 
  185: # ---------------------------------------------------------------- Main handler
  186: 
  187: sub handler {
  188:     my $r = shift;
  189:     my $form;
  190: # Are we re-routing?
  191:     if (-e '/home/httpd/html/lon-status/reroute.txt') {
  192: 	&reroute($r);
  193: 	return OK;
  194:     }
  195: 
  196:     &Apache::lonlocal::get_language_handle($r);
  197: 
  198: # -------------------------------- Prevent users from attempting to login twice
  199:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  200:     if ($handle ne '') {
  201:         my $lonidsdir=$r->dir_config('lonIDsDir');
  202:         if ($handle=~/^publicuser\_/) {
  203: # For "public user" - remove it, we apparently really want to login
  204:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
  205:         } else {
  206: # Indeed, a valid token is found
  207:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  208: 	    &Apache::loncommon::content_type($r,'text/html');
  209: 	    $r->send_http_header;
  210: 	    my $start_page = 
  211: 	        &Apache::loncommon::start_page('Already logged in');
  212: 	    my $end_page = 
  213: 	        &Apache::loncommon::end_page();
  214:             my $dest = '/adm/roles';
  215:             if ($env{'form.firsturl'} ne '') {
  216:                 $dest = $env{'form.firsturl'};
  217:             }
  218:             $r->print(
  219:                $start_page
  220:               .'<h1>'.&mt('You are already logged in!').'</h1>'
  221:               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  222:                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
  223:               .'</p>'
  224:               .$end_page
  225:             );
  226:             return OK;
  227:         }
  228:     }
  229: 
  230: # ---------------------------------------------------- No valid token, continue
  231: 
  232: 
  233:     my $buffer;
  234:     if ($r->header_in('Content-length') > 0) {
  235: 	$r->read($buffer,$r->header_in('Content-length'),0);
  236:     }
  237:     my %form;
  238:     foreach my $pair (split(/&/,$buffer)) {
  239:        my ($name,$value) = split(/=/,$pair);
  240:        $value =~ tr/+/ /;
  241:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  242:        $form{$name}=$value;
  243:     } 
  244: 
  245:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  246: 	&failed($r,'Username, password and domain need to be specified.',
  247: 		\%form);
  248:         return OK;
  249:     }
  250: 
  251: # split user logging in and "su"-user
  252: 
  253:     ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});
  254:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  255:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  256:     $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});
  257: 
  258:     my $role   = $r->dir_config('lonRole');
  259:     my $domain = $r->dir_config('lonDefDomain');
  260:     my $prodir = $r->dir_config('lonUsersDir');
  261:     my $contact_name = &mt('LON-CAPA helpdesk');
  262: 
  263: # ---------------------------------------- Get the information from login token
  264: 
  265:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  266:                                       $form{'serverid'});
  267: 
  268:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
  269: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  270:         return OK;
  271:     } else {
  272: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  273: 					   $form{'serverid'});
  274:         if ( $reply ne 'ok' ) {
  275:             &failed($r,'Session could not be opened.',\%form);
  276: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  277: 	    return OK;
  278: 	}
  279:     }
  280: 
  281:     if (!&Apache::lonnet::domain($form{'udom'})) {
  282:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  283:         return OK;
  284:     }
  285: 
  286:     my ($key,$firsturl,$rolestr,$symbstr)=split(/&/,$tmpinfo);
  287:     if ($rolestr) {
  288:         $rolestr = &unescape($rolestr);
  289:     }
  290:     if ($symbstr) {
  291:         $symbstr= &unescape($symbstr);
  292:     }
  293:     if ($rolestr =~ /^role=/) {
  294:         (undef,$form{'role'}) = split('=',$rolestr);
  295:     }
  296:     if ($symbstr =~ /^symb=/) { 
  297:         (undef,$form{'symb'}) = split('=',$symbstr);
  298:     }
  299: 
  300:     my $keybin=pack("H16",$key);
  301: 
  302:     my $cipher;
  303:     if ($Crypt::DES::VERSION>=2.03) {
  304: 	$cipher=new Crypt::DES $keybin;
  305:     }
  306:     else {
  307: 	$cipher=new DES $keybin;
  308:     }
  309:     my $upass='';
  310:     for (my $i=0;$i<=2;$i++) {
  311: 	my $chunk=
  312: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},0,16))));
  313: 
  314: 	$chunk.=
  315: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},16,16))));
  316: 
  317: 	$chunk=substr($chunk,1,ord(substr($chunk,0,1)));
  318: 	$upass.=$chunk;
  319:     }
  320: 
  321: # ---------------------------------------------------------------- Authenticate
  322:     my @cancreate;
  323:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  324:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
  325:         if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
  326:             if (ref($domconfig{'usercreation'}{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  327:                 @cancreate = @{$domconfig{'usercreation'}{'cancreate'}{'selfcreate'}};
  328:             } elsif (($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') && 
  329:                      ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne '')) {
  330:                 @cancreate = ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'});
  331:             }
  332:         }
  333:     }
  334:     my $defaultauth;
  335:     if (grep(/^login$/,@cancreate)) {
  336:         $defaultauth = 1;
  337:     }
  338:     my $clientcancheckhost = 1;
  339:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  340:                                               $form{'udom'},$defaultauth,
  341:                                               $clientcancheckhost);
  342:     
  343: # --------------------------------------------------------------------- Failed?
  344: 
  345:     if ($authhost eq 'no_host') {
  346: 	&failed($r,'Username and/or password could not be authenticated.',
  347: 		\%form);
  348:         return OK;
  349:     } elsif ($authhost eq 'no_account_on_host') {
  350:         my %domconfig = 
  351:             &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  352:         if (grep(/^login$/,@cancreate)) {
  353:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  354:             &check_can_host($r,\%form,'no_account_on_host',$domdesc);
  355:             my $start_page = 
  356:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA');
  357:             my $lonhost = $r->dir_config('lonHostID');
  358:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  359:             my $contacts = 
  360:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  361:                                                         $form{'udom'},$origmail);
  362:             my ($contact_email) = split(',',$contacts); 
  363:             my $output = &Apache::createaccount::username_check($form{'uname'}, 
  364:                                                                 $form{'udom'},$domdesc,'',
  365:                                                                 $lonhost,$contact_email,$contact_name);
  366:             &Apache::loncommon::content_type($r,'text/html');
  367:             $r->send_http_header;
  368:             &Apache::createaccount::print_header($r,$start_page);
  369:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  370:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  371:                       $output.&Apache::loncommon::end_page());
  372:             return OK;
  373:         } else {
  374:             &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);
  375:             return OK;
  376:         }
  377:     }
  378: 
  379:     if (($firsturl eq '') || 
  380: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  381: 	$firsturl='/adm/roles';
  382:     }
  383: # --------------------------------- Are we attempting to login as somebody else?
  384:     if ($form{'suname'}) {
  385: # ------------ see if the original user has enough privileges to pull this stunt
  386: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {
  387: # ---------------------------------------------------- see if the su-user exists
  388: 	    unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})
  389: 		eq 'no_host') {
  390: 		&Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));
  391: # ------------------------------ see if the su-user is not too highly privileged
  392: 		unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {
  393: # -------------------------------------------------------- actually switch users
  394: 		    &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.
  395: 			' logging in as '.$form{'suname'});
  396: 		    $form{'uname'}=$form{'suname'};
  397: 		} else {
  398: 		    &Apache::lonnet::logthis('Attempted switch user to privileged user');
  399: 		}
  400: 	    }
  401: 	} else {
  402: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  403: 	}
  404:     }
  405: 
  406:     &check_can_host($r,\%form,$authhost);
  407: 
  408:     if ($r->dir_config("lonBalancer") eq 'yes') {
  409: 	&success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  410: 		 \%form);
  411:         my ($otherserver) = &choose_server($form{'udom'});
  412: 	$r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
  413:     } else {
  414: 	&success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
  415: 		 \%form);
  416:     }
  417:     return OK;
  418: }
  419: 
  420: sub check_can_host {
  421:     my ($r,$form,$authhost,$domdesc) = @_;
  422:     return unless (ref($form) eq 'HASH');
  423:     my $canhost = 1;
  424:     my @machinedoms = &Apache::lonnet::current_machine_domains();
  425:     my $udom = $form->{'udom'};
  426:     unless (grep(/^\Q$udom\E/,@machinedoms)) {
  427:         my $defdom = &Apache::lonnet::default_login_domain();
  428:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($defdom);
  429:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  430:         my $loncaparev;
  431:         if ($authhost eq 'no_account_on_host') {
  432:             $loncaparev = &Apache::lonnet::get_server_loncaparev($defdom);
  433:         } else {
  434:             $loncaparev = &Apache::lonnet::get_server_loncaparev($defdom,$authhost);
  435:         }
  436:         $canhost = &Apache::lonnet::can_host_session($udom,$defdom,$loncaparev,$udomdefaults{'remotesessions'},$defdomdefaults{'hostedsessions'});
  437:     }
  438:     unless ($canhost) {
  439:         if ($authhost eq 'no_account_on_host') {
  440:             my ($login_host,$hostname) = &choose_server($udom);
  441:             &Apache::loncommon::content_type($r,'text/html');
  442:             $r->send_http_header;
  443:             if ($login_host ne '') {
  444:                 my $protocol = $Apache::lonnet::protocol{$login_host};
  445:                 $protocol = 'http' if ($protocol ne 'https');
  446:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
  447:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
  448:                           '<h3>'.&mt('Account creation').'</h3>'.
  449:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  450:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
  451:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
  452:                           &Apache::loncommon::end_page());
  453:             } else {
  454:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  455:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
  456:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  457:                           '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.
  458:                           &Apache::loncommon::end_page());
  459:             }
  460:             return OK;
  461:         } else {
  462:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
  463:                      $form);
  464:             my ($otherserver) = &choose_server($udom);
  465:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
  466:         }
  467:     }
  468: }
  469: 
  470: sub choose_server {
  471:     my ($udom) = @_;
  472:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  473:     my %servers = &Apache::lonnet::get_servers($udom);
  474:     my $lowest_load = 30000;
  475:     my ($login_host,$hostname);
  476:     foreach my $lonhost (keys(%servers)) {
  477:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  478:         if ($loginvia eq '') {
  479:             ($login_host, $lowest_load) =
  480:             &Apache::lonnet::compare_server_load($lonhost, $login_host, $lowest_load);
  481:         }
  482:     }
  483:     if ($login_host ne '') {
  484:         $hostname = $servers{$login_host};
  485:     }
  486:     return ($login_host,$hostname);
  487: }
  488: 
  489: 1;
  490: __END__
  491: 
  492: 

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