File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.121.2.18: download - view: text, annotated - select for diffs
Sat Aug 3 22:45:30 2019 UTC (4 years, 10 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.143, 1.154

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.121.2.18 2019/08/03 22:45:30 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 Apache::loncommon();
   36: use Apache::lonnet;
   37: use Apache::lonmenu();
   38: use Apache::createaccount;
   39: use Fcntl qw(:flock);
   40: use Apache::lonlocal;
   41: use Apache::File();
   42: use HTML::Entities;
   43: use Digest::MD5;
   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 cookies ready
   75:     my ($securecookie,$defaultcookie);
   76:     my $ssl = $r->subprocess_env('https');
   77:     if ($ssl) {
   78:         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
   79:         my $lonidsdir=$r->dir_config('lonIDsDir');
   80:         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
   81:             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
   82:             if (-e "$lonidsdir/$linkname.id") {
   83:                 unlink("$lonidsdir/$linkname.id");
   84:             }
   85:             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
   86:                                               "$lonidsdir/$linkname.id"); 1 };
   87:             if ($made_symlink) {
   88:                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
   89:                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
   90:             }
   91:         }
   92:     } else {
   93:         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
   94:     }
   95: # -------------------------------------------------------- Menu script and info
   96:     my $destination = $lowerurl;
   97: 
   98:     if (defined($form->{role})) {
   99:         my $envkey = 'user.role.'.$form->{role};
  100:         my $now=time;
  101:         my $then=$env{'user.login.time'};
  102:         my $refresh=$env{'user.refresh.time'};
  103:         my $update=$env{'user.update.time'};
  104:         if (!$update) {
  105:             $update = $then;
  106:         }
  107:         if (exists($env{$envkey})) {
  108:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
  109:             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
  110:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  111:             if ($tstatus eq 'is') {
  112:                 $destination  .= ($destination =~ /\?/) ? '&' : '?';
  113:                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
  114:                 $destination .= 'selectrole=1&'.$newrole.'=1';
  115:             }
  116:         }
  117:     }
  118:     if (defined($form->{symb})) {
  119:         my $destsymb = $form->{symb};
  120:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  121:         if ($destsymb =~ /___/) {
  122:             # FIXME Need to deal with encrypted symbs and urls as needed.
  123:             my ($map,$resid,$desturl)=split(/___/,$destsymb);
  124:             $desturl = &Apache::lonnet::clutter($desturl);
  125:             $desturl = &HTML::Entities::encode($desturl,'"<>&');
  126:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  127:             $destination .= 'destinationurl='.$desturl.
  128:                             '&destsymb='.$destsymb;
  129:         } else {
  130:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  131:             $destination .= 'destinationurl='.$destsymb;
  132:         }
  133:     }
  134:     if ($destination =~ m{^/adm/roles}) {
  135:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  136:         $destination .= 'source=login';
  137:     }
  138: 
  139:     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});
  140:     my $startupremote=&Apache::lonmenu::startupremote($destination);
  141:     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
  142:     my $setflags=&Apache::lonmenu::setflags();
  143:     my $maincall=&Apache::lonmenu::maincall();
  144:     my $brcrum = [{'href' => '',
  145:                    'text' => 'Successful Login'},];
  146:     my $start_page=&Apache::loncommon::start_page('Successful Login',
  147:                                                   $startupremote,
  148:                                                   {'no_inline_link' => 1,
  149:                                                    'bread_crumbs' => $brcrum,});
  150:     my $end_page  =&Apache::loncommon::end_page();
  151: 
  152:     my $continuelink;
  153:     if ($env{'environment.remote'} eq 'off') {
  154: 	$continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
  155:     }
  156: # ------------------------------------------------- Output for successful login
  157: 
  158:     &Apache::loncommon::content_type($r,'text/html');
  159:     if ($securecookie) {
  160:         $r->headers_out->add('Set-cookie' => $securecookie);
  161:     }
  162:     if ($defaultcookie) {
  163:         $r->headers_out->add('Set-cookie' => $defaultcookie);
  164:     }
  165:     $r->send_http_header;
  166: 
  167:     my %lt=&Apache::lonlocal::texthash(
  168: 				       'wel' => 'Welcome',
  169: 				       'pro' => 'Login problems?',
  170: 				       );
  171:     my $loginhelp = &loginhelpdisplay($domain);
  172:     if ($loginhelp) {
  173:         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
  174:     }
  175: 
  176:     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>'); 
  177:     $r->print(<<ENDSUCCESS);
  178: $start_page
  179: $setflags
  180: $windowinfo
  181: <h1>$lt{'wel'}</h1>
  182: $welcome
  183: $loginhelp
  184: $remoteinfo
  185: $maincall
  186: $continuelink
  187: $end_page
  188: ENDSUCCESS
  189:     return;
  190: }
  191: 
  192: # --------------------------------------------------------------- Failed login!
  193: 
  194: sub failed {
  195:     my ($r,$message,$form) = @_;
  196:     (undef,undef,undef,my $clientmathml,my $clientunicode) =
  197:         &Apache::loncommon::decode_user_agent();
  198:     my $args = {};
  199:     if ($clientunicode && !$clientmathml) {
  200:         $args = {'browser.unicode' => 1};
  201:     }
  202: 
  203:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
  204:     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
  205:     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
  206:     if (&Apache::lonnet::domain($udom,'description') eq '') {
  207:         undef($udom);
  208:     }
  209:     my $retry = '/adm/login';
  210:     if ($uname eq $form->{'uname'}) {
  211:         $retry .= '?username='.$uname;
  212:     }
  213:     if ($udom) {
  214:         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
  215:     }
  216:     if (exists($form->{role})) {
  217:         my $role = &Apache::loncommon::cleanup_html($form->{role});
  218:         if ($role ne '') {
  219:             $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
  220:         }
  221:     }
  222:     if (exists($form->{symb})) {
  223:         my $symb = &Apache::loncommon::cleanup_html($form->{symb});
  224:         if ($symb ne '') {
  225:             $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
  226:         }
  227:     }
  228:     my $end_page = &Apache::loncommon::end_page();
  229:     &Apache::loncommon::content_type($r,'text/html');
  230:     $r->send_http_header;
  231:     my @actions =
  232:          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
  233:     my $loginhelp = &loginhelpdisplay($udom);
  234:     if ($loginhelp) {
  235:         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
  236:     }
  237:     #FIXME: link to helpdesk might be added here
  238: 
  239:     $r->print(
  240:        $start_page
  241:       .'<h2>'.&mt('Sorry ...').'</h2>'
  242:       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
  243:       .&Apache::lonhtmlcommon::actionbox(\@actions)
  244:       .$end_page
  245:     );
  246:  }
  247: 
  248: # ------------------------------------------------------------------ Rerouting!
  249: 
  250: sub reroute {
  251:     my ($r) = @_;
  252:     &Apache::loncommon::content_type($r,'text/html');
  253:     $r->send_http_header;
  254:     my $msg='<b>'.&mt('Sorry ...').'</b><br />'
  255:            .&mt('Please [_1]log in again[_2].');
  256:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
  257: }
  258: 
  259: # ---------------------------------------------------------------- Main handler
  260: 
  261: sub handler {
  262:     my $r = shift;
  263:     my $londocroot = $r->dir_config('lonDocRoot');
  264: # Are we re-routing?
  265:     if (-e "$londocroot/lon-status/reroute.txt") {
  266: 	&reroute($r);
  267: 	return OK;
  268:     }
  269: 
  270:     &Apache::lonlocal::get_language_handle($r);
  271: 
  272: # -------------------------------- Prevent users from attempting to login twice
  273:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  274:     if ($handle ne '') {
  275:         my $lonidsdir=$r->dir_config('lonIDsDir');
  276:         if ($handle=~/^publicuser\_/) {
  277: # For "public user" - remove it, we apparently really want to login
  278:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
  279:         } else {
  280: # Indeed, a valid token is found
  281:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  282: 	    &Apache::loncommon::content_type($r,'text/html');
  283: 	    $r->send_http_header;
  284: 	    my $start_page = 
  285: 	        &Apache::loncommon::start_page('Already logged in');
  286: 	    my $end_page = 
  287: 	        &Apache::loncommon::end_page();
  288:             my $dest = '/adm/roles';
  289:             if ($env{'form.firsturl'} ne '') {
  290:                 $dest = $env{'form.firsturl'};
  291:             }
  292:             $r->print(
  293:                $start_page
  294:               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  295:               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  296:                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
  297:               .'</p>'
  298:               .$end_page
  299:             );
  300:             return OK;
  301:         }
  302:     }
  303: 
  304: # ---------------------------------------------------- No valid token, continue
  305: 
  306: 
  307:     my $buffer;
  308:     if ($r->header_in('Content-length') > 0) {
  309: 	$r->read($buffer,$r->header_in('Content-length'),0);
  310:     }
  311:     my %form;
  312:     foreach my $pair (split(/&/,$buffer)) {
  313:        my ($name,$value) = split(/=/,$pair);
  314:        $value =~ tr/+/ /;
  315:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  316:        $form{$name}=$value;
  317:     }
  318: 
  319:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  320: 	&failed($r,'Username, password and domain need to be specified.',
  321: 		\%form);
  322:         return OK;
  323:     }
  324: 
  325: # split user logging in and "su"-user
  326: 
  327:     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
  328:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  329:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  330:     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
  331:     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
  332: 
  333:     my $role   = $r->dir_config('lonRole');
  334:     my $domain = $r->dir_config('lonDefDomain');
  335:     my $prodir = $r->dir_config('lonUsersDir');
  336:     my $contact_name = &mt('LON-CAPA helpdesk');
  337: 
  338: # ---------------------------------------- Get the information from login token
  339: 
  340:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  341:                                       $form{'serverid'});
  342: 
  343:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
  344:         ($tmpinfo eq 'no_such_host')) {
  345: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  346:         return OK;
  347:     } else {
  348: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  349: 					   $form{'serverid'});
  350:         if ( $reply ne 'ok' ) {
  351:             &failed($r,'Session could not be opened.',\%form);
  352: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  353: 	    return OK;
  354: 	}
  355:     }
  356: 
  357:     if (!&Apache::lonnet::domain($form{'udom'})) {
  358:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  359:         return OK;
  360:     }
  361: 
  362:     my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
  363:     if ($rolestr) {
  364:         $rolestr = &unescape($rolestr);
  365:     }
  366:     if ($symbstr) {
  367:         $symbstr= &unescape($symbstr);
  368:     }
  369:     if ($iptokenstr) {
  370:         $iptokenstr = &unescape($iptokenstr);
  371:     }
  372:     if ($rolestr =~ /^role=/) {
  373:         (undef,$form{'role'}) = split('=',$rolestr);
  374:     }
  375:     if ($symbstr =~ /^symb=/) { 
  376:         (undef,$form{'symb'}) = split('=',$symbstr);
  377:     }
  378:     if ($iptokenstr =~ /^iptoken=/) {
  379:         (undef,$form{'iptoken'}) = split('=',$iptokenstr);
  380:     }
  381: 
  382:     my $upass = &Apache::loncommon::des_decrypt($key,$form{'upass0'});
  383: 
  384: # ---------------------------------------------------------------- Authenticate
  385: 
  386:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  387:     my ($cancreate,$statustocreate) =
  388:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
  389:     my $defaultauth;
  390:     if (ref($cancreate) eq 'ARRAY') {
  391:         if (grep(/^login$/,@{$cancreate})) {
  392:             $defaultauth = 1;
  393:         }
  394:     }
  395:     my $clientcancheckhost = 1;
  396:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  397:                                               $form{'udom'},$defaultauth,
  398:                                               $clientcancheckhost);
  399:     
  400: # --------------------------------------------------------------------- Failed?
  401: 
  402:     if ($authhost eq 'no_host') {
  403: 	&failed($r,'Username and/or password could not be authenticated.',
  404: 		\%form);
  405:         return OK;
  406:     } elsif ($authhost eq 'no_account_on_host') {
  407:         if ($defaultauth) {
  408:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  409:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
  410:                 return OK;
  411:             }
  412:             my $start_page = 
  413:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',
  414:                                                '',{'no_inline_link'   => 1,});
  415:             my $lonhost = $r->dir_config('lonHostID');
  416:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  417:             my $contacts = 
  418:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  419:                                                         $form{'udom'},$origmail);
  420:             my ($contact_email) = split(',',$contacts); 
  421:             my $output = 
  422:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
  423:                                                        $domdesc,'',$lonhost,
  424:                                                        $contact_email,$contact_name,
  425:                                                        undef,$statustocreate);
  426:             &Apache::loncommon::content_type($r,'text/html');
  427:             $r->send_http_header;
  428:             &Apache::createaccount::print_header($r,$start_page);
  429:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  430:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  431:                       $output.&Apache::loncommon::end_page());
  432:             return OK;
  433:         } else {
  434:             &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);
  435:             return OK;
  436:         }
  437:     }
  438: 
  439:     if (($firsturl eq '') || 
  440: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  441: 	$firsturl='/adm/roles';
  442:     }
  443: 
  444:     my $hosthere;
  445:     if ($form{'iptoken'}) {
  446:         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  447:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  448:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
  449:             ($sessiondata{'username'} eq $form{'uname'})) {
  450:             $hosthere = 1;
  451:         }
  452:     }
  453: 
  454: # --------------------------------- Are we attempting to login as somebody else?
  455:     if ($form{'suname'}) {
  456:         my ($suname,$sudom,$sudomref);
  457:         $suname = $form{'suname'};
  458:         $sudom = $form{'udom'};
  459:         if ($form{'sudom'}) {
  460:             unless ($sudom eq $form{'sudom'}) {
  461:                 if (&Apache::lonnet::domain($form{'sudom'})) {
  462:                     $sudomref = [$form{'sudom'}];
  463:                     $sudom = $form{'sudom'};
  464:                 }
  465:             }
  466:         }
  467: # ------------ see if the original user has enough privileges to pull this stunt
  468: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
  469: # ---------------------------------------------------- see if the su-user exists
  470: 	    unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
  471: # ------------------------------ see if the su-user is not too highly privileged
  472: 		if (&Apache::lonnet::privileged($suname,$sudom)) {
  473:                     &Apache::lonnet::logthis('Attempted switch user to privileged user');
  474:                 } else {
  475:                     my $noprivswitch;
  476: #
  477: # su-user's home server and user's home server must have one of:
  478: # (a) same domain
  479: # (b) same primary library server for the two domains
  480: # (c) same "internet domain" for primary library server(s) for home servers' domains
  481: #
  482:                     my $suprim = &Apache::lonnet::domain($sudom,'primary');
  483:                     my $suintdom = &Apache::lonnet::internet_dom($suprim);
  484:                     unless ($sudom eq $form{'udom'}) {
  485:                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
  486:                         my $uintdom = &Apache::lonnet::internet_dom($uprim);
  487:                         unless ($suprim eq $uprim) {
  488:                             unless ($suintdom eq $uintdom) {
  489:                                 &Apache::lonnet::logthis('Attempted switch user '
  490:                                    .'to user with different "internet domain".');
  491:                                 $noprivswitch = 1;
  492:                             }
  493:                         }
  494:                     }
  495: 
  496:                     unless ($noprivswitch) {
  497: #
  498: # server where log-in occurs must have same "internet domain" as su-user's home
  499: # server
  500: #
  501:                         my $lonhost = $r->dir_config('lonHostID');
  502:                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
  503:                         if ($hostintdom ne $suintdom) {
  504:                             &Apache::lonnet::logthis('Attempted switch user on a '
  505:                                 .'server with a different "internet domain".');
  506:                         } else {
  507: 
  508: # -------------------------------------------------------- actually switch users
  509: 
  510: 			    &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
  511: 				$form{'udom'}.' logging in as '.$suname.':'.$sudom);
  512: 			    $form{'uname'}=$suname;
  513:                             if ($form{'udom'} ne $sudom) {
  514:                                 $form{'udom'}=$sudom;
  515:                             }
  516:                         }
  517:                     }
  518: 		}
  519: 	    }
  520: 	} else {
  521: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  522: 	}
  523:     }
  524: 
  525:     my ($is_balancer,$otherserver);
  526: 
  527:     unless ($hosthere) {
  528:         ($is_balancer,$otherserver) =
  529:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
  530:         if ($is_balancer) {
  531:             if ($otherserver eq '') {
  532:                 my $lowest_load;
  533:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
  534:                 if ($lowest_load > 100) {
  535:                     $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
  536:                 }
  537:             }
  538:             if ($otherserver ne '') {
  539:                 my @hosts = &Apache::lonnet::current_machine_ids();
  540:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
  541:                     $hosthere = $otherserver;
  542:                 }
  543:             }
  544:         }
  545:     }
  546: 
  547:     if (($is_balancer) && (!$hosthere)) {
  548:         if ($otherserver) {
  549:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  550:                      \%form);
  551:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  552:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  553:                 $switchto .= '&origurl='.$firsturl;
  554:             }
  555:             if ($form{'role'}) {
  556:                 $switchto .= '&role='.$form{'role'};
  557:             }
  558:             if ($form{'symb'}) {
  559:                 $switchto .= '&symb='.$form{'symb'};
  560:             }
  561:             $r->internal_redirect($switchto);
  562:         } else {
  563:             $r->print(&noswitch());
  564:         }
  565:         return OK;
  566:     } else {
  567:         if (!&check_can_host($r,\%form,$authhost)) {
  568:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
  569:             if ($otherserver) {
  570:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  571:                          \%form);
  572:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  573:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  574:                     $switchto .= '&origurl='.$firsturl;
  575:                 }
  576:                 if ($form{'role'}) {
  577:                     $switchto .= '&role='.$form{'role'};
  578:                 }
  579:                 if ($form{'symb'}) {
  580:                     $switchto .= '&symb='.$form{'symb'};
  581:                 }
  582:                 $r->internal_redirect($switchto);
  583:             } else {
  584:                 $r->print(&noswitch());
  585:             }
  586:             return OK;
  587:         }
  588: 
  589: # ------------------------------------------------------- Do the load balancing
  590: 
  591: # ---------------------------------------------------------- Determine own load
  592:         my $loadlim = $r->dir_config('lonLoadLim');
  593:         my $loadavg;
  594:         {
  595:             my $loadfile=Apache::File->new('/proc/loadavg');
  596:             $loadavg=<$loadfile>;
  597:         }
  598:         $loadavg =~ s/\s.*//g;
  599:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
  600:         my $userloadpercent=&Apache::lonnet::userload();
  601: 
  602: # ---------------------------------------------------------- Are we overloaded?
  603:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
  604:             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
  605:             if (!$unloaded) {
  606:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
  607:             }
  608:             if ($unloaded) {
  609:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
  610:                          undef,\%form);
  611:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
  612:                 return OK;
  613:             }
  614:         }
  615:         if (($is_balancer) && ($hosthere)) {
  616:             $form{'noloadbalance'} = $hosthere;
  617:         }
  618:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
  619:                  \%form);
  620:         return OK;
  621:     }
  622: }
  623: 
  624: sub check_can_host {
  625:     my ($r,$form,$authhost,$domdesc) = @_;
  626:     return unless (ref($form) eq 'HASH');
  627:     my $canhost = 1;
  628:     my $lonhost = $r->dir_config('lonHostID');
  629:     my $udom = $form->{'udom'};
  630:     my @intdoms;
  631:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
  632:     if (ref($internet_names) eq 'ARRAY') {
  633:         @intdoms = @{$internet_names};
  634:     }
  635:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  636:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  637:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
  638:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
  639:         my $hostname = &Apache::lonnet::hostname($lonhost);
  640:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
  641:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
  642:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
  643:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  644:         my $loncaparev;
  645:         if ($authhost eq 'no_account_on_host') {
  646:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
  647:         } else {
  648:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
  649:         }
  650:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
  651:                                                      $udomdefaults{'remotesessions'},
  652:                                                      $defdomdefaults{'hostedsessions'});
  653:     }
  654:     unless ($canhost) {
  655:         if ($authhost eq 'no_account_on_host') {
  656:             my $checkloginvia = 1;
  657:             my ($login_host,$hostname) = 
  658:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
  659:             &Apache::loncommon::content_type($r,'text/html');
  660:             $r->send_http_header;
  661:             if ($login_host ne '') {
  662:                 my $protocol = $Apache::lonnet::protocol{$login_host};
  663:                 $protocol = 'http' if ($protocol ne 'https');
  664:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
  665:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
  666:                           '<h3>'.&mt('Account creation').'</h3>'.
  667:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  668:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
  669:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
  670:                           &Apache::loncommon::end_page());
  671:             } else {
  672:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  673:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
  674:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  675:                           '<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>'.
  676:                           &Apache::loncommon::end_page());
  677:             }
  678:         } else {
  679:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
  680:                      $form);
  681:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
  682:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
  683:         }
  684:     }
  685:     return $canhost;
  686: }
  687: 
  688: sub noswitch {
  689:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  690:                  '<h3>'.&mt('Session unavailable').'</h3>'.
  691:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
  692:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
  693:                  &Apache::loncommon::end_page();
  694:     return $result;
  695: }
  696: 
  697: sub loginhelpdisplay {
  698:     my ($authdomain) = @_;
  699:     my $login_help = 1;
  700:     my $lang = &Apache::lonlocal::current_language();
  701:     if ($login_help) {
  702:         my $dom = $authdomain;
  703:         if ($dom eq '') {
  704:             $dom = &Apache::lonnet::default_login_domain();
  705:         }
  706:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
  707:         my $loginhelp_url;
  708:         if ($lang) {
  709:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
  710:             if ($loginhelp_url ne '') {
  711:                 return $loginhelp_url;
  712:             }
  713:         }
  714:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
  715:         if ($loginhelp_url ne '') {
  716:             return $loginhelp_url;
  717:         } else {
  718:             return '/adm/loginproblems.html';
  719:         }
  720:     }
  721:     return;
  722: }
  723: 
  724: 1;
  725: __END__
  726: 
  727: 

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