File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.156: download - view: text, annotated - select for diffs
Wed Dec 26 20:10:21 2018 UTC (5 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6400 Deep-linking
  - URLs like /adm/lti/tiny/domain/uniqueID can be used to restrict use of
    deep links to access from another LTI-enabled application (no user data
    passed in this context).

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

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