File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.150: download - view: text, annotated - select for diffs
Sat Apr 14 02:30:11 2018 UTC (6 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  - Original LTI launch of LON-CAPA is for a resource, a map, or an entire
    course, and display is for iframe, tab or window; retain this in %env.

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

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