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

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


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