File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.174: download - view: text, annotated - select for diffs
Sat Jun 18 02:10:18 2022 UTC (2 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907
  For LTI-protected deep links in which username is included in launch payload
  compare username in payload with username for any existing LON-CAPA session
  in current web browser and expire old session, if different user.

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.174 2022/06/18 02:10:18 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonauth;
   30: 
   31: use strict;
   32: use LONCAPA qw(:DEFAULT :match);
   33: use Apache::Constants qw(:common);
   34: use CGI qw(:standard);
   35: use Apache::loncommon();
   36: use Apache::lonnet;
   37: use Apache::lonmenu();
   38: use Apache::createaccount;
   39: use Apache::ltiauth;
   40: use Fcntl qw(:flock);
   41: use Apache::lonlocal;
   42: use Apache::File();
   43: use HTML::Entities;
   44: use Digest::MD5;
   45: use CGI::Cookie();
   46:  
   47: # ------------------------------------------------------------ Successful login
   48: sub success {
   49:     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
   50: 	$form,$skipcritical,$cid,$expirepub) = @_;
   51: 
   52: # ------------------------------------------------------------ Get cookie ready
   53:     my $cookie =
   54: 	&Apache::loncommon::init_user_environment($r, $username, $domain,
   55: 						  $authhost, $form,
   56: 						  {'extra_env' => $extra_env,});
   57: 
   58:     my $public=($username eq 'public' && $domain eq 'public');
   59: 
   60:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   61: 
   62: # -------------------------------------------------------------------- Log this
   63: 
   64:     my $ip = &Apache::lonnet::get_requestor_ip();
   65:     &Apache::lonnet::log($domain,$username,$authhost,
   66:                          "Login $ip");
   67: 
   68: # ------------------------------------------------- Check for critical messages
   69: 
   70:     unless ($skipcritical) {
   71:         my @what=&Apache::lonnet::dump('critical',$domain,$username);
   72:         if ($what[0]) {
   73: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
   74: 	        $lowerurl='/adm/email?critical=display';
   75:             }
   76:         }
   77:     }
   78: 
   79: # ----------------------------------------------------------- Get cookies ready
   80:     my ($securecookie,$defaultcookie);
   81:     my $ssl = $r->subprocess_env('https');
   82:     if ($ssl) {
   83:         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
   84:         my $lonidsdir=$r->dir_config('lonIDsDir');
   85:         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
   86:             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
   87:             if (-e "$lonidsdir/$linkname.id") {
   88:                 unlink("$lonidsdir/$linkname.id");
   89:             }
   90:             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
   91:                                               "$lonidsdir/$linkname.id"); 1 };
   92:             if ($made_symlink) {
   93:                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
   94:                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
   95:             }
   96:         }
   97:     } else {
   98:         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
   99:     }
  100: # -------------------------------------------------------- Menu script and info
  101:     my $destination = $lowerurl;
  102:     if ($env{'request.lti.login'}) {
  103:         if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
  104:             &Apache::loncommon::content_type($r,'text/html');
  105:             if ($securecookie) {
  106:                 $r->headers_out->add('Set-cookie' => $securecookie);
  107:             }
  108:             if ($defaultcookie) {
  109:                 $r->headers_out->add('Set-cookie' => $defaultcookie);
  110:             }
  111:             $r->send_http_header;
  112:             if (ref($form) eq 'HASH') {
  113:                 $form->{'lti.login'} = $env{'request.lti.login'};
  114:                 $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
  115:                 $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
  116:                 $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
  117:             }
  118:             &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
  119:             return;
  120:         }
  121:         if ($env{'request.lti.selfenrollrole'}) {
  122:             if (&Apache::ltiauth::lti_enroll($username,$domain,
  123:                                              $env{'request.lti.selfenrollrole'}) eq 'ok') {
  124:                 $form->{'role'} = $env{'request.lti.selfenrollrole'};
  125:                 &Apache::lonnet::delenv('request.lti.selfenrollrole');
  126:             } else {
  127:                 &Apache::ltiauth::invalid_request($r,24);
  128:             }
  129:         }
  130:     }
  131:     if (defined($form->{role})) {
  132:         my $envkey = 'user.role.'.$form->{role};
  133:         my $now=time;
  134:         my $then=$env{'user.login.time'};
  135:         my $refresh=$env{'user.refresh.time'};
  136:         my $update=$env{'user.update.time'};
  137:         if (!$update) {
  138:             $update = $then;
  139:         }
  140:         if (exists($env{$envkey})) {
  141:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
  142:             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
  143:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  144:             if ($tstatus eq 'is') {
  145:                 $destination  .= ($destination =~ /\?/) ? '&' : '?';
  146:                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
  147:                 $destination .= 'selectrole=1&'.$newrole.'=1';
  148:             }
  149:         }
  150:     }
  151:     if (defined($form->{symb})) {
  152:         my $destsymb = $form->{symb};
  153:         my $encrypted;
  154:         if ($destsymb =~ m{^/enc/}) {
  155:             $encrypted = 1;
  156:             if ($cid) {
  157:                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
  158:             }
  159:         }
  160:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  161:         if ($destsymb =~ /___/) {
  162:             my ($map,$resid,$desturl)=split(/___/,$destsymb);
  163:             $desturl = &Apache::lonnet::clutter($desturl);
  164:             if ($encrypted) {
  165:                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
  166:                 $destsymb = $form->{symb};
  167:             }
  168:             $desturl = &HTML::Entities::encode($desturl,'"<>&');
  169:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  170:             $destination .= 'destinationurl='.$desturl.
  171:                             '&destsymb='.$destsymb;
  172:         } elsif (!$encrypted) {
  173:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  174:             $destination .= 'destinationurl='.$destsymb;
  175:         }
  176:     }
  177:     if ($destination =~ m{^/adm/roles}) {
  178:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
  179:         $destination .= 'source=login';
  180:     }
  181: 
  182:     if (($env{'request.deeplink.login'} eq $lowerurl) &&
  183:         (($env{'request.linkprot'}) || ($env{'request.linkkey'} ne ''))) {
  184:         my %info;
  185:         if ($env{'request.linkprot'}) {
  186:             $info{'linkprot'} = $env{'request.linkprot'};
  187:         } elsif ($env{'request.linkkey'} ne '') {
  188:             $info{'linkkey'} = $env{'request.linkkey'};
  189:         }
  190:         $info{'origurl'} = $lowerurl;
  191:         my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
  192:         unless (($token eq 'con_lost') || ($token eq 'refused') ||
  193:                 ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
  194:             $destination .= (($destination =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
  195:         }
  196:     }
  197: 
  198:     my $windowname = 'loncapaclient';
  199:     if ($env{'request.lti.login'}) {
  200:         $windowname .= 'lti';
  201:     }
  202:     my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
  203:     my $brcrum = [{'href' => '',
  204:                    'text' => 'Successful Login'},];
  205:     my $args = {'bread_crumbs' => $brcrum,};
  206:     unless ((defined($form->{role})) || (defined($form->{symb}))) {
  207:         my $update=$env{'user.update.time'};
  208:         if (!$update) {
  209:             $update = $env{'user.login.time'};
  210:         }
  211:         my %roles_in_env;
  212:         my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
  213:         if ($showcount == 1) {
  214:             foreach my $rolecode (keys(%roles_in_env)) {
  215:                 my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
  216:                 if ($cid) {
  217:                     my %coursedescription =
  218:                         &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
  219:                     if ($coursedescription{'type'} eq 'Placement') {
  220:                         $args->{'crstype'} = 'Placement';
  221:                     }
  222:                     last;
  223:                 }
  224:             }
  225:         }
  226:     }
  227: 
  228: # ------------------------------------------------- Output for successful login
  229: 
  230:     &Apache::loncommon::content_type($r,'text/html');
  231:     if ($securecookie) {
  232:         $r->headers_out->add('Set-cookie' => $securecookie);
  233:     }
  234:     if ($defaultcookie) {
  235:         $r->headers_out->add('Set-cookie' => $defaultcookie);
  236:     }
  237:     if ($expirepub) {
  238:         my $c = new CGI::Cookie(-name    => 'lonPubID',
  239:                                 -value   => '',
  240:                                 -expires => '-10y',);
  241:         $r->headers_out->add('Set-cookie' => $c);
  242:     }
  243:     $r->send_http_header;
  244: 
  245:     my ($start_page,$js,$pagebody,$end_page);
  246:     if ($env{'request.lti.login'}) {
  247:         $args = {'only_body' => 1};
  248:         if ($env{'request.lti.target'} eq '') {
  249:             my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
  250:                             'ltitarget=iframe';
  251:             &js_escape(\$destination);
  252:             $js = <<"ENDJS";
  253: 
  254: <script type="text/javascript">
  255: // <![CDATA[
  256: function setLTItarget() {
  257:     var newloc = '$destination';
  258:     if (parent !== window) {
  259:         newloc += '$ltitarget';
  260:     }
  261:     window.location.href=newloc;
  262: }
  263: // ]]>
  264: </script>
  265: 
  266: ENDJS
  267:             $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
  268:             $pagebody =  '<noscript><span class="LC_warning">'
  269:                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
  270:                         .'</span></noscript>';
  271:         } else {
  272:             $args->{'redirect'} = [0,$destination,1];
  273:         }
  274:         $start_page=&Apache::loncommon::start_page('',$js,$args);
  275:     } else {
  276:         $args->{'redirect'} = [0,$destination];
  277:         $start_page=&Apache::loncommon::start_page('Successful Login',
  278:                                                    $js,$args);
  279: 
  280:         my %lt=&Apache::lonlocal::texthash(
  281: 				           'wel' => 'Welcome',
  282: 				           'pro' => 'Login problems?',
  283: 				          );
  284:         $pagebody = "<h1>$lt{'wel'}</h1>\n".
  285:                     &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
  286:         my $loginhelp = &loginhelpdisplay($domain);
  287:         if ($loginhelp) {
  288:             $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
  289:         }
  290:     }
  291:     $end_page = &Apache::loncommon::end_page();
  292:     $r->print(<<ENDSUCCESS);
  293: $start_page
  294: $windowinfo
  295: $pagebody
  296: $end_page
  297: ENDSUCCESS
  298:     return;
  299: }
  300: 
  301: # --------------------------------------------------------------- Failed login!
  302: 
  303: sub failed {
  304:     my ($r,$message,$form,$authhost) = @_;
  305:     (undef,undef,undef,my $clientmathml,my $clientunicode) =
  306:         &Apache::loncommon::decode_user_agent();
  307:     my $args = {};
  308:     if ($clientunicode && !$clientmathml) {
  309:         $args = {'browser.unicode' => 1};
  310:     }
  311:     if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
  312:         if ($form->{linkprot}) {
  313:             $args->{only_body} = 1;
  314:         }
  315:     }
  316: 
  317:     my @actions;
  318:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
  319:     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
  320:     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
  321:     if (&Apache::lonnet::domain($udom,'description') eq '') {
  322:         undef($udom);
  323:     }
  324:     my $authtype;
  325:     if (($udom ne '') && ($uname ne '') && ($authhost eq 'no_host')) {
  326:         $authtype = &Apache::lonnet::queryauthenticate($uname,$udom);
  327:     }
  328:     my $retry = '/adm/login';
  329:     if (($uname eq $form->{'uname'}) && ($authtype !~ /^lti:/)) {
  330:         $retry .= '?username='.$uname;
  331:     }
  332:     if ($udom) {
  333:         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
  334:     }
  335:     my $lonhost = $r->dir_config('lonHostID');
  336:     my $querystr;
  337:     my $result = &set_retry_token($form,$lonhost,\$querystr);
  338:     if ($result eq 'fail') {
  339:         if (exists($form->{role})) {
  340:             my $role = &Apache::loncommon::cleanup_html($form->{role});
  341:             if ($role ne '') {
  342:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
  343:             }
  344:         }
  345:         if (exists($form->{symb})) {
  346:             my $symb = &Apache::loncommon::cleanup_html($form->{symb});
  347:             if ($symb ne '') {
  348:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
  349:             }
  350:         }
  351:         if (exists($form->{firsturl})) {
  352:             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
  353:             if ($firsturl ne '') {
  354:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
  355:                 if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
  356:                     unless (exists($form->{linkprot})) {
  357:                         if (exists($form->{linkkey})) {
  358:                             $retry .= 'linkkey='.$form->{linkkey};
  359:                         }
  360:                     }
  361:                 }
  362:             }
  363:         }
  364:         if (exists($form->{linkprot})) {
  365:             my %info = (
  366:                          'linkprot' => $form->{'linkprot'},
  367:                        );
  368:             if ($form->{linkprotuser} ne '') {
  369:                 $info{'linkprotuser'} = $form->{linkprotuser};
  370:             }
  371:             my $ltoken = &Apache::lonnet::tmpput(\%info,
  372:                                                  $r->dir_config('lonHostID'),'retry');
  373:             if ($ltoken) {
  374:                 $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
  375:             }
  376:         }
  377:     } elsif ($querystr ne '') {
  378:         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;
  379:     }
  380:     my $end_page = &Apache::loncommon::end_page();
  381:     &Apache::loncommon::content_type($r,'text/html');
  382:     $r->send_http_header;
  383:     if ($authtype =~ /^lti:/) {
  384:         $message = &mt('Direct login is not supported with the username you entered.').
  385:                    '<br /><br />'.
  386:                    &mt('You likely need to launch LON-CAPA from within a course in a different Learning Management System.').
  387:                    '<br />'.
  388:                    &mt('You can also try to log in with a different username.');
  389:         @actions = 
  390:             (&mt('Try your [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
  391:     } else {
  392:         $message = &mt($message);
  393:         @actions =
  394:             (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
  395:     }
  396:     my $loginhelp = &loginhelpdisplay($udom);
  397:     if ($loginhelp) {
  398:         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
  399:     }
  400:     #FIXME: link to helpdesk might be added here
  401:     $r->print(
  402:        $start_page
  403:       .'<h2>'.&mt('Sorry ...').'</h2>'
  404:       .&Apache::lonhtmlcommon::confirm_success($message,1).'<br /><br />'
  405:       .&Apache::lonhtmlcommon::actionbox(\@actions)
  406:       .$end_page
  407:     );
  408:  }
  409: 
  410: # ------------------------------------------------------------------ Rerouting!
  411: 
  412: sub reroute {
  413:     my ($r) = @_;
  414:     &Apache::loncommon::content_type($r,'text/html');
  415:     $r->send_http_header;
  416:     my $msg='<b>'.&mt('Sorry ...').'</b><br />'
  417:            .&mt('Please [_1]log in again[_2].');
  418:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
  419: }
  420: 
  421: # ---------------------------------------------------------------- Main handler
  422: 
  423: sub handler {
  424:     my $r = shift;
  425:     my $londocroot = $r->dir_config('lonDocRoot');
  426: # Are we re-routing?
  427:     if (-e "$londocroot/lon-status/reroute.txt") {
  428: 	&reroute($r);
  429: 	return OK;
  430:     }
  431: 
  432:     &Apache::lonlocal::get_language_handle($r);
  433: 
  434: # -------------------------------- Prevent users from attempting to login twice
  435:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  436:     if ($handle ne '') {
  437:         my $lonidsdir=$r->dir_config('lonIDsDir');
  438:         if ($handle=~/^publicuser\_/) {
  439: # For "public user" - remove it, we apparently really want to login
  440:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
  441:         } else {
  442: # Indeed, a valid token is found
  443:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  444: 	    &Apache::loncommon::content_type($r,'text/html');
  445: 	    $r->send_http_header;
  446: 	    my $start_page =
  447: 	        &Apache::loncommon::start_page('Already logged in');
  448: 	    my $end_page = 
  449: 	        &Apache::loncommon::end_page();
  450:             my $dest = '/adm/roles';
  451:             my %form = &get_form_items($r);
  452:             if ($form{'logtoken'}) {
  453:                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  454:                                                      $form{'serverid'});
  455:                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
  456:                         ($tmpinfo eq 'no_such_host')) {
  457:                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
  458:                     $firsturl = &unescape($firsturl);
  459:                     my %info;
  460:                     foreach my $item (@rest) {
  461:                         my ($key,$value) = split(/=/,$item);
  462:                         $info{$key} = &unescape($value);
  463:                     }
  464:                     if ($firsturl ne '') {
  465:                         $info{'firsturl'} = $firsturl;
  466:                         $dest = $firsturl;
  467:                         my $relogin;
  468:                         if ($dest =~ m{^/tiny/$match_domain/\w+$}) {
  469:                             if ($env{'request.course.id'}) {
  470:                                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  471:                                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  472:                                 my $symb = &Apache::loncommon::symb_from_tinyurl($dest,$cnum,$cdom);
  473:                                 if ($symb) {
  474:                                     unless (&set_deeplink_login(%info) eq 'ok') {
  475:                                         $relogin = 1;
  476:                                     }
  477:                                 }
  478:                             }
  479:                             if ($relogin) {
  480:                                 $r->print(
  481:                                       $start_page
  482:                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  483:                                      .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',
  484:                                                 '<a href="/adm/logout">','</a>')
  485:                                      .'</p>'
  486:                                      .$end_page);
  487:                             } else {
  488:                                 if (($info{'linkprot'}) || ($info{'linkkey'} ne '')) {
  489:                                     if (($info{'linkprot'}) && ($info{'linkprotuser'} ne '')) {
  490:                                         unless ($info{'linkprotuser'} eq $env{'user.name'}.':'.$env{'user.domain'}) {
  491:                                             $r->print(
  492:                                                       $start_page
  493:                                                       .'<p class="LC_warning">'.&mt('You are already logged in, but as a different user from the one expected for the link you followed from another system').'</p>'
  494:                                                       .'<p>'.&mt('Please [_1]log out[_2] first, and then try following the link again from the other system',
  495:                                                                  '<a href="/adm/logout">','</a>')
  496: 
  497:                                                       .'</p>'
  498:                                                       .$end_page);
  499:                                             return OK;
  500:                                         }
  501:                                     }
  502:                                     my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
  503:                                     unless (($token eq 'con_lost') || ($token eq 'refused') ||
  504:                                             ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
  505:                                         $dest .= (($dest =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
  506:                                     }
  507:                                 }
  508:                                 $r->print(
  509:                                       $start_page
  510:                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  511:                                      .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4] first, and then try your access again',
  512:                                                 '<a href="'.$dest.'">','</a>',
  513:                                                 '<a href="/adm/logout">','</a>')
  514:                                      .'</p>'
  515:                                      .$end_page);
  516:                             }
  517:                             return OK;
  518:                         }
  519:                     }
  520:                 }
  521:             }
  522:             $r->print(
  523:                   $start_page
  524:                  .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  525:                  .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  526:                           ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
  527:                  .'</p>'
  528:                  .$end_page
  529:             );
  530:             return OK;
  531:         }
  532:     }
  533: 
  534: # ---------------------------------------------------- No valid token, continue
  535: 
  536:     my %form = &get_form_items($r);
  537:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  538: 	&failed($r,'Username, password and domain need to be specified.',
  539: 		\%form);
  540:         return OK;
  541:     }
  542: 
  543: # split user logging in and "su"-user
  544: 
  545:     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
  546:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  547:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  548:     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
  549:     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
  550: 
  551:     my $role   = $r->dir_config('lonRole');
  552:     my $domain = $r->dir_config('lonDefDomain');
  553:     my $prodir = $r->dir_config('lonUsersDir');
  554:     my $contact_name = &mt('LON-CAPA helpdesk');
  555: 
  556: # ---------------------------------------- Get the information from login token
  557: 
  558:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  559:                                       $form{'serverid'});
  560: 
  561:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
  562:         ($tmpinfo eq 'no_such_host')) {
  563: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  564:         return OK;
  565:     } else {
  566: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  567: 					   $form{'serverid'});
  568:         if ( $reply ne 'ok' ) {
  569:             &failed($r,'Session could not be opened.',\%form);
  570: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  571: 	    return OK;
  572: 	}
  573:     }
  574: 
  575:     if (!&Apache::lonnet::domain($form{'udom'})) {
  576:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  577:         return OK;
  578:     }
  579: 
  580:     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
  581:     $firsturl = &unescape($firsturl);
  582:     foreach my $item (@rest) {
  583:         my ($key,$value) = split(/=/,$item);
  584:         $form{$key} = &unescape($value);
  585:     }
  586:     if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
  587:         $form{'firsturl'} = $firsturl;
  588:     }
  589:     my $upass = $ENV{HTTPS} ? $form{'upass0'} 
  590:         : &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});
  591: 
  592: # ---------------------------------------------------------------- Authenticate
  593: 
  594:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  595:     my ($cancreate,$statustocreate) =
  596:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
  597:     my $defaultauth;
  598:     if (ref($cancreate) eq 'ARRAY') {
  599:         if (grep(/^login$/,@{$cancreate})) {
  600:             $defaultauth = 1;
  601:         }
  602:     }
  603:     my $clientcancheckhost = 1;
  604:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  605:                                               $form{'udom'},$defaultauth,
  606:                                               $clientcancheckhost);
  607: 
  608: # --------------------------------------------------------------------- Failed?
  609: 
  610:     if ($authhost eq 'no_host') {
  611:         my $pwdverify;
  612:         if (&Apache::lonnet::homeserver($form{'uname'},$form{'udom'}) eq 'no_host') {
  613:             my %possunames = &alternate_unames_check($form{'uname'},$form{'udom'});
  614:             if (keys(%possunames) > 0) {
  615:                 foreach my $rulematch (keys(%possunames)) {
  616:                     my $possuname = $possunames{$rulematch};
  617:                     if (($possuname ne '') && ($possuname =~ /^$match_username$/)) {
  618:                         $authhost=Apache::lonnet::authenticate($possuname,$upass,
  619:                                                                $form{'udom'},undef,
  620:                                                                $clientcancheckhost);
  621:                         if (($authhost eq 'no_host') || ($authhost eq 'no_account_on_host')) {
  622:                             next;
  623:                         } elsif (($authhost ne '') && (&Apache::lonnet::hostname($authhost) ne '')) {
  624:                             $pwdverify = 1;
  625:                             &Apache::lonnet::logthis("Authenticated user: $possuname was submitted as: $form{'uname'}"); 
  626:                             $form{'uname'} = $possuname;
  627:                             last;
  628:                         }
  629:                     }
  630:                 }
  631:             }
  632:         }
  633:         unless ($pwdverify) {
  634:             &failed($r,'Username and/or password could not be authenticated.',
  635:                     \%form,$authhost);
  636:             return OK;
  637:         }
  638:     } elsif ($authhost eq 'no_account_on_host') {
  639:         if ($defaultauth) {
  640:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  641:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
  642:                 return OK;
  643:             }
  644:             my $start_page = 
  645:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',
  646:                                                '',{'no_inline_link'   => 1,});
  647:             my $lonhost = $r->dir_config('lonHostID');
  648:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  649:             my $contacts = 
  650:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  651:                                                         $form{'udom'},$origmail);
  652:             my ($contact_email) = split(',',$contacts); 
  653:             my $output = 
  654:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
  655:                                                        $domdesc,'',$lonhost,
  656:                                                        $contact_email,$contact_name,
  657:                                                        undef,$statustocreate);
  658:             &Apache::loncommon::content_type($r,'text/html');
  659:             $r->send_http_header;
  660:             &Apache::createaccount::print_header($r,$start_page);
  661:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  662:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  663:                       $output.&Apache::loncommon::end_page());
  664:             return OK;
  665:         } else {
  666:             &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);
  667:             return OK;
  668:         }
  669:     }
  670: 
  671:     if (($firsturl eq '') || 
  672: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  673: 	$firsturl='/adm/roles';
  674:     }
  675: 
  676:     my ($hosthere,%sessiondata);
  677:     if ($form{'iptoken'}) {
  678:         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  679:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  680:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
  681:             ($sessiondata{'username'} eq $form{'uname'})) {
  682:             $hosthere = 1;
  683:         }
  684:     }
  685: 
  686: # --------------------------------- Are we attempting to login as somebody else?
  687:     if ($form{'suname'}) {
  688:         my ($suname,$sudom,$sudomref);
  689:         $suname = $form{'suname'};
  690:         $sudom = $form{'udom'};
  691:         if ($form{'sudom'}) {
  692:             unless ($sudom eq $form{'sudom'}) {
  693:                 if (&Apache::lonnet::domain($form{'sudom'})) {
  694:                     $sudomref = [$form{'sudom'}];
  695:                     $sudom = $form{'sudom'};
  696:                 }
  697:             }
  698:         }
  699: # ------------ see if the original user has enough privileges to pull this stunt
  700: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
  701: # ---------------------------------------------------- see if the su-user exists
  702: 	    unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
  703: # ------------------------------ see if the su-user is not too highly privileged
  704: 		if (&Apache::lonnet::privileged($suname,$sudom)) {
  705:                     &Apache::lonnet::logthis('Attempted switch user to privileged user');
  706:                 } else {
  707:                     my $noprivswitch;
  708: #
  709: # su-user's home server and user's home server must have one of:
  710: # (a) same domain
  711: # (b) same primary library server for the two domains
  712: # (c) same "internet domain" for primary library server(s) for home servers' domains
  713: #
  714:                     my $suprim = &Apache::lonnet::domain($sudom,'primary');
  715:                     my $suintdom = &Apache::lonnet::internet_dom($suprim);
  716:                     unless ($sudom eq $form{'udom'}) {
  717:                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
  718:                         my $uintdom = &Apache::lonnet::internet_dom($uprim);
  719:                         unless ($suprim eq $uprim) {
  720:                             unless ($suintdom eq $uintdom) {
  721:                                 &Apache::lonnet::logthis('Attempted switch user '
  722:                                    .'to user with different "internet domain".');
  723:                                 $noprivswitch = 1;
  724:                             }
  725:                         }
  726:                     }
  727: 
  728:                     unless ($noprivswitch) {
  729: #
  730: # server where log-in occurs must have same "internet domain" as su-user's home
  731: # server
  732: #
  733:                         my $lonhost = $r->dir_config('lonHostID');
  734:                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
  735:                         if ($hostintdom ne $suintdom) {
  736:                             &Apache::lonnet::logthis('Attempted switch user on a '
  737:                                 .'server with a different "internet domain".'); 
  738:                         } else {
  739: 
  740: # -------------------------------------------------------- actually switch users
  741: 
  742: 		            &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
  743:                               $form{'udom'}.' logging in as '.$suname.':'.$sudom);
  744: 		            $form{'uname'}=$suname;
  745:                             if ($form{'udom'} ne $sudom) {
  746:                                 $form{'udom'}=$sudom;
  747:                             }
  748:                         }
  749:                     }
  750: 		}
  751: 	    }
  752: 	} else {
  753: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  754: 	}
  755:     }
  756: 
  757:     if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  758:         if (($form{'linkprot'}) && ($form{'linkprotuser'} ne '')) {
  759:             unless($form{'linkprotuser'} eq $form{'uname'}.':'.$form{'udom'}) {
  760:                 delete($form{'udom'});
  761:                 delete($form{'uname'});
  762:                 &failed($r,'Username and/or domain are different to that expected for the link you followed from another system',
  763:                         \%form,$authhost);
  764:                 return OK;
  765:             }
  766:         }
  767:     }
  768: 
  769:     my ($is_balancer,$otherserver);
  770: 
  771:     unless ($hosthere) {
  772:         ($is_balancer,$otherserver) =
  773:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
  774:         if ($is_balancer) {
  775:             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
  776:             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
  777:             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
  778:                 $otherserver = $found_server;
  779:             }
  780:             if ($otherserver eq '') {
  781:                 my $lowest_load;
  782:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
  783:                 if ($lowest_load > 100) {
  784:                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
  785:                 }
  786:             }
  787:             if ($otherserver ne '') {
  788:                 my @hosts = &Apache::lonnet::current_machine_ids();
  789:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
  790:                     $hosthere = $otherserver;
  791:                 }
  792:             }
  793:         }
  794:     }
  795: 
  796:     if (($is_balancer) && (!$hosthere)) {
  797:         if ($otherserver) {
  798:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  799:                      \%form);
  800:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  801:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  802:                 $switchto .= '&origurl='.$firsturl;
  803:             }
  804:             if ($form{'role'}) {
  805:                 $switchto .= '&role='.$form{'role'};
  806:             }
  807:             if ($form{'symb'}) {
  808:                 $switchto .= '&symb='.$form{'symb'};
  809:             }
  810:             if ($form{'linkprot'}) {
  811:                 $env{'request.linkprot'} = $form{'linkprot'};
  812:             } elsif ($form{'linkkey'} ne '') {
  813:                 $env{'request.linkkey'} = $form{'linkkey'};
  814:             }
  815:             if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  816:                 &set_deeplink_login(%form);
  817:             }
  818:             $r->internal_redirect($switchto);
  819:         } else {
  820:             &Apache::loncommon::content_type($r,'text/html');
  821:             $r->send_http_header;
  822:             $r->print(&noswitch());
  823:         }
  824:         return OK;
  825:     } else {
  826:         if (!&check_can_host($r,\%form,$authhost)) {
  827:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
  828:             if ($otherserver) {
  829:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  830:                          \%form);
  831:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  832:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  833:                     $switchto .= '&origurl='.$firsturl;
  834:                 }
  835:                 if ($form{'role'}) {
  836:                     $switchto .= '&role='.$form{'role'};
  837:                 }
  838:                 if ($form{'symb'}) {
  839:                     $switchto .= '&symb='.$form{'symb'};
  840:                 }
  841:                 if ($form{'linkprot'}) {
  842:                     $env{'request.linkprot'} = $form{'linkprot'};
  843:                 } elsif ($form{'linkkey'} ne '') {
  844:                     $env{'request.linkkey'} = $form{'linkkey'};
  845:                 }
  846:                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  847:                     &set_deeplink_login(%form);
  848:                 }
  849:                 $r->internal_redirect($switchto);
  850:             } else {
  851:                 &Apache::loncommon::content_type($r,'text/html');
  852:                 $r->send_http_header;
  853:                 $r->print(&noswitch());
  854:             }
  855:             return OK;
  856:         }
  857: 
  858: # ------------------------------------------------------- Do the load balancing
  859: 
  860: # ---------------------------------------------------------- Determine own load
  861:         my $loadlim = $r->dir_config('lonLoadLim');
  862:         my $loadavg;
  863:         {
  864:             my $loadfile=Apache::File->new('/proc/loadavg');
  865:             $loadavg=<$loadfile>;
  866:         }
  867:         $loadavg =~ s/\s.*//g;
  868:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
  869:         my $userloadpercent=&Apache::lonnet::userload();
  870: 
  871: # ---------------------------------------------------------- Are we overloaded?
  872:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
  873:             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});
  874:             if (!$unloaded) {
  875:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
  876:             }
  877:             if ($unloaded) {
  878:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
  879:                          undef,\%form);
  880:                 if ($form{'linkprot'}) {
  881:                     $env{'request.linkprot'} = $form{'linkprot'};
  882:                 } elsif ($form{'linkkey'} ne '') {
  883:                     $env{'request.linkkey'} = $form{'linkkey'};
  884:                 }
  885:                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  886:                     &set_deeplink_login(%form);
  887:                 }
  888:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
  889:                 return OK;
  890:             }
  891:         }
  892:         if (($is_balancer) && ($hosthere)) {
  893:             $form{'noloadbalance'} = $hosthere;
  894:         }
  895:         my $extra_env;
  896:         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {
  897:             if ($sessiondata{'origurl'} ne '') {
  898:                 $firsturl = $sessiondata{'origurl'};
  899:                 $form{'firsturl'} = $sessiondata{'origurl'};
  900:                 my @names = ('role','symb','linkprot','linkkey');
  901:                 foreach my $item (@names) {
  902:                     if ($sessiondata{$item} ne '') {
  903:                         $form{$item} = $sessiondata{$item};
  904:                     }
  905:                 }
  906:             }
  907:         }
  908:         if ($form{'linkprot'}) {
  909:             my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
  910:             if ($linkprotector) {
  911:                 $extra_env = {'user.linkprotector' => $linkprotector,
  912:                               'user.linkproturi'   => $uri};
  913:             }
  914:         } elsif ($form{'linkkey'} ne '') {
  915:             $extra_env = {'user.deeplinkkey'  => $form{'linkkey'},
  916:                           'user.keyedlinkuri' => $form{'firsturl'}};
  917:         }
  918:         if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  919:             &set_deeplink_login(%form);
  920:             if ($form{'linkprot'}) {
  921:                 if (ref($extra_env) eq 'HASH') {
  922:                     %{$extra_env} = ( %{$extra_env}, 'request.linkprot' => $form{'linkprot'} );
  923:                 } else {
  924:                     $extra_env = {'request.linkprot' => $form{'linkprot'}};
  925:                 }
  926:             } elsif ($form{'linkkey'} ne '') {
  927:                 if (ref($extra_env) eq 'HASH') {
  928:                     %{$extra_env} = ( %{$extra_env}, 'request.linkkey' => $form{'linkkey'} );
  929:                 } else {
  930:                     $extra_env = {'request.linkkey' => $form{'linkkey'}};
  931:                 }
  932:             }
  933:             if ($env{'request.deeplink.login'}) {
  934:                 if (ref($extra_env) eq 'HASH') {
  935:                     %{$extra_env} = ( %{$extra_env}, 'request.deeplink.login' => $form{'firsturl'} );
  936:                 } else {
  937:                     $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
  938:                 }
  939:             }
  940:         }
  941:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
  942:                  \%form);
  943:         return OK;
  944:     }
  945: }
  946: 
  947: sub get_form_items {
  948:     my ($r) = @_;
  949:     my $buffer;
  950:     if ($r->header_in('Content-length') > 0) {
  951:         $r->read($buffer,$r->header_in('Content-length'),0);
  952:     }
  953:     my %form;
  954:     foreach my $pair (split(/&/,$buffer)) {
  955:        my ($name,$value) = split(/=/,$pair);
  956:        $value =~ tr/+/ /;
  957:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  958:        $form{$name}=$value;
  959:     }
  960:     return %form;
  961: }
  962: 
  963: sub set_deeplink_login {
  964:     my (%form) = @_;
  965:     my $disallow;
  966:     if ($form{'firsturl'} =~ m{^/tiny/($match_domain)/\w+$}) {
  967:         my $cdom = $1;
  968:         my ($cnum,$symb) = &Apache::loncommon::symb_from_tinyurl($form{'firsturl'},'',$cdom);
  969:         if ($symb) {
  970:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
  971:                 my $deeplink;
  972:                 if ($symb =~ /\.(page|sequence)$/) {
  973:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($symb))[2]);
  974:                     my $navmap = Apache::lonnavmaps::navmap->new();
  975:                     if (ref($navmap)) {
  976:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
  977:                     }
  978:                 } else {
  979:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
  980:                 }
  981:                 if ($deeplink ne '') {
  982:                     my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
  983:                     if (($protect ne 'none') && ($protect ne '')) {
  984:                         my ($acctype,$item) = split(/:/,$protect);
  985:                         if ($acctype =~ /lti(c|d)$/) {
  986:                             unless ($form{'linkprot'} eq $item.$1.':'.$env{'request.deeplink.login'}) {
  987:                                 $disallow = 1;
  988:                             }
  989:                         } elsif ($acctype eq 'key') {
  990:                             unless ($form{'linkkey'} eq $item) {
  991:                                 $disallow = 1;
  992:                             }
  993:                         }
  994:                     }
  995:                 }
  996:                 unless ($disallow) {
  997:                     $env{'request.deeplink.login'} = $form{'firsturl'};
  998:                 }
  999:             } else {
 1000:                 $env{'request.deeplink.login'} = $form{'firsturl'};
 1001:             }
 1002:         }
 1003:     }
 1004:     if ($disallow) {
 1005:         return;
 1006:     }
 1007:     return 'ok';
 1008: }
 1009: 
 1010: sub set_retry_token {
 1011:     my ($form,$lonhost,$querystr) = @_;
 1012:     if (ref($form) eq 'HASH') {
 1013:         my ($firsturl,$token,$extras,@names);
 1014:         @names = ('role','symb','linkprotuser','linkprot','linkkey','iptoken');
 1015:         foreach my $name (@names) {
 1016:             if ($form->{$name} ne '') {
 1017:                 $extras .= '&'.$name.'='.&escape($form->{$name});
 1018:                 last if ($name eq 'linkprot');
 1019:             }
 1020:         }
 1021:         my $firsturl = $form->{'firsturl'};
 1022:         if (($firsturl ne '') || ($extras ne '')) {
 1023:             $extras .= ':retry';
 1024:             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).
 1025:                                             $extras,$lonhost);
 1026:             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {
 1027:                 return 'fail';
 1028:             } else {
 1029:                 if (ref($querystr)) {
 1030:                     $$querystr = 'retry='.$token;
 1031:                 }
 1032:                 return 'ok';
 1033:             }
 1034:         }
 1035:     }
 1036:     return;
 1037: }
 1038: 
 1039: sub check_can_host {
 1040:     my ($r,$form,$authhost,$domdesc) = @_;
 1041:     return unless (ref($form) eq 'HASH');
 1042:     my $canhost = 1;
 1043:     my $lonhost = $r->dir_config('lonHostID');
 1044:     my $udom = $form->{'udom'};
 1045:     my @intdoms;
 1046:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 1047:     if (ref($internet_names) eq 'ARRAY') {
 1048:         @intdoms = @{$internet_names};
 1049:     }
 1050:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1051:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1052:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1053:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
 1054:         my $hostname = &Apache::lonnet::hostname($lonhost);
 1055:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
 1056:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1057:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1058:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
 1059:         my $loncaparev;
 1060:         if ($authhost eq 'no_account_on_host') {
 1061:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
 1062:         } else {
 1063:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
 1064:         }
 1065:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
 1066:                                                      $udomdefaults{'remotesessions'},
 1067:                                                      $defdomdefaults{'hostedsessions'});
 1068:     }
 1069:     unless ($canhost) {
 1070:         if ($authhost eq 'no_account_on_host') {
 1071:             my $checkloginvia = 1;
 1072:             my ($login_host,$hostname) = 
 1073:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
 1074:             &Apache::loncommon::content_type($r,'text/html');
 1075:             $r->send_http_header;
 1076:             if ($login_host ne '') {
 1077:                 my $protocol = $Apache::lonnet::protocol{$login_host};
 1078:                 $protocol = 'http' if ($protocol ne 'https');
 1079:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);
 1080:                 $hostname = $alias if ($alias ne '');
 1081:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
 1082: #FIXME Should preserve where user was going and linkprot by setting ltoken at $login_host
 1083:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
 1084:                           '<h3>'.&mt('Account creation').'</h3>'.
 1085:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
 1086:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
 1087:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
 1088:                           &Apache::loncommon::end_page());
 1089:             } else {
 1090:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
 1091:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
 1092:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
 1093:                           '<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>'.
 1094:                           &Apache::loncommon::end_page());
 1095:             }
 1096:         } else {
 1097:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
 1098:                      $form);
 1099:             if ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
 1100:                 $env{'request.deeplink.login'} = $form->{'firsturl'};
 1101:             }
 1102:             if ($form->{'linkprot'}) {
 1103:                 $env{'request.linkprot'} = $form->{'linkprot'};
 1104:             } elsif ($form->{'linkkey'} ne '') {
 1105:                 $env{'request.linkkey'} = $form->{'linkkey'};
 1106:             }
 1107:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
 1108:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
 1109:         }
 1110:     }
 1111:     return $canhost;
 1112: }
 1113: 
 1114: sub noswitch {
 1115:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
 1116:                  '<h3>'.&mt('Session unavailable').'</h3>'.
 1117:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
 1118:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
 1119:                  &Apache::loncommon::end_page();
 1120:     return $result;
 1121: }
 1122: 
 1123: sub loginhelpdisplay {
 1124:     my ($authdomain) = @_;
 1125:     my $login_help = 1;
 1126:     my $lang = &Apache::lonlocal::current_language();
 1127:     if ($login_help) {
 1128:         my $dom = $authdomain;
 1129:         if ($dom eq '') {
 1130:             $dom = &Apache::lonnet::default_login_domain();
 1131:         }
 1132:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
 1133:         my $loginhelp_url;
 1134:         if ($lang) {
 1135:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
 1136:             if ($loginhelp_url ne '') {
 1137:                 return $loginhelp_url;
 1138:             }
 1139:         }
 1140:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
 1141:         if ($loginhelp_url ne '') {
 1142:             return $loginhelp_url;
 1143:         } else {
 1144:             return '/adm/loginproblems.html';
 1145:         }
 1146:     }
 1147:     return;
 1148: }
 1149: 
 1150: sub alternate_unames_check {
 1151:     my ($uname,$udom) = @_;
 1152:     my %possunames;
 1153:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1154:     if (ref($domdefs{'unamemap_rule'}) eq 'ARRAY') { 
 1155:         if (@{$domdefs{'unamemap_rule'}} > 0) {
 1156:             %possunames =
 1157:                 &Apache::lonnet::inst_rulecheck($udom,$uname,undef,
 1158:                                                 'unamemap',$domdefs{'unamemap_rule'});
 1159:         }
 1160:     }
 1161:     return %possunames;
 1162: }
 1163: 
 1164: 1;
 1165: __END__
 1166: 
 1167: 

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