File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.157: download - view: text, annotated - select for diffs
Sun Jan 27 16:02:43 2019 UTC (5 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6400
  - Enforce access restrictions for content which is deeplink-only (users
    with "advanced priv for current role are exempt).
  - Support "key" link type in deeplink parameter (requested link must either
    be sent with linkkey as element in POSTed data, or with linkkey in query
    string).  Corresponding value must match key set in deeplink parameter.

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.157 2019/01/27 16:02:43 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:             if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
  306:                 unless (exists($form->{linkprot})) {
  307:                     if (exists($form->{linkkey})) {
  308:                         $retry .= 'linkkey='.$form->{linkkey};
  309:                     }
  310:                 }
  311:             }
  312:         }
  313:     }
  314:     if (exists($form->{linkprot})) {
  315:         my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
  316:                                              $r->dir_config('lonHostID'));
  317:         if ($ltoken) {
  318:             $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
  319:         }
  320:     }
  321:     my $end_page = &Apache::loncommon::end_page();
  322:     &Apache::loncommon::content_type($r,'text/html');
  323:     $r->send_http_header;
  324:     my @actions =
  325:          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
  326:     my $loginhelp = &loginhelpdisplay($udom);
  327:     if ($loginhelp) {
  328:         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
  329:     }
  330:     #FIXME: link to helpdesk might be added here
  331: 
  332:     $r->print(
  333:        $start_page
  334:       .'<h2>'.&mt('Sorry ...').'</h2>'
  335:       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
  336:       .&Apache::lonhtmlcommon::actionbox(\@actions)
  337:       .$end_page
  338:     );
  339:  }
  340: 
  341: # ------------------------------------------------------------------ Rerouting!
  342: 
  343: sub reroute {
  344:     my ($r) = @_;
  345:     &Apache::loncommon::content_type($r,'text/html');
  346:     $r->send_http_header;
  347:     my $msg='<b>'.&mt('Sorry ...').'</b><br />'
  348:            .&mt('Please [_1]log in again[_2].');
  349:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
  350: }
  351: 
  352: # ---------------------------------------------------------------- Main handler
  353: 
  354: sub handler {
  355:     my $r = shift;
  356:     my $londocroot = $r->dir_config('lonDocRoot');
  357: # Are we re-routing?
  358:     if (-e "$londocroot/lon-status/reroute.txt") {
  359: 	&reroute($r);
  360: 	return OK;
  361:     }
  362: 
  363:     &Apache::lonlocal::get_language_handle($r);
  364: 
  365: # -------------------------------- Prevent users from attempting to login twice
  366:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  367:     if ($handle ne '') {
  368:         my $lonidsdir=$r->dir_config('lonIDsDir');
  369:         if ($handle=~/^publicuser\_/) {
  370: # For "public user" - remove it, we apparently really want to login
  371:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
  372:         } else {
  373: # Indeed, a valid token is found
  374:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  375: 	    &Apache::loncommon::content_type($r,'text/html');
  376: 	    $r->send_http_header;
  377: 	    my $start_page = 
  378: 	        &Apache::loncommon::start_page('Already logged in');
  379: 	    my $end_page = 
  380: 	        &Apache::loncommon::end_page();
  381:             my $dest = '/adm/roles';
  382:             if ($env{'form.firsturl'} ne '') {
  383:                 $dest = $env{'form.firsturl'};
  384:                 if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  385:                     &Apache::lonnet::appenv({'request.deeplink.login' => $env{'form.firsturl'}}); 
  386:                 }
  387:             }
  388:             $r->print(
  389:                $start_page
  390:               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  391:               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  392:                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
  393:               .'</p>'
  394:               .$end_page
  395:             );
  396:             return OK;
  397:         }
  398:     }
  399: 
  400: # ---------------------------------------------------- No valid token, continue
  401: 
  402: 
  403:     my $buffer;
  404:     if ($r->header_in('Content-length') > 0) {
  405: 	$r->read($buffer,$r->header_in('Content-length'),0);
  406:     }
  407:     my %form;
  408:     foreach my $pair (split(/&/,$buffer)) {
  409:        my ($name,$value) = split(/=/,$pair);
  410:        $value =~ tr/+/ /;
  411:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  412:        $form{$name}=$value;
  413:     }
  414: 
  415:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  416: 	&failed($r,'Username, password and domain need to be specified.',
  417: 		\%form);
  418:         return OK;
  419:     }
  420: 
  421: # split user logging in and "su"-user
  422: 
  423:     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
  424:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  425:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  426:     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
  427:     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
  428: 
  429:     my $role   = $r->dir_config('lonRole');
  430:     my $domain = $r->dir_config('lonDefDomain');
  431:     my $prodir = $r->dir_config('lonUsersDir');
  432:     my $contact_name = &mt('LON-CAPA helpdesk');
  433: 
  434: # ---------------------------------------- Get the information from login token
  435: 
  436:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  437:                                       $form{'serverid'});
  438: 
  439:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
  440:         ($tmpinfo eq 'no_such_host')) {
  441: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  442:         return OK;
  443:     } else {
  444: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  445: 					   $form{'serverid'});
  446:         if ( $reply ne 'ok' ) {
  447:             &failed($r,'Session could not be opened.',\%form);
  448: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  449: 	    return OK;
  450: 	}
  451:     }
  452: 
  453:     if (!&Apache::lonnet::domain($form{'udom'})) {
  454:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  455:         return OK;
  456:     }
  457: 
  458:     my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr,$linkstr)=split(/&/,$tmpinfo);
  459:     if ($rolestr) {
  460:         $rolestr = &unescape($rolestr);
  461:     }
  462:     if ($symbstr) {
  463:         $symbstr= &unescape($symbstr);
  464:     }
  465:     if ($iptokenstr) {
  466:         $iptokenstr = &unescape($iptokenstr);
  467:     }
  468:     if ($linkstr) {
  469:         $linkstr = &unescape($linkstr);
  470:     }
  471:     if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
  472:         $form{'firsturl'} = $firsturl;
  473:     }
  474:     if ($rolestr =~ /^role=/) {
  475:         (undef,$form{'role'}) = split('=',$rolestr);
  476:     }
  477:     if ($symbstr =~ /^symb=/) { 
  478:         (undef,$form{'symb'}) = split('=',$symbstr);
  479:     }
  480:     if ($iptokenstr =~ /^iptoken=/) {
  481:         (undef,$form{'iptoken'}) = split('=',$iptokenstr);
  482:     }
  483:     if ($linkstr =~ /^linkprot=/) {
  484:         (undef,$form{'linkprot'}) = split('=',$linkstr);
  485:     } elsif ($linkstr =~ /^linkkey=/) {
  486:         (undef,$form{'linkkey'}) = split('=',$linkstr);
  487:     }
  488: 
  489:     my $upass = $ENV{HTTPS} ? $form{'upass0'} 
  490:         : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
  491: 
  492: # ---------------------------------------------------------------- Authenticate
  493: 
  494:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  495:     my ($cancreate,$statustocreate) =
  496:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
  497:     my $defaultauth;
  498:     if (ref($cancreate) eq 'ARRAY') {
  499:         if (grep(/^login$/,@{$cancreate})) {
  500:             $defaultauth = 1;
  501:         }
  502:     }
  503:     my $clientcancheckhost = 1;
  504:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  505:                                               $form{'udom'},$defaultauth,
  506:                                               $clientcancheckhost);
  507: 
  508: # --------------------------------------------------------------------- Failed?
  509: 
  510:     if ($authhost eq 'no_host') {
  511: 	&failed($r,'Username and/or password could not be authenticated.',
  512: 		\%form);
  513:         return OK;
  514:     } elsif ($authhost eq 'no_account_on_host') {
  515:         if ($defaultauth) {
  516:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  517:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
  518:                 return OK;
  519:             }
  520:             my $start_page = 
  521:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA');
  522:             my $lonhost = $r->dir_config('lonHostID');
  523:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  524:             my $contacts = 
  525:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  526:                                                         $form{'udom'},$origmail);
  527:             my ($contact_email) = split(',',$contacts); 
  528:             my $output = 
  529:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
  530:                                                        $domdesc,'',$lonhost,
  531:                                                        $contact_email,$contact_name,
  532:                                                        undef,$statustocreate);
  533:             &Apache::loncommon::content_type($r,'text/html');
  534:             $r->send_http_header;
  535:             &Apache::createaccount::print_header($r,$start_page);
  536:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  537:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  538:                       $output.&Apache::loncommon::end_page());
  539:             return OK;
  540:         } else {
  541:             &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);
  542:             return OK;
  543:         }
  544:     }
  545: 
  546:     if (($firsturl eq '') || 
  547: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  548: 	$firsturl='/adm/roles';
  549:     }
  550: 
  551:     my $hosthere;
  552:     if ($form{'iptoken'}) {
  553:         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  554:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  555:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
  556:             ($sessiondata{'username'} eq $form{'uname'})) {
  557:             $hosthere = 1;
  558:         }
  559:     }
  560: 
  561: # --------------------------------- Are we attempting to login as somebody else?
  562:     if ($form{'suname'}) {
  563:         my ($suname,$sudom,$sudomref);
  564:         $suname = $form{'suname'};
  565:         $sudom = $form{'udom'};
  566:         if ($form{'sudom'}) {
  567:             unless ($sudom eq $form{'sudom'}) {
  568:                 if (&Apache::lonnet::domain($form{'sudom'})) {
  569:                     $sudomref = [$form{'sudom'}];
  570:                     $sudom = $form{'sudom'};
  571:                 }
  572:             }
  573:         }
  574: # ------------ see if the original user has enough privileges to pull this stunt
  575: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
  576: # ---------------------------------------------------- see if the su-user exists
  577: 	    unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
  578: # ------------------------------ see if the su-user is not too highly privileged
  579: 		if (&Apache::lonnet::privileged($suname,$sudom)) {
  580:                     &Apache::lonnet::logthis('Attempted switch user to privileged user');
  581:                 } else {
  582:                     my $noprivswitch;
  583: #
  584: # su-user's home server and user's home server must have one of:
  585: # (a) same domain
  586: # (b) same primary library server for the two domains
  587: # (c) same "internet domain" for primary library server(s) for home servers' domains
  588: #
  589:                     my $suprim = &Apache::lonnet::domain($sudom,'primary');
  590:                     my $suintdom = &Apache::lonnet::internet_dom($suprim);
  591:                     unless ($sudom eq $form{'udom'}) {
  592:                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
  593:                         my $uintdom = &Apache::lonnet::internet_dom($uprim);
  594:                         unless ($suprim eq $uprim) {
  595:                             unless ($suintdom eq $uintdom) {
  596:                                 &Apache::lonnet::logthis('Attempted switch user '
  597:                                    .'to user with different "internet domain".');                        
  598:                                 $noprivswitch = 1;
  599:                             }
  600:                         }
  601:                     }
  602: 
  603:                     unless ($noprivswitch) {
  604: #
  605: # server where log-in occurs must have same "internet domain" as su-user's home
  606: # server
  607: #
  608:                         my $lonhost = $r->dir_config('lonHostID');
  609:                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
  610:                         if ($hostintdom ne $suintdom) {
  611:                             &Apache::lonnet::logthis('Attempted switch user on a '
  612:                                 .'server with a different "internet domain".'); 
  613:                         } else {
  614: 
  615: # -------------------------------------------------------- actually switch users
  616: 
  617: 		            &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
  618:                               $form{'udom'}.' logging in as '.$suname.':'.$sudom);
  619: 		            $form{'uname'}=$suname;
  620:                             if ($form{'udom'} ne $sudom) {
  621:                                 $form{'udom'}=$sudom;
  622:                             }
  623:                         }
  624:                     }
  625: 		}
  626: 	    }
  627: 	} else {
  628: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  629: 	}
  630:     }
  631: 
  632:     my ($is_balancer,$otherserver);
  633: 
  634:     unless ($hosthere) {
  635:         ($is_balancer,$otherserver) =
  636:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
  637:         if ($is_balancer) {
  638:             if ($otherserver eq '') {
  639:                 my $lowest_load;
  640:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
  641:                 if ($lowest_load > 100) {
  642:                     $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
  643:                 }
  644:             }
  645:             if ($otherserver ne '') {
  646:                 my @hosts = &Apache::lonnet::current_machine_ids();
  647:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
  648:                     $hosthere = $otherserver;
  649:                 }
  650:             }
  651:         }
  652:     }
  653: 
  654:     if (($is_balancer) && (!$hosthere)) {
  655:         if ($otherserver) {
  656:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  657:                      \%form);
  658:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  659:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  660:                 $switchto .= '&origurl='.$firsturl; #should escape
  661:             }
  662:             if ($form{'role'}) {
  663:                 $switchto .= '&role='.$form{'role'};
  664:             }
  665:             if ($form{'symb'}) {
  666:                 $switchto .= '&symb='.$form{'symb'};
  667:             }
  668:             if ($form{'linkprot'}) {
  669:                 $env{'request.linkprot'} = $form{'linkprot'};
  670:             } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  671:                 if ($form{'linkkey'}) {
  672:                     $env{'request.linkkey'} = $form{'linkkey'};
  673:                 }
  674:                 $env{'request.deeplink.login'} = $form{'firsturl'};
  675:             }
  676:             $r->internal_redirect($switchto);
  677:         } else {
  678:             $r->print(&noswitch());
  679:         }
  680:         return OK;
  681:     } else {
  682:         if (!&check_can_host($r,\%form,$authhost)) {
  683:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
  684:             if ($otherserver) {
  685:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  686:                          \%form);
  687:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
  688:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
  689:                     $switchto .= '&origurl='.$firsturl; #should escape
  690:                 }
  691:                 if ($form{'role'}) {
  692:                     $switchto .= '&role='.$form{'role'};
  693:                 }
  694:                 if ($form{'symb'}) {
  695:                     $switchto .= '&symb='.$form{'symb'};
  696:                 }
  697:                 if ($form{'linkprot'}) {
  698:                     $env{'request.linkprot'} = $form{'linkprot'};
  699:                 } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  700:                     if ($form{'linkkey'}) {
  701:                         $env{'request.linkkey'} = $form{'linkkey'};
  702:                     }
  703:                     $env{'request.deeplink.login'} = $form{'firsturl'};
  704: 
  705:                 }
  706:                 $r->internal_redirect($switchto);
  707:             } else {
  708:                 $r->print(&noswitch());
  709:             }
  710:             return OK;
  711:         }
  712: 
  713: # ------------------------------------------------------- Do the load balancing
  714: 
  715: # ---------------------------------------------------------- Determine own load
  716:         my $loadlim = $r->dir_config('lonLoadLim');
  717:         my $loadavg;
  718:         {
  719:             my $loadfile=Apache::File->new('/proc/loadavg');
  720:             $loadavg=<$loadfile>;
  721:         }
  722:         $loadavg =~ s/\s.*//g;
  723:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
  724:         my $userloadpercent=&Apache::lonnet::userload();
  725: 
  726: # ---------------------------------------------------------- Are we overloaded?
  727:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
  728:             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
  729:             if (!$unloaded) {
  730:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
  731:             }
  732:             if ($unloaded) {
  733:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
  734:                          undef,\%form);
  735:                 if ($form{'linkprot'}) {
  736:                     $env{'request.linkprot'} = $form{'linkprot'};
  737:                 } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  738:                     if ($form{'linkkey'}) {
  739:                         $env{'request.linkkey'} = $form{'linkkey'};
  740:                     }
  741:                     $env{'request.deeplink.login'} = $form{'firsturl'};
  742:                 }
  743:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
  744:                 return OK;
  745:             }
  746:         }
  747:         if (($is_balancer) && ($hosthere)) {
  748:             $form{'noloadbalance'} = $hosthere;
  749:         }
  750:         my $extra_env;
  751:         if ($form{'linkprot'}) {
  752:             my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
  753:             if ($linkprotector) {
  754:                 $extra_env = {'user.linkprotector' => $linkprotector,
  755:                               'user.linkproturi'   => $uri,};
  756:             }
  757:         } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  758:             if ($form{'linkkey'}) {
  759:                 $extra_env = {'user.deeplinkkey' => $form{'linkkey'},
  760:                               'user.keyedlinkuri' => $form{'firsturl'},
  761:                               'request.deeplink.login' => $form{'firsturl'}};
  762:             } else {
  763:                 $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
  764:             }
  765:         }
  766:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
  767:                  \%form);
  768:         return OK;
  769:     }
  770: }
  771: 
  772: sub check_can_host {
  773:     my ($r,$form,$authhost,$domdesc) = @_;
  774:     return unless (ref($form) eq 'HASH');
  775:     my $canhost = 1;
  776:     my $lonhost = $r->dir_config('lonHostID');
  777:     my $udom = $form->{'udom'};
  778:     my @intdoms;
  779:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
  780:     if (ref($internet_names) eq 'ARRAY') {
  781:         @intdoms = @{$internet_names};
  782:     }
  783:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  784:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  785:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
  786:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
  787:         my $hostname = &Apache::lonnet::hostname($lonhost);
  788:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
  789:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
  790:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
  791:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  792:         my $loncaparev;
  793:         if ($authhost eq 'no_account_on_host') {
  794:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
  795:         } else {
  796:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
  797:         }
  798:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
  799:                                                      $udomdefaults{'remotesessions'},
  800:                                                      $defdomdefaults{'hostedsessions'});
  801:     }
  802:     unless ($canhost) {
  803:         if ($authhost eq 'no_account_on_host') {
  804:             my $checkloginvia = 1;
  805:             my ($login_host,$hostname) = 
  806:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
  807:             &Apache::loncommon::content_type($r,'text/html');
  808:             $r->send_http_header;
  809:             if ($login_host ne '') {
  810:                 my $protocol = $Apache::lonnet::protocol{$login_host};
  811:                 $protocol = 'http' if ($protocol ne 'https');
  812:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
  813: #FIXME Should preserve where user was going and linkprot by setting ltoken at $login_host
  814:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
  815:                           '<h3>'.&mt('Account creation').'</h3>'.
  816:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  817:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
  818:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
  819:                           &Apache::loncommon::end_page());
  820:             } else {
  821:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  822:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
  823:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
  824:                           '<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>'.
  825:                           &Apache::loncommon::end_page());
  826:             }
  827:         } else {
  828:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
  829:                      $form);
  830:             if ($form->{'linkprot'}) {
  831:                 $env{'request.linkprot'} = $form->{'linkprot'};
  832:             } elsif ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  833:                 if ($form->{'linkkey'}) {
  834:                     $env{'request.linkkey'} = $form->{'linkkey'};
  835:                 }
  836:                 $env{'request.deeplink.login'} = $form->{'firsturl'};
  837:             }
  838:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
  839:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
  840:         }
  841:     }
  842:     return $canhost;
  843: }
  844: 
  845: sub noswitch {
  846:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
  847:                  '<h3>'.&mt('Session unavailable').'</h3>'.
  848:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
  849:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
  850:                  &Apache::loncommon::end_page();
  851:     return $result;
  852: }
  853: 
  854: sub loginhelpdisplay {
  855:     my ($authdomain) = @_;
  856:     my $login_help = 1;
  857:     my $lang = &Apache::lonlocal::current_language();
  858:     if ($login_help) {
  859:         my $dom = $authdomain;
  860:         if ($dom eq '') {
  861:             $dom = &Apache::lonnet::default_login_domain();
  862:         }
  863:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
  864:         my $loginhelp_url;
  865:         if ($lang) {
  866:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
  867:             if ($loginhelp_url ne '') {
  868:                 return $loginhelp_url;
  869:             }
  870:         }
  871:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
  872:         if ($loginhelp_url ne '') {
  873:             return $loginhelp_url;
  874:         } else {
  875:             return '/adm/loginproblems.html';
  876:         }
  877:     }
  878:     return;
  879: }
  880: 
  881: 1;
  882: __END__
  883: 
  884: 

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