File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.144: download - view: text, annotated - select for diffs
Tue Aug 8 16:43:54 2017 UTC (6 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove "use" calls no longer needed, as DES decryption now uses
  loncommon::des_decrypt().

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.144 2017/08/08 16:43:54 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'})=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: 
  342:     my $role   = $r->dir_config('lonRole');
  343:     my $domain = $r->dir_config('lonDefDomain');
  344:     my $prodir = $r->dir_config('lonUsersDir');
  345:     my $contact_name = &mt('LON-CAPA helpdesk');
  346: 
  347: # ---------------------------------------- Get the information from login token
  348: 
  349:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  350:                                       $form{'serverid'});
  351: 
  352:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
  353:         ($tmpinfo eq 'no_such_host')) {
  354: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  355:         return OK;
  356:     } else {
  357: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  358: 					   $form{'serverid'});
  359:         if ( $reply ne 'ok' ) {
  360:             &failed($r,'Session could not be opened.',\%form);
  361: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  362: 	    return OK;
  363: 	}
  364:     }
  365: 
  366:     if (!&Apache::lonnet::domain($form{'udom'})) {
  367:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  368:         return OK;
  369:     }
  370: 
  371:     my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
  372:     if ($rolestr) {
  373:         $rolestr = &unescape($rolestr);
  374:     }
  375:     if ($symbstr) {
  376:         $symbstr= &unescape($symbstr);
  377:     }
  378:     if ($iptokenstr) {
  379:         $iptokenstr = &unescape($iptokenstr);
  380:     }
  381:     if ($rolestr =~ /^role=/) {
  382:         (undef,$form{'role'}) = split('=',$rolestr);
  383:     }
  384:     if ($symbstr =~ /^symb=/) { 
  385:         (undef,$form{'symb'}) = split('=',$symbstr);
  386:     }
  387:     if ($iptokenstr =~ /^iptoken=/) {
  388:         (undef,$form{'iptoken'}) = split('=',$iptokenstr);
  389:     }
  390: 
  391:     my $upass = $ENV{HTTPS} ? $form{'upass0'} 
  392:         : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
  393: 
  394: # ---------------------------------------------------------------- Authenticate
  395: 
  396:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  397:     my ($cancreate,$statustocreate) =
  398:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
  399:     my $defaultauth;
  400:     if (ref($cancreate) eq 'ARRAY') {
  401:         if (grep(/^login$/,@{$cancreate})) {
  402:             $defaultauth = 1;
  403:         }
  404:     }
  405:     my $clientcancheckhost = 1;
  406:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  407:                                               $form{'udom'},$defaultauth,
  408:                                               $clientcancheckhost);
  409:     
  410: # --------------------------------------------------------------------- Failed?
  411: 
  412:     if ($authhost eq 'no_host') {
  413: 	&failed($r,'Username and/or password could not be authenticated.',
  414: 		\%form);
  415:         return OK;
  416:     } elsif ($authhost eq 'no_account_on_host') {
  417:         if ($defaultauth) {
  418:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  419:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
  420:                 return OK;
  421:             }
  422:             my $start_page = 
  423:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA');
  424:             my $lonhost = $r->dir_config('lonHostID');
  425:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  426:             my $contacts = 
  427:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  428:                                                         $form{'udom'},$origmail);
  429:             my ($contact_email) = split(',',$contacts); 
  430:             my $output = 
  431:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
  432:                                                        $domdesc,'',$lonhost,
  433:                                                        $contact_email,$contact_name,
  434:                                                        undef,$statustocreate);
  435:             &Apache::loncommon::content_type($r,'text/html');
  436:             $r->send_http_header;
  437:             &Apache::createaccount::print_header($r,$start_page);
  438:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  439:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  440:                       $output.&Apache::loncommon::end_page());
  441:             return OK;
  442:         } else {
  443:             &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);
  444:             return OK;
  445:         }
  446:     }
  447: 
  448:     if (($firsturl eq '') || 
  449: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  450: 	$firsturl='/adm/roles';
  451:     }
  452: 
  453:     my $hosthere;
  454:     if ($form{'iptoken'}) {
  455:         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  456:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  457:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
  458:             ($sessiondata{'username'} eq $form{'uname'})) {
  459:             $hosthere = 1;
  460:         }
  461:     }
  462: 
  463: # --------------------------------- Are we attempting to login as somebody else?
  464:     if ($form{'suname'}) {
  465: # ------------ see if the original user has enough privileges to pull this stunt
  466: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {
  467: # ---------------------------------------------------- see if the su-user exists
  468: 	    unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})
  469: 		eq 'no_host') {
  470: 		&Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));
  471: # ------------------------------ see if the su-user is not too highly privileged
  472: 		unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {
  473: # -------------------------------------------------------- actually switch users
  474: 		    &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.
  475: 			' logging in as '.$form{'suname'});
  476: 		    $form{'uname'}=$form{'suname'};
  477: 		} else {
  478: 		    &Apache::lonnet::logthis('Attempted switch user to privileged user');
  479: 		}
  480: 	    }
  481: 	} else {
  482: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  483: 	}
  484:     }
  485: 
  486:     my ($is_balancer,$otherserver);
  487: 
  488:     unless ($hosthere) {
  489:         ($is_balancer,$otherserver) =
  490:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
  491:         if ($is_balancer) {
  492:             if ($otherserver eq '') {
  493:                 my $lowest_load;
  494:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
  495:                 if ($lowest_load > 100) {
  496:                     $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
  497:                 }
  498:             }
  499:             if ($otherserver ne '') {
  500:                 my @hosts = &Apache::lonnet::current_machine_ids();
  501:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
  502:                     $hosthere = $otherserver;
  503:                 }
  504:             }
  505:         }
  506:     }
  507: 
  508:     if (($is_balancer) && (!$hosthere)) {
  509:         if ($otherserver) {
  510:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  511:                      \%form);
  512:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  513:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  514:                 $switchto .= '&origurl='.$firsturl;
  515:             }
  516:             if ($form{'role'}) {
  517:                 $switchto .= '&role='.$form{'role'};
  518:             }
  519:             if ($form{'symb'}) {
  520:                 $switchto .= '&symb='.$form{'symb'};
  521:             }
  522:             $r->internal_redirect($switchto);
  523:         } else {
  524:             $r->print(&noswitch());
  525:         }
  526:         return OK;
  527:     } else {
  528:         if (!&check_can_host($r,\%form,$authhost)) {
  529:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
  530:             if ($otherserver) {
  531:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  532:                          \%form);
  533:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  534:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  535:                     $switchto .= '&origurl='.$firsturl;
  536:                 }
  537:                 if ($form{'role'}) {
  538:                     $switchto .= '&role='.$form{'role'};
  539:                 }
  540:                 if ($form{'symb'}) {
  541:                     $switchto .= '&symb='.$form{'symb'};
  542:                 }
  543:                 $r->internal_redirect($switchto);
  544:             } else {
  545:                 $r->print(&noswitch());
  546:             }
  547:             return OK;
  548:         }
  549: 
  550: # ------------------------------------------------------- Do the load balancing
  551: 
  552: # ---------------------------------------------------------- Determine own load
  553:         my $loadlim = $r->dir_config('lonLoadLim');
  554:         my $loadavg;
  555:         {
  556:             my $loadfile=Apache::File->new('/proc/loadavg');
  557:             $loadavg=<$loadfile>;
  558:         }
  559:         $loadavg =~ s/\s.*//g;
  560:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
  561:         my $userloadpercent=&Apache::lonnet::userload();
  562: 
  563: # ---------------------------------------------------------- Are we overloaded?
  564:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
  565:             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
  566:             if (!$unloaded) {
  567:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
  568:             }
  569:             if ($unloaded) {
  570:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
  571:                          undef,\%form);
  572:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
  573:                 return OK;
  574:             }
  575:         }
  576:         if (($is_balancer) && ($hosthere)) {
  577:             $form{'noloadbalance'} = $hosthere;
  578:         }
  579:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
  580:                  \%form);
  581:         return OK;
  582:     }
  583: }
  584: 
  585: sub check_can_host {
  586:     my ($r,$form,$authhost,$domdesc) = @_;
  587:     return unless (ref($form) eq 'HASH');
  588:     my $canhost = 1;
  589:     my $lonhost = $r->dir_config('lonHostID');
  590:     my $udom = $form->{'udom'};
  591:     my @intdoms;
  592:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
  593:     if (ref($internet_names) eq 'ARRAY') {
  594:         @intdoms = @{$internet_names};
  595:     }
  596:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  597:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  598:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
  599:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
  600:         my $hostname = &Apache::lonnet::hostname($lonhost);
  601:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
  602:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
  603:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
  604:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  605:         my $loncaparev;
  606:         if ($authhost eq 'no_account_on_host') {
  607:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
  608:         } else {
  609:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
  610:         }
  611:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
  612:                                                      $udomdefaults{'remotesessions'},
  613:                                                      $defdomdefaults{'hostedsessions'});
  614:     }
  615:     unless ($canhost) {
  616:         if ($authhost eq 'no_account_on_host') {
  617:             my $checkloginvia = 1;
  618:             my ($login_host,$hostname) = 
  619:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
  620:             &Apache::loncommon::content_type($r,'text/html');
  621:             $r->send_http_header;
  622:             if ($login_host ne '') {
  623:                 my $protocol = $Apache::lonnet::protocol{$login_host};
  624:                 $protocol = 'http' if ($protocol ne 'https');
  625:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
  626:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
  627:                           '<h3>'.&mt('Account creation').'</h3>'.
  628:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  629:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
  630:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
  631:                           &Apache::loncommon::end_page());
  632:             } else {
  633:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  634:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
  635:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  636:                           '<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>'.
  637:                           &Apache::loncommon::end_page());
  638:             }
  639:         } else {
  640:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
  641:                      $form);
  642:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
  643:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
  644:         }
  645:     }
  646:     return $canhost;
  647: }
  648: 
  649: sub noswitch {
  650:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  651:                  '<h3>'.&mt('Session unavailable').'</h3>'.
  652:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
  653:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
  654:                  &Apache::loncommon::end_page();
  655:     return $result;
  656: }
  657: 
  658: sub loginhelpdisplay {
  659:     my ($authdomain) = @_;
  660:     my $login_help = 1;
  661:     my $lang = &Apache::lonlocal::current_language();
  662:     if ($login_help) {
  663:         my $dom = $authdomain;
  664:         if ($dom eq '') {
  665:             $dom = &Apache::lonnet::default_login_domain();
  666:         }
  667:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
  668:         my $loginhelp_url;
  669:         if ($lang) {
  670:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
  671:             if ($loginhelp_url ne '') {
  672:                 return $loginhelp_url;
  673:             }
  674:         }
  675:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
  676:         if ($loginhelp_url ne '') {
  677:             return $loginhelp_url;
  678:         } else {
  679:             return '/adm/loginproblems.html';
  680:         }
  681:     }
  682:     return;
  683: }
  684: 
  685: 1;
  686: __END__
  687: 
  688: 

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