File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.121.2.24.2.7: download - view: text, annotated - select for diffs
Wed Jul 5 17:33:03 2023 UTC (10 months, 1 week ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in 1.149, 1.150, 1.151, 1.152, 1.158, 1.179

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

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