Diff for /loncom/auth/lonauth.pm between versions 1.71 and 1.138

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


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