File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.146: download - view: text, annotated - select for diffs
Tue Aug 8 18:12:18 2017 UTC (6 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 876 for multi-domain servers.
  - Session hosting server and user's home server must have the same "internet
    domain".

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

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