File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.121.2.22: download - view: text, annotated - select for diffs
Sun Dec 12 01:48:40 2021 UTC (2 years, 5 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.163, 1.168 (part), 1.169 (part) 1.170

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.121.2.22 2021/12/12 01:48:40 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonauth;
   30: 
   31: use strict;
   32: use LONCAPA;
   33: use Apache::Constants qw(:common);
   34: use CGI qw(:standard);
   35: use Apache::loncommon();
   36: use Apache::lonnet;
   37: use Apache::lonmenu();
   38: use Apache::createaccount;
   39: use Fcntl qw(:flock);
   40: use Apache::lonlocal;
   41: use Apache::File();
   42: use HTML::Entities;
   43: use Digest::MD5;
   44:  
   45: # ------------------------------------------------------------ Successful login
   46: sub success {
   47:     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
   48: 	$form,$cid,$expirepub) = @_;
   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:     my $ip = &Apache::lonnet::get_requestor_ip();
   63:     &Apache::lonnet::log($domain,$username,$authhost,
   64:                          "Login $ip");
   65: 
   66: # ------------------------------------------------- Check for critical messages
   67: 
   68:     my @what=&Apache::lonnet::dump('critical',$domain,$username);
   69:     if ($what[0]) {
   70: 	if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
   71: 	    $lowerurl='/adm/email?critical=display';
   72:         }
   73:     }
   74: 
   75: # ------------------------------------------------------------ Get cookies ready
   76:     my ($securecookie,$defaultcookie);
   77:     my $ssl = $r->subprocess_env('https');
   78:     if ($ssl) {
   79:         $securecookie="lonSID=$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' => $linkname});
   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:         my $encrypted;
  122:         if ($destsymb =~ m{^/enc/}) {
  123:             $encrypted = 1;
  124:             if ($cid) {
  125:                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
  126:             }
  127:         }
  128:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  129:         if ($destsymb =~ /___/) {
  130:             my ($map,$resid,$desturl)=split(/___/,$destsymb);
  131:             $desturl = &Apache::lonnet::clutter($desturl);
  132:             if ($encrypted) {
  133:                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
  134:                 $destsymb = $form->{symb};
  135:             }
  136:             $desturl = &HTML::Entities::encode($desturl,'"<>&');
  137:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  138:             $destination .= 'destinationurl='.$desturl.
  139:                             '&destsymb='.$destsymb;
  140:         } elsif (!$encrypted) {
  141:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  142:             $destination .= 'destinationurl='.$destsymb;
  143:         }
  144:     }
  145:     if ($destination =~ m{^/adm/roles}) {
  146:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  147:         $destination .= 'source=login';
  148:     }
  149: 
  150:     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});
  151:     my $startupremote=&Apache::lonmenu::startupremote($destination);
  152:     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
  153:     my $setflags=&Apache::lonmenu::setflags();
  154:     my $maincall=&Apache::lonmenu::maincall();
  155:     my $brcrum = [{'href' => '',
  156:                    'text' => 'Successful Login'},];
  157:     my $start_page=&Apache::loncommon::start_page('Successful Login',
  158:                                                   $startupremote,
  159:                                                   {'no_inline_link' => 1,
  160:                                                    'bread_crumbs' => $brcrum,});
  161:     my $end_page  =&Apache::loncommon::end_page();
  162: 
  163:     my $continuelink;
  164:     if ($env{'environment.remote'} eq 'off') {
  165: 	$continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
  166:     }
  167: # ------------------------------------------------- Output for successful login
  168: 
  169:     &Apache::loncommon::content_type($r,'text/html');
  170:     if ($securecookie) {
  171:         $r->headers_out->add('Set-cookie' => $securecookie);
  172:     }
  173:     if ($defaultcookie) {
  174:         $r->headers_out->add('Set-cookie' => $defaultcookie);
  175:     }
  176:     if ($expirepub) {
  177:         my $c = new CGI::Cookie(-name    => 'lonPubID',
  178:                                 -value   => '',
  179:                                 -expires => '-10y',);
  180:         $r->headers_out->add('Set-cookie' => $c);
  181:     }
  182:     $r->send_http_header;
  183: 
  184:     my %lt=&Apache::lonlocal::texthash(
  185: 				       'wel' => 'Welcome',
  186: 				       'pro' => 'Login problems?',
  187: 				       );
  188:     my $loginhelp = &loginhelpdisplay($domain);
  189:     if ($loginhelp) {
  190:         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
  191:     }
  192: 
  193:     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>'); 
  194:     $r->print(<<ENDSUCCESS);
  195: $start_page
  196: $setflags
  197: $windowinfo
  198: <h1>$lt{'wel'}</h1>
  199: $welcome
  200: $loginhelp
  201: $remoteinfo
  202: $maincall
  203: $continuelink
  204: $end_page
  205: ENDSUCCESS
  206:     return;
  207: }
  208: 
  209: # --------------------------------------------------------------- Failed login!
  210: 
  211: sub failed {
  212:     my ($r,$message,$form,$authhost) = @_;
  213:     (undef,undef,undef,my $clientmathml,my $clientunicode) =
  214:         &Apache::loncommon::decode_user_agent();
  215:     my $args = {};
  216:     if ($clientunicode && !$clientmathml) {
  217:         $args = {'browser.unicode' => 1};
  218:     }
  219: 
  220:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
  221:     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
  222:     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
  223:     if (&Apache::lonnet::domain($udom,'description') eq '') {
  224:         undef($udom);
  225:     }
  226:     my $retry = '/adm/login';
  227:     if ($uname eq $form->{'uname'}) {
  228:         $retry .= '?username='.$uname;
  229:     }
  230:     if ($udom) {
  231:         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
  232:     }
  233:     my $lonhost = $r->dir_config('lonHostID');
  234:     my $querystr;
  235:     my $result = &set_retry_token($form,$lonhost,\$querystr);
  236:     if ($result eq 'fail') {
  237:         if (exists($form->{role})) {
  238:             my $role = &Apache::loncommon::cleanup_html($form->{role});
  239:             if ($role ne '') {
  240:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
  241:             }
  242:         }
  243:         if (exists($form->{symb})) {
  244:             my $symb = &Apache::loncommon::cleanup_html($form->{symb});
  245:             if ($symb ne '') {
  246:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
  247:             }
  248:         }
  249:         if (exists($form->{firsturl})) {
  250:             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
  251:             if ($firsturl ne '') {
  252:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
  253:                 if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
  254:                     unless (exists($form->{linkprot})) {
  255:                         if (exists($form->{linkkey})) {
  256:                             $retry .= 'linkkey='.$form->{linkkey};
  257:                         }
  258:                     }
  259:                 }
  260:             }
  261:         }
  262:     } elsif ($querystr ne '') {
  263:         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;
  264:     }
  265:     my $end_page = &Apache::loncommon::end_page();
  266:     &Apache::loncommon::content_type($r,'text/html');
  267:     $r->send_http_header;
  268:     my @actions =
  269:          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
  270:     my $loginhelp = &loginhelpdisplay($udom);
  271:     if ($loginhelp) {
  272:         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
  273:     }
  274:     #FIXME: link to helpdesk might be added here
  275: 
  276:     $r->print(
  277:        $start_page
  278:       .'<h2>'.&mt('Sorry ...').'</h2>'
  279:       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
  280:       .&Apache::lonhtmlcommon::actionbox(\@actions)
  281:       .$end_page
  282:     );
  283:  }
  284: 
  285: # ------------------------------------------------------------------ Rerouting!
  286: 
  287: sub reroute {
  288:     my ($r) = @_;
  289:     &Apache::loncommon::content_type($r,'text/html');
  290:     $r->send_http_header;
  291:     my $msg='<b>'.&mt('Sorry ...').'</b><br />'
  292:            .&mt('Please [_1]log in again[_2].');
  293:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
  294: }
  295: 
  296: # ---------------------------------------------------------------- Main handler
  297: 
  298: sub handler {
  299:     my $r = shift;
  300:     my $londocroot = $r->dir_config('lonDocRoot');
  301: # Are we re-routing?
  302:     if (-e "$londocroot/lon-status/reroute.txt") {
  303: 	&reroute($r);
  304: 	return OK;
  305:     }
  306: 
  307:     &Apache::lonlocal::get_language_handle($r);
  308: 
  309: # -------------------------------- Prevent users from attempting to login twice
  310:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  311:     if ($handle ne '') {
  312:         my $lonidsdir=$r->dir_config('lonIDsDir');
  313:         if ($handle=~/^publicuser\_/) {
  314: # For "public user" - remove it, we apparently really want to login
  315:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
  316:         } else {
  317: # Indeed, a valid token is found
  318:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  319: 	    &Apache::loncommon::content_type($r,'text/html');
  320: 	    $r->send_http_header;
  321: 	    my $start_page = 
  322: 	        &Apache::loncommon::start_page('Already logged in');
  323: 	    my $end_page = 
  324: 	        &Apache::loncommon::end_page();
  325:             my $dest = '/adm/roles';
  326:             my %form = &get_form_items($r);
  327:             if ($form{'logtoken'}) {
  328:                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  329:                                                      $form{'serverid'});
  330:                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
  331:                         ($tmpinfo eq 'no_such_host')) {
  332:                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo)l
  333:                     $firsturl = &unescape($firsturl);
  334:                     my %info;
  335:                     foreach my $item (@rest) {
  336:                         my ($key,$value) = split(/=/,$item);
  337:                         $info{$key} = &unescape($value);
  338:                     }
  339:                     if ($firsturl ne '') {
  340:                         $info{'firsturl'} = $firsturl;
  341:                         $dest = $firsturl;
  342:                     }
  343:                 }
  344:             }
  345:             $r->print(
  346:                $start_page
  347:               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  348:               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  349:                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
  350:               .'</p>'
  351:               .$end_page
  352:             );
  353:             return OK;
  354:         }
  355:     }
  356: 
  357: # ---------------------------------------------------- No valid token, continue
  358: 
  359:     my %form = &get_form_items($r);
  360:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  361: 	&failed($r,'Username, password and domain need to be specified.',
  362: 		\%form);
  363:         return OK;
  364:     }
  365: 
  366: # split user logging in and "su"-user
  367: 
  368:     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
  369:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  370:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  371:     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
  372:     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
  373: 
  374:     my $role   = $r->dir_config('lonRole');
  375:     my $domain = $r->dir_config('lonDefDomain');
  376:     my $prodir = $r->dir_config('lonUsersDir');
  377:     my $contact_name = &mt('LON-CAPA helpdesk');
  378: 
  379: # ---------------------------------------- Get the information from login token
  380: 
  381:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  382:                                       $form{'serverid'});
  383: 
  384:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
  385:         ($tmpinfo eq 'no_such_host')) {
  386: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  387:         return OK;
  388:     } else {
  389: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  390: 					   $form{'serverid'});
  391:         if ( $reply ne 'ok' ) {
  392:             &failed($r,'Session could not be opened.',\%form);
  393: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  394: 	    return OK;
  395: 	}
  396:     }
  397: 
  398:     if (!&Apache::lonnet::domain($form{'udom'})) {
  399:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  400:         return OK;
  401:     }
  402: 
  403:     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
  404:     $firsturl = &unescape($firsturl);
  405:     foreach my $item (@rest) {
  406:         my ($key,$value) = split(/=/,$item);
  407:         $form{$key} = &unescape($value);
  408:     }
  409:     my $upass = &Apache::loncommon::des_decrypt($key,$form{'upass0'});
  410: 
  411: # ---------------------------------------------------------------- Authenticate
  412: 
  413:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  414:     my ($cancreate,$statustocreate) =
  415:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
  416:     my $defaultauth;
  417:     if (ref($cancreate) eq 'ARRAY') {
  418:         if (grep(/^login$/,@{$cancreate})) {
  419:             $defaultauth = 1;
  420:         }
  421:     }
  422:     my $clientcancheckhost = 1;
  423:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  424:                                               $form{'udom'},$defaultauth,
  425:                                               $clientcancheckhost);
  426:     
  427: # --------------------------------------------------------------------- Failed?
  428: 
  429:     if ($authhost eq 'no_host') {
  430: 	&failed($r,'Username and/or password could not be authenticated.',
  431: 		\%form);
  432:         return OK;
  433:     } elsif ($authhost eq 'no_account_on_host') {
  434:         if ($defaultauth) {
  435:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  436:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
  437:                 return OK;
  438:             }
  439:             my $start_page = 
  440:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',
  441:                                                '',{'no_inline_link'   => 1,});
  442:             my $lonhost = $r->dir_config('lonHostID');
  443:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  444:             my $contacts = 
  445:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  446:                                                         $form{'udom'},$origmail);
  447:             my ($contact_email) = split(',',$contacts); 
  448:             my $output = 
  449:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
  450:                                                        $domdesc,'',$lonhost,
  451:                                                        $contact_email,$contact_name,
  452:                                                        undef,$statustocreate);
  453:             &Apache::loncommon::content_type($r,'text/html');
  454:             $r->send_http_header;
  455:             &Apache::createaccount::print_header($r,$start_page);
  456:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  457:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  458:                       $output.&Apache::loncommon::end_page());
  459:             return OK;
  460:         } else {
  461:             &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);
  462:             return OK;
  463:         }
  464:     }
  465: 
  466:     if (($firsturl eq '') || 
  467: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  468: 	$firsturl='/adm/roles';
  469:     }
  470: 
  471:     my $hosthere;
  472:     if ($form{'iptoken'}) {
  473:         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  474:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  475:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
  476:             ($sessiondata{'username'} eq $form{'uname'})) {
  477:             $hosthere = 1;
  478:         }
  479:     }
  480: 
  481: # --------------------------------- Are we attempting to login as somebody else?
  482:     if ($form{'suname'}) {
  483:         my ($suname,$sudom,$sudomref);
  484:         $suname = $form{'suname'};
  485:         $sudom = $form{'udom'};
  486:         if ($form{'sudom'}) {
  487:             unless ($sudom eq $form{'sudom'}) {
  488:                 if (&Apache::lonnet::domain($form{'sudom'})) {
  489:                     $sudomref = [$form{'sudom'}];
  490:                     $sudom = $form{'sudom'};
  491:                 }
  492:             }
  493:         }
  494: # ------------ see if the original user has enough privileges to pull this stunt
  495: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
  496: # ---------------------------------------------------- see if the su-user exists
  497: 	    unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
  498: # ------------------------------ see if the su-user is not too highly privileged
  499: 		if (&Apache::lonnet::privileged($suname,$sudom)) {
  500:                     &Apache::lonnet::logthis('Attempted switch user to privileged user');
  501:                 } else {
  502:                     my $noprivswitch;
  503: #
  504: # su-user's home server and user's home server must have one of:
  505: # (a) same domain
  506: # (b) same primary library server for the two domains
  507: # (c) same "internet domain" for primary library server(s) for home servers' domains
  508: #
  509:                     my $suprim = &Apache::lonnet::domain($sudom,'primary');
  510:                     my $suintdom = &Apache::lonnet::internet_dom($suprim);
  511:                     unless ($sudom eq $form{'udom'}) {
  512:                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
  513:                         my $uintdom = &Apache::lonnet::internet_dom($uprim);
  514:                         unless ($suprim eq $uprim) {
  515:                             unless ($suintdom eq $uintdom) {
  516:                                 &Apache::lonnet::logthis('Attempted switch user '
  517:                                    .'to user with different "internet domain".');
  518:                                 $noprivswitch = 1;
  519:                             }
  520:                         }
  521:                     }
  522: 
  523:                     unless ($noprivswitch) {
  524: #
  525: # server where log-in occurs must have same "internet domain" as su-user's home
  526: # server
  527: #
  528:                         my $lonhost = $r->dir_config('lonHostID');
  529:                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
  530:                         if ($hostintdom ne $suintdom) {
  531:                             &Apache::lonnet::logthis('Attempted switch user on a '
  532:                                 .'server with a different "internet domain".');
  533:                         } else {
  534: 
  535: # -------------------------------------------------------- actually switch users
  536: 
  537: 			    &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
  538: 				$form{'udom'}.' logging in as '.$suname.':'.$sudom);
  539: 			    $form{'uname'}=$suname;
  540:                             if ($form{'udom'} ne $sudom) {
  541:                                 $form{'udom'}=$sudom;
  542:                             }
  543:                         }
  544:                     }
  545: 		}
  546: 	    }
  547: 	} else {
  548: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  549: 	}
  550:     }
  551: 
  552:     my ($is_balancer,$otherserver);
  553: 
  554:     unless ($hosthere) {
  555:         ($is_balancer,$otherserver) =
  556:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
  557:         if ($is_balancer) {
  558:             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
  559:             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
  560:             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
  561:                 $otherserver = $found_server;
  562:             }
  563:             if ($otherserver eq '') {
  564:                 my $lowest_load;
  565:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
  566:                 if ($lowest_load > 100) {
  567:                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
  568:                 }
  569:             }
  570:             if ($otherserver ne '') {
  571:                 my @hosts = &Apache::lonnet::current_machine_ids();
  572:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
  573:                     $hosthere = $otherserver;
  574:                 }
  575:             }
  576:         }
  577:     }
  578: 
  579:     if (($is_balancer) && (!$hosthere)) {
  580:         if ($otherserver) {
  581:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  582:                      \%form);
  583:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  584:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  585:                 $switchto .= '&origurl='.$firsturl;
  586:             }
  587:             if ($form{'role'}) {
  588:                 $switchto .= '&role='.$form{'role'};
  589:             }
  590:             if ($form{'symb'}) {
  591:                 $switchto .= '&symb='.$form{'symb'};
  592:             }
  593:             $r->internal_redirect($switchto);
  594:         } else {
  595:             &Apache::loncommon::content_type($r,'text/html');
  596:             $r->send_http_header;
  597:             $r->print(&noswitch());
  598:         }
  599:         return OK;
  600:     } else {
  601:         if (!&check_can_host($r,\%form,$authhost)) {
  602:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
  603:             if ($otherserver) {
  604:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  605:                          \%form);
  606:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  607:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  608:                     $switchto .= '&origurl='.$firsturl;
  609:                 }
  610:                 if ($form{'role'}) {
  611:                     $switchto .= '&role='.$form{'role'};
  612:                 }
  613:                 if ($form{'symb'}) {
  614:                     $switchto .= '&symb='.$form{'symb'};
  615:                 }
  616:                 $r->internal_redirect($switchto);
  617:             } else {
  618:                 &Apache::loncommon::content_type($r,'text/html');
  619:                 $r->send_http_header;
  620:                 $r->print(&noswitch());
  621:             }
  622:             return OK;
  623:         }
  624: 
  625: # ------------------------------------------------------- Do the load balancing
  626: 
  627: # ---------------------------------------------------------- Determine own load
  628:         my $loadlim = $r->dir_config('lonLoadLim');
  629:         my $loadavg;
  630:         {
  631:             my $loadfile=Apache::File->new('/proc/loadavg');
  632:             $loadavg=<$loadfile>;
  633:         }
  634:         $loadavg =~ s/\s.*//g;
  635:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
  636:         my $userloadpercent=&Apache::lonnet::userload();
  637: 
  638: # ---------------------------------------------------------- Are we overloaded?
  639:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
  640:             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});
  641:             if (!$unloaded) {
  642:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
  643:             }
  644:             if ($unloaded) {
  645:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
  646:                          undef,\%form);
  647:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
  648:                 return OK;
  649:             }
  650:         }
  651:         if (($is_balancer) && ($hosthere)) {
  652:             $form{'noloadbalance'} = $hosthere;
  653:         }
  654:         my $extra_env;
  655:         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {
  656:             if ($sessiondata{'origurl'} ne '') {
  657:                 $firsturl = $sessiondata{'origurl'};
  658:                 $form{'firsturl'} = $sessiondata{'origurl'};
  659:                 my @names = ('role','symb','linkprot','linkkey');
  660:                 foreach my $item (@names) {
  661:                     if ($sessiondata{$item} ne '') {
  662:                         $form{$item} = $sessiondata{$item};
  663:                     }
  664:                 }
  665:             }
  666:         }
  667:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
  668:                  \%form);
  669:         return OK;
  670:     }
  671: }
  672: 
  673: sub get_form_items {
  674:     my ($r) = @_;
  675:     my $buffer;
  676:     if ($r->header_in('Content-length') > 0) {
  677:         $r->read($buffer,$r->header_in('Content-length'),0);
  678:     }
  679:     my %form;
  680:     foreach my $pair (split(/&/,$buffer)) {
  681:        my ($name,$value) = split(/=/,$pair);
  682:        $value =~ tr/+/ /;
  683:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  684:        $form{$name}=$value;
  685:     }
  686:     return %form;
  687: }
  688: 
  689: sub set_retry_token {
  690:     my ($form,$lonhost,$querystr) = @_;
  691:     if (ref($form) eq 'HASH') {
  692:         my ($firsturl,$token,$extras,@names);
  693:         @names = ('role','symb','iptoken');
  694:         foreach my $name (@names) {
  695:             if ($form->{$name} ne '') {
  696:                 $extras .= '&'.$name.'='.&escape($form->{$name});
  697:                 last if ($name eq 'linkprot');
  698:             }
  699:         }
  700:         my $firsturl = $form->{'firsturl'};
  701:         if (($firsturl ne '') || ($extras ne '')) {
  702:             $extras .= ':retry';
  703:             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).
  704:                                             $extras,$lonhost);
  705:             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {
  706:                 return 'fail';
  707:             } else {
  708:                 if (ref($querystr)) {
  709:                     $$querystr = 'retry='.$token;
  710:                 }
  711:                 return 'ok';
  712:             }
  713:         }
  714:     }
  715:     return;
  716: }
  717: 
  718: sub check_can_host {
  719:     my ($r,$form,$authhost,$domdesc) = @_;
  720:     return unless (ref($form) eq 'HASH');
  721:     my $canhost = 1;
  722:     my $lonhost = $r->dir_config('lonHostID');
  723:     my $udom = $form->{'udom'};
  724:     my @intdoms;
  725:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
  726:     if (ref($internet_names) eq 'ARRAY') {
  727:         @intdoms = @{$internet_names};
  728:     }
  729:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  730:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  731:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
  732:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
  733:         my $hostname = &Apache::lonnet::hostname($lonhost);
  734:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
  735:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
  736:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
  737:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  738:         my $loncaparev;
  739:         if ($authhost eq 'no_account_on_host') {
  740:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
  741:         } else {
  742:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
  743:         }
  744:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
  745:                                                      $udomdefaults{'remotesessions'},
  746:                                                      $defdomdefaults{'hostedsessions'});
  747:     }
  748:     unless ($canhost) {
  749:         if ($authhost eq 'no_account_on_host') {
  750:             my $checkloginvia = 1;
  751:             my ($login_host,$hostname) = 
  752:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
  753:             &Apache::loncommon::content_type($r,'text/html');
  754:             $r->send_http_header;
  755:             if ($login_host ne '') {
  756:                 my $protocol = $Apache::lonnet::protocol{$login_host};
  757:                 $protocol = 'http' if ($protocol ne 'https');
  758:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);
  759:                 $hostname = $alias if ($alias ne '');
  760:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
  761:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
  762:                           '<h3>'.&mt('Account creation').'</h3>'.
  763:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  764:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
  765:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
  766:                           &Apache::loncommon::end_page());
  767:             } else {
  768:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  769:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
  770:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  771:                           '<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>'.
  772:                           &Apache::loncommon::end_page());
  773:             }
  774:         } else {
  775:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
  776:                      $form);
  777:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
  778:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
  779:         }
  780:     }
  781:     return $canhost;
  782: }
  783: 
  784: sub noswitch {
  785:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  786:                  '<h3>'.&mt('Session unavailable').'</h3>'.
  787:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
  788:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
  789:                  &Apache::loncommon::end_page();
  790:     return $result;
  791: }
  792: 
  793: sub loginhelpdisplay {
  794:     my ($authdomain) = @_;
  795:     my $login_help = 1;
  796:     my $lang = &Apache::lonlocal::current_language();
  797:     if ($login_help) {
  798:         my $dom = $authdomain;
  799:         if ($dom eq '') {
  800:             $dom = &Apache::lonnet::default_login_domain();
  801:         }
  802:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
  803:         my $loginhelp_url;
  804:         if ($lang) {
  805:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
  806:             if ($loginhelp_url ne '') {
  807:                 return $loginhelp_url;
  808:             }
  809:         }
  810:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
  811:         if ($loginhelp_url ne '') {
  812:             return $loginhelp_url;
  813:         } else {
  814:             return '/adm/loginproblems.html';
  815:         }
  816:     }
  817:     return;
  818: }
  819: 
  820: 1;
  821: __END__
  822: 
  823: 

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