File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.143: download - view: text, annotated - select for diffs
Sat Feb 25 20:00:36 2017 UTC (7 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use 'secure' attribute for session cookie on servers using Apache/SSL.

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

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