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

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


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