Annotation of loncom/auth/lonauth.pm, revision 1.152

1.136     kruse       1: # The LearningOnline Network
                      2: # User Authentication Module
                      3: #
1.152   ! raeburn     4: # $Id: lonauth.pm,v 1.151 2018/04/21 21:29:31 raeburn Exp $
1.136     kruse       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;
1.140     raeburn    32: use LONCAPA qw(:DEFAULT :match);
1.136     kruse      33: use Apache::Constants qw(:common);
                     34: use CGI qw(:standard);
                     35: use Apache::loncommon();
                     36: use Apache::lonnet;
                     37: use Apache::lonmenu();
                     38: use Apache::createaccount;
1.149     raeburn    39: use Apache::ltiauth;
1.136     kruse      40: use Fcntl qw(:flock);
                     41: use Apache::lonlocal;
                     42: use Apache::File();
                     43: use HTML::Entities;
1.143     raeburn    44: use Digest::MD5;
1.136     kruse      45:  
                     46: # ------------------------------------------------------------ Successful login
                     47: sub success {
                     48:     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
1.149     raeburn    49: 	$form,$skipcritical) = @_;
1.136     kruse      50: 
                     51: # ------------------------------------------------------------ Get cookie ready
                     52:     my $cookie =
                     53: 	&Apache::loncommon::init_user_environment($r, $username, $domain,
                     54: 						  $authhost, $form,
                     55: 						  {'extra_env' => $extra_env,});
                     56: 
                     57:     my $public=($username eq 'public' && $domain eq 'public');
                     58: 
                     59:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
                     60: 
                     61: # -------------------------------------------------------------------- Log this
                     62: 
                     63:     &Apache::lonnet::log($domain,$username,$authhost,
                     64:                          "Login $ENV{'REMOTE_ADDR'}");
                     65: 
                     66: # ------------------------------------------------- Check for critical messages
                     67: 
1.149     raeburn    68:     unless ($skipcritical) {
                     69:         my @what=&Apache::lonnet::dump('critical',$domain,$username);
                     70:         if ($what[0]) {
                     71: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                     72: 	        $lowerurl='/adm/email?critical=display';
                     73:             }
1.136     kruse      74:         }
                     75:     }
                     76: 
1.143     raeburn    77: # ----------------------------------------------------------- Get cookies ready
                     78:     my ($securecookie,$defaultcookie);
                     79:     if ($ENV{'SERVER_PORT'} == 443) {
                     80:         $securecookie="lonID=$cookie; path=/; HttpOnly; secure";
                     81:         my $lonidsdir=$r->dir_config('lonIDsDir');
                     82:         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
                     83:             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
                     84:             if (-e "$lonidsdir/$linkname.id") {
                     85:                 unlink("$lonidsdir/$linkname.id");
                     86:             }
                     87:             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
                     88:                                               "$lonidsdir/$linkname.id"); 1 };
                     89:             if ($made_symlink) {
                     90:                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
                     91:                 &Apache::lonnet::appenv({'user.linkedenv' => "$lonidsdir/$linkname.id"});
                     92:             }
                     93:         }
                     94:     } else {
                     95:         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
                     96:     }
1.136     kruse      97: # -------------------------------------------------------- Menu script and info
                     98:     my $destination = $lowerurl;
1.149     raeburn    99:     if ($env{'request.lti.login'}) {
                    100:         if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
                    101:             &Apache::loncommon::content_type($r,'text/html');
                    102:             if ($securecookie) {
                    103:                 $r->headers_out->add('Set-cookie' => $securecookie);
                    104:             }
                    105:             if ($defaultcookie) {
                    106:                 $r->headers_out->add('Set-cookie' => $defaultcookie);
                    107:             }
                    108:             $r->send_http_header;
1.152   ! raeburn   109:             if (ref($form) eq 'HASH') {
        !           110:                 $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
        !           111:                 $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
        !           112:                 $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
        !           113:             }
1.149     raeburn   114:             &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
                    115:             return;
                    116:         }
                    117:         if ($env{'request.lti.selfenrollrole'}) {
                    118:             if (&Apache::ltiauth::lti_enroll($username,$domain,
                    119:                                              $env{'request.lti.selfenrollrole'}) eq 'ok') {
                    120:                 $form->{'role'} = $env{'request.lti.selfenrollrole'};
                    121:                 &Apache::lonnet::delenv('request.lti.selfenrollrole');
                    122:             } else {
                    123:                 &Apache::ltiauth::invalid_request($r,24);
                    124:             }
                    125:         }
                    126:     }
1.136     kruse     127:     if (defined($form->{role})) {
                    128:         my $envkey = 'user.role.'.$form->{role};
                    129:         my $now=time;
                    130:         my $then=$env{'user.login.time'};
                    131:         my $refresh=$env{'user.refresh.time'};
                    132:         my $update=$env{'user.update.time'};
                    133:         if (!$update) {
                    134:             $update = $then;
                    135:         }
                    136:         if (exists($env{$envkey})) {
                    137:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
                    138:             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
                    139:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
                    140:             if ($tstatus eq 'is') {
                    141:                 $destination  .= ($destination =~ /\?/) ? '&' : '?';
                    142:                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
                    143:                 $destination .= 'selectrole=1&'.$newrole.'=1';
                    144:             }
                    145:         }
                    146:     }
                    147:     if (defined($form->{symb})) {
                    148:         my $destsymb = $form->{symb};
                    149:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
                    150:         if ($destsymb =~ /___/) {
                    151:             # FIXME Need to deal with encrypted symbs and urls as needed.
                    152:             my ($map,$resid,$desturl)=split(/___/,$destsymb);
1.137     raeburn   153:             $desturl = &Apache::lonnet::clutter($desturl);
1.136     kruse     154:             $desturl = &HTML::Entities::encode($desturl,'"<>&');
                    155:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
                    156:             $destination .= 'destinationurl='.$desturl.
                    157:                             '&destsymb='.$destsymb;
                    158:         } else {
                    159:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
                    160:             $destination .= 'destinationurl='.$destsymb;
                    161:         }
                    162:     }
                    163:     if ($destination =~ m{^/adm/roles}) {
                    164:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
                    165:         $destination .= 'source=login';
                    166:     }
                    167: 
1.150     raeburn   168:     my $windowname = 'loncapaclient';
                    169:     if ($env{'request.lti.login'}) {
                    170:         $windowname .= 'lti';
                    171:     }
                    172:     my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
1.136     kruse     173:     my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';
                    174:     my $brcrum = [{'href' => '',
                    175:                    'text' => 'Successful Login'},];
1.140     raeburn   176:     my $args = {'bread_crumbs' => $brcrum,};
                    177:     unless ((defined($form->{role})) || (defined($form->{symb}))) {
                    178:         my $update=$env{'user.update.time'};
                    179:         if (!$update) {
                    180:             $update = $env{'user.login.time'};
                    181:         }
                    182:         my %roles_in_env;
                    183:         my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
                    184:         if ($showcount == 1) {
                    185:             foreach my $rolecode (keys(%roles_in_env)) {
                    186:                 my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
                    187:                 if ($cid) {
                    188:                     my %coursedescription =
                    189:                         &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
                    190:                     if ($coursedescription{'type'} eq 'Placement') {
                    191:                         $args->{'crstype'} = 'Placement';
                    192:                     }
                    193:                     last;
                    194:                 }
                    195:             }
                    196:         }
                    197:     }
1.136     kruse     198: 
                    199: # ------------------------------------------------- Output for successful login
                    200: 
                    201:     &Apache::loncommon::content_type($r,'text/html');
1.143     raeburn   202:     if ($securecookie) {
                    203:         $r->headers_out->add('Set-cookie' => $securecookie);
                    204:     }
                    205:     if ($defaultcookie) {
                    206:         $r->headers_out->add('Set-cookie' => $defaultcookie);
                    207:     }
1.136     kruse     208:     $r->send_http_header;
                    209: 
1.151     raeburn   210:     my $start_page;
                    211:     if ($env{'request.lti.login'}) {
                    212:         $args = {'only_body' => 1,};
                    213:         $start_page=&Apache::loncommon::start_page('',$header,$args);
                    214:     } else {
                    215:         $start_page=&Apache::loncommon::start_page('Successful Login',
                    216:                                                    $header,$args);
                    217:     }
1.149     raeburn   218:     my $end_page  =&Apache::loncommon::end_page();
                    219: 
                    220:     my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
                    221: 
1.151     raeburn   222:     my $pagebody;
                    223:     unless ($env{'request.lti.login'}) {
                    224:         my %lt=&Apache::lonlocal::texthash(
                    225: 				           'wel' => 'Welcome',
                    226: 				           'pro' => 'Login problems?',
                    227: 				          );
                    228:         $pagebody = "<h1>$lt{'wel'}</h1>\n".
                    229:                     &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
                    230:         my $loginhelp = &loginhelpdisplay($domain);
                    231:         if ($loginhelp) {
                    232:             $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
                    233:         }
1.136     kruse     234:     }
                    235:     $r->print(<<ENDSUCCESS);
                    236: $start_page
                    237: $windowinfo
1.151     raeburn   238: $pagebody
1.136     kruse     239: $continuelink
                    240: $end_page
                    241: ENDSUCCESS
                    242:     return;
                    243: }
                    244: 
                    245: # --------------------------------------------------------------- Failed login!
                    246: 
                    247: sub failed {
                    248:     my ($r,$message,$form) = @_;
                    249:     (undef,undef,undef,my $clientmathml,my $clientunicode) =
                    250:         &Apache::loncommon::decode_user_agent();
                    251:     my $args = {};
                    252:     if ($clientunicode && !$clientmathml) {
                    253:         $args = {'browser.unicode' => 1};
                    254:     }
                    255: 
                    256:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
                    257:     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
                    258:     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
                    259:     if (&Apache::lonnet::domain($udom,'description') eq '') {
                    260:         undef($udom);
                    261:     }
                    262:     my $retry = '/adm/login';
                    263:     if ($uname eq $form->{'uname'}) {
                    264:         $retry .= '?username='.$uname;
                    265:     }
                    266:     if ($udom) {
                    267:         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
                    268:     }
                    269:     if (exists($form->{role})) {
                    270:         my $role = &Apache::loncommon::cleanup_html($form->{role});
                    271:         if ($role ne '') {
                    272:             $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
                    273:         }
                    274:     }
                    275:     if (exists($form->{symb})) {
                    276:         my $symb = &Apache::loncommon::cleanup_html($form->{symb});
                    277:         if ($symb ne '') {
                    278:             $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
                    279:         }
                    280:     }
                    281:     my $end_page = &Apache::loncommon::end_page();
                    282:     &Apache::loncommon::content_type($r,'text/html');
                    283:     $r->send_http_header;
                    284:     my @actions =
                    285:          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
                    286:     my $loginhelp = &loginhelpdisplay($udom);
                    287:     if ($loginhelp) {
                    288:         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
                    289:     }
                    290:     #FIXME: link to helpdesk might be added here
                    291: 
                    292:     $r->print(
                    293:        $start_page
                    294:       .'<h2>'.&mt('Sorry ...').'</h2>'
                    295:       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
                    296:       .&Apache::lonhtmlcommon::actionbox(\@actions)
                    297:       .$end_page
                    298:     );
                    299:  }
                    300: 
                    301: # ------------------------------------------------------------------ Rerouting!
                    302: 
                    303: sub reroute {
                    304:     my ($r) = @_;
                    305:     &Apache::loncommon::content_type($r,'text/html');
                    306:     $r->send_http_header;
                    307:     my $msg='<b>'.&mt('Sorry ...').'</b><br />'
                    308:            .&mt('Please [_1]log in again[_2].');
                    309:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
                    310: }
                    311: 
                    312: # ---------------------------------------------------------------- Main handler
                    313: 
                    314: sub handler {
                    315:     my $r = shift;
                    316:     my $londocroot = $r->dir_config('lonDocRoot');
                    317: # Are we re-routing?
                    318:     if (-e "$londocroot/lon-status/reroute.txt") {
                    319: 	&reroute($r);
                    320: 	return OK;
                    321:     }
                    322: 
                    323:     &Apache::lonlocal::get_language_handle($r);
                    324: 
                    325: # -------------------------------- Prevent users from attempting to login twice
                    326:     my $handle = &Apache::lonnet::check_for_valid_session($r);
                    327:     if ($handle ne '') {
                    328:         my $lonidsdir=$r->dir_config('lonIDsDir');
                    329:         if ($handle=~/^publicuser\_/) {
                    330: # For "public user" - remove it, we apparently really want to login
                    331:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
                    332:         } else {
                    333: # Indeed, a valid token is found
                    334:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
                    335: 	    &Apache::loncommon::content_type($r,'text/html');
                    336: 	    $r->send_http_header;
                    337: 	    my $start_page = 
                    338: 	        &Apache::loncommon::start_page('Already logged in');
                    339: 	    my $end_page = 
                    340: 	        &Apache::loncommon::end_page();
                    341:             my $dest = '/adm/roles';
                    342:             if ($env{'form.firsturl'} ne '') {
                    343:                 $dest = $env{'form.firsturl'};
                    344:             }
                    345:             $r->print(
                    346:                $start_page
                    347:               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
                    348:               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
                    349:                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
                    350:               .'</p>'
                    351:               .$end_page
                    352:             );
                    353:             return OK;
                    354:         }
                    355:     }
                    356: 
                    357: # ---------------------------------------------------- No valid token, continue
                    358: 
                    359: 
                    360:     my $buffer;
                    361:     if ($r->header_in('Content-length') > 0) {
                    362: 	$r->read($buffer,$r->header_in('Content-length'),0);
                    363:     }
                    364:     my %form;
                    365:     foreach my $pair (split(/&/,$buffer)) {
                    366:        my ($name,$value) = split(/=/,$pair);
                    367:        $value =~ tr/+/ /;
                    368:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                    369:        $form{$name}=$value;
                    370:     }
                    371: 
                    372:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
                    373: 	&failed($r,'Username, password and domain need to be specified.',
                    374: 		\%form);
                    375:         return OK;
                    376:     }
                    377: 
                    378: # split user logging in and "su"-user
                    379: 
1.145     raeburn   380:     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
1.136     kruse     381:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
                    382:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
1.145     raeburn   383:     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
                    384:     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
1.136     kruse     385: 
                    386:     my $role   = $r->dir_config('lonRole');
                    387:     my $domain = $r->dir_config('lonDefDomain');
                    388:     my $prodir = $r->dir_config('lonUsersDir');
                    389:     my $contact_name = &mt('LON-CAPA helpdesk');
                    390: 
                    391: # ---------------------------------------- Get the information from login token
                    392: 
                    393:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
                    394:                                       $form{'serverid'});
                    395: 
                    396:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
                    397:         ($tmpinfo eq 'no_such_host')) {
                    398: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
                    399:         return OK;
                    400:     } else {
                    401: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
                    402: 					   $form{'serverid'});
                    403:         if ( $reply ne 'ok' ) {
                    404:             &failed($r,'Session could not be opened.',\%form);
                    405: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
                    406: 	    return OK;
                    407: 	}
                    408:     }
                    409: 
                    410:     if (!&Apache::lonnet::domain($form{'udom'})) {
                    411:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
                    412:         return OK;
                    413:     }
                    414: 
1.138     raeburn   415:     my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
1.136     kruse     416:     if ($rolestr) {
                    417:         $rolestr = &unescape($rolestr);
                    418:     }
                    419:     if ($symbstr) {
                    420:         $symbstr= &unescape($symbstr);
                    421:     }
1.138     raeburn   422:     if ($iptokenstr) {
                    423:         $iptokenstr = &unescape($iptokenstr);
                    424:     }
1.136     kruse     425:     if ($rolestr =~ /^role=/) {
                    426:         (undef,$form{'role'}) = split('=',$rolestr);
                    427:     }
                    428:     if ($symbstr =~ /^symb=/) { 
                    429:         (undef,$form{'symb'}) = split('=',$symbstr);
                    430:     }
1.138     raeburn   431:     if ($iptokenstr =~ /^iptoken=/) {
                    432:         (undef,$form{'iptoken'}) = split('=',$iptokenstr);
                    433:     }
1.136     kruse     434: 
1.139     raeburn   435:     my $upass = $ENV{HTTPS} ? $form{'upass0'} 
                    436:         : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
1.136     kruse     437: 
                    438: # ---------------------------------------------------------------- Authenticate
                    439: 
                    440:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
                    441:     my ($cancreate,$statustocreate) =
                    442:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
                    443:     my $defaultauth;
                    444:     if (ref($cancreate) eq 'ARRAY') {
                    445:         if (grep(/^login$/,@{$cancreate})) {
                    446:             $defaultauth = 1;
                    447:         }
                    448:     }
                    449:     my $clientcancheckhost = 1;
                    450:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
                    451:                                               $form{'udom'},$defaultauth,
                    452:                                               $clientcancheckhost);
1.149     raeburn   453: 
1.136     kruse     454: # --------------------------------------------------------------------- Failed?
                    455: 
                    456:     if ($authhost eq 'no_host') {
                    457: 	&failed($r,'Username and/or password could not be authenticated.',
                    458: 		\%form);
                    459:         return OK;
                    460:     } elsif ($authhost eq 'no_account_on_host') {
                    461:         if ($defaultauth) {
                    462:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
                    463:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
                    464:                 return OK;
                    465:             }
                    466:             my $start_page = 
                    467:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA');
                    468:             my $lonhost = $r->dir_config('lonHostID');
                    469:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                    470:             my $contacts = 
                    471:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                    472:                                                         $form{'udom'},$origmail);
                    473:             my ($contact_email) = split(',',$contacts); 
                    474:             my $output = 
                    475:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
                    476:                                                        $domdesc,'',$lonhost,
                    477:                                                        $contact_email,$contact_name,
                    478:                                                        undef,$statustocreate);
                    479:             &Apache::loncommon::content_type($r,'text/html');
                    480:             $r->send_http_header;
                    481:             &Apache::createaccount::print_header($r,$start_page);
                    482:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
                    483:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
                    484:                       $output.&Apache::loncommon::end_page());
                    485:             return OK;
                    486:         } else {
                    487:             &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);
                    488:             return OK;
                    489:         }
                    490:     }
                    491: 
                    492:     if (($firsturl eq '') || 
                    493: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
                    494: 	$firsturl='/adm/roles';
                    495:     }
                    496: 
                    497:     my $hosthere;
                    498:     if ($form{'iptoken'}) {
1.138     raeburn   499:         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
                    500:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
1.136     kruse     501:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
                    502:             ($sessiondata{'username'} eq $form{'uname'})) {
                    503:             $hosthere = 1;
                    504:         }
                    505:     }
                    506: 
                    507: # --------------------------------- Are we attempting to login as somebody else?
                    508:     if ($form{'suname'}) {
1.145     raeburn   509:         my ($suname,$sudom,$sudomref);
                    510:         $suname = $form{'suname'};
                    511:         $sudom = $form{'udom'};
                    512:         if ($form{'sudom'}) {
                    513:             unless ($sudom eq $form{'sudom'}) {
                    514:                 if (&Apache::lonnet::domain($form{'sudom'})) {
                    515:                     $sudomref = [$form{'sudom'}];
                    516:                     $sudom = $form{'sudom'};
                    517:                 }
                    518:             }
                    519:         }
1.136     kruse     520: # ------------ see if the original user has enough privileges to pull this stunt
1.145     raeburn   521: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
1.136     kruse     522: # ---------------------------------------------------- see if the su-user exists
1.145     raeburn   523: 	    unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
1.136     kruse     524: # ------------------------------ see if the su-user is not too highly privileged
1.146     raeburn   525: 		if (&Apache::lonnet::privileged($suname,$sudom)) {
                    526:                     &Apache::lonnet::logthis('Attempted switch user to privileged user');
                    527:                 } else {
                    528:                     my $noprivswitch;
1.145     raeburn   529: #
                    530: # su-user's home server and user's home server must have one of:
1.147     raeburn   531: # (a) same domain
                    532: # (b) same primary library server for the two domains
                    533: # (c) same "internet domain" for primary library server(s) for home servers' domains
1.145     raeburn   534: #
1.148     raeburn   535:                     my $suprim = &Apache::lonnet::domain($sudom,'primary');
                    536:                     my $suintdom = &Apache::lonnet::internet_dom($suprim);
1.145     raeburn   537:                     unless ($sudom eq $form{'udom'}) {
1.148     raeburn   538:                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
                    539:                         my $uintdom = &Apache::lonnet::internet_dom($uprim);
1.145     raeburn   540:                         unless ($suprim eq $uprim) {
                    541:                             unless ($suintdom eq $uintdom) {
                    542:                                 &Apache::lonnet::logthis('Attempted switch user '
1.146     raeburn   543:                                    .'to user with different "internet domain".');                        
                    544:                                 $noprivswitch = 1;
1.145     raeburn   545:                             }
                    546:                         }
                    547:                     }
                    548: 
1.146     raeburn   549:                     unless ($noprivswitch) {
                    550: #
                    551: # server where log-in occurs must have same "internet domain" as su-user's home
                    552: # server
                    553: #
                    554:                         my $lonhost = $r->dir_config('lonHostID');
                    555:                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
1.148     raeburn   556:                         if ($hostintdom ne $suintdom) {
1.146     raeburn   557:                             &Apache::lonnet::logthis('Attempted switch user on a '
                    558:                                 .'server with a different "internet domain".'); 
                    559:                         } else {
                    560: 
1.136     kruse     561: # -------------------------------------------------------- actually switch users
1.145     raeburn   562: 
1.146     raeburn   563: 		            &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
                    564:                               $form{'udom'}.' logging in as '.$suname.':'.$sudom);
                    565: 		            $form{'uname'}=$suname;
                    566:                             if ($form{'udom'} ne $sudom) {
                    567:                                 $form{'udom'}=$sudom;
                    568:                             }
                    569:                         }
1.145     raeburn   570:                     }
1.136     kruse     571: 		}
                    572: 	    }
                    573: 	} else {
                    574: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                    575: 	}
                    576:     }
                    577: 
                    578:     my ($is_balancer,$otherserver);
                    579: 
                    580:     unless ($hosthere) {
                    581:         ($is_balancer,$otherserver) =
1.141     raeburn   582:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
                    583:         if ($is_balancer) {
                    584:             if ($otherserver eq '') {
                    585:                 my $lowest_load;
                    586:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
                    587:                 if ($lowest_load > 100) {
                    588:                     $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
                    589:                 }
                    590:             }
                    591:             if ($otherserver ne '') {
                    592:                 my @hosts = &Apache::lonnet::current_machine_ids();
                    593:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
                    594:                     $hosthere = $otherserver;
                    595:                 }
                    596:             }
                    597:         }
1.136     kruse     598:     }
                    599: 
1.141     raeburn   600:     if (($is_balancer) && (!$hosthere)) {
1.136     kruse     601:         if ($otherserver) {
                    602:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                    603:                      \%form);
                    604:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                    605:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                    606:                 $switchto .= '&origurl='.$firsturl;
                    607:             }
                    608:             if ($form{'role'}) {
                    609:                 $switchto .= '&role='.$form{'role'};
                    610:             }
                    611:             if ($form{'symb'}) {
                    612:                 $switchto .= '&symb='.$form{'symb'};
                    613:             }
                    614:             $r->internal_redirect($switchto);
                    615:         } else {
                    616:             $r->print(&noswitch());
                    617:         }
                    618:         return OK;
                    619:     } else {
                    620:         if (!&check_can_host($r,\%form,$authhost)) {
                    621:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
                    622:             if ($otherserver) {
                    623:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                    624:                          \%form);
                    625:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                    626:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                    627:                     $switchto .= '&origurl='.$firsturl;
                    628:                 }
                    629:                 if ($form{'role'}) {
                    630:                     $switchto .= '&role='.$form{'role'};
                    631:                 }
                    632:                 if ($form{'symb'}) {
                    633:                     $switchto .= '&symb='.$form{'symb'};
                    634:                 }
                    635:                 $r->internal_redirect($switchto);
                    636:             } else {
                    637:                 $r->print(&noswitch());
                    638:             }
                    639:             return OK;
                    640:         }
                    641: 
                    642: # ------------------------------------------------------- Do the load balancing
                    643: 
                    644: # ---------------------------------------------------------- Determine own load
                    645:         my $loadlim = $r->dir_config('lonLoadLim');
                    646:         my $loadavg;
                    647:         {
                    648:             my $loadfile=Apache::File->new('/proc/loadavg');
                    649:             $loadavg=<$loadfile>;
                    650:         }
                    651:         $loadavg =~ s/\s.*//g;
                    652:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
                    653:         my $userloadpercent=&Apache::lonnet::userload();
                    654: 
                    655: # ---------------------------------------------------------- Are we overloaded?
                    656:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
                    657:             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
                    658:             if (!$unloaded) {
                    659:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
                    660:             }
                    661:             if ($unloaded) {
                    662:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                    663:                          undef,\%form);
                    664:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                    665:                 return OK;
                    666:             }
                    667:         }
1.141     raeburn   668:         if (($is_balancer) && ($hosthere)) {
                    669:             $form{'noloadbalance'} = $hosthere;
                    670:         }
1.136     kruse     671:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
                    672:                  \%form);
                    673:         return OK;
                    674:     }
                    675: }
                    676: 
                    677: sub check_can_host {
                    678:     my ($r,$form,$authhost,$domdesc) = @_;
                    679:     return unless (ref($form) eq 'HASH');
                    680:     my $canhost = 1;
                    681:     my $lonhost = $r->dir_config('lonHostID');
                    682:     my $udom = $form->{'udom'};
                    683:     my @intdoms;
                    684:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                    685:     if (ref($internet_names) eq 'ARRAY') {
                    686:         @intdoms = @{$internet_names};
                    687:     }
                    688:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    689:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    690:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                    691:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
                    692:         my $hostname = &Apache::lonnet::hostname($lonhost);
                    693:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                    694:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                    695:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                    696:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    697:         my $loncaparev;
                    698:         if ($authhost eq 'no_account_on_host') {
                    699:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
                    700:         } else {
                    701:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
                    702:         }
                    703:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
                    704:                                                      $udomdefaults{'remotesessions'},
                    705:                                                      $defdomdefaults{'hostedsessions'});
                    706:     }
                    707:     unless ($canhost) {
                    708:         if ($authhost eq 'no_account_on_host') {
                    709:             my $checkloginvia = 1;
                    710:             my ($login_host,$hostname) = 
                    711:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
                    712:             &Apache::loncommon::content_type($r,'text/html');
                    713:             $r->send_http_header;
                    714:             if ($login_host ne '') {
                    715:                 my $protocol = $Apache::lonnet::protocol{$login_host};
                    716:                 $protocol = 'http' if ($protocol ne 'https');
                    717:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
                    718:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                    719:                           '<h3>'.&mt('Account creation').'</h3>'.
                    720:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                    721:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                    722:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                    723:                           &Apache::loncommon::end_page());
                    724:             } else {
                    725:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                    726:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
                    727:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                    728:                           '<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>'.
                    729:                           &Apache::loncommon::end_page());
                    730:             }
                    731:         } else {
                    732:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                    733:                      $form);
                    734:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
                    735:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
                    736:         }
                    737:     }
                    738:     return $canhost;
                    739: }
                    740: 
                    741: sub noswitch {
                    742:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                    743:                  '<h3>'.&mt('Session unavailable').'</h3>'.
                    744:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
                    745:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                    746:                  &Apache::loncommon::end_page();
                    747:     return $result;
                    748: }
                    749: 
                    750: sub loginhelpdisplay {
                    751:     my ($authdomain) = @_;
                    752:     my $login_help = 1;
                    753:     my $lang = &Apache::lonlocal::current_language();
                    754:     if ($login_help) {
                    755:         my $dom = $authdomain;
                    756:         if ($dom eq '') {
                    757:             $dom = &Apache::lonnet::default_login_domain();
                    758:         }
                    759:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
                    760:         my $loginhelp_url;
                    761:         if ($lang) {
                    762:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
                    763:             if ($loginhelp_url ne '') {
                    764:                 return $loginhelp_url;
                    765:             }
                    766:         }
                    767:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
                    768:         if ($loginhelp_url ne '') {
                    769:             return $loginhelp_url;
                    770:         } else {
                    771:             return '/adm/loginproblems.html';
                    772:         }
                    773:     }
                    774:     return;
                    775: }
                    776: 
                    777: 1;
                    778: __END__
                    779: 
                    780: 

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