Diff for /loncom/auth/lonauth.pm between versions 1.67 and 1.143

version 1.67, 2005/06/07 02:14:28 version 1.143, 2017/02/25 20:00:36
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 Apache::Constants qw(:common);  use LONCAPA qw(:DEFAULT :match);
 use Apache::File;  use Apache::Constants qw(:common);
 use CGI qw(:standard);  use CGI qw(:standard);
 use CGI::Cookie();  use DynaLoader; # for Crypt::DES version
 use DynaLoader; # for Crypt::DES version  use Crypt::DES;
 use Crypt::DES;  use Apache::loncommon();
 use Apache::loncommon();  use Apache::lonnet;
 use Apache::lonnet;  use Apache::lonmenu();
 use Apache::lonmenu();  use Apache::createaccount;
 use Fcntl qw(:flock);  use Fcntl qw(:flock);
 use Apache::lonlocal;  use Apache::lonlocal;
   use Apache::File();
 my %FORM;  use HTML::Entities;
   use Digest::MD5;
 # ------------------------------------------------------------ Successful login   
   # ------------------------------------------------------------ Successful login
 sub success {  sub success {
     my ($r, $username, $domain, $authhost,$lowerurl) = @_;      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
     my $lonids=$r->dir_config('lonIDsDir');   $form) = @_;
   
 # See if old ID present, if so, remove  # ------------------------------------------------------------ Get cookie ready
       my $cookie =
     my $filename;   &Apache::loncommon::init_user_environment($r, $username, $domain,
     opendir(DIR,$lonids);    $authhost, $form,
     while ($filename=readdir(DIR)) {    {'extra_env' => $extra_env,});
        if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {  
   unlink($lonids.'/'.$filename);      my $public=($username eq 'public' && $domain eq 'public');
        }  
     }      if ($public or $lowerurl eq 'noredirect') { return $cookie; }
     closedir(DIR);  
   # -------------------------------------------------------------------- Log this
 # Give them a new cookie  
       &Apache::lonnet::log($domain,$username,$authhost,
     my $cookie;                           "Login $ENV{'REMOTE_ADDR'}");
     my $now=time;  
     $cookie="$username\_$now\_$domain\_$authhost";  # ------------------------------------------------- Check for critical messages
   
 # Initialize roles      my @what=&Apache::lonnet::dump('critical',$domain,$username);
       if ($what[0]) {
     my $userroles=Apache::lonnet::rolesinit($domain,$username,$authhost);   if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
       $lowerurl='/adm/email?critical=display';
 # ------------------------------------ Check browser type and MathML capability          }
       }
     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,  
         $clientunicode,$clientos) = &Apache::loncommon::decode_user_agent($r);  # ----------------------------------------------------------- Get cookies ready
       my ($securecookie,$defaultcookie);
 # -------------------------------------- Any accessibility options to remember?      if ($ENV{'SERVER_PORT'} == 443) {
     if (($FORM{'interface'}) && ($FORM{'remember'} eq 'true')) {          $securecookie="lonID=$cookie; path=/; HttpOnly; secure";
  foreach ('imagesuppress','appletsuppress',          my $lonidsdir=$r->dir_config('lonIDsDir');
  'embedsuppress','fontenhance','blackwhite') {          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
     if ($FORM{$_} eq 'true') {              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
  &Apache::lonnet::put('environment',{$_ => 'on'},              if (-e "$lonidsdir/$linkname.id") {
      $domain,$username);                  unlink("$lonidsdir/$linkname.id");
     } else {              }
  &Apache::lonnet::del('environment',[$_],$domain,$username);              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
     }                                                "$lonidsdir/$linkname.id"); 1 };
  }              if ($made_symlink) {
     }                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
 # ------------------------------------------------------------- Get environment                  &Apache::lonnet::appenv({'user.linkedenv' => "$lonidsdir/$linkname.id"});
               }
     my $userenv;          }
     my %userenv=Apache::lonnet::dump('environment',$domain,$username);      } else {
     my ($tmp) = keys(%userenv);          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {      }
  foreach my $key (keys(%userenv)) {  # -------------------------------------------------------- Menu script and info
     $userenv.="environment.$key=$userenv{$key}\n";      my $destination = $lowerurl;
  }  
     }      if (defined($form->{role})) {
     if (($userenv{'interface'}) && (!$FORM{'interface'})) {          my $envkey = 'user.role.'.$form->{role};
  $FORM{'interface'}=$userenv{'interface'};          my $now=time;
     }          my $then=$env{'user.login.time'};
     $env{'environment.remote'}=$userenv{'remote'};          my $refresh=$env{'user.refresh.time'};
     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }          my $update=$env{'user.update.time'};
           if (!$update) {
 # --------------- Do not trust query string to be put directly into environment              $update = $then;
     foreach ('imagesuppress','appletsuppress',          }
      'embedsuppress','fontenhance','blackwhite',          if (exists($env{$envkey})) {
      'interface','localpath','localres') {              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
  $FORM{$_}=~s/[\n\r\=]//gs;              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
     }                                           \$trolecode,\$tstatus,\$tstart,\$tend);
 # --------------------------------------------------------- Write first profile              if ($tstatus eq 'is') {
                   $destination  .= ($destination =~ /\?/) ? '&' : '?';
     {                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
  my $idf=Apache::File->new(">$lonids/$cookie.id");                  $destination .= 'selectrole=1&'.$newrole.'=1';
  unless (flock($idf,LOCK_EX)) {              }
     &Apache::lonnet::logthis("<font color=blue>WARNING: ".          }
    'Could not obtain exclusive lock in lonauth: '.$!);      }
     $idf->close();      if (defined($form->{symb})) {
     return 'error: '.$!;          my $destsymb = $form->{symb};
  }          $destination  .= ($destination =~ /\?/) ? '&' : '?';
  if ($userenv ne '') { print $idf "$userenv\n"; }          if ($destsymb =~ /___/) {
  print $idf "user.name=$username\n";              # FIXME Need to deal with encrypted symbs and urls as needed.
  print $idf "user.domain=$domain\n";              my ($map,$resid,$desturl)=split(/___/,$destsymb);
  print $idf "user.home=$authhost\n";              $desturl = &Apache::lonnet::clutter($desturl);
  print $idf "browser.type=$clientbrowser\n";              $desturl = &HTML::Entities::encode($desturl,'"<>&');
  print $idf "browser.version=$clientversion\n";              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
  print $idf "browser.mathml=$clientmathml\n";              $destination .= 'destinationurl='.$desturl.
  print $idf "browser.unicode=$clientunicode\n";                              '&destsymb='.$destsymb;
  print $idf "browser.os=$clientos\n";          } else {
         if ($FORM{'localpath'}) {              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
            print $idf "browser.localpath=$FORM{'localpath'}\n";              $destination .= 'destinationurl='.$destsymb;
            print $idf "browser.localres=$FORM{'localres'}\n";          }
         }      }
  print $idf "request.course.fn=\n";      if ($destination =~ m{^/adm/roles}) {
  print $idf "request.course.uri=\n";          $destination  .= ($destination =~ /\?/) ? '&' : '?';
  print $idf "request.course.sec=\n";          $destination .= 'source=login';
  print $idf "request.role=cm\n";      }
         print $idf "request.role.adv=$env{'user.adv'}\n";  
  print $idf "request.host=$ENV{'REMOTE_ADDR'}\n";      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="loncapaclient";');
  if ($FORM{'interface'}) {      my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';
     $FORM{'interface'}=~s/\W//gs;      my $brcrum = [{'href' => '',
     print $idf "browser.interface=$FORM{'interface'}\n";                     'text' => 'Successful Login'},];
     $env{'browser.interface'}=$FORM{'interface'};      my $args = {'bread_crumbs' => $brcrum,};
     foreach ('imagesuppress','appletsuppress',      unless ((defined($form->{role})) || (defined($form->{symb}))) {
      'embedsuppress','fontenhance','blackwhite') {          my $update=$env{'user.update.time'};
  if (($FORM{$_} eq 'true') ||          if (!$update) {
     ($userenv{$_} eq 'on')) {              $update = $env{'user.login.time'};
     print $idf "browser.$_=on\n";          }
  }          my %roles_in_env;
     }          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
  }          if ($showcount == 1) {
  if ($userroles ne '') { print $idf "$userroles"; }              foreach my $rolecode (keys(%roles_in_env)) {
  $idf->close();                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
     }                  if ($cid) {
     $env{'request.role'}='cm';                      my %coursedescription =
     $env{'request.role.adv'}=$env{'user.adv'};                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
     $env{'browser.type'}=$clientbrowser;                      if ($coursedescription{'type'} eq 'Placement') {
 # -------------------------------------------------------------------- Log this                          $args->{'crstype'} = 'Placement';
                       }
     &Apache::lonnet::log($domain,$username,$authhost,                      last;
                          "Login $ENV{'REMOTE_ADDR'}");                  }
               }
 # ------------------------------------------------- Check for critical messages          }
       }
     my @what=&Apache::lonnet::dump('critical',$domain,$username);      my $start_page=&Apache::loncommon::start_page('Successful Login',
     if ($what[0]) {                                                    $header,$args);
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {      my $end_page  =&Apache::loncommon::end_page();
     $lowerurl='/adm/email?critical=display';  
         }   my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
     }  # ------------------------------------------------- Output for successful login
   
 # ------------------------------------------------------------ Get cookie ready      &Apache::loncommon::content_type($r,'text/html');
       if ($securecookie) {
     $cookie="lonID=$cookie; path=/";          $r->headers_out->add('Set-cookie' => $securecookie);
 # -------------------------------------------------------- Menu script and info      }
     my $windowinfo=&Apache::lonmenu::open($clientos);      if ($defaultcookie) {
     my $startupremote=&Apache::lonmenu::startupremote($lowerurl);          $r->headers_out->add('Set-cookie' => $defaultcookie);
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);      }
     my $setflags=&Apache::lonmenu::setflags();      $r->send_http_header;
     my $maincall=&Apache::lonmenu::maincall();  
     my $bodytag=&Apache::loncommon::bodytag('Successful Login');      my %lt=&Apache::lonlocal::texthash(
     my $add=&addcontent();         'wel' => 'Welcome',
     my $continuelink;         'pro' => 'Login problems?',
     if (($env{'browser.interface'} eq 'textual') ||         );
         ($env{'environment.remote'} eq 'off')) {      my $loginhelp = &loginhelpdisplay($domain);
  $continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";      if ($loginhelp) {
     }          $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
 # ------------------------------------------------- Output for successful login      }
   
     $r->send_cgi_header(<<ENDHEADER);      my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
 Content-type: text/html$add      $r->print(<<ENDSUCCESS);
 Set-cookie: $cookie  $start_page
   $windowinfo
 ENDHEADER  <h1>$lt{'wel'}</h1>
     my %lt=&Apache::lonlocal::texthash(  $welcome
        'wel' => 'Welcome',  $loginhelp
        'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up',  $continuelink
        'pro' => 'Problems',  $end_page
        'log' => 'loginproblems.html',  ENDSUCCESS
        );      return;
     $r->print(<<ENDSUCCESS);  }
 <html>  
 <head>  # --------------------------------------------------------------- Failed login!
 <title>Successful Login to the LearningOnline Network with CAPA</title>  
 $startupremote  sub failed {
 </head>      my ($r,$message,$form) = @_;
 $bodytag      (undef,undef,undef,my $clientmathml,my $clientunicode) =
 $setflags          &Apache::loncommon::decode_user_agent();
 $windowinfo      my $args = {};
 <h1>$lt{'wel'}</h1>      if ($clientunicode && !$clientmathml) {
 $lt{'mes'}.<p>          $args = {'browser.unicode' => 1};
 <a href="/adm/$lt{'log'}">$lt{'pro'}?</a></p>      }
 $remoteinfo  
 $maincall      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
 $continuelink      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
 </body>      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
 </html>      if (&Apache::lonnet::domain($udom,'description') eq '') {
 ENDSUCCESS          undef($udom);
 }      }
       my $retry = '/adm/login';
 # --------------------------------------------------------------- Failed login!      if ($uname eq $form->{'uname'}) {
           $retry .= '?username='.$uname;
 sub failed {      }
     my ($r,$message) = @_;      if ($udom) {
     my $bodytag=&Apache::loncommon::bodytag('Unsuccessful Login');          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
     my $add=&addcontent();      }
     $r->send_cgi_header(<<ENDFHEADER);      if (exists($form->{role})) {
 Content-type: text/html$add          my $role = &Apache::loncommon::cleanup_html($form->{role});
           if ($role ne '') {
 ENDFHEADER              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
     $r->print(<<ENDFAILED);          }
 <html>      }
 <head>      if (exists($form->{symb})) {
 <title>Unsuccessful Login to the LearningOnline Network with CAPA</title>          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
 </head>          if ($symb ne '') {
 $bodytag              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
 <h1>Sorry ...</h1>          }
 <p><b>$message</b></p>      }
 <p>Please <a href="/adm/login?username=$FORM{'uname'}&domain=$FORM{'udom'}">log in again</a>.</p>      my $end_page = &Apache::loncommon::end_page();
 <p>      &Apache::loncommon::content_type($r,'text/html');
 <a href="/adm/loginproblems.html">Problems?</a></p>      $r->send_http_header;
 </body>      my @actions =
 </html>           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
 ENDFAILED      my $loginhelp = &loginhelpdisplay($udom);
 }      if ($loginhelp) {
           push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
 # --------------------------------------------------------------------- Charset      }
       #FIXME: link to helpdesk might be added here
 sub addcontent {  
     my $encoding=&Apache::lonlocal::current_encoding;      $r->print(
     if ($encoding) {         $start_page
  return '; charset='.$encoding;        .'<h2>'.&mt('Sorry ...').'</h2>'
     } else {        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
  return '';        .&Apache::lonhtmlcommon::actionbox(\@actions)
     }        .$end_page
 }      );
    }
 # ------------------------------------------------------------------ Rerouting!  
   # ------------------------------------------------------------------ Rerouting!
 sub reroute {  
     my $r=shift;  sub reroute {
     my $bodytag=&Apache::loncommon::bodytag('Rerouting');      my ($r) = @_;
     $r->send_cgi_header(<<ENDRFHEADER);      &Apache::loncommon::content_type($r,'text/html');
 Content-type: text/html      $r->send_http_header;
       my $msg='<b>'.&mt('Sorry ...').'</b><br />'
 ENDRFHEADER             .&mt('Please [_1]log in again[_2].');
     $r->print(<<ENDRFAILED);      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
 <html>  }
 <head>  
 <title>Rerouting Login to the LearningOnline Network with CAPA</title>  # ---------------------------------------------------------------- Main handler
 </head>  
 $bodytag  sub handler {
 <h1>Sorry ...</h1>      my $r = shift;
 Please <a href="/">log in again</a>.      my $londocroot = $r->dir_config('lonDocRoot');
 </body>  # Are we re-routing?
 </html>      if (-e "$londocroot/lon-status/reroute.txt") {
 ENDRFAILED   &reroute($r);
 }   return OK;
       }
 # ---------------------------------------------------------------- Main handler  
       &Apache::lonlocal::get_language_handle($r);
 sub handler {  
     my $r = shift;  # -------------------------------- Prevent users from attempting to login twice
       my $handle = &Apache::lonnet::check_for_valid_session($r);
 # Are we re-routing?      if ($handle ne '') {
     if (-e '/home/httpd/html/lon-status/reroute.txt') {          my $lonidsdir=$r->dir_config('lonIDsDir');
  &reroute($r);          if ($handle=~/^publicuser\_/) {
  return OK;  # For "public user" - remove it, we apparently really want to login
     }              unlink($r->dir_config('lonIDsDir')."/$handle.id");
           } else {
     &Apache::lonlocal::get_language_handle($r);  # Indeed, a valid token is found
               &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
 # -------------------------------- Prevent users from attempting to login twice      &Apache::loncommon::content_type($r,'text/html');
     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));      $r->send_http_header;
     my $lonid=$cookies{'lonID'};      my $start_page =
     my $cookie;          &Apache::loncommon::start_page('Already logged in');
     if ($lonid) {      my $end_page =
  my $handle=$lonid->value;          &Apache::loncommon::end_page();
         $handle=~s/\W//g;              my $dest = '/adm/roles';
         my $lonidsdir=$r->dir_config('lonIDsDir');              if ($env{'form.firsturl'} ne '') {
         if ((-e "$lonidsdir/$handle.id") && ($handle ne '')) {                  $dest = $env{'form.firsturl'};
 # Indeed, a valid token is found              }
     $r->send_cgi_header(<<ENDFHEADER);              $r->print(
 Content-type: text/html                 $start_page
                 .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
 ENDFHEADER                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
     my $bodytag=&Apache::loncommon::bodytag('Already logged in');                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
     $r->print(<<ENDFAILED);                .'</p>'
 <html>                .$end_page
 <head>              );
 <title>Already logged in</title>              return OK;
 </head>          }
 $bodytag      }
 <h1>You are already logged in</h1>  
 <p>Please either <a href="/adm/roles">continue the current session</a> or  # ---------------------------------------------------- No valid token, continue
 <a href="/adm/logout">logout</a>.</p>  
 <p>  
 <a href="/adm/loginproblems.html">Problems?</a></p>      my $buffer;
 </body>      if ($r->header_in('Content-length') > 0) {
 </html>   $r->read($buffer,$r->header_in('Content-length'),0);
 ENDFAILED      }
            return OK;      my %form;
  }      foreach my $pair (split(/&/,$buffer)) {
     }         my ($name,$value) = split(/=/,$pair);
          $value =~ tr/+/ /;
 # ---------------------------------------------------- No valid token, continue         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
          $form{$name}=$value;
       }
     my $buffer;  
     $r->read($buffer,$r->header_in('Content-length'),0);      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
     my @pairs=split(/&/,$buffer);   &failed($r,'Username, password and domain need to be specified.',
     my $pair; my $name; my $value;   \%form);
     undef %FORM;          return OK;
     %FORM=();      }
     foreach $pair (@pairs) {  
        ($name,$value) = split(/=/,$pair);  # split user logging in and "su"-user
        $value =~ tr/+/ /;  
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;      ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});
        $FORM{$name}=$value;      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
     }       $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
       $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});
     if ((!$FORM{'uname'}) || (!$FORM{'upass0'}) || (!$FORM{'udom'})) {  
  failed($r,'Username, password and domain need to be specified.');      my $role   = $r->dir_config('lonRole');
         return OK;      my $domain = $r->dir_config('lonDefDomain');
     }      my $prodir = $r->dir_config('lonUsersDir');
       my $contact_name = &mt('LON-CAPA helpdesk');
 # split user logging in and "su"-user  
   # ---------------------------------------- Get the information from login token
     ($FORM{'uname'},$FORM{'suname'})=split(/\:/,$FORM{'uname'});  
     $FORM{'uname'} =~ s/\W//g;      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
     $FORM{'suname'} =~ s/\W//g;                                        $form{'serverid'});
     $FORM{'udom'}  =~ s/\W//g;  
       if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
     my $role   = $r->dir_config('lonRole');          ($tmpinfo eq 'no_such_host')) {
     my $domain = $r->dir_config('lonDefDomain');   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
     my $prodir = $r->dir_config('lonUsersDir');          return OK;
       } else {
 # ---------------------------------------- Get the information from login token   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
      $form{'serverid'});
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$FORM{'logtoken'},          if ( $reply ne 'ok' ) {
                                       $FORM{'serverid'});              &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");
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {      return OK;
  failed($r,'Information needed to verify your login information is missing, inaccessible or expired.');   }
         return OK;      }
     } else {  
         unless (&Apache::lonnet::reply('tmpdel:'.$FORM{'logtoken'},      if (!&Apache::lonnet::domain($form{'udom'})) {
                                          $FORM{'serverid'}) eq 'ok') {          &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
             &failed($r,'Session could not be opened.');          return OK;
  }      }
     }  
     my ($key,$firsturl)=split(/&/,$tmpinfo);      my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
       if ($rolestr) {
     my $keybin=pack("H16",$key);          $rolestr = &unescape($rolestr);
       }
     my $cipher;      if ($symbstr) {
     if ($Crypt::DES::VERSION>=2.03) {          $symbstr= &unescape($symbstr);
  $cipher=new Crypt::DES $keybin;      }
     }      if ($iptokenstr) {
     else {          $iptokenstr = &unescape($iptokenstr);
  $cipher=new DES $keybin;      }
     }      if ($rolestr =~ /^role=/) {
     my $upass='';          (undef,$form{'role'}) = split('=',$rolestr);
     for (my $i=0;$i<=2;$i++) {      }
  my $chunk=      if ($symbstr =~ /^symb=/) {
     $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},0,16))));          (undef,$form{'symb'}) = split('=',$symbstr);
       }
  $chunk.=      if ($iptokenstr =~ /^iptoken=/) {
     $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},16,16))));          (undef,$form{'iptoken'}) = split('=',$iptokenstr);
       }
  $chunk=substr($chunk,1,ord(substr($chunk,0,1)));  
  $upass.=$chunk;      my $upass = $ENV{HTTPS} ? $form{'upass0'}
     }          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
   
 # ---------------------------------------------------------------- Authenticate  # ---------------------------------------------------------------- Authenticate
     my $authhost=Apache::lonnet::authenticate($FORM{'uname'},  
                                               $upass,      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
                                               $FORM{'udom'});      my ($cancreate,$statustocreate) =
               &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
 # --------------------------------------------------------------------- Failed?      my $defaultauth;
       if (ref($cancreate) eq 'ARRAY') {
     if ($authhost eq 'no_host') {          if (grep(/^login$/,@{$cancreate})) {
  failed($r,'Username and/or password could not be authenticated.');              $defaultauth = 1;
         return OK;          }
     }      }
       my $clientcancheckhost = 1;
     if (($firsturl eq '') ||       my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  ($firsturl=~/^\/adm\/(logout|remote)/)) {                                                $form{'udom'},$defaultauth,
  $firsturl='/adm/roles';                                                $clientcancheckhost);
     }     
 # --------------------------------- Are we attempting to login as somebody else?  # --------------------------------------------------------------------- Failed?
     if ($FORM{'suname'}) {  
 # ------------ see if the original user has enough privileges to pull this stunt      if ($authhost eq 'no_host') {
  if (&Apache::lonnet::privileged($FORM{'uname'},$FORM{'udom'})) {   &failed($r,'Username and/or password could not be authenticated.',
 # ---------------------------------------------------- see if the su-user exists   \%form);
     unless (&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'})          return OK;
  eq 'no_host') {      } elsif ($authhost eq 'no_account_on_host') {
  &Apache::lonnet::logthis(&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'}));          if ($defaultauth) {
 # ------------------------------ see if the su-user is not too highly privileged              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  unless (&Apache::lonnet::privileged($FORM{'suname'},$FORM{'udom'})) {              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
 # -------------------------------------------------------- actually switch users                  return OK;
     &Apache::lonnet::logperm('User '.$FORM{'uname'}.' at '.$FORM{'udom'}.              }
  ' logging in as '.$FORM{'suname'});              my $start_page =
     $FORM{'uname'}=$FORM{'suname'};                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
  } else {              my $lonhost = $r->dir_config('lonHostID');
     &Apache::lonnet::logthis('Attempted switch user to privileged user');              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  }              my $contacts =
     }                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  } else {                                                          $form{'udom'},$origmail);
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');              my ($contact_email) = split(',',$contacts);
  }              my $output =
     }                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
     &success($r,$FORM{'uname'},$FORM{'udom'},$authhost,$firsturl);                                                         $domdesc,'',$lonhost,
     return OK;                                                         $contact_email,$contact_name,
 }                                                         undef,$statustocreate);
               &Apache::loncommon::content_type($r,'text/html');
 1;              $r->send_http_header;
 __END__              &Apache::createaccount::print_header($r,$start_page);
               $r->print('<h3>'.&mt('Account creation').'</h3>'.
                         &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());
               return OK;
           } 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);
               return OK;
           }
       }
   
       if (($firsturl eq '') ||
    ($firsturl=~/^\/adm\/(logout|remote)/)) {
    $firsturl='/adm/roles';
       }
   
       my $hosthere;
       if ($form{'iptoken'}) {
           my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
           my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
           if (($sessiondata{'domain'} eq $form{'udom'}) &&
               ($sessiondata{'username'} eq $form{'uname'})) {
               $hosthere = 1;
           }
       }
   
   # --------------------------------- Are we attempting to login as somebody else?
       if ($form{'suname'}) {
   # ------------ see if the original user has enough privileges to pull this stunt
    if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {
   # ---------------------------------------------------- see if the su-user exists
       unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})
    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'})) {
   # -------------------------------------------------------- actually switch users
       &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.
    ' logging in as '.$form{'suname'});
       $form{'uname'}=$form{'suname'};
    } else {
       &Apache::lonnet::logthis('Attempted switch user to privileged user');
    }
       }
    } else {
       &Apache::lonnet::logthis('Non-privileged user attempting switch user');
    }
       }
   
       my ($is_balancer,$otherserver);
   
       unless ($hosthere) {
           ($is_balancer,$otherserver) =
               &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
           if ($is_balancer) {
               if ($otherserver eq '') {
                   my $lowest_load;
                   ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
                   if ($lowest_load > 100) {
                       $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
                   }
               }
               if ($otherserver ne '') {
                   my @hosts = &Apache::lonnet::current_machine_ids();
                   if (grep(/^\Q$otherserver\E$/,@hosts)) {
                       $hosthere = $otherserver;
                   }
               }
           }
       }
   
       if (($is_balancer) && (!$hosthere)) {
           if ($otherserver) {
               &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                        \%form);
               my $switchto = '/adm/switchserver?otherserver='.$otherserver;
               if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                   $switchto .= '&origurl='.$firsturl;
               }
               if ($form{'role'}) {
                   $switchto .= '&role='.$form{'role'};
               }
               if ($form{'symb'}) {
                   $switchto .= '&symb='.$form{'symb'};
               }
               $r->internal_redirect($switchto);
           } else {
               $r->print(&noswitch());
           }
           return OK;
       } else {
           if (!&check_can_host($r,\%form,$authhost)) {
               my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
               if ($otherserver) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                            \%form);
                   my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                   if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                       $switchto .= '&origurl='.$firsturl;
                   }
                   if ($form{'role'}) {
                       $switchto .= '&role='.$form{'role'};
                   }
                   if ($form{'symb'}) {
                       $switchto .= '&symb='.$form{'symb'};
                   }
                   $r->internal_redirect($switchto);
               } else {
                   $r->print(&noswitch());
               }
               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.67  
changed lines
  Added in v.1.143


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