File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.163: download - view: text, annotated - select for diffs
Tue May 4 18:47:37 2021 UTC (3 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6914.
  Replace hostname with alias when creating absolute URLs, if alias in use.

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

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