File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.121.2.26: download - view: text, annotated - select for diffs
Mon Feb 28 01:07:15 2022 UTC (2 years, 2 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_4_uiuc, version_2_11_4
- For 2.11
  Include a single change from changes in rev. 1.140

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

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