Diff for /loncom/auth/lonauth.pm between versions 1.101.8.8 and 1.144

version 1.101.8.8, 2011/09/29 14:05:41 version 1.144, 2017/08/08 16:43:54
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # User Authentication Module  # User Authentication Module
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonauth;  package Apache::lonauth;
   
 use strict;  use strict;
 use LONCAPA;  use LONCAPA qw(:DEFAULT :match);
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use CGI qw(:standard);  use CGI qw(:standard);
 use DynaLoader; # for Crypt::DES version  use Apache::loncommon();
 use Crypt::DES;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::lonmenu();
 use Apache::lonnet;  use Apache::createaccount;
 use Apache::lonmenu();  use Fcntl qw(:flock);
 use Apache::createaccount;  use Apache::lonlocal;
 use Fcntl qw(:flock);  use Apache::File();
 use Apache::lonlocal;  use HTML::Entities;
 use Apache::File();  use Digest::MD5;
 use HTML::Entities;   
    # ------------------------------------------------------------ Successful login
 # ------------------------------------------------------------ Successful login  sub success {
 sub success {      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,   $form) = @_;
  $form) = @_;  
   # ------------------------------------------------------------ Get cookie ready
 # ------------------------------------------------------------ Get cookie ready      my $cookie =
     my $cookie =   &Apache::loncommon::init_user_environment($r, $username, $domain,
  &Apache::loncommon::init_user_environment($r, $username, $domain,    $authhost, $form,
   $authhost, $form,    {'extra_env' => $extra_env,});
   {'extra_env' => $extra_env,});  
       my $public=($username eq 'public' && $domain eq 'public');
     my $public=($username eq 'public' && $domain eq 'public');  
       if ($public or $lowerurl eq 'noredirect') { return $cookie; }
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }  
   # -------------------------------------------------------------------- Log this
 # -------------------------------------------------------------------- Log this  
       &Apache::lonnet::log($domain,$username,$authhost,
     &Apache::lonnet::log($domain,$username,$authhost,                           "Login $ENV{'REMOTE_ADDR'}");
                          "Login $ENV{'REMOTE_ADDR'}");  
   # ------------------------------------------------- Check for critical messages
 # ------------------------------------------------- Check for critical messages  
       my @what=&Apache::lonnet::dump('critical',$domain,$username);
     my @what=&Apache::lonnet::dump('critical',$domain,$username);      if ($what[0]) {
     if ($what[0]) {   if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {      $lowerurl='/adm/email?critical=display';
     $lowerurl='/adm/email?critical=display';          }
         }      }
     }  
   # ----------------------------------------------------------- Get cookies ready
 # ------------------------------------------------------------ Get cookie ready      my ($securecookie,$defaultcookie);
     $cookie="lonID=$cookie; path=/";      if ($ENV{'SERVER_PORT'} == 443) {
 # -------------------------------------------------------- Menu script and info          $securecookie="lonID=$cookie; path=/; HttpOnly; secure";
     my $destination = $lowerurl;          my $lonidsdir=$r->dir_config('lonIDsDir');
           if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
     if (defined($form->{role})) {              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
         my $envkey = 'user.role.'.$form->{role};              if (-e "$lonidsdir/$linkname.id") {
         my $now=time;                  unlink("$lonidsdir/$linkname.id");
         my $then=$env{'user.login.time'};              }
         my $refresh=$env{'user.refresh.time'};              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
         if (exists($env{$envkey})) {                                                "$lonidsdir/$linkname.id"); 1 };
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);              if ($made_symlink) {
             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
                                          \$trolecode,\$tstatus,\$tstart,\$tend);                  &Apache::lonnet::appenv({'user.linkedenv' => "$lonidsdir/$linkname.id"});
             if ($tstatus eq 'is') {              }
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';          }
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');      } else {
                 $destination .= 'selectrole=1&'.$newrole.'=1';          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
             }      }
         }  # -------------------------------------------------------- Menu script and info
     }      my $destination = $lowerurl;
     if (defined($form->{symb})) {  
         my $destsymb = $form->{symb};      if (defined($form->{role})) {
         $destination  .= ($destination =~ /\?/) ? '&' : '?';          my $envkey = 'user.role.'.$form->{role};
         if ($destsymb =~ /___/) {          my $now=time;
             # FIXME Need to deal with encrypted symbs and urls as needed.          my $then=$env{'user.login.time'};
             my ($map,$resid,$desturl)=split(/___/,$destsymb);          my $refresh=$env{'user.refresh.time'};
             unless ($desturl=~/^(adm|uploaded|editupload|public)/) {          my $update=$env{'user.update.time'};
                 $desturl = &Apache::lonnet::clutter($desturl);          if (!$update) {
             }              $update = $then;
             $desturl = &HTML::Entities::encode($desturl,'"<>&');          }
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');          if (exists($env{$envkey})) {
             $destination .= '&destinationurl='.$desturl.              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
                             '&destsymb='.$destsymb;              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
         } else {                                           \$trolecode,\$tstatus,\$tstart,\$tend);
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              if ($tstatus eq 'is') {
             $destination .= '&destinationurl='.$destsymb;                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
         }                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
     }                  $destination .= 'selectrole=1&'.$newrole.'=1';
               }
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});          }
     my $startupremote=&Apache::lonmenu::startupremote($destination);      }
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);      if (defined($form->{symb})) {
     my $setflags=&Apache::lonmenu::setflags();          my $destsymb = $form->{symb};
     my $maincall=&Apache::lonmenu::maincall();          $destination  .= ($destination =~ /\?/) ? '&' : '?';
     my $brcrum = [{'href' => '',          if ($destsymb =~ /___/) {
                    'text' => 'Successful Login'},];              # FIXME Need to deal with encrypted symbs and urls as needed.
     my $start_page=&Apache::loncommon::start_page('Successful Login',              my ($map,$resid,$desturl)=split(/___/,$destsymb);
                                                   $startupremote,              $desturl = &Apache::lonnet::clutter($desturl);
                                                   {'no_inline_link' => 1,              $desturl = &HTML::Entities::encode($desturl,'"<>&');
                                                    'bread_crumbs' => $brcrum,});              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     my $end_page  =&Apache::loncommon::end_page();              $destination .= 'destinationurl='.$desturl.
                               '&destsymb='.$destsymb;
     my $continuelink;          } else {
     if ($env{'environment.remote'} eq 'off') {              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';              $destination .= 'destinationurl='.$destsymb;
     }          }
 # ------------------------------------------------- Output for successful login      }
       if ($destination =~ m{^/adm/roles}) {
     &Apache::loncommon::content_type($r,'text/html');          $destination  .= ($destination =~ /\?/) ? '&' : '?';
     $r->header_out('Set-cookie' => $cookie);          $destination .= 'source=login';
     $r->send_http_header;      }
   
     my %lt=&Apache::lonlocal::texthash(      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="loncapaclient";');
        'wel' => 'Welcome',      my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';
        'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up.',      my $brcrum = [{'href' => '',
        'pro' => 'Login problems?',                     'text' => 'Successful Login'},];
        'log' => 'loginproblems.html',      my $args = {'bread_crumbs' => $brcrum,};
        );      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     $r->print(<<ENDSUCCESS);          my $update=$env{'user.update.time'};
 $start_page          if (!$update) {
 $setflags              $update = $env{'user.login.time'};
 $windowinfo          }
 <h1>$lt{'wel'}</h1>          my %roles_in_env;
 $lt{'mes'}<p>          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
 <a href="/adm/$lt{'log'}">$lt{'pro'}</a></p>          if ($showcount == 1) {
 $remoteinfo              foreach my $rolecode (keys(%roles_in_env)) {
 $maincall                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
 $continuelink                  if ($cid) {
 $end_page                      my %coursedescription =
 ENDSUCCESS                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
 }                      if ($coursedescription{'type'} eq 'Placement') {
                           $args->{'crstype'} = 'Placement';
 # --------------------------------------------------------------- Failed login!                      }
                       last;
 sub failed {                  }
     my ($r,$message,$form) = @_;              }
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,          }
     {'no_inline_link' => 1,});      }
     my $retry = '/adm/login?username='.$form->{'uname'}.      my $start_page=&Apache::loncommon::start_page('Successful Login',
                 '&domain='.$form->{'udom'};                                                    $header,$args);
     if (exists($form->{role})) {      my $end_page  =&Apache::loncommon::end_page();
         $retry .= '&role='.$form->{role};  
     }   my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
     if (exists($form->{symb})) {  # ------------------------------------------------- Output for successful login
         $retry .= '&symb='.$form->{symb};  
     }      &Apache::loncommon::content_type($r,'text/html');
     my $end_page   = &Apache::loncommon::end_page();      if ($securecookie) {
     &Apache::loncommon::content_type($r,'text/html');          $r->headers_out->add('Set-cookie' => $securecookie);
     $r->send_http_header;      }
     $r->print(      if ($defaultcookie) {
        $start_page          $r->headers_out->add('Set-cookie' => $defaultcookie);
       .'<h1>'.&mt('Sorry ...').'</h1>'      }
       .'<p class="LC_warning">'.&mt($message).'</p>'      $r->send_http_header;
       .'<p>'.&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>')  
       .'</p>'      my %lt=&Apache::lonlocal::texthash(
       .'<p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'         'wel' => 'Welcome',
       .$end_page         'pro' => 'Login problems?',
     );         );
  }      my $loginhelp = &loginhelpdisplay($domain);
       if ($loginhelp) {
 # ------------------------------------------------------------------ Rerouting!          $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
       }
 sub reroute {  
     my ($r) = @_;      my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
     &Apache::loncommon::content_type($r,'text/html');      $r->print(<<ENDSUCCESS);
     $r->send_http_header;  $start_page
     my $msg='<h1>'.&mt('Sorry ...').'</h1>'  $windowinfo
            .&mt('Please [_1]log in again[_2].');  <h1>$lt{'wel'}</h1>
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg);  $welcome
 }  $loginhelp
   $continuelink
 # ---------------------------------------------------------------- Main handler  $end_page
   ENDSUCCESS
 sub handler {      return;
     my $r = shift;  }
     my $form;  
 # Are we re-routing?  # --------------------------------------------------------------- Failed login!
     if (-e '/home/httpd/html/lon-status/reroute.txt') {  
  &reroute($r);  sub failed {
  return OK;      my ($r,$message,$form) = @_;
     }      (undef,undef,undef,my $clientmathml,my $clientunicode) =
           &Apache::loncommon::decode_user_agent();
     &Apache::lonlocal::get_language_handle($r);      my $args = {};
       if ($clientunicode && !$clientmathml) {
 # -------------------------------- Prevent users from attempting to login twice          $args = {'browser.unicode' => 1};
     my $handle = &Apache::lonnet::check_for_valid_session($r);      }
     if ($handle ne '') {  
         my $lonidsdir=$r->dir_config('lonIDsDir');      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
         if ($handle=~/^publicuser\_/) {      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
 # For "public user" - remove it, we apparently really want to login      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
             unlink($r->dir_config('lonIDsDir')."/$handle.id");      if (&Apache::lonnet::domain($udom,'description') eq '') {
         } else {          undef($udom);
 # Indeed, a valid token is found      }
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);      my $retry = '/adm/login';
             &Apache::loncommon::content_type($r,'text/html');      if ($uname eq $form->{'uname'}) {
             $r->send_http_header;          $retry .= '?username='.$uname;
             my $start_page =      }
                 &Apache::loncommon::start_page('Already logged in');      if ($udom) {
             my $end_page =          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
                 &Apache::loncommon::end_page();      }
             my $dest = '/adm/roles';      if (exists($form->{role})) {
             if ($env{'form.firsturl'} ne '') {          my $role = &Apache::loncommon::cleanup_html($form->{role});
                 $dest = $env{'form.firsturl'};          if ($role ne '') {
             }              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
             $r->print(          }
                $start_page      }
               .'<h1>'.&mt('You are already logged in!').'</h1>'      if (exists($form->{symb})) {
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')          if ($symb ne '') {
               .'</p>'              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
               .$end_page          }
             );      }
             return OK;      my $end_page = &Apache::loncommon::end_page();
         }      &Apache::loncommon::content_type($r,'text/html');
     }      $r->send_http_header;
       my @actions =
 # ---------------------------------------------------- No valid token, continue           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
       my $loginhelp = &loginhelpdisplay($udom);
       if ($loginhelp) {
     my $buffer;          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
     if ($r->header_in('Content-length') > 0) {      }
  $r->read($buffer,$r->header_in('Content-length'),0);      #FIXME: link to helpdesk might be added here
     }  
     my %form;      $r->print(
     foreach my $pair (split(/&/,$buffer)) {         $start_page
        my ($name,$value) = split(/=/,$pair);        .'<h2>'.&mt('Sorry ...').'</h2>'
        $value =~ tr/+/ /;        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;        .&Apache::lonhtmlcommon::actionbox(\@actions)
        $form{$name}=$value;        .$end_page
     }       );
    }
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {  
  &failed($r,'Username, password and domain need to be specified.',  # ------------------------------------------------------------------ Rerouting!
  \%form);  
         return OK;  sub reroute {
     }      my ($r) = @_;
       &Apache::loncommon::content_type($r,'text/html');
 # split user logging in and "su"-user      $r->send_http_header;
       my $msg='<b>'.&mt('Sorry ...').'</b><br />'
     ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});             .&mt('Please [_1]log in again[_2].');
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});  }
     $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});  
   # ---------------------------------------------------------------- Main handler
     my $role   = $r->dir_config('lonRole');  
     my $domain = $r->dir_config('lonDefDomain');  sub handler {
     my $prodir = $r->dir_config('lonUsersDir');      my $r = shift;
     my $contact_name = &mt('LON-CAPA helpdesk');      my $londocroot = $r->dir_config('lonDocRoot');
   # Are we re-routing?
 # ---------------------------------------- Get the information from login token      if (-e "$londocroot/lon-status/reroute.txt") {
    &reroute($r);
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},   return OK;
                                       $form{'serverid'});      }
   
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||      &Apache::lonlocal::get_language_handle($r);
        ($tmpinfo eq 'no_such_host')) {  
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);  # -------------------------------- Prevent users from attempting to login twice
         return OK;      my $handle = &Apache::lonnet::check_for_valid_session($r);
     } else {      if ($handle ne '') {
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},          my $lonidsdir=$r->dir_config('lonIDsDir');
    $form{'serverid'});          if ($handle=~/^publicuser\_/) {
         if ( $reply ne 'ok' ) {  # For "public user" - remove it, we apparently really want to login
             &failed($r,'Session could not be opened.',\%form);              unlink($r->dir_config('lonIDsDir')."/$handle.id");
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");          } else {
     return OK;  # Indeed, a valid token is found
  }              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
     }      &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
     if (!&Apache::lonnet::domain($form{'udom'})) {      my $start_page =
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);          &Apache::loncommon::start_page('Already logged in');
         return OK;      my $end_page =
     }          &Apache::loncommon::end_page();
               my $dest = '/adm/roles';
     my ($key,$firsturl,$rolestr,$symbstr)=split(/&/,$tmpinfo);              if ($env{'form.firsturl'} ne '') {
     if ($rolestr) {                  $dest = $env{'form.firsturl'};
         $rolestr = &unescape($rolestr);              }
     }              $r->print(
     if ($symbstr) {                 $start_page
         $symbstr= &unescape($symbstr);                .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
     }                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
     if ($rolestr =~ /^role=/) {                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
         (undef,$form{'role'}) = split('=',$rolestr);                .'</p>'
     }                .$end_page
     if ($symbstr =~ /^symb=/) {               );
         (undef,$form{'symb'}) = split('=',$symbstr);              return OK;
     }          }
       }
     my $keybin=pack("H16",$key);  
   # ---------------------------------------------------- No valid token, continue
     my $cipher;  
     if ($Crypt::DES::VERSION>=2.03) {  
  $cipher=new Crypt::DES $keybin;      my $buffer;
     }      if ($r->header_in('Content-length') > 0) {
     else {   $r->read($buffer,$r->header_in('Content-length'),0);
  $cipher=new DES $keybin;      }
     }      my %form;
     my $upass='';      foreach my $pair (split(/&/,$buffer)) {
     for (my $i=0;$i<=2;$i++) {         my ($name,$value) = split(/=/,$pair);
  my $chunk=         $value =~ tr/+/ /;
     $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},0,16))));         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
          $form{$name}=$value;
  $chunk.=      }
     $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},16,16))));  
       if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  $chunk=substr($chunk,1,ord(substr($chunk,0,1)));   &failed($r,'Username, password and domain need to be specified.',
  $upass.=$chunk;   \%form);
     }          return OK;
       }
 # ---------------------------------------------------------------- Authenticate  
   # split user logging in and "su"-user
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});  
     my ($cancreate,$statustocreate) =      ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
     my $defaultauth;      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
     if (ref($cancreate) eq 'ARRAY') {      $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});
         if (grep(/^login$/,@{$cancreate})) {  
             $defaultauth = 1;      my $role   = $r->dir_config('lonRole');
         }      my $domain = $r->dir_config('lonDefDomain');
     }      my $prodir = $r->dir_config('lonUsersDir');
     my $clientcancheckhost = 1;      my $contact_name = &mt('LON-CAPA helpdesk');
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,  
                                               $form{'udom'},$defaultauth,  # ---------------------------------------- Get the information from login token
                                               $clientcancheckhost);  
           my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
 # --------------------------------------------------------------------- Failed?                                        $form{'serverid'});
   
     if ($authhost eq 'no_host') {      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
  &failed($r,'Username and/or password could not be authenticated.',          ($tmpinfo eq 'no_such_host')) {
  \%form);   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
         return OK;          return OK;
     } elsif ($authhost eq 'no_account_on_host') {      } else {
         if ($defaultauth) {   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');     $form{'serverid'});
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {          if ( $reply ne 'ok' ) {
                 return OK;              &failed($r,'Session could not be opened.',\%form);
             }      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
             my $start_page =       return OK;
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',   }
                                                '',{'no_inline_link'   => 1,});      }
             my $lonhost = $r->dir_config('lonHostID');  
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      if (!&Apache::lonnet::domain($form{'udom'})) {
             my $contacts =           &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',          return OK;
                                                         $form{'udom'},$origmail);      }
             my ($contact_email) = split(',',$contacts);   
             my $output =      my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},      if ($rolestr) {
                                                        $domdesc,'',$lonhost,          $rolestr = &unescape($rolestr);
                                                        $contact_email,$contact_name,      }
                                                        undef,$statustocreate);      if ($symbstr) {
             &Apache::loncommon::content_type($r,'text/html');          $symbstr= &unescape($symbstr);
             $r->send_http_header;      }
             &Apache::createaccount::print_header($r,$start_page);      if ($iptokenstr) {
             $r->print('<h3>'.&mt('Account creation').'</h3>'.          $iptokenstr = &unescape($iptokenstr);
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.      }
                       $output.&Apache::loncommon::end_page());      if ($rolestr =~ /^role=/) {
             return OK;          (undef,$form{'role'}) = split('=',$rolestr);
         } else {      }
             &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);      if ($symbstr =~ /^symb=/) {
             return OK;          (undef,$form{'symb'}) = split('=',$symbstr);
         }      }
     }      if ($iptokenstr =~ /^iptoken=/) {
           (undef,$form{'iptoken'}) = split('=',$iptokenstr);
     if (($firsturl eq '') ||       }
  ($firsturl=~/^\/adm\/(logout|remote)/)) {  
  $firsturl='/adm/roles';      my $upass = $ENV{HTTPS} ? $form{'upass0'}
     }          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
 # --------------------------------- Are we attempting to login as somebody else?  
     if ($form{'suname'}) {  # ---------------------------------------------------------------- Authenticate
 # ------------ see if the original user has enough privileges to pull this stunt  
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
 # ---------------------------------------------------- see if the su-user exists      my ($cancreate,$statustocreate) =
     unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
  eq 'no_host') {      my $defaultauth;
  &Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));      if (ref($cancreate) eq 'ARRAY') {
 # ------------------------------ see if the su-user is not too highly privileged          if (grep(/^login$/,@{$cancreate})) {
  unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {              $defaultauth = 1;
 # -------------------------------------------------------- actually switch users          }
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.      }
  ' logging in as '.$form{'suname'});      my $clientcancheckhost = 1;
     $form{'uname'}=$form{'suname'};      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  } else {                                                $form{'udom'},$defaultauth,
     &Apache::lonnet::logthis('Attempted switch user to privileged user');                                                $clientcancheckhost);
  }     
     }  # --------------------------------------------------------------------- Failed?
  } else {  
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');      if ($authhost eq 'no_host') {
  }   &failed($r,'Username and/or password could not be authenticated.',
     }   \%form);
           return OK;
     if ($r->dir_config("lonBalancer") eq 'yes') {      } elsif ($authhost eq 'no_account_on_host') {
         my $otherserver = &Apache::lonnet::spareserver(30000,undef,1,$form{'udom'});          if ($defaultauth) {
         if (!$otherserver) {              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
             ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
         }                  return OK;
         if ($otherserver) {              }
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,              my $start_page =
                      \%form);                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver.'&origurl='.$firsturl);              my $lonhost = $r->dir_config('lonHostID');
         } else {              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
             $r->print(&noswitch());              my $contacts =
         }                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
         return OK;                                                          $form{'udom'},$origmail);
     } else {              my ($contact_email) = split(',',$contacts);
         if (!&check_can_host($r,\%form,$authhost)) {              my $output =
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
             if ($otherserver) {                                                         $domdesc,'',$lonhost,
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                                                         $contact_email,$contact_name,
                          \%form);                                                         undef,$statustocreate);
                 $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver.'&origurl='.$firsturl);              &Apache::loncommon::content_type($r,'text/html');
             } else {              $r->send_http_header;
                 $r->print(&noswitch());              &Apache::createaccount::print_header($r,$start_page);
             }              $r->print('<h3>'.&mt('Account creation').'</h3>'.
             return OK;                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
         }                        $output.&Apache::loncommon::end_page());
 # ------------------------------------------------------- Do the load balancing              return OK;
           } else {
 # ---------------------------------------------------------- Determine own load              &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);
         my $loadlim = $r->dir_config('lonLoadLim');              return OK;
         my $loadavg;          }
         {      }
             my $loadfile=Apache::File->new('/proc/loadavg');  
             $loadavg=<$loadfile>;      if (($firsturl eq '') ||
         }   ($firsturl=~/^\/adm\/(logout|remote)/)) {
         $loadavg =~ s/\s.*//g;   $firsturl='/adm/roles';
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);      }
         my $userloadpercent=&Apache::lonnet::userload();  
       my $hosthere;
 # ---------------------------------------------------------- Are we overloaded?      if ($form{'iptoken'}) {
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
             if (!$unloaded) {          if (($sessiondata{'domain'} eq $form{'udom'}) &&
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});              ($sessiondata{'username'} eq $form{'uname'})) {
             }              $hosthere = 1;
             if ($unloaded) {          }
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',      }
                          undef,\%form);  
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);  # --------------------------------- Are we attempting to login as somebody else?
                 return OK;      if ($form{'suname'}) {
             }  # ------------ see if the original user has enough privileges to pull this stunt
         }   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,  # ---------------------------------------------------- see if the su-user exists
                  \%form);      unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})
         return OK;   eq 'no_host') {
     }   &Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));
 }  # ------------------------------ see if the su-user is not too highly privileged
    unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {
 sub check_can_host {  # -------------------------------------------------------- actually switch users
     my ($r,$form,$authhost,$domdesc) = @_;      &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.
     return unless (ref($form) eq 'HASH');   ' logging in as '.$form{'suname'});
     my $canhost = 1;      $form{'uname'}=$form{'suname'};
     my $lonhost = $r->dir_config('lonHostID');   } else {
     my $udom = $form->{'udom'};      &Apache::lonnet::logthis('Attempted switch user to privileged user');
     my @intdoms;   }
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);      }
     if (ref($internet_names) eq 'ARRAY') {   } else {
         @intdoms = @{$internet_names};      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
     }   }
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');      }
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);  
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {      my ($is_balancer,$otherserver);
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);  
         my $hostname = &Apache::lonnet::hostname($lonhost);      unless ($hosthere) {
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);          ($is_balancer,$otherserver) =
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);          if ($is_balancer) {
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);              if ($otherserver eq '') {
         my $loncaparev;                  my $lowest_load;
         if ($authhost eq 'no_account_on_host') {                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);                  if ($lowest_load > 100) {
         } else {                      $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);                  }
         }              }
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,              if ($otherserver ne '') {
                                                      $udomdefaults{'remotesessions'},                  my @hosts = &Apache::lonnet::current_machine_ids();
                                                      $defdomdefaults{'hostedsessions'});                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
     }                      $hosthere = $otherserver;
     unless ($canhost) {                  }
         if ($authhost eq 'no_account_on_host') {              }
             my $checkloginvia = 1;          }
             my ($login_host,$hostname) =      }
                 &Apache::lonnet::choose_server($udom,$checkloginvia);  
             &Apache::loncommon::content_type($r,'text/html');      if (($is_balancer) && (!$hosthere)) {
             $r->send_http_header;          if ($otherserver) {
             if ($login_host ne '') {              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                 my $protocol = $Apache::lonnet::protocol{$login_host};                       \%form);
                 $protocol = 'http' if ($protocol ne 'https');              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').                  $switchto .= '&origurl='.$firsturl;
                           '<h3>'.&mt('Account creation').'</h3>'.              }
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.              if ($form{'role'}) {
                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.                  $switchto .= '&role='.$form{'role'};
                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').              }
                           &Apache::loncommon::end_page());              if ($form{'symb'}) {
             } else {                  $switchto .= '&symb='.$form{'symb'};
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').              }
                           '<h3>'.&mt('Account creation unavailable').'</h3>'.              $r->internal_redirect($switchto);
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.          } else {
                           '<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>'.              $r->print(&noswitch());
                           &Apache::loncommon::end_page());          }
             }          return OK;
         } else {      } else {
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,          if (!&check_can_host($r,\%form,$authhost)) {
                      $form);              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
             my ($otherserver) = &Apache::lonnet::choose_server($udom);              if ($otherserver) {
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
         }                           \%form);
     }                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
     return $canhost;                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
 }                      $switchto .= '&origurl='.$firsturl;
                   }
 sub noswitch {                  if ($form{'role'}) {
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').                      $switchto .= '&role='.$form{'role'};
                  '<h3>'.&mt('Session unavailable').'</h3>'.                  }
                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.                  if ($form{'symb'}) {
                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.                      $switchto .= '&symb='.$form{'symb'};
                  &Apache::loncommon::end_page();                  }
     return $result;                  $r->internal_redirect($switchto);
 }              } else {
                   $r->print(&noswitch());
 1;              }
 __END__              return OK;
           }
   
   # ------------------------------------------------------- Do the load balancing
   
   # ---------------------------------------------------------- Determine own load
           my $loadlim = $r->dir_config('lonLoadLim');
           my $loadavg;
           {
               my $loadfile=Apache::File->new('/proc/loadavg');
               $loadavg=<$loadfile>;
           }
           $loadavg =~ s/\s.*//g;
           my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
           my $userloadpercent=&Apache::lonnet::userload();
   
   # ---------------------------------------------------------- Are we overloaded?
           if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
               my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
               if (!$unloaded) {
                   ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
               }
               if ($unloaded) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                            undef,\%form);
                   $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                   return OK;
               }
           }
           if (($is_balancer) && ($hosthere)) {
               $form{'noloadbalance'} = $hosthere;
           }
           &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
                    \%form);
           return OK;
       }
   }
   
   sub check_can_host {
       my ($r,$form,$authhost,$domdesc) = @_;
       return unless (ref($form) eq 'HASH');
       my $canhost = 1;
       my $lonhost = $r->dir_config('lonHostID');
       my $udom = $form->{'udom'};
       my @intdoms;
       my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
       if (ref($internet_names) eq 'ARRAY') {
           @intdoms = @{$internet_names};
       }
       my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
       my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
       unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
           my $machine_dom = &Apache::lonnet::host_domain($lonhost);
           my $hostname = &Apache::lonnet::hostname($lonhost);
           my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
           my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
           my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
           my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
           my $loncaparev;
           if ($authhost eq 'no_account_on_host') {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
           } else {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
           }
           $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
                                                        $udomdefaults{'remotesessions'},
                                                        $defdomdefaults{'hostedsessions'});
       }
       unless ($canhost) {
           if ($authhost eq 'no_account_on_host') {
               my $checkloginvia = 1;
               my ($login_host,$hostname) =
                   &Apache::lonnet::choose_server($udom,$checkloginvia);
               &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
               if ($login_host ne '') {
                   my $protocol = $Apache::lonnet::protocol{$login_host};
                   $protocol = 'http' if ($protocol ne 'https');
                   my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
                   $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                             '<h3>'.&mt('Account creation').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                             '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                             &Apache::loncommon::end_page());
               } else {
                   $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                             '<h3>'.&mt('Account creation unavailable').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<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>'.
                             &Apache::loncommon::end_page());
               }
           } else {
               &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                        $form);
               my ($otherserver) = &Apache::lonnet::choose_server($udom);
               $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
           }
       }
       return $canhost;
   }
   
   sub noswitch {
       my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                    '<h3>'.&mt('Session unavailable').'</h3>'.
                    &mt('This LON-CAPA server is unable to host your session.').'<br />'.
                    '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                    &Apache::loncommon::end_page();
       return $result;
   }
   
   sub loginhelpdisplay {
       my ($authdomain) = @_;
       my $login_help = 1;
       my $lang = &Apache::lonlocal::current_language();
       if ($login_help) {
           my $dom = $authdomain;
           if ($dom eq '') {
               $dom = &Apache::lonnet::default_login_domain();
           }
           my %domconfhash = &Apache::loncommon::get_domainconf($dom);
           my $loginhelp_url;
           if ($lang) {
               $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
               if ($loginhelp_url ne '') {
                   return $loginhelp_url;
               }
           }
           $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
           if ($loginhelp_url ne '') {
               return $loginhelp_url;
           } else {
               return '/adm/loginproblems.html';
           }
       }
       return;
   }
   
   1;
   __END__
   
   

Removed from v.1.101.8.8  
changed lines
  Added in v.1.144


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