File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.142: download - view: text, annotated - select for diffs
Fri Feb 17 14:34:21 2017 UTC (7 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- cookie protection

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

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