File:  [LON-CAPA] / loncom / auth / lonauth.pm
Revision 1.91: download - view: text, annotated - select for diffs
Wed May 14 18:27:30 2008 UTC (16 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- If a user successfully authenticates via SSO, but a LON-CAPA account is lacking for the username used to authenticate, offer the possibility of creating an account, if selfcreation is allowed for the 'sso' auth type.
- selfcreation auth types are now stored as an array, instead of a single-valued scalar.

    1: # The LearningOnline Network
    2: # User Authentication Module
    3: #
    4: # $Id: lonauth.pm,v 1.91 2008/05/14 18:27:30 raeburn 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{'browser.interface'} eq 'textual') ||
   88:         ($env{'environment.remote'} eq 'off')) {
   89: 	$continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";
   90:     }
   91: # ------------------------------------------------- Output for successful login
   92: 
   93:     &Apache::loncommon::content_type($r,'text/html');
   94:     $r->header_out('Set-cookie' => $cookie);
   95:     $r->send_http_header;
   96: 
   97:     my %lt=&Apache::lonlocal::texthash(
   98: 				       'wel' => 'Welcome',
   99: 				       'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up',
  100: 				       'pro' => 'Problems',
  101: 				       'log' => 'loginproblems.html',
  102: 				       );
  103:     $r->print(<<ENDSUCCESS);
  104: $start_page
  105: $setflags
  106: $windowinfo
  107: <h1>$lt{'wel'}</h1>
  108: $lt{'mes'}.<p>
  109: <a href="/adm/$lt{'log'}">$lt{'pro'}?</a></p>
  110: $remoteinfo
  111: $maincall
  112: $continuelink
  113: $end_page
  114: ENDSUCCESS
  115: }
  116: 
  117: # --------------------------------------------------------------- Failed login!
  118: 
  119: sub failed {
  120:     my ($r,$message,$form) = @_;
  121:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,
  122: 						    {'no_inline_link' => 1,});
  123:     my $end_page   = &Apache::loncommon::end_page();
  124: 
  125:     $message = &mt($message);
  126:     my %lt=('sorry'  => &mt('Sorry ...'),
  127: 	    'please' => 
  128: 	    &mt('Please [_1]log in again[_2].',
  129: 		"<a href=\"/adm/login?username=$form->{'uname'}&domain=$form->{'udom'}\">",
  130: 		'</a>'),
  131: 	    'problemspage' => &mt('loginproblems.html'),
  132: 	    'problems'     => 'Problems',
  133: 	    );
  134:     &Apache::loncommon::content_type($r,'text/html');
  135:     $r->send_http_header;
  136: 
  137:     $r->print(<<ENDFAILED);
  138: $start_page
  139: <h1>$lt{'sorry'}</h1>
  140: <p><b>$message</b></p>
  141: <p>$lt{'please'}</p>
  142: <p>
  143: <a href="/adm/$lt{'problemspage'}">$lt{'problems'}</a></p>
  144: $end_page
  145: ENDFAILED
  146: }
  147: 
  148: # ------------------------------------------------------------------ Rerouting!
  149: 
  150: sub reroute {
  151:     my ($r) = @_;
  152:     &Apache::loncommon::content_type($r,'text/html');
  153:     $r->send_http_header;
  154:     my $msg='<h1>Sorry ...</h1>
  155:              Please <a href="/">log in again</a>.';
  156:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg);
  157: }
  158: 
  159: # ---------------------------------------------------------------- Main handler
  160: 
  161: sub handler {
  162:     my $r = shift;
  163:     my $form;
  164: # Are we re-routing?
  165:     if (-e '/home/httpd/html/lon-status/reroute.txt') {
  166: 	&reroute($r);
  167: 	return OK;
  168:     }
  169: 
  170:     &Apache::lonlocal::get_language_handle($r);
  171: 
  172: # -------------------------------- Prevent users from attempting to login twice
  173:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  174:     if ($handle ne '') {
  175: # Indeed, a valid token is found
  176: 	&Apache::loncommon::content_type($r,'text/html');
  177: 	$r->send_http_header;
  178: 	my $start_page = 
  179: 	    &Apache::loncommon::start_page('Already logged in');
  180: 	my $end_page = 
  181: 	    &Apache::loncommon::end_page();
  182: 	$r->print(<<ENDFAILED);
  183: $start_page
  184: <h1>You are already logged in</h1>
  185: <p>Please either <a href="/adm/roles">continue the current session</a> or
  186: <a href="/adm/logout">logout</a>.</p>
  187: <p>
  188: <a href="/adm/loginproblems.html">Problems?</a></p>
  189: $end_page
  190: ENDFAILED
  191:        return OK;
  192:     }
  193: 
  194: # ---------------------------------------------------- No valid token, continue
  195: 
  196: 
  197:     my $buffer;
  198:     if ($r->header_in('Content-length') > 0) {
  199: 	$r->read($buffer,$r->header_in('Content-length'),0);
  200:     }
  201:     my %form;
  202:     foreach my $pair (split(/&/,$buffer)) {
  203:        my ($name,$value) = split(/=/,$pair);
  204:        $value =~ tr/+/ /;
  205:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  206:        $form{$name}=$value;
  207:     } 
  208: 
  209:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  210: 	&failed($r,'Username, password and domain need to be specified.',
  211: 		\%form);
  212:         return OK;
  213:     }
  214: 
  215: # split user logging in and "su"-user
  216: 
  217:     ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});
  218:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
  219:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
  220:     $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});
  221: 
  222:     my $role   = $r->dir_config('lonRole');
  223:     my $domain = $r->dir_config('lonDefDomain');
  224:     my $prodir = $r->dir_config('lonUsersDir');
  225: 
  226: # ---------------------------------------- Get the information from login token
  227: 
  228:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  229:                                       $form{'serverid'});
  230: 
  231:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
  232: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
  233:         return OK;
  234:     } else {
  235: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
  236: 					   $form{'serverid'});
  237:         if ( $reply ne 'ok' ) {
  238:             &failed($r,'Session could not be opened.',\%form);
  239: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  240: 	    return OK;
  241: 	}
  242:     }
  243:     my ($key,$firsturl)=split(/&/,$tmpinfo);
  244: 
  245:     my $keybin=pack("H16",$key);
  246: 
  247:     my $cipher;
  248:     if ($Crypt::DES::VERSION>=2.03) {
  249: 	$cipher=new Crypt::DES $keybin;
  250:     }
  251:     else {
  252: 	$cipher=new DES $keybin;
  253:     }
  254:     my $upass='';
  255:     for (my $i=0;$i<=2;$i++) {
  256: 	my $chunk=
  257: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},0,16))));
  258: 
  259: 	$chunk.=
  260: 	    $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},16,16))));
  261: 
  262: 	$chunk=substr($chunk,1,ord(substr($chunk,0,1)));
  263: 	$upass.=$chunk;
  264:     }
  265: 
  266: # ---------------------------------------------------------------- Authenticate
  267:     my @cancreate;
  268:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  269:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
  270:         if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
  271:             if (ref($domconfig{'usercreation'}{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  272:                 @cancreate = @{$domconfig{'usercreation'}{'cancreate'}{'selfcreate'}};
  273:             } elsif (($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') && 
  274:                      ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne '')) {
  275:                 @cancreate = ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'});
  276:             }
  277:         }
  278:     }
  279:     my $defaultauth;
  280:     if (grep(/^login$/,@cancreate)) {
  281:         $defaultauth = 1;
  282:     }
  283:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
  284:                                               $form{'udom'},$defaultauth);
  285:     
  286: # --------------------------------------------------------------------- Failed?
  287: 
  288:     if ($authhost eq 'no_host') {
  289: 	&failed($r,'Username and/or password could not be authenticated.',
  290: 		\%form);
  291:         return OK;
  292:     } elsif ($authhost eq 'no_account_on_host') {
  293:         my %domconfig = 
  294:             &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  295:         if (grep(/^login$/,@cancreate)) {
  296:             my $start_page = 
  297:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',
  298:                                                '',{'no_inline_link'   => 1,});
  299:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  300:             my ($output,$checkfail) = &Apache::createaccount::username_check($form{'uname'},
  301:                                                                   $form{'udom'},$domdesc);
  302:             &Apache::loncommon::content_type($r,'text/html');
  303:             $r->send_http_header;
  304:             &Apache::createaccount::print_header($r,$start_page);
  305:             my $msg = '<h4>'.&mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain.').'<br />';
  306:             if ($checkfail) {
  307:                 $msg .= &mt('A LON-CAPA account may not be created with the username you used.');
  308:             } else {
  309:                 $msg .= &mt('To create one, use the table below to provide information about yourself (if appropriate), then click the "Create LON-CAPA account" button.');
  310:             }
  311:             $r->print('<h4>'.$msg.'</h4>'.$output);
  312:             $r->print(&Apache::loncommon::end_page());
  313:             return OK;
  314:         } else {
  315:             &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);
  316:             return OK;
  317:         }
  318:     }
  319: 
  320:     if (($firsturl eq '') || 
  321: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
  322: 	$firsturl='/adm/roles';
  323:     }
  324: # --------------------------------- Are we attempting to login as somebody else?
  325:     if ($form{'suname'}) {
  326: # ------------ see if the original user has enough privileges to pull this stunt
  327: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {
  328: # ---------------------------------------------------- see if the su-user exists
  329: 	    unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})
  330: 		eq 'no_host') {
  331: 		&Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));
  332: # ------------------------------ see if the su-user is not too highly privileged
  333: 		unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {
  334: # -------------------------------------------------------- actually switch users
  335: 		    &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.
  336: 			' logging in as '.$form{'suname'});
  337: 		    $form{'uname'}=$form{'suname'};
  338: 		} else {
  339: 		    &Apache::lonnet::logthis('Attempted switch user to privileged user');
  340: 		}
  341: 	    }
  342: 	} else {
  343: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
  344: 	}
  345:     }
  346: 
  347:     if ($r->dir_config("lonBalancer") eq 'yes') {
  348: 	&success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
  349: 		 \%form);
  350: 	$r->internal_redirect('/adm/switchserver');
  351:     } else {
  352: 	&success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
  353: 		 \%form);
  354:     }
  355:     return OK;
  356: }
  357: 
  358: 1;
  359: __END__
  360: 
  361: 

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