File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.176: download - view: text, annotated - select for diffs
Thu Jun 30 21:04:13 2022 UTC (22 months, 4 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907
  "Exit Tool" button available to logout a session launched via deep link
  and escape iframe and redirect (for LTI-protected link).

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

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