File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.145: download - view: text, annotated - select for diffs
Tue Aug 8 17:01:25 2017 UTC (6 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 876 for multi-domain servers.

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

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