File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.98: download - view: text, annotated - select for diffs
Wed May 27 16:54:52 2009 UTC (15 years ago) by www
Branches: MAIN
CVS tags: bz5969, HEAD, BZ5971-printing-apage
Redesign: no separate accessibility interface, cleaning up a bit

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.98 2009/05/27 16:54:52 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonauth;
   30: 
   31: use strict;
   32: use LONCAPA;
   33: use Apache::Constants qw(:common);
   34: use CGI qw(:standard);
   35: use DynaLoader; # for Crypt::DES version
   36: use Crypt::DES;
   37: use Apache::loncommon();
   38: use Apache::lonnet;
   39: use Apache::lonmenu();
   40: use Apache::createaccount;
   41: use Fcntl qw(:flock);
   42: use Apache::lonlocal;
   43:  
   44: # ------------------------------------------------------------ Successful login
   45: sub success {
   46:     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
   47: 	$form) = @_;
   48: 
   49: # ------------------------------------------------------------ Get cookie ready
   50:     my $cookie =
   51: 	&Apache::loncommon::init_user_environment($r, $username, $domain,
   52: 						  $authhost, $form,
   53: 						  {'extra_env' => $extra_env,});
   54: 
   55:     my $public=($username eq 'public' && $domain eq 'public');
   56: 
   57:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   58: 
   59: # -------------------------------------------------------------------- Log this
   60: 
   61:     &Apache::lonnet::log($domain,$username,$authhost,
   62:                          "Login $ENV{'REMOTE_ADDR'}");
   63: 
   64: # ------------------------------------------------- Check for critical messages
   65: 
   66:     my @what=&Apache::lonnet::dump('critical',$domain,$username);
   67:     if ($what[0]) {
   68: 	if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
   69: 	    $lowerurl='/adm/email?critical=display';
   70:         }
   71:     }
   72: 
   73: # ------------------------------------------------------------ Get cookie ready
   74:     $cookie="lonID=$cookie; path=/";
   75: # -------------------------------------------------------- Menu script and info
   76:     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});
   77:     my $startupremote=&Apache::lonmenu::startupremote($lowerurl);
   78:     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
   79:     my $setflags=&Apache::lonmenu::setflags();
   80:     my $maincall=&Apache::lonmenu::maincall();
   81:     my $start_page=&Apache::loncommon::start_page('Successful Login',
   82: 						  $startupremote,
   83: 						  {'no_inline_link' => 1,});
   84:     my $end_page  =&Apache::loncommon::end_page();
   85: 
   86:     my $continuelink;
   87:     if ($env{'environment.remote'} eq 'off') {
   88: 	$continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";
   89:     }
   90: # ------------------------------------------------- Output for successful login
   91: 
   92:     &Apache::loncommon::content_type($r,'text/html');
   93:     $r->header_out('Set-cookie' => $cookie);
   94:     $r->send_http_header;
   95: 
   96:     my %lt=&Apache::lonlocal::texthash(
   97: 				       'wel' => 'Welcome',
   98: 				       'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up.',
   99: 				       'pro' => 'Login problems?',
  100: 				       'log' => 'loginproblems.html',
  101: 				       );
  102:     $r->print(<<ENDSUCCESS);
  103: $start_page
  104: $setflags
  105: $windowinfo
  106: <h1>$lt{'wel'}</h1>
  107: $lt{'mes'}<p>
  108: <a href="/adm/$lt{'log'}">$lt{'pro'}</a></p>
  109: $remoteinfo
  110: $maincall
  111: $continuelink
  112: $end_page
  113: ENDSUCCESS
  114: }
  115: 
  116: # --------------------------------------------------------------- Failed login!
  117: 
  118: sub failed {
  119:     my ($r,$message,$form) = @_;
  120:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,
  121: 						    {'no_inline_link' => 1,});
  122:     my $end_page   = &Apache::loncommon::end_page();
  123:     &Apache::loncommon::content_type($r,'text/html');
  124:     $r->send_http_header;
  125:     $r->print(
  126:        $start_page
  127:       .'<h1>'.&mt('Sorry ...').'</h1>'
  128:       .'<p class="LC_warning">'.&mt($message).'</p>'
  129:       .'<p>'.&mt('Please [_1]log in again[_2].'
  130:                 ,"<a href=\"/adm/login?username=$form->{'uname'}&domain=$form->{'udom'}\">",'</a>')
  131:       .'</p>'
  132:       .'<p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'
  133:       .$end_page
  134:     );
  135:  }
  136: 
  137: # ------------------------------------------------------------------ Rerouting!
  138: 
  139: sub reroute {
  140:     my ($r) = @_;
  141:     &Apache::loncommon::content_type($r,'text/html');
  142:     $r->send_http_header;
  143:     my $msg='<h1>'.&mt('Sorry ...').'</h1>'
  144:            .&mt('Please [_1]log in again[_2].');
  145:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg);
  146: }
  147: 
  148: # ---------------------------------------------------------------- Main handler
  149: 
  150: sub handler {
  151:     my $r = shift;
  152:     my $form;
  153: # Are we re-routing?
  154:     if (-e '/home/httpd/html/lon-status/reroute.txt') {
  155: 	&reroute($r);
  156: 	return OK;
  157:     }
  158: 
  159:     &Apache::lonlocal::get_language_handle($r);
  160: 
  161: # -------------------------------- Prevent users from attempting to login twice
  162:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  163:     if ($handle ne '') {
  164: # Indeed, a valid token is found
  165: 	&Apache::loncommon::content_type($r,'text/html');
  166: 	$r->send_http_header;
  167: 	my $start_page = 
  168: 	    &Apache::loncommon::start_page('Already logged in');
  169: 	my $end_page = 
  170: 	    &Apache::loncommon::end_page();
  171:         $r->print(
  172:            $start_page
  173:           .'<h1>'.&mt('You are already logged in!').'</h1>'
  174:           .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
  175:                     ,'<a href="/adm/roles">','</a>','<a href="/adm/logout">','</a>')
  176:           .'</p>'
  177:           .'<p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'
  178:           .$end_page
  179:         );
  180:         return OK;
  181:     }
  182: 
  183: # ---------------------------------------------------- No valid token, continue
  184: 
  185: 
  186:     my $buffer;
  187:     if ($r->header_in('Content-length') > 0) {
  188: 	$r->read($buffer,$r->header_in('Content-length'),0);
  189:     }
  190:     my %form;
  191:     foreach my $pair (split(/&/,$buffer)) {
  192:        my ($name,$value) = split(/=/,$pair);
  193:        $value =~ tr/+/ /;
  194:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  195:        $form{$name}=$value;
  196:     } 
  197: 
  198:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  199: 	&failed($r,'Username, password and domain need to be specified.',
  200: 		\%form);
  201:         return OK;
  202:     }
  203: 
  204: # split user logging in and "su"-user
  205: 
  206:     ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});
  207:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  208:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  209:     $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});
  210: 
  211:     my $role   = $r->dir_config('lonRole');
  212:     my $domain = $r->dir_config('lonDefDomain');
  213:     my $prodir = $r->dir_config('lonUsersDir');
  214:     my $contact_name = &mt('LON-CAPA helpdesk');
  215: 
  216: # ---------------------------------------- Get the information from login token
  217: 
  218:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  219:                                       $form{'serverid'});
  220: 
  221:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
  222: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  223:         return OK;
  224:     } else {
  225: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  226: 					   $form{'serverid'});
  227:         if ( $reply ne 'ok' ) {
  228:             &failed($r,'Session could not be opened.',\%form);
  229: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  230: 	    return OK;
  231: 	}
  232:     }
  233:     if (!&Apache::lonnet::domain($form{'udom'})) {
  234:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  235:         return OK;
  236:     }
  237:     my ($key,$firsturl)=split(/&/,$tmpinfo);
  238: 
  239:     my $keybin=pack("H16",$key);
  240: 
  241:     my $cipher;
  242:     if ($Crypt::DES::VERSION>=2.03) {
  243: 	$cipher=new Crypt::DES $keybin;
  244:     }
  245:     else {
  246: 	$cipher=new DES $keybin;
  247:     }
  248:     my $upass='';
  249:     for (my $i=0;$i<=2;$i++) {
  250: 	my $chunk=
  251: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},0,16))));
  252: 
  253: 	$chunk.=
  254: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},16,16))));
  255: 
  256: 	$chunk=substr($chunk,1,ord(substr($chunk,0,1)));
  257: 	$upass.=$chunk;
  258:     }
  259: 
  260: # ---------------------------------------------------------------- Authenticate
  261:     my @cancreate;
  262:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  263:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
  264:         if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
  265:             if (ref($domconfig{'usercreation'}{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  266:                 @cancreate = @{$domconfig{'usercreation'}{'cancreate'}{'selfcreate'}};
  267:             } elsif (($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') && 
  268:                      ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne '')) {
  269:                 @cancreate = ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'});
  270:             }
  271:         }
  272:     }
  273:     my $defaultauth;
  274:     if (grep(/^login$/,@cancreate)) {
  275:         $defaultauth = 1;
  276:     }
  277:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  278:                                               $form{'udom'},$defaultauth);
  279:     
  280: # --------------------------------------------------------------------- Failed?
  281: 
  282:     if ($authhost eq 'no_host') {
  283: 	&failed($r,'Username and/or password could not be authenticated.',
  284: 		\%form);
  285:         return OK;
  286:     } elsif ($authhost eq 'no_account_on_host') {
  287:         my %domconfig = 
  288:             &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  289:         if (grep(/^login$/,@cancreate)) {
  290:             my $start_page = 
  291:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',
  292:                                                '',{'no_inline_link'   => 1,});
  293:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  294:             my $lonhost = $r->dir_config('lonHostID');
  295:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  296:             my $contacts = 
  297:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  298:                                                         $form{'udom'},$origmail);
  299:             my ($contact_email) = split(',',$contacts); 
  300:             my $output = &Apache::createaccount::username_check($form{'uname'}, 
  301:                                                                 $form{'udom'},$domdesc,'',
  302:                                                                 $lonhost,$contact_email,$contact_name);
  303:             &Apache::loncommon::content_type($r,'text/html');
  304:             $r->send_http_header;
  305:             &Apache::createaccount::print_header($r,$start_page);
  306:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
  307:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  308:                       $output.&Apache::loncommon::end_page());
  309:             return OK;
  310:         } else {
  311:             &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);
  312:             return OK;
  313:         }
  314:     }
  315: 
  316:     if (($firsturl eq '') || 
  317: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  318: 	$firsturl='/adm/roles';
  319:     }
  320: # --------------------------------- Are we attempting to login as somebody else?
  321:     if ($form{'suname'}) {
  322: # ------------ see if the original user has enough privileges to pull this stunt
  323: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {
  324: # ---------------------------------------------------- see if the su-user exists
  325: 	    unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})
  326: 		eq 'no_host') {
  327: 		&Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));
  328: # ------------------------------ see if the su-user is not too highly privileged
  329: 		unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {
  330: # -------------------------------------------------------- actually switch users
  331: 		    &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.
  332: 			' logging in as '.$form{'suname'});
  333: 		    $form{'uname'}=$form{'suname'};
  334: 		} else {
  335: 		    &Apache::lonnet::logthis('Attempted switch user to privileged user');
  336: 		}
  337: 	    }
  338: 	} else {
  339: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  340: 	}
  341:     }
  342: 
  343:     if ($r->dir_config("lonBalancer") eq 'yes') {
  344: 	&success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  345: 		 \%form);
  346: 	$r->internal_redirect('/adm/switchserver');
  347:     } else {
  348: 	&success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
  349: 		 \%form);
  350:     }
  351:     return OK;
  352: }
  353: 
  354: 1;
  355: __END__
  356: 
  357: 

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