File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.151: download - view: text, annotated - select for diffs
Sat Apr 21 21:29:31 2018 UTC (6 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  - Simplified display when initializing LON-CAPA session after LTI launch.

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

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