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

1.136     kruse       1: # The LearningOnline Network
                      2: # User Authentication Module
                      3: #
1.172   ! raeburn     4: # $Id: lonauth.pm,v 1.171 2021/11/24 20:15:15 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.170     raeburn    45: use CGI::Cookie();
1.136     kruse      46:  
                     47: # ------------------------------------------------------------ Successful login
                     48: sub success {
                     49:     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
1.170     raeburn    50: 	$form,$skipcritical,$cid,$expirepub) = @_;
1.136     kruse      51: 
                     52: # ------------------------------------------------------------ Get cookie ready
                     53:     my $cookie =
                     54: 	&Apache::loncommon::init_user_environment($r, $username, $domain,
                     55: 						  $authhost, $form,
                     56: 						  {'extra_env' => $extra_env,});
                     57: 
                     58:     my $public=($username eq 'public' && $domain eq 'public');
                     59: 
                     60:     if ($public or $lowerurl eq 'noredirect') { return $cookie; }
                     61: 
                     62: # -------------------------------------------------------------------- Log this
                     63: 
1.162     raeburn    64:     my $ip = &Apache::lonnet::get_requestor_ip();
1.136     kruse      65:     &Apache::lonnet::log($domain,$username,$authhost,
1.162     raeburn    66:                          "Login $ip");
1.136     kruse      67: 
                     68: # ------------------------------------------------- Check for critical messages
                     69: 
1.149     raeburn    70:     unless ($skipcritical) {
                     71:         my @what=&Apache::lonnet::dump('critical',$domain,$username);
                     72:         if ($what[0]) {
                     73: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                     74: 	        $lowerurl='/adm/email?critical=display';
                     75:             }
1.136     kruse      76:         }
                     77:     }
                     78: 
1.143     raeburn    79: # ----------------------------------------------------------- Get cookies ready
                     80:     my ($securecookie,$defaultcookie);
1.154     raeburn    81:     my $ssl = $r->subprocess_env('https');
                     82:     if ($ssl) {
                     83:         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
1.143     raeburn    84:         my $lonidsdir=$r->dir_config('lonIDsDir');
                     85:         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
                     86:             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
                     87:             if (-e "$lonidsdir/$linkname.id") {
                     88:                 unlink("$lonidsdir/$linkname.id");
                     89:             }
                     90:             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
                     91:                                               "$lonidsdir/$linkname.id"); 1 };
                     92:             if ($made_symlink) {
                     93:                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
1.154     raeburn    94:                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
1.143     raeburn    95:             }
                     96:         }
                     97:     } else {
                     98:         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
                     99:     }
1.136     kruse     100: # -------------------------------------------------------- Menu script and info
                    101:     my $destination = $lowerurl;
1.149     raeburn   102:     if ($env{'request.lti.login'}) {
                    103:         if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
                    104:             &Apache::loncommon::content_type($r,'text/html');
                    105:             if ($securecookie) {
                    106:                 $r->headers_out->add('Set-cookie' => $securecookie);
                    107:             }
                    108:             if ($defaultcookie) {
                    109:                 $r->headers_out->add('Set-cookie' => $defaultcookie);
                    110:             }
                    111:             $r->send_http_header;
1.152     raeburn   112:             if (ref($form) eq 'HASH') {
1.158     raeburn   113:                 $form->{'lti.login'} = $env{'request.lti.login'};
1.152     raeburn   114:                 $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
                    115:                 $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
                    116:                 $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
                    117:             }
1.149     raeburn   118:             &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
                    119:             return;
                    120:         }
                    121:         if ($env{'request.lti.selfenrollrole'}) {
                    122:             if (&Apache::ltiauth::lti_enroll($username,$domain,
                    123:                                              $env{'request.lti.selfenrollrole'}) eq 'ok') {
                    124:                 $form->{'role'} = $env{'request.lti.selfenrollrole'};
                    125:                 &Apache::lonnet::delenv('request.lti.selfenrollrole');
                    126:             } else {
                    127:                 &Apache::ltiauth::invalid_request($r,24);
                    128:             }
                    129:         }
                    130:     }
1.136     kruse     131:     if (defined($form->{role})) {
                    132:         my $envkey = 'user.role.'.$form->{role};
                    133:         my $now=time;
                    134:         my $then=$env{'user.login.time'};
                    135:         my $refresh=$env{'user.refresh.time'};
                    136:         my $update=$env{'user.update.time'};
                    137:         if (!$update) {
                    138:             $update = $then;
                    139:         }
                    140:         if (exists($env{$envkey})) {
                    141:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
                    142:             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
                    143:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
                    144:             if ($tstatus eq 'is') {
                    145:                 $destination  .= ($destination =~ /\?/) ? '&' : '?';
                    146:                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
                    147:                 $destination .= 'selectrole=1&'.$newrole.'=1';
                    148:             }
                    149:         }
                    150:     }
                    151:     if (defined($form->{symb})) {
                    152:         my $destsymb = $form->{symb};
1.159     raeburn   153:         my $encrypted;
                    154:         if ($destsymb =~ m{^/enc/}) {
                    155:             $encrypted = 1;
                    156:             if ($cid) {
                    157:                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
                    158:             }
                    159:         }
1.136     kruse     160:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
                    161:         if ($destsymb =~ /___/) {
                    162:             my ($map,$resid,$desturl)=split(/___/,$destsymb);
1.137     raeburn   163:             $desturl = &Apache::lonnet::clutter($desturl);
1.159     raeburn   164:             if ($encrypted) {
                    165:                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
                    166:                 $destsymb = $form->{symb};
                    167:             }
1.136     kruse     168:             $desturl = &HTML::Entities::encode($desturl,'"<>&');
                    169:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
                    170:             $destination .= 'destinationurl='.$desturl.
                    171:                             '&destsymb='.$destsymb;
1.159     raeburn   172:         } elsif (!$encrypted) {
1.136     kruse     173:             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
                    174:             $destination .= 'destinationurl='.$destsymb;
                    175:         }
                    176:     }
                    177:     if ($destination =~ m{^/adm/roles}) {
                    178:         $destination  .= ($destination =~ /\?/) ? '&' : '?';
                    179:         $destination .= 'source=login';
                    180:     }
                    181: 
1.169     raeburn   182:     if (($env{'request.deeplink.login'} eq $lowerurl) &&
                    183:         (($env{'request.linkprot'}) || ($env{'request.linkkey'} ne ''))) {
                    184:         my %info;
                    185:         if ($env{'request.linkprot'}) {
                    186:             $info{'linkprot'} = $env{'request.linkprot'};
                    187:         } elsif ($env{'request.linkkey'} ne '') {
                    188:             $info{'linkkey'} = $env{'request.linkkey'};
                    189:         }
                    190:         $info{'origurl'} = $lowerurl;
                    191:         my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
                    192:         unless (($token eq 'con_lost') || ($token eq 'refused') ||
                    193:                 ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
                    194:             $destination .= (($destination =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
                    195:         }
                    196:     }
                    197: 
1.150     raeburn   198:     my $windowname = 'loncapaclient';
                    199:     if ($env{'request.lti.login'}) {
                    200:         $windowname .= 'lti';
                    201:     }
                    202:     my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
1.136     kruse     203:     my $brcrum = [{'href' => '',
                    204:                    'text' => 'Successful Login'},];
1.140     raeburn   205:     my $args = {'bread_crumbs' => $brcrum,};
                    206:     unless ((defined($form->{role})) || (defined($form->{symb}))) {
                    207:         my $update=$env{'user.update.time'};
                    208:         if (!$update) {
                    209:             $update = $env{'user.login.time'};
                    210:         }
                    211:         my %roles_in_env;
                    212:         my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
                    213:         if ($showcount == 1) {
                    214:             foreach my $rolecode (keys(%roles_in_env)) {
                    215:                 my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
                    216:                 if ($cid) {
                    217:                     my %coursedescription =
                    218:                         &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
                    219:                     if ($coursedescription{'type'} eq 'Placement') {
                    220:                         $args->{'crstype'} = 'Placement';
                    221:                     }
                    222:                     last;
                    223:                 }
                    224:             }
                    225:         }
                    226:     }
1.136     kruse     227: 
                    228: # ------------------------------------------------- Output for successful login
                    229: 
                    230:     &Apache::loncommon::content_type($r,'text/html');
1.143     raeburn   231:     if ($securecookie) {
                    232:         $r->headers_out->add('Set-cookie' => $securecookie);
                    233:     }
                    234:     if ($defaultcookie) {
                    235:         $r->headers_out->add('Set-cookie' => $defaultcookie);
                    236:     }
1.170     raeburn   237:     if ($expirepub) {
                    238:         my $c = new CGI::Cookie(-name    => 'lonPubID',
                    239:                                 -value   => '',
                    240:                                 -expires => '-10y',);
                    241:         $r->headers_out->add('Set-cookie' => $c);
                    242:     }
1.136     kruse     243:     $r->send_http_header;
                    244: 
1.153     raeburn   245:     my ($start_page,$js,$pagebody,$end_page);
1.151     raeburn   246:     if ($env{'request.lti.login'}) {
1.153     raeburn   247:         $args = {'only_body' => 1};
                    248:         if ($env{'request.lti.target'} eq '') {
                    249:             my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
                    250:                             'ltitarget=iframe';
                    251:             $js = <<"ENDJS";
                    252: 
                    253: <script type="text/javascript">
                    254: // <![CDATA[
                    255: function setLTItarget() {
                    256:     var newloc = '$destination';
                    257:     if (parent !== window) {
                    258:         newloc += '$ltitarget';
                    259:     }
                    260:     window.location.href=newloc;
                    261: }
                    262: // ]]>
                    263: </script>
                    264: 
                    265: ENDJS
                    266:             $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
                    267:             $pagebody =  '<noscript><span class="LC_warning">'
                    268:                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
                    269:                         .'</span></noscript>';
                    270:         } else {
                    271:             $args->{'redirect'} = [0,$destination,1];
                    272:         }
                    273:         $start_page=&Apache::loncommon::start_page('',$js,$args);
1.151     raeburn   274:     } else {
1.153     raeburn   275:         $args->{'redirect'} = [0,$destination];
1.151     raeburn   276:         $start_page=&Apache::loncommon::start_page('Successful Login',
1.153     raeburn   277:                                                    $js,$args);
1.149     raeburn   278: 
1.151     raeburn   279:         my %lt=&Apache::lonlocal::texthash(
                    280: 				           'wel' => 'Welcome',
                    281: 				           'pro' => 'Login problems?',
                    282: 				          );
                    283:         $pagebody = "<h1>$lt{'wel'}</h1>\n".
                    284:                     &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
                    285:         my $loginhelp = &loginhelpdisplay($domain);
                    286:         if ($loginhelp) {
                    287:             $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
                    288:         }
1.136     kruse     289:     }
1.153     raeburn   290:     $end_page = &Apache::loncommon::end_page();
1.136     kruse     291:     $r->print(<<ENDSUCCESS);
                    292: $start_page
                    293: $windowinfo
1.151     raeburn   294: $pagebody
1.136     kruse     295: $end_page
                    296: ENDSUCCESS
                    297:     return;
                    298: }
                    299: 
                    300: # --------------------------------------------------------------- Failed login!
                    301: 
                    302: sub failed {
1.171     raeburn   303:     my ($r,$message,$form,$authhost) = @_;
1.136     kruse     304:     (undef,undef,undef,my $clientmathml,my $clientunicode) =
                    305:         &Apache::loncommon::decode_user_agent();
                    306:     my $args = {};
                    307:     if ($clientunicode && !$clientmathml) {
                    308:         $args = {'browser.unicode' => 1};
                    309:     }
                    310: 
1.171     raeburn   311:     my @actions;
1.136     kruse     312:     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
                    313:     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
                    314:     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
                    315:     if (&Apache::lonnet::domain($udom,'description') eq '') {
                    316:         undef($udom);
                    317:     }
1.171     raeburn   318:     my $authtype;
                    319:     if (($udom ne '') && ($uname ne '') && ($authhost eq 'no_host')) {
                    320:         $authtype = &Apache::lonnet::queryauthenticate($uname,$udom);
                    321:     }
1.136     kruse     322:     my $retry = '/adm/login';
1.171     raeburn   323:     if (($uname eq $form->{'uname'}) && ($authtype !~ /^lti:/)) {
1.136     kruse     324:         $retry .= '?username='.$uname;
                    325:     }
                    326:     if ($udom) {
                    327:         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
                    328:     }
1.168     raeburn   329:     my $lonhost = $r->dir_config('lonHostID');
                    330:     my $querystr;
                    331:     my $result = &set_retry_token($form,$lonhost,\$querystr);
                    332:     if ($result eq 'fail') {
                    333:         if (exists($form->{role})) {
                    334:             my $role = &Apache::loncommon::cleanup_html($form->{role});
                    335:             if ($role ne '') {
                    336:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
                    337:             }
                    338:         }
                    339:         if (exists($form->{symb})) {
                    340:             my $symb = &Apache::loncommon::cleanup_html($form->{symb});
                    341:             if ($symb ne '') {
                    342:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
                    343:             }
                    344:         }
                    345:         if (exists($form->{firsturl})) {
                    346:             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
                    347:             if ($firsturl ne '') {
                    348:                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
                    349:                 if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
                    350:                     unless (exists($form->{linkprot})) {
                    351:                         if (exists($form->{linkkey})) {
                    352:                             $retry .= 'linkkey='.$form->{linkkey};
                    353:                         }
1.157     raeburn   354:                     }
                    355:                 }
                    356:             }
1.155     raeburn   357:         }
1.168     raeburn   358:         if (exists($form->{linkprot})) {
                    359:             my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
1.169     raeburn   360:                                                  $r->dir_config('lonHostID'),'retry');
1.168     raeburn   361:             if ($ltoken) {
                    362:                 $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
                    363:             }
1.156     raeburn   364:         }
1.168     raeburn   365:     } elsif ($querystr ne '') {
                    366:         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;
1.156     raeburn   367:     }
1.136     kruse     368:     my $end_page = &Apache::loncommon::end_page();
                    369:     &Apache::loncommon::content_type($r,'text/html');
                    370:     $r->send_http_header;
1.171     raeburn   371:     if ($authtype =~ /^lti:/) {
                    372:         $message = &mt('Direct login is not supported with the username you entered.').
                    373:                    '<br /><br />'.
                    374:                    &mt('You likely need to launch LON-CAPA from within a course in a different Learning Management System.').
                    375:                    '<br />'.
                    376:                    &mt('You can also try to log in with a different username.');
                    377:         @actions = 
                    378:             (&mt('Try your [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
                    379:     } else {
                    380:         $message = &mt($message);
                    381:         @actions =
                    382:             (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
                    383:     }
1.136     kruse     384:     my $loginhelp = &loginhelpdisplay($udom);
                    385:     if ($loginhelp) {
                    386:         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
                    387:     }
                    388:     #FIXME: link to helpdesk might be added here
                    389:     $r->print(
                    390:        $start_page
                    391:       .'<h2>'.&mt('Sorry ...').'</h2>'
1.171     raeburn   392:       .&Apache::lonhtmlcommon::confirm_success($message,1).'<br /><br />'
1.136     kruse     393:       .&Apache::lonhtmlcommon::actionbox(\@actions)
                    394:       .$end_page
                    395:     );
                    396:  }
                    397: 
                    398: # ------------------------------------------------------------------ Rerouting!
                    399: 
                    400: sub reroute {
                    401:     my ($r) = @_;
                    402:     &Apache::loncommon::content_type($r,'text/html');
                    403:     $r->send_http_header;
                    404:     my $msg='<b>'.&mt('Sorry ...').'</b><br />'
                    405:            .&mt('Please [_1]log in again[_2].');
                    406:     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
                    407: }
                    408: 
                    409: # ---------------------------------------------------------------- Main handler
                    410: 
                    411: sub handler {
                    412:     my $r = shift;
                    413:     my $londocroot = $r->dir_config('lonDocRoot');
                    414: # Are we re-routing?
                    415:     if (-e "$londocroot/lon-status/reroute.txt") {
                    416: 	&reroute($r);
                    417: 	return OK;
                    418:     }
                    419: 
                    420:     &Apache::lonlocal::get_language_handle($r);
                    421: 
                    422: # -------------------------------- Prevent users from attempting to login twice
                    423:     my $handle = &Apache::lonnet::check_for_valid_session($r);
                    424:     if ($handle ne '') {
                    425:         my $lonidsdir=$r->dir_config('lonIDsDir');
                    426:         if ($handle=~/^publicuser\_/) {
                    427: # For "public user" - remove it, we apparently really want to login
                    428:             unlink($r->dir_config('lonIDsDir')."/$handle.id");
                    429:         } else {
                    430: # Indeed, a valid token is found
                    431:             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
                    432: 	    &Apache::loncommon::content_type($r,'text/html');
                    433: 	    $r->send_http_header;
1.166     raeburn   434: 	    my $start_page =
1.136     kruse     435: 	        &Apache::loncommon::start_page('Already logged in');
                    436: 	    my $end_page = 
                    437: 	        &Apache::loncommon::end_page();
                    438:             my $dest = '/adm/roles';
1.169     raeburn   439:             my %form = &get_form_items($r);
                    440:             if ($form{'logtoken'}) {
                    441:                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
                    442:                                                      $form{'serverid'});
                    443:                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
                    444:                         ($tmpinfo eq 'no_such_host')) {
                    445:                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
                    446:                     $firsturl = &unescape($firsturl);
                    447:                     my %info;
                    448:                     foreach my $item (@rest) {
                    449:                         my ($key,$value) = split(/=/,$item);
                    450:                         $info{$key} = &unescape($value);
                    451:                     }
                    452:                     if ($firsturl ne '') {
                    453:                         $info{'firsturl'} = $firsturl;
                    454:                         $dest = $firsturl;
                    455:                         my $relogin;
                    456:                         if ($dest =~ m{^/tiny/$match_domain/\w+$}) {
                    457:                             if ($env{'request.course.id'}) {
                    458:                                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    459:                                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    460:                                 my $symb = &Apache::loncommon::symb_from_tinyurl($dest,$cnum,$cdom);
                    461:                                 if ($symb) {
                    462:                                     unless (&set_deeplink_login(%info) eq 'ok') {
                    463:                                         $relogin = 1;
                    464:                                     }
                    465:                                 }
                    466:                             }
                    467:                             if ($relogin) {
                    468:                                 $r->print(
                    469:                                       $start_page
                    470:                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
                    471:                                      .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',
                    472:                                                 '<a href="/adm/logout">','</a>')
                    473:                                      .'</p>'
                    474:                                      .$end_page);
                    475:                             } else {
                    476:                                 if (($info{'linkprot'}) || ($info{'linkkey'} ne '')) {
                    477:                                     my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
                    478:                                     unless (($token eq 'con_lost') || ($token eq 'refused') ||
                    479:                                             ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
                    480:                                         $dest .= (($dest =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
                    481:                                     }
                    482:                                 }
                    483:                                 $r->print(
                    484:                                       $start_page
                    485:                                      .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
                    486:                                      .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4] first, and then try your access again',
                    487:                                                 '<a href="'.$dest.'">','</a>',
                    488:                                                 '<a href="/adm/logout">','</a>')
                    489:                                      .'</p>'
                    490:                                      .$end_page);
                    491:                             }
                    492:                             return OK;
1.164     raeburn   493:                         }
                    494:                     }
1.157     raeburn   495:                 }
1.136     kruse     496:             }
                    497:             $r->print(
1.169     raeburn   498:                   $start_page
                    499:                  .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
                    500:                  .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
                    501:                           ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
                    502:                  .'</p>'
                    503:                  .$end_page
1.136     kruse     504:             );
                    505:             return OK;
                    506:         }
                    507:     }
                    508: 
                    509: # ---------------------------------------------------- No valid token, continue
                    510: 
1.169     raeburn   511:     my %form = &get_form_items($r);
1.136     kruse     512:     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
                    513: 	&failed($r,'Username, password and domain need to be specified.',
                    514: 		\%form);
                    515:         return OK;
                    516:     }
                    517: 
                    518: # split user logging in and "su"-user
                    519: 
1.145     raeburn   520:     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
1.136     kruse     521:     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
                    522:     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
1.145     raeburn   523:     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
                    524:     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
1.136     kruse     525: 
                    526:     my $role   = $r->dir_config('lonRole');
                    527:     my $domain = $r->dir_config('lonDefDomain');
                    528:     my $prodir = $r->dir_config('lonUsersDir');
                    529:     my $contact_name = &mt('LON-CAPA helpdesk');
                    530: 
                    531: # ---------------------------------------- Get the information from login token
                    532: 
                    533:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
                    534:                                       $form{'serverid'});
                    535: 
                    536:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') || 
                    537:         ($tmpinfo eq 'no_such_host')) {
                    538: 	&failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
                    539:         return OK;
                    540:     } else {
                    541: 	my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
                    542: 					   $form{'serverid'});
                    543:         if ( $reply ne 'ok' ) {
                    544:             &failed($r,'Session could not be opened.',\%form);
                    545: 	    &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
                    546: 	    return OK;
                    547: 	}
                    548:     }
                    549: 
                    550:     if (!&Apache::lonnet::domain($form{'udom'})) {
                    551:         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
                    552:         return OK;
                    553:     }
                    554: 
1.169     raeburn   555:     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
                    556:     $firsturl = &unescape($firsturl);
1.168     raeburn   557:     foreach my $item (@rest) {
                    558:         my ($key,$value) = split(/=/,$item);
                    559:         $form{$key} = &unescape($value);
1.156     raeburn   560:     }
1.155     raeburn   561:     if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
                    562:         $form{'firsturl'} = $firsturl;
                    563:     }
1.139     raeburn   564:     my $upass = $ENV{HTTPS} ? $form{'upass0'} 
1.169     raeburn   565:         : &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});
1.136     kruse     566: 
                    567: # ---------------------------------------------------------------- Authenticate
                    568: 
                    569:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
                    570:     my ($cancreate,$statustocreate) =
                    571:         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
                    572:     my $defaultauth;
                    573:     if (ref($cancreate) eq 'ARRAY') {
                    574:         if (grep(/^login$/,@{$cancreate})) {
                    575:             $defaultauth = 1;
                    576:         }
                    577:     }
                    578:     my $clientcancheckhost = 1;
                    579:     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
                    580:                                               $form{'udom'},$defaultauth,
                    581:                                               $clientcancheckhost);
1.149     raeburn   582: 
1.136     kruse     583: # --------------------------------------------------------------------- Failed?
                    584: 
                    585:     if ($authhost eq 'no_host') {
1.172   ! raeburn   586:         my $pwdverify;
        !           587:         if (&Apache::lonnet::homeserver($form{'uname'},$form{'udom'}) eq 'no_host') {
        !           588:             my %possunames = &alternate_unames_check($form{'uname'},$form{'udom'});
        !           589:             if (keys(%possunames) > 0) {
        !           590:                 foreach my $rulematch (keys(%possunames)) {
        !           591:                     my $possuname = $possunames{$rulematch};
        !           592:                     if (($possuname ne '') && ($possuname =~ /^$match_username$/)) {
        !           593:                         $authhost=Apache::lonnet::authenticate($possuname,$upass,
        !           594:                                                                $form{'udom'},undef,
        !           595:                                                                $clientcancheckhost);
        !           596:                         if (($authhost eq 'no_host') || ($authhost eq 'no_account_on_host')) {
        !           597:                             next;
        !           598:                         } elsif (($authhost ne '') && (&Apache::lonnet::hostname($authhost) ne '')) {
        !           599:                             $pwdverify = 1;
        !           600:                             &Apache::lonnet::logthis("Authenticated user: $possuname was submitted as: $form{'uname'}"); 
        !           601:                             $form{'uname'} = $possuname;
        !           602:                             last;
        !           603:                         }
        !           604:                     }
        !           605:                 }
        !           606:             }
        !           607:         }
        !           608:         unless ($pwdverify) {
        !           609:             &failed($r,'Username and/or password could not be authenticated.',
        !           610:                     \%form,$authhost);
        !           611:             return OK;
        !           612:         }
1.136     kruse     613:     } elsif ($authhost eq 'no_account_on_host') {
                    614:         if ($defaultauth) {
                    615:             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
                    616:             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
                    617:                 return OK;
                    618:             }
                    619:             my $start_page = 
1.168     raeburn   620:                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',
                    621:                                                '',{'no_inline_link'   => 1,});
1.136     kruse     622:             my $lonhost = $r->dir_config('lonHostID');
                    623:             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                    624:             my $contacts = 
                    625:                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                    626:                                                         $form{'udom'},$origmail);
                    627:             my ($contact_email) = split(',',$contacts); 
                    628:             my $output = 
                    629:                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
                    630:                                                        $domdesc,'',$lonhost,
                    631:                                                        $contact_email,$contact_name,
                    632:                                                        undef,$statustocreate);
                    633:             &Apache::loncommon::content_type($r,'text/html');
                    634:             $r->send_http_header;
                    635:             &Apache::createaccount::print_header($r,$start_page);
                    636:             $r->print('<h3>'.&mt('Account creation').'</h3>'.
                    637:                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
                    638:                       $output.&Apache::loncommon::end_page());
                    639:             return OK;
                    640:         } else {
                    641:             &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);
                    642:             return OK;
                    643:         }
                    644:     }
                    645: 
                    646:     if (($firsturl eq '') || 
                    647: 	($firsturl=~/^\/adm\/(logout|remote)/)) {
                    648: 	$firsturl='/adm/roles';
                    649:     }
                    650: 
1.169     raeburn   651:     my ($hosthere,%sessiondata);
1.136     kruse     652:     if ($form{'iptoken'}) {
1.169     raeburn   653:         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
1.138     raeburn   654:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
1.136     kruse     655:         if (($sessiondata{'domain'} eq $form{'udom'}) &&
                    656:             ($sessiondata{'username'} eq $form{'uname'})) {
                    657:             $hosthere = 1;
                    658:         }
                    659:     }
                    660: 
                    661: # --------------------------------- Are we attempting to login as somebody else?
                    662:     if ($form{'suname'}) {
1.145     raeburn   663:         my ($suname,$sudom,$sudomref);
                    664:         $suname = $form{'suname'};
                    665:         $sudom = $form{'udom'};
                    666:         if ($form{'sudom'}) {
                    667:             unless ($sudom eq $form{'sudom'}) {
                    668:                 if (&Apache::lonnet::domain($form{'sudom'})) {
                    669:                     $sudomref = [$form{'sudom'}];
                    670:                     $sudom = $form{'sudom'};
                    671:                 }
                    672:             }
                    673:         }
1.136     kruse     674: # ------------ see if the original user has enough privileges to pull this stunt
1.145     raeburn   675: 	if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
1.136     kruse     676: # ---------------------------------------------------- see if the su-user exists
1.145     raeburn   677: 	    unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
1.136     kruse     678: # ------------------------------ see if the su-user is not too highly privileged
1.146     raeburn   679: 		if (&Apache::lonnet::privileged($suname,$sudom)) {
                    680:                     &Apache::lonnet::logthis('Attempted switch user to privileged user');
                    681:                 } else {
                    682:                     my $noprivswitch;
1.145     raeburn   683: #
                    684: # su-user's home server and user's home server must have one of:
1.147     raeburn   685: # (a) same domain
                    686: # (b) same primary library server for the two domains
                    687: # (c) same "internet domain" for primary library server(s) for home servers' domains
1.145     raeburn   688: #
1.148     raeburn   689:                     my $suprim = &Apache::lonnet::domain($sudom,'primary');
                    690:                     my $suintdom = &Apache::lonnet::internet_dom($suprim);
1.145     raeburn   691:                     unless ($sudom eq $form{'udom'}) {
1.148     raeburn   692:                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
                    693:                         my $uintdom = &Apache::lonnet::internet_dom($uprim);
1.145     raeburn   694:                         unless ($suprim eq $uprim) {
                    695:                             unless ($suintdom eq $uintdom) {
                    696:                                 &Apache::lonnet::logthis('Attempted switch user '
1.169     raeburn   697:                                    .'to user with different "internet domain".');
1.146     raeburn   698:                                 $noprivswitch = 1;
1.145     raeburn   699:                             }
                    700:                         }
                    701:                     }
                    702: 
1.146     raeburn   703:                     unless ($noprivswitch) {
                    704: #
                    705: # server where log-in occurs must have same "internet domain" as su-user's home
                    706: # server
                    707: #
                    708:                         my $lonhost = $r->dir_config('lonHostID');
                    709:                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
1.148     raeburn   710:                         if ($hostintdom ne $suintdom) {
1.146     raeburn   711:                             &Apache::lonnet::logthis('Attempted switch user on a '
                    712:                                 .'server with a different "internet domain".'); 
                    713:                         } else {
                    714: 
1.136     kruse     715: # -------------------------------------------------------- actually switch users
1.145     raeburn   716: 
1.146     raeburn   717: 		            &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
                    718:                               $form{'udom'}.' logging in as '.$suname.':'.$sudom);
                    719: 		            $form{'uname'}=$suname;
                    720:                             if ($form{'udom'} ne $sudom) {
                    721:                                 $form{'udom'}=$sudom;
                    722:                             }
                    723:                         }
1.145     raeburn   724:                     }
1.136     kruse     725: 		}
                    726: 	    }
                    727: 	} else {
                    728: 	    &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                    729: 	}
                    730:     }
                    731: 
                    732:     my ($is_balancer,$otherserver);
                    733: 
                    734:     unless ($hosthere) {
                    735:         ($is_balancer,$otherserver) =
1.141     raeburn   736:             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
                    737:         if ($is_balancer) {
1.161     raeburn   738:             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
                    739:             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
                    740:             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
                    741:                 $otherserver = $found_server;
                    742:             }
1.141     raeburn   743:             if ($otherserver eq '') {
                    744:                 my $lowest_load;
                    745:                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
                    746:                 if ($lowest_load > 100) {
1.163     raeburn   747:                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
1.141     raeburn   748:                 }
                    749:             }
                    750:             if ($otherserver ne '') {
                    751:                 my @hosts = &Apache::lonnet::current_machine_ids();
                    752:                 if (grep(/^\Q$otherserver\E$/,@hosts)) {
                    753:                     $hosthere = $otherserver;
                    754:                 }
                    755:             }
                    756:         }
1.136     kruse     757:     }
                    758: 
1.141     raeburn   759:     if (($is_balancer) && (!$hosthere)) {
1.136     kruse     760:         if ($otherserver) {
                    761:             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                    762:                      \%form);
                    763:             my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                    764:             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
1.168     raeburn   765:                 $switchto .= '&origurl='.$firsturl;
1.136     kruse     766:             }
                    767:             if ($form{'role'}) {
                    768:                 $switchto .= '&role='.$form{'role'};
                    769:             }
                    770:             if ($form{'symb'}) {
                    771:                 $switchto .= '&symb='.$form{'symb'};
                    772:             }
1.156     raeburn   773:             if ($form{'linkprot'}) {
                    774:                 $env{'request.linkprot'} = $form{'linkprot'};
1.167     raeburn   775:             } elsif ($form{'linkkey'} ne '') {
1.164     raeburn   776:                 $env{'request.linkkey'} = $form{'linkkey'};
                    777:             }
                    778:             if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                    779:                 &set_deeplink_login(%form);
1.156     raeburn   780:             }
1.136     kruse     781:             $r->internal_redirect($switchto);
                    782:         } else {
1.160     raeburn   783:             &Apache::loncommon::content_type($r,'text/html');
                    784:             $r->send_http_header;
1.136     kruse     785:             $r->print(&noswitch());
                    786:         }
                    787:         return OK;
                    788:     } else {
                    789:         if (!&check_can_host($r,\%form,$authhost)) {
                    790:             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
                    791:             if ($otherserver) {
                    792:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                    793:                          \%form);
                    794:                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                    795:                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
1.168     raeburn   796:                     $switchto .= '&origurl='.$firsturl;
1.136     kruse     797:                 }
                    798:                 if ($form{'role'}) {
                    799:                     $switchto .= '&role='.$form{'role'};
                    800:                 }
                    801:                 if ($form{'symb'}) {
                    802:                     $switchto .= '&symb='.$form{'symb'};
                    803:                 }
1.156     raeburn   804:                 if ($form{'linkprot'}) {
                    805:                     $env{'request.linkprot'} = $form{'linkprot'};
1.167     raeburn   806:                 } elsif ($form{'linkkey'} ne '') {
1.164     raeburn   807:                     $env{'request.linkkey'} = $form{'linkkey'};
                    808:                 }
                    809:                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                    810:                     &set_deeplink_login(%form);
1.156     raeburn   811:                 }
1.136     kruse     812:                 $r->internal_redirect($switchto);
                    813:             } else {
1.160     raeburn   814:                 &Apache::loncommon::content_type($r,'text/html');
                    815:                 $r->send_http_header;
1.136     kruse     816:                 $r->print(&noswitch());
                    817:             }
                    818:             return OK;
                    819:         }
                    820: 
                    821: # ------------------------------------------------------- Do the load balancing
                    822: 
                    823: # ---------------------------------------------------------- Determine own load
                    824:         my $loadlim = $r->dir_config('lonLoadLim');
                    825:         my $loadavg;
                    826:         {
                    827:             my $loadfile=Apache::File->new('/proc/loadavg');
                    828:             $loadavg=<$loadfile>;
                    829:         }
                    830:         $loadavg =~ s/\s.*//g;
                    831:         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
                    832:         my $userloadpercent=&Apache::lonnet::userload();
                    833: 
                    834: # ---------------------------------------------------------- Are we overloaded?
                    835:         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
1.163     raeburn   836:             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});
1.136     kruse     837:             if (!$unloaded) {
                    838:                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
                    839:             }
                    840:             if ($unloaded) {
                    841:                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                    842:                          undef,\%form);
1.156     raeburn   843:                 if ($form{'linkprot'}) {
                    844:                     $env{'request.linkprot'} = $form{'linkprot'};
1.167     raeburn   845:                 } elsif ($form{'linkkey'} ne '') {
1.164     raeburn   846:                     $env{'request.linkkey'} = $form{'linkkey'};
                    847:                 }
                    848:                 if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                    849:                     &set_deeplink_login(%form);
1.156     raeburn   850:                 }
1.136     kruse     851:                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                    852:                 return OK;
                    853:             }
                    854:         }
1.141     raeburn   855:         if (($is_balancer) && ($hosthere)) {
                    856:             $form{'noloadbalance'} = $hosthere;
                    857:         }
1.156     raeburn   858:         my $extra_env;
1.169     raeburn   859:         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {
                    860:             if ($sessiondata{'origurl'} ne '') {
                    861:                 $firsturl = $sessiondata{'origurl'};
                    862:                 $form{'firsturl'} = $sessiondata{'origurl'};
                    863:                 my @names = ('role','symb','linkprot','linkkey');
                    864:                 foreach my $item (@names) {
                    865:                     if ($sessiondata{$item} ne '') {
                    866:                         $form{$item} = $sessiondata{$item};
                    867:                     }
                    868:                 }
                    869:             }
                    870:         }
1.156     raeburn   871:         if ($form{'linkprot'}) {
                    872:             my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
                    873:             if ($linkprotector) {
                    874:                 $extra_env = {'user.linkprotector' => $linkprotector,
1.164     raeburn   875:                               'user.linkproturi'   => $uri};
1.156     raeburn   876:             }
1.167     raeburn   877:         } elsif ($form{'linkkey'} ne '') {
1.166     raeburn   878:             $extra_env = {'user.deeplinkkey'  => $form{'linkkey'},
1.164     raeburn   879:                           'user.keyedlinkuri' => $form{'firsturl'}};
                    880:         }
                    881:         if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                    882:             &set_deeplink_login(%form);
1.166     raeburn   883:             if ($form{'linkprot'}) {
                    884:                 if (ref($extra_env) eq 'HASH') {
                    885:                     %{$extra_env} = ( %{$extra_env}, 'request.linkprot' => $form{'linkprot'} );
                    886:                 } else {
                    887:                     $extra_env = {'request.linkprot' => $form{'linkprot'}};
                    888:                 }
1.167     raeburn   889:             } elsif ($form{'linkkey'} ne '') {
1.166     raeburn   890:                 if (ref($extra_env) eq 'HASH') {
                    891:                     %{$extra_env} = ( %{$extra_env}, 'request.linkkey' => $form{'linkkey'} );
                    892:                 } else {
                    893:                     $extra_env = {'request.linkkey' => $form{'linkkey'}};
                    894:                 }
                    895:             }
1.164     raeburn   896:             if ($env{'request.deeplink.login'}) {
                    897:                 if (ref($extra_env) eq 'HASH') {
                    898:                     %{$extra_env} = ( %{$extra_env}, 'request.deeplink.login' => $form{'firsturl'} );
                    899:                 } else {
                    900:                     $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
                    901:                 }
1.157     raeburn   902:             }
1.156     raeburn   903:         }
                    904:         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
1.136     kruse     905:                  \%form);
                    906:         return OK;
                    907:     }
                    908: }
                    909: 
1.169     raeburn   910: sub get_form_items {
                    911:     my ($r) = @_;
                    912:     my $buffer;
                    913:     if ($r->header_in('Content-length') > 0) {
                    914:         $r->read($buffer,$r->header_in('Content-length'),0);
                    915:     }
                    916:     my %form;
                    917:     foreach my $pair (split(/&/,$buffer)) {
                    918:        my ($name,$value) = split(/=/,$pair);
                    919:        $value =~ tr/+/ /;
                    920:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                    921:        $form{$name}=$value;
                    922:     }
                    923:     return %form;
                    924: }
                    925: 
1.164     raeburn   926: sub set_deeplink_login {
                    927:     my (%form) = @_;
1.169     raeburn   928:     my $disallow;
1.164     raeburn   929:     if ($form{'firsturl'} =~ m{^/tiny/($match_domain)/\w+$}) {
                    930:         my $cdom = $1;
                    931:         my ($cnum,$symb) = &Apache::loncommon::symb_from_tinyurl($form{'firsturl'},'',$cdom);
                    932:         if ($symb) {
1.166     raeburn   933:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
1.169     raeburn   934:                 my $deeplink;
1.166     raeburn   935:                 if ($symb =~ /\.(page|sequence)$/) {
                    936:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($symb))[2]);
                    937:                     my $navmap = Apache::lonnavmaps::navmap->new();
                    938:                     if (ref($navmap)) {
                    939:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                    940:                     }
                    941:                 } else {
                    942:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                    943:                 }
                    944:                 if ($deeplink ne '') {
                    945:                     my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                    946:                     if (($protect ne 'none') && ($protect ne '')) {
                    947:                         my ($acctype,$item) = split(/:/,$protect);
                    948:                         if ($acctype =~ /lti(c|d)$/) {
                    949:                             unless ($form{'linkprot'} eq $item.$1.':'.$env{'request.deeplink.login'}) {
                    950:                                 $disallow = 1;
                    951:                             }
                    952:                         } elsif ($acctype eq 'key') {
                    953:                             unless ($form{'linkkey'} eq $item) {
                    954:                                 $disallow = 1;
                    955:                             }
1.164     raeburn   956:                         }
                    957:                     }
                    958:                 }
1.166     raeburn   959:                 unless ($disallow) {
                    960:                     $env{'request.deeplink.login'} = $form{'firsturl'};
                    961:                 }
                    962:             } else {
1.164     raeburn   963:                 $env{'request.deeplink.login'} = $form{'firsturl'};
                    964:             }
                    965:         }
                    966:     }
1.169     raeburn   967:     if ($disallow) {
                    968:         return;
                    969:     }
                    970:     return 'ok';
1.164     raeburn   971: }
                    972: 
1.168     raeburn   973: sub set_retry_token {
                    974:     my ($form,$lonhost,$querystr) = @_;
                    975:     if (ref($form) eq 'HASH') {
                    976:         my ($firsturl,$token,$extras,@names);
1.169     raeburn   977:         @names = ('role','symb','linkprot','linkkey','iptoken');
1.168     raeburn   978:         foreach my $name (@names) {
                    979:             if ($form->{$name} ne '') {
                    980:                 $extras .= '&'.$name.'='.&escape($form->{$name});
                    981:                 last if ($name eq 'linkprot');
                    982:             }
                    983:         }
                    984:         my $firsturl = $form->{'firsturl'};
                    985:         if (($firsturl ne '') || ($extras ne '')) {
                    986:             $extras .= ':retry';
                    987:             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).
                    988:                                             $extras,$lonhost);
                    989:             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {
                    990:                 return 'fail';
                    991:             } else {
                    992:                 if (ref($querystr)) {
                    993:                     $$querystr = 'retry='.$token;
                    994:                 }
                    995:                 return 'ok';
                    996:             }
                    997:         }
                    998:     }
                    999:     return;
                   1000: }
                   1001: 
1.136     kruse    1002: sub check_can_host {
                   1003:     my ($r,$form,$authhost,$domdesc) = @_;
                   1004:     return unless (ref($form) eq 'HASH');
                   1005:     my $canhost = 1;
                   1006:     my $lonhost = $r->dir_config('lonHostID');
                   1007:     my $udom = $form->{'udom'};
                   1008:     my @intdoms;
                   1009:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   1010:     if (ref($internet_names) eq 'ARRAY') {
                   1011:         @intdoms = @{$internet_names};
                   1012:     }
                   1013:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1014:     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                   1015:     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1016:         my $machine_dom = &Apache::lonnet::host_domain($lonhost);
                   1017:         my $hostname = &Apache::lonnet::hostname($lonhost);
                   1018:         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   1019:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1020:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1021:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                   1022:         my $loncaparev;
                   1023:         if ($authhost eq 'no_account_on_host') {
                   1024:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
                   1025:         } else {
                   1026:             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
                   1027:         }
                   1028:         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
                   1029:                                                      $udomdefaults{'remotesessions'},
                   1030:                                                      $defdomdefaults{'hostedsessions'});
                   1031:     }
                   1032:     unless ($canhost) {
                   1033:         if ($authhost eq 'no_account_on_host') {
                   1034:             my $checkloginvia = 1;
                   1035:             my ($login_host,$hostname) = 
                   1036:                 &Apache::lonnet::choose_server($udom,$checkloginvia);
                   1037:             &Apache::loncommon::content_type($r,'text/html');
                   1038:             $r->send_http_header;
                   1039:             if ($login_host ne '') {
                   1040:                 my $protocol = $Apache::lonnet::protocol{$login_host};
                   1041:                 $protocol = 'http' if ($protocol ne 'https');
1.163     raeburn  1042:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);
                   1043:                 $hostname = $alias if ($alias ne '');
1.136     kruse    1044:                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
1.156     raeburn  1045: #FIXME Should preserve where user was going and linkprot by setting ltoken at $login_host
1.136     kruse    1046:                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                   1047:                           '<h3>'.&mt('Account creation').'</h3>'.
                   1048:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                   1049:                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                   1050:                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                   1051:                           &Apache::loncommon::end_page());
                   1052:             } else {
                   1053:                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                   1054:                           '<h3>'.&mt('Account creation unavailable').'</h3>'.
                   1055:                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                   1056:                           '<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>'.
                   1057:                           &Apache::loncommon::end_page());
                   1058:             }
                   1059:         } else {
                   1060:             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                   1061:                      $form);
1.168     raeburn  1062:             if ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                   1063:                 $env{'request.deeplink.login'} = $form->{'firsturl'};
                   1064:             }
1.156     raeburn  1065:             if ($form->{'linkprot'}) {
                   1066:                 $env{'request.linkprot'} = $form->{'linkprot'};
1.168     raeburn  1067:             } elsif ($form->{'linkkey'} ne '') {
                   1068:                 $env{'request.linkkey'} = $form->{'linkkey'};
1.156     raeburn  1069:             }
1.136     kruse    1070:             my ($otherserver) = &Apache::lonnet::choose_server($udom);
                   1071:             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
                   1072:         }
                   1073:     }
                   1074:     return $canhost;
                   1075: }
                   1076: 
                   1077: sub noswitch {
                   1078:     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                   1079:                  '<h3>'.&mt('Session unavailable').'</h3>'.
                   1080:                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.
                   1081:                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                   1082:                  &Apache::loncommon::end_page();
                   1083:     return $result;
                   1084: }
                   1085: 
                   1086: sub loginhelpdisplay {
                   1087:     my ($authdomain) = @_;
                   1088:     my $login_help = 1;
                   1089:     my $lang = &Apache::lonlocal::current_language();
                   1090:     if ($login_help) {
                   1091:         my $dom = $authdomain;
                   1092:         if ($dom eq '') {
                   1093:             $dom = &Apache::lonnet::default_login_domain();
                   1094:         }
                   1095:         my %domconfhash = &Apache::loncommon::get_domainconf($dom);
                   1096:         my $loginhelp_url;
                   1097:         if ($lang) {
                   1098:             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
                   1099:             if ($loginhelp_url ne '') {
                   1100:                 return $loginhelp_url;
                   1101:             }
                   1102:         }
                   1103:         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
                   1104:         if ($loginhelp_url ne '') {
                   1105:             return $loginhelp_url;
                   1106:         } else {
                   1107:             return '/adm/loginproblems.html';
                   1108:         }
                   1109:     }
                   1110:     return;
                   1111: }
                   1112: 
1.172   ! raeburn  1113: sub alternate_unames_check {
        !          1114:     my ($uname,$udom) = @_;
        !          1115:     my %possunames;
        !          1116:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
        !          1117:     if (ref($domdefs{'unamemap_rule'}) eq 'ARRAY') { 
        !          1118:         if (@{$domdefs{'unamemap_rule'}} > 0) {
        !          1119:             %possunames =
        !          1120:                 &Apache::lonnet::inst_rulecheck($udom,$uname,undef,
        !          1121:                                                 'unamemap',$domdefs{'unamemap_rule'});
        !          1122:         }
        !          1123:     }
        !          1124:     return %possunames;
        !          1125: }
        !          1126: 
1.136     kruse    1127: 1;
                   1128: __END__
                   1129: 
                   1130: 

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