File:  [LON-CAPA] / loncom / auth / lonacc.pm
Revision 1.105: download - view: text, annotated - select for diffs
Fri Jan 12 15:06:18 2007 UTC (17 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
If SSO auth, need to set $env{'request.sso.login'} = 1 before internal_redirect to switchserver.

    1: # The LearningOnline Network
    2: # Cookie Based Access Handler
    3: #
    4: # $Id: lonacc.pm,v 1.105 2007/01/12 15:06:18 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: 
   30: package Apache::lonacc;
   31: 
   32: use strict;
   33: use Apache::Constants qw(:common :http :methods);
   34: use Apache::File;
   35: use Apache::lonnet;
   36: use Apache::loncommon();
   37: use Apache::lonlocal;
   38: use Apache::restrictedaccess();
   39: use Apache::blockedaccess(); 
   40: use CGI::Cookie();
   41: use Fcntl qw(:flock);
   42: use LONCAPA;
   43: 
   44: sub cleanup {
   45:     my ($r)=@_;
   46:     if (! $r->is_initial_req()) { return DECLINED; }
   47:     &Apache::lonnet::save_cache();
   48:     &Apache::lontexconvert::jsMath_reset();
   49:     return OK;
   50: }
   51: 
   52: sub goodbye {
   53:     my ($r)=@_;
   54:     &Apache::lonnet::goodbye();
   55:     return DONE;
   56: }
   57: 
   58: ###############################################
   59: 
   60: sub get_posted_cgi {
   61:     my ($r) = @_;
   62: 
   63:     my $buffer;
   64:     if ($r->header_in('Content-length')) {
   65: 	$r->read($buffer,$r->header_in('Content-length'),0);
   66:     }
   67:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
   68: 	my @pairs=split(/&/,$buffer);
   69: 	my $pair;
   70: 	foreach $pair (@pairs) {
   71: 	    my ($name,$value) = split(/=/,$pair);
   72: 	    $value =~ tr/+/ /;
   73: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
   74: 	    $name  =~ tr/+/ /;
   75: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
   76: 	    &Apache::loncommon::add_to_env("form.$name",$value);
   77: 	}
   78:     } else {
   79: 	my $contentsep=$1;
   80: 	my @lines = split (/\n/,$buffer);
   81: 	my $name='';
   82: 	my $value='';
   83: 	my $fname='';
   84: 	my $fmime='';
   85: 	my $i;
   86: 	for ($i=0;$i<=$#lines;$i++) {
   87: 	    if ($lines[$i]=~/^$contentsep/) {
   88: 		if ($name) {
   89: 		    chomp($value);
   90: 		    if ($fname) {
   91: 			$env{"form.$name.filename"}=$fname;
   92: 			$env{"form.$name.mimetype"}=$fmime;
   93: 		    } else {
   94: 			$value=~s/\s+$//s;
   95: 		    }
   96: 		    &Apache::loncommon::add_to_env("form.$name",$value);
   97: 		}
   98: 		if ($i<$#lines) {
   99: 		    $i++;
  100: 		    $lines[$i]=~
  101: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
  102: 		    $name=$1;
  103: 		    $value='';
  104: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
  105: 			$fname=$1;
  106: 			if 
  107:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
  108: 				$fmime=$1;
  109: 				$i++;
  110: 			    } else {
  111: 				$fmime='';
  112: 			    }
  113: 		    } else {
  114: 			$fname='';
  115: 			$fmime='';
  116: 		    }
  117: 		    $i++;
  118: 		}
  119: 	    } else {
  120: 		$value.=$lines[$i]."\n";
  121: 	    }
  122: 	}
  123:     }
  124: #
  125: # Digested POSTed values
  126: #
  127: # Remember the way this was originally done (GET or POST)
  128: #
  129:     $env{'request.method'}=$ENV{'REQUEST_METHOD'};
  130: #
  131: # There may also be stuff in the query string
  132: # Tell subsequent handlers that this was GET, not POST, so they can access query string.
  133: # Also, unset POSTed content length to cover all tracks.
  134: #
  135: 
  136:     $r->method_number(M_GET);
  137: 
  138:     $r->method('GET');
  139:     $r->headers_in->unset('Content-length');
  140: }
  141: 
  142: # handle the case of the single sign on user, at this point $r->user 
  143: # will be set and valid now need to find the loncapa user info and possibly
  144: # balance them
  145: # returns OK if it was a SSO and user was handled
  146: #         undef if not SSO or no means to hanle the user
  147: sub sso_login {
  148:     my ($r,$lonid,$handle) = @_;
  149: 
  150:     my $lonidsdir=$r->dir_config('lonIDsDir');
  151:     if (!($r->user 
  152: 	  && (!defined($env{'user.name'}) && !defined($env{'user.domain'}))
  153: 	  && (!$lonid || !-e "$lonidsdir/$handle.id" || $handle eq ''))) {
  154: 	# not an SSO case or already logged in
  155: 	return undef;
  156:     }
  157: 
  158:     my ($user) = ($r->user =~ m/([a-zA-Z0-9_\-@.]*)/);
  159: 
  160:     my $domain = $r->dir_config('lonDefDomain');
  161:     my $home=&Apache::lonnet::homeserver($user,$domain);
  162:     if ($home !~ /(con_lost|no_host|no_such_host)/) {
  163: 	if ($r->dir_config("lonBalancer") eq 'yes') {
  164: 	    # login but immeaditly go to switch server to find us a new 
  165: 	    # machine
  166: 	    &Apache::lonauth::success($r,$user,$domain,$home,'noredirect');
  167:             $env{'request.sso.login'} = 1;
  168: 	    $r->internal_redirect('/adm/switchserver');
  169: 	    $r->set_handlers('PerlHandler'=> undef);
  170: 	} else {
  171: 	    # need to login them in, so generate the need data that
  172: 	    # migrate expects to do login
  173: 	    my %info=('ip'        => $r->connection->remote_ip(),
  174: 		      'domain'    => $domain,
  175: 		      'username'  => $user,
  176: 		      'server'    => $r->dir_config('lonHostID'),
  177: 		      'sso.login' => 1
  178: 		      );
  179: 	    my $token = 
  180: 		&Apache::lonnet::tmpput(\%info,
  181: 					$r->dir_config('lonHostID'));
  182: 	    $env{'form.token'} = $token;
  183: 	    $r->internal_redirect('/adm/migrateuser');
  184: 	    $r->set_handlers('PerlHandler'=> undef);
  185: 	}
  186: 	return OK;
  187:     } elsif (defined($r->dir_config('lonSSOUserUnknownRedirect'))) {
  188:         $r->subprocess_env->set('SSOUserUnknown' => $user);
  189:         $r->subprocess_env->set('SSOUserDomain' => $domain);
  190: 	$r->internal_redirect($r->dir_config('lonSSOUserUnknownRedirect'));
  191: 	$r->set_handlers('PerlHandler'=> undef);
  192: 	return OK;
  193:     }
  194:     return undef;
  195: }
  196: 
  197: sub handler {
  198:     my $r = shift;
  199:     my $requrl=$r->uri;
  200:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  201:     my $lonid=$cookies{'lonID'};
  202:     my $cookie;
  203:     my $lonidsdir=$r->dir_config('lonIDsDir');
  204: 
  205:     my $handle;
  206:     if ($lonid) {
  207: 	$handle=&LONCAPA::clean_handle($lonid->value);
  208:     }
  209: 
  210:     my $result = &sso_login($r,$lonid,$handle);
  211:     if (defined($result)) {
  212: 	return $result
  213:     }
  214: 
  215: 
  216:     if ($r->dir_config("lonBalancer") eq 'yes') {
  217: 	$r->set_handlers('PerlResponseHandler'=>
  218: 			 [\&Apache::switchserver::handler]);
  219:     }
  220:     
  221:     if ($handle eq '') {
  222: 	$r->log_reason("Cookie $handle not valid", $r->filename); 
  223:     } elsif ((-e "$lonidsdir/$handle.id") && ($handle ne '')) {
  224: 
  225: # ------------------------------------------------------ Initialize Environment
  226: 
  227: 	&Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  228: 
  229: # --------------------------------------------------------- Initialize Language
  230: 
  231: 	&Apache::lonlocal::get_language_handle($r);
  232: 
  233:     }
  234: 
  235: # -------------------------------------------------- Should be a valid user now
  236:     if ($env{'user.name'} ne '' && $env{'user.domain'} ne '') {
  237: # -------------------------------------------------------------- Resource State
  238: 
  239: 	if ($requrl=~/^\/+(res|uploaded)\//) {
  240: 	    $env{'request.state'} = "published";
  241: 	} else {
  242: 	    $env{'request.state'} = 'unknown';
  243: 	}
  244: 	$env{'request.filename'} = $r->filename;
  245: 	$env{'request.noversionuri'} = &Apache::lonnet::deversion($requrl);
  246: # -------------------------------------------------------- Load POST parameters
  247: 
  248: 	&Apache::lonacc::get_posted_cgi($r);
  249: 
  250: # ---------------------------------------------------------------- Check access
  251: 	my $now = time;
  252: 	if ($requrl !~ m{^/(?:adm|public|prtspool)/}
  253: 	    || $requrl =~ /^\/adm\/.*\/(smppg|bulletinboard)(\?|$ )/x) {
  254: 	    my $access=&Apache::lonnet::allowed('bre',$requrl);
  255: 	    if ($access eq '1') {
  256: 		$env{'user.error.msg'}="$requrl:bre:0:0:Choose Course";
  257: 		return HTTP_NOT_ACCEPTABLE; 
  258: 	    }
  259: 	    if ($access eq 'A') {
  260: 		&Apache::restrictedaccess::setup_handler($r);
  261: 		return OK;
  262: 	    }
  263:             if ($access eq 'B') {
  264:                 &Apache::blockedaccess::setup_handler($r);
  265:                 return OK;
  266:             }
  267: 	    if (($access ne '2') && ($access ne 'F')) {
  268: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  269: 		return HTTP_NOT_ACCEPTABLE; 
  270: 	    }
  271: 	}
  272: 	if ($requrl =~ m|^/prtspool/|) {
  273: 	    my $start='/prtspool/'.$env{'user.name'}.'_'.
  274: 		$env{'user.domain'};
  275: 	    if ($requrl !~ /^\Q$start\E/) {
  276: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  277: 		return HTTP_NOT_ACCEPTABLE;
  278: 	    }
  279: 	}
  280: 	if ($env{'user.name'} eq 'public' && 
  281: 	    $env{'user.domain'} eq 'public' &&
  282: 	    $requrl !~ m{^/+(res|public|uploaded)/} &&
  283: 	    $requrl !~ m{^/adm/[^/]+/[^/]+/aboutme/portfolio$ }x &&
  284: 	    $requrl !~ m{^/+adm/(help|logout|restrictedaccess|randomlabel\.png)}) {
  285: 	    $env{'request.querystring'}=$r->args;
  286: 	    $env{'request.firsturl'}=$requrl;
  287: 	    return FORBIDDEN;
  288: 	}
  289: # ------------------------------------------------------------- This is allowed
  290: 	if ($env{'request.course.id'}) {
  291: 	    &Apache::lonnet::countacc($requrl);
  292: 	    $requrl=~/\.(\w+)$/;
  293: 	    if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  294: 		($requrl=~/^\/adm\/.*\/(aboutme|navmaps|smppg|bulletinboard)(\?|$ )/x) ||
  295: 		($requrl=~/^\/adm\/wrapper\//) ||
  296: 		($requrl=~m|^/adm/coursedocs/showdoc/|) ||
  297: 		($requrl=~m|\.problem/smpedit$|) ||
  298: 		($requrl=~/^\/public\/.*\/syllabus$/)) {
  299: # ------------------------------------- This is serious stuff, get symb and log
  300: 		my $query=$r->args;
  301: 		my $symb;
  302: 		if ($query) {
  303: 		    &Apache::loncommon::get_unprocessed_cgi($query,['symb']);
  304: 		}
  305: 		if ($env{'form.symb'}) {
  306: 		    $symb=&Apache::lonnet::symbclean($env{'form.symb'});
  307: 		    if ($requrl =~ m|^/adm/wrapper/|
  308: 			|| $requrl =~ m|^/adm/coursedocs/showdoc/|) {
  309: 			my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  310: 			&Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  311: 						  'last_known' =>[$murl,$mid]);
  312: 		    } elsif ((&Apache::lonnet::symbverify($symb,$requrl)) ||
  313: 			     (($requrl=~m|(.*)/smpedit$|) &&
  314: 			      &Apache::lonnet::symbverify($symb,$1))) {
  315: 			my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  316: 			&Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  317: 						  'last_known' =>[$murl,$mid]);
  318: 		    } else {
  319: 			$r->log_reason('Invalid symb for '.$requrl.': '.
  320: 				       $symb);
  321: 			$env{'user.error.msg'}=
  322: 			    "$requrl:bre:1:1:Invalid Access";
  323: 			return HTTP_NOT_ACCEPTABLE; 
  324: 		    }
  325: 		} else {
  326: 		    $symb=&Apache::lonnet::symbread($requrl);
  327: 		    if (&Apache::lonnet::is_on_map($requrl) && $symb &&
  328: 			!&Apache::lonnet::symbverify($symb,$requrl)) {
  329: 			$r->log_reason('Invalid symb for '.$requrl.': '.$symb);
  330: 			$env{'user.error.msg'}=
  331: 			    "$requrl:bre:1:1:Invalid Access";
  332: 			return HTTP_NOT_ACCEPTABLE; 
  333: 		    }
  334: 		    if ($symb) {
  335: 			my ($map,$mid,$murl)=
  336: 			    &Apache::lonnet::decode_symb($symb);
  337: 			&Apache::lonnet::symblist($map,$murl =>[$murl,$mid],
  338: 						  'last_known' =>[$murl,$mid]);
  339: 		    }
  340: 		}
  341: 		$env{'request.symb'}=$symb;
  342: 		&Apache::lonnet::courseacclog($symb);
  343: 	    } else {
  344: # ------------------------------------------------------- This is other content
  345: 		&Apache::lonnet::courseacclog($requrl);    
  346: 	    }
  347: 	}
  348: 	return OK;
  349:     }
  350: # -------------------------------------------- See if this is a public resource
  351:     if ($requrl=~m|^/+adm/+help/+|) {
  352:  	return OK;
  353:     }
  354: # ------------------------------------ See if this is a viewable portfolio file
  355:     if (&Apache::lonnet::is_portfolio_url($requrl)) {
  356: 	my $access=&Apache::lonnet::allowed('bre',$requrl);
  357: 	if ($access eq 'A') {
  358: 	    &Apache::restrictedaccess::setup_handler($r);
  359: 	    return OK;
  360: 	}
  361: 	if (($access ne '2') && ($access ne 'F')) {
  362: 	    $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  363: 	    return HTTP_NOT_ACCEPTABLE;
  364: 	}
  365:     }
  366: 
  367: # -------------------------------------------------------------- Not authorized
  368:     $requrl=~/\.(\w+)$/;
  369: #    if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  370: #        ($requrl=~/^\/adm\/(roles|logout|email|menu|remote)/) ||
  371: #        ($requrl=~m|^/prtspool/|)) {
  372: # -------------------------- Store where they wanted to go and get login screen
  373: 	$env{'request.querystring'}=$r->args;
  374: 	$env{'request.firsturl'}=$requrl;
  375:        return FORBIDDEN;
  376: #   } else {
  377: # --------------------------------------------------------------------- Goodbye
  378: #       return HTTP_BAD_REQUEST;
  379: #   }
  380: }
  381: 
  382: 1;
  383: __END__
  384: 
  385: =head1 NAME
  386: 
  387: Apache::lonacc - Cookie Based Access Handler
  388: 
  389: =head1 SYNOPSIS
  390: 
  391: Invoked (for various locations) by /etc/httpd/conf/srm.conf:
  392: 
  393:  PerlAccessHandler       Apache::lonacc
  394: 
  395: =head1 INTRODUCTION
  396: 
  397: This module enables cookie based authentication and is used
  398: to control access for many different LON-CAPA URIs.
  399: 
  400: Whenever the client sends the cookie back to the server, 
  401: this cookie is handled by either lonacc.pm or loncacc.pm
  402: (see srm.conf for what is invoked when).  If
  403: the cookie is missing or invalid, the user is re-challenged
  404: for login information.
  405: 
  406: This is part of the LearningOnline Network with CAPA project
  407: described at http://www.lon-capa.org.
  408: 
  409: =head1 HANDLER SUBROUTINE
  410: 
  411: This routine is called by Apache and mod_perl.
  412: 
  413: =over 4
  414: 
  415: =item *
  416: 
  417: transfer profile into environment
  418: 
  419: =item *
  420: 
  421: load POST parameters
  422: 
  423: =item *
  424: 
  425: check access
  426: 
  427: =item *
  428: 
  429: if allowed, get symb, log, generate course statistics if applicable
  430: 
  431: =item *
  432: 
  433: otherwise return error
  434: 
  435: =item *
  436: 
  437: see if public resource
  438: 
  439: =item *
  440: 
  441: store attempted access
  442: 
  443: =back
  444: 
  445: =cut

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