1: # The LearningOnline Network
2: # User Authentication Module
3: #
4: # $Id: lonauth.pm,v 1.121.2.24.2.2 2022/02/24 14:42:30 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::lonauth;
30:
31: use strict;
32: use LONCAPA qw(:DEFAULT :match);
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;
39: use Fcntl qw(:flock);
40: use Apache::lonlocal;
41: use Apache::File();
42: use HTML::Entities;
43: use Digest::MD5;
44: use CGI::Cookie();
45:
46: # ------------------------------------------------------------ Successful login
47: sub success {
48: my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
49: $form,$cid,$expirepub) = @_;
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: my $ip = &Apache::lonnet::get_requestor_ip();
64: &Apache::lonnet::log($domain,$username,$authhost,
65: "Login $ip");
66:
67: # ------------------------------------------------- Check for critical messages
68:
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: }
74: }
75:
76: # ------------------------------------------------------------ Get cookies ready
77: my ($securecookie,$defaultcookie);
78: my $ssl = $r->subprocess_env('https');
79: if ($ssl) {
80: $securecookie="lonSID=$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' => $linkname});
92: }
93: }
94: } else {
95: $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
96: }
97: # -------------------------------------------------------- Menu script and info
98: my $destination = $lowerurl;
99:
100: if (defined($form->{role})) {
101: my $envkey = 'user.role.'.$form->{role};
102: my $now=time;
103: my $then=$env{'user.login.time'};
104: my $refresh=$env{'user.refresh.time'};
105: my $update=$env{'user.update.time'};
106: if (!$update) {
107: $update = $then;
108: }
109: if (exists($env{$envkey})) {
110: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
111: &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
112: \$trolecode,\$tstatus,\$tstart,\$tend);
113: if ($tstatus eq 'is') {
114: $destination .= ($destination =~ /\?/) ? '&' : '?';
115: my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
116: $destination .= 'selectrole=1&'.$newrole.'=1';
117: }
118: }
119: }
120: if (defined($form->{symb})) {
121: my $destsymb = $form->{symb};
122: my $encrypted;
123: if ($destsymb =~ m{^/enc/}) {
124: $encrypted = 1;
125: if ($cid) {
126: $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
127: }
128: }
129: $destination .= ($destination =~ /\?/) ? '&' : '?';
130: if ($destsymb =~ /___/) {
131: my ($map,$resid,$desturl)=split(/___/,$destsymb);
132: $desturl = &Apache::lonnet::clutter($desturl);
133: if ($encrypted) {
134: $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
135: $destsymb = $form->{symb};
136: }
137: $desturl = &HTML::Entities::encode($desturl,'"<>&');
138: $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
139: $destination .= 'destinationurl='.$desturl.
140: '&destsymb='.$destsymb;
141: } elsif (!$encrypted) {
142: $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
143: $destination .= 'destinationurl='.$destsymb;
144: }
145: }
146: if ($destination =~ m{^/adm/roles}) {
147: $destination .= ($destination =~ /\?/) ? '&' : '?';
148: $destination .= 'source=login';
149: }
150:
151: if (($env{'request.deeplink.login'} eq $lowerurl) &&
152: (($env{'request.linkprot'}) || ($env{'request.linkkey'} ne ''))) {
153: my %info;
154: if ($env{'request.linkprot'}) {
155: $info{'linkprot'} = $env{'request.linkprot'};
156: } elsif ($env{'request.linkkey'} ne '') {
157: $info{'linkkey'} = $env{'request.linkkey'};
158: }
159: $info{'origurl'} = $lowerurl;
160: my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
161: unless (($token eq 'con_lost') || ($token eq 'refused') ||
162: ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
163: $destination .= (($destination =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
164: }
165: }
166: if ($env{'request.deeplink.login'}) {
167: if ($env{'environment.remote'} eq 'on') {
168: &Apache::lonnet::appenv({'environment.remote' => 'off'});
169: }
170: }
171:
172: my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});
173: my $startupremote=&Apache::lonmenu::startupremote($destination);
174: my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
175: my $setflags=&Apache::lonmenu::setflags();
176: my $maincall=&Apache::lonmenu::maincall();
177: my $brcrum = [{'href' => '',
178: 'text' => 'Successful Login'},];
179: my $start_page=&Apache::loncommon::start_page('Successful Login',
180: $startupremote,
181: {'no_inline_link' => 1,
182: 'bread_crumbs' => $brcrum,});
183: my $end_page =&Apache::loncommon::end_page();
184:
185: my $continuelink;
186: if ($env{'environment.remote'} eq 'off') {
187: $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
188: }
189: # ------------------------------------------------- Output for successful login
190:
191: &Apache::loncommon::content_type($r,'text/html');
192: if ($securecookie) {
193: $r->headers_out->add('Set-cookie' => $securecookie);
194: }
195: if ($defaultcookie) {
196: $r->headers_out->add('Set-cookie' => $defaultcookie);
197: }
198: if ($expirepub) {
199: my $c = new CGI::Cookie(-name => 'lonPubID',
200: -value => '',
201: -expires => '-10y',);
202: $r->headers_out->add('Set-cookie' => $c);
203: }
204: $r->send_http_header;
205:
206: my %lt=&Apache::lonlocal::texthash(
207: 'wel' => 'Welcome',
208: 'pro' => 'Login problems?',
209: );
210: my $loginhelp = &loginhelpdisplay($domain);
211: if ($loginhelp) {
212: $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
213: }
214:
215: my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
216: $r->print(<<ENDSUCCESS);
217: $start_page
218: $setflags
219: $windowinfo
220: <h1>$lt{'wel'}</h1>
221: $welcome
222: $loginhelp
223: $remoteinfo
224: $maincall
225: $continuelink
226: $end_page
227: ENDSUCCESS
228: return;
229: }
230:
231: # --------------------------------------------------------------- Failed login!
232:
233: sub failed {
234: my ($r,$message,$form,$authhost) = @_;
235: (undef,undef,undef,my $clientmathml,my $clientunicode) =
236: &Apache::loncommon::decode_user_agent();
237: my $args = {};
238: if ($clientunicode && !$clientmathml) {
239: $args = {'browser.unicode' => 1};
240: }
241:
242: my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
243: my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
244: my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
245: if (&Apache::lonnet::domain($udom,'description') eq '') {
246: undef($udom);
247: }
248: my $retry = '/adm/login';
249: if ($uname eq $form->{'uname'}) {
250: $retry .= '?username='.$uname;
251: }
252: if ($udom) {
253: $retry .= (($retry=~/\?/)?'&':'?').'domain='.$udom;
254: }
255: my $lonhost = $r->dir_config('lonHostID');
256: my $querystr;
257: my $result = &set_retry_token($form,$lonhost,\$querystr);
258: if ($result eq 'fail') {
259: if (exists($form->{role})) {
260: my $role = &Apache::loncommon::cleanup_html($form->{role});
261: if ($role ne '') {
262: $retry .= (($retry=~/\?/)?'&':'?').'role='.$role;
263: }
264: }
265: if (exists($form->{symb})) {
266: my $symb = &Apache::loncommon::cleanup_html($form->{symb});
267: if ($symb ne '') {
268: $retry .= (($retry=~/\?/)?'&':'?').'symb='.$symb;
269: }
270: }
271: if (exists($form->{firsturl})) {
272: my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
273: if ($firsturl ne '') {
274: $retry .= (($retry=~/\?/)?'&':'?').'firsturl='.$firsturl;
275: if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
276: unless (exists($form->{linkprot})) {
277: if (exists($form->{linkkey})) {
278: $retry .= 'linkkey='.$form->{linkkey};
279: }
280: }
281: }
282: }
283: }
284: if (exists($form->{linkprot})) {
285: my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
286: $r->dir_config('lonHostID'),'retry');
287: if ($ltoken) {
288: $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
289: }
290: }
291: } elsif ($querystr ne '') {
292: $retry .= (($retry=~/\?/)?'&':'?').$querystr;
293: }
294: my $end_page = &Apache::loncommon::end_page();
295: &Apache::loncommon::content_type($r,'text/html');
296: $r->send_http_header;
297: my @actions =
298: (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
299: my $loginhelp = &loginhelpdisplay($udom);
300: if ($loginhelp) {
301: push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
302: }
303: #FIXME: link to helpdesk might be added here
304:
305: $r->print(
306: $start_page
307: .'<h2>'.&mt('Sorry ...').'</h2>'
308: .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
309: .&Apache::lonhtmlcommon::actionbox(\@actions)
310: .$end_page
311: );
312: }
313:
314: # ------------------------------------------------------------------ Rerouting!
315:
316: sub reroute {
317: my ($r) = @_;
318: &Apache::loncommon::content_type($r,'text/html');
319: $r->send_http_header;
320: my $msg='<b>'.&mt('Sorry ...').'</b><br />'
321: .&mt('Please [_1]log in again[_2].');
322: &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
323: }
324:
325: # ---------------------------------------------------------------- Main handler
326:
327: sub handler {
328: my $r = shift;
329: my $londocroot = $r->dir_config('lonDocRoot');
330: # Are we re-routing?
331: if (-e "$londocroot/lon-status/reroute.txt") {
332: &reroute($r);
333: return OK;
334: }
335:
336: &Apache::lonlocal::get_language_handle($r);
337:
338: # -------------------------------- Prevent users from attempting to login twice
339: my $handle = &Apache::lonnet::check_for_valid_session($r);
340: if ($handle ne '') {
341: my $lonidsdir=$r->dir_config('lonIDsDir');
342: if ($handle=~/^publicuser\_/) {
343: # For "public user" - remove it, we apparently really want to login
344: unlink($r->dir_config('lonIDsDir')."/$handle.id");
345: } else {
346: # Indeed, a valid token is found
347: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
348: &Apache::loncommon::content_type($r,'text/html');
349: $r->send_http_header;
350: my $start_page =
351: &Apache::loncommon::start_page('Already logged in');
352: my $end_page =
353: &Apache::loncommon::end_page();
354: my $dest = '/adm/roles';
355: my %form = &get_form_items($r);
356: if ($form{'logtoken'}) {
357: my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
358: $form{'serverid'});
359: unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
360: ($tmpinfo eq 'no_such_host')) {
361: my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
362: $firsturl = &unescape($firsturl);
363: my %info;
364: foreach my $item (@rest) {
365: my ($key,$value) = split(/=/,$item);
366: $info{$key} = &unescape($value);
367: }
368: if ($firsturl ne '') {
369: $info{'firsturl'} = $firsturl;
370: $dest = $firsturl;
371: my $relogin;
372: if ($dest =~ m{^/tiny/$match_domain/\w+$}) {
373: if ($env{'request.course.id'}) {
374: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
375: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
376: my $symb = &Apache::loncommon::symb_from_tinyurl($dest,$cnum,$cdom);
377: if ($symb) {
378: unless (&set_deeplink_login(%info) eq 'ok') {
379: $relogin = 1;
380: }
381: }
382: }
383: if ($relogin) {
384: $r->print(
385: $start_page
386: .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
387: .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',
388: '<a href="/adm/logout">','</a>')
389: .'</p>'
390: .$end_page);
391: } else {
392: if (($info{'linkprot'}) || ($info{'linkkey'} ne '')) {
393: my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
394: unless (($token eq 'con_lost') || ($token eq 'refused') ||
395: ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
396: $dest .= (($dest =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
397: }
398: }
399: $r->print(
400: $start_page
401: .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
402: .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4] first, and then try your access again',
403: '<a href="'.$dest.'">','</a>',
404: '<a href="/adm/logout">','</a>')
405: .'</p>'
406: .$end_page);
407: }
408: return OK;
409: }
410: }
411: }
412: }
413: $r->print(
414: $start_page
415: .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
416: .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
417: ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
418: .'</p>'
419: .$end_page
420: );
421: return OK;
422: }
423: }
424:
425: # ---------------------------------------------------- No valid token, continue
426:
427: my %form = &get_form_items($r);
428: if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
429: &failed($r,'Username, password and domain need to be specified.',
430: \%form);
431: return OK;
432: }
433:
434: # split user logging in and "su"-user
435:
436: ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
437: $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
438: $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
439: $form{'udom'} = &LONCAPA::clean_domain($form{'udom'});
440: $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
441:
442: my $role = $r->dir_config('lonRole');
443: my $domain = $r->dir_config('lonDefDomain');
444: my $prodir = $r->dir_config('lonUsersDir');
445: my $contact_name = &mt('LON-CAPA helpdesk');
446:
447: # ---------------------------------------- Get the information from login token
448:
449: my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
450: $form{'serverid'});
451:
452: if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
453: ($tmpinfo eq 'no_such_host')) {
454: &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
455: return OK;
456: } else {
457: my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
458: $form{'serverid'});
459: if ( $reply ne 'ok' ) {
460: &failed($r,'Session could not be opened.',\%form);
461: &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
462: return OK;
463: }
464: }
465:
466: if (!&Apache::lonnet::domain($form{'udom'})) {
467: &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
468: return OK;
469: }
470:
471: my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
472: $firsturl = &unescape($firsturl);
473: foreach my $item (@rest) {
474: my ($key,$value) = split(/=/,$item);
475: $form{$key} = &unescape($value);
476: }
477: if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
478: $form{'firsturl'} = $firsturl;
479: }
480: my $upass = &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});
481:
482: # ---------------------------------------------------------------- Authenticate
483:
484: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
485: my ($cancreate,$statustocreate) =
486: &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
487: my $defaultauth;
488: if (ref($cancreate) eq 'ARRAY') {
489: if (grep(/^login$/,@{$cancreate})) {
490: $defaultauth = 1;
491: }
492: }
493: my $clientcancheckhost = 1;
494: my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
495: $form{'udom'},$defaultauth,
496: $clientcancheckhost);
497:
498: # --------------------------------------------------------------------- Failed?
499:
500: if ($authhost eq 'no_host') {
501: &failed($r,'Username and/or password could not be authenticated.',
502: \%form);
503: return OK;
504: } elsif ($authhost eq 'no_account_on_host') {
505: if ($defaultauth) {
506: my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
507: unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
508: return OK;
509: }
510: my $start_page =
511: &Apache::loncommon::start_page('Create a user account in LON-CAPA',
512: '',{'no_inline_link' => 1,});
513: my $lonhost = $r->dir_config('lonHostID');
514: my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
515: my $contacts =
516: &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
517: $form{'udom'},$origmail);
518: my ($contact_email) = split(',',$contacts);
519: my $output =
520: &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
521: $domdesc,'',$lonhost,
522: $contact_email,$contact_name,
523: undef,$statustocreate);
524: &Apache::loncommon::content_type($r,'text/html');
525: $r->send_http_header;
526: &Apache::createaccount::print_header($r,$start_page);
527: $r->print('<h3>'.&mt('Account creation').'</h3>'.
528: &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
529: $output.&Apache::loncommon::end_page());
530: return OK;
531: } else {
532: &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);
533: return OK;
534: }
535: }
536:
537: if (($firsturl eq '') ||
538: ($firsturl=~/^\/adm\/(logout|remote)/)) {
539: $firsturl='/adm/roles';
540: }
541:
542: my ($hosthere,%sessiondata);
543: if ($form{'iptoken'}) {
544: %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
545: my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
546: if (($sessiondata{'domain'} eq $form{'udom'}) &&
547: ($sessiondata{'username'} eq $form{'uname'})) {
548: $hosthere = 1;
549: }
550: }
551:
552: # --------------------------------- Are we attempting to login as somebody else?
553: if ($form{'suname'}) {
554: my ($suname,$sudom,$sudomref);
555: $suname = $form{'suname'};
556: $sudom = $form{'udom'};
557: if ($form{'sudom'}) {
558: unless ($sudom eq $form{'sudom'}) {
559: if (&Apache::lonnet::domain($form{'sudom'})) {
560: $sudomref = [$form{'sudom'}];
561: $sudom = $form{'sudom'};
562: }
563: }
564: }
565: # ------------ see if the original user has enough privileges to pull this stunt
566: if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
567: # ---------------------------------------------------- see if the su-user exists
568: unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
569: # ------------------------------ see if the su-user is not too highly privileged
570: if (&Apache::lonnet::privileged($suname,$sudom)) {
571: &Apache::lonnet::logthis('Attempted switch user to privileged user');
572: } else {
573: my $noprivswitch;
574: #
575: # su-user's home server and user's home server must have one of:
576: # (a) same domain
577: # (b) same primary library server for the two domains
578: # (c) same "internet domain" for primary library server(s) for home servers' domains
579: #
580: my $suprim = &Apache::lonnet::domain($sudom,'primary');
581: my $suintdom = &Apache::lonnet::internet_dom($suprim);
582: unless ($sudom eq $form{'udom'}) {
583: my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
584: my $uintdom = &Apache::lonnet::internet_dom($uprim);
585: unless ($suprim eq $uprim) {
586: unless ($suintdom eq $uintdom) {
587: &Apache::lonnet::logthis('Attempted switch user '
588: .'to user with different "internet domain".');
589: $noprivswitch = 1;
590: }
591: }
592: }
593:
594: unless ($noprivswitch) {
595: #
596: # server where log-in occurs must have same "internet domain" as su-user's home
597: # server
598: #
599: my $lonhost = $r->dir_config('lonHostID');
600: my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
601: if ($hostintdom ne $suintdom) {
602: &Apache::lonnet::logthis('Attempted switch user on a '
603: .'server with a different "internet domain".');
604: } else {
605:
606: # -------------------------------------------------------- actually switch users
607:
608: &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
609: $form{'udom'}.' logging in as '.$suname.':'.$sudom);
610: $form{'uname'}=$suname;
611: if ($form{'udom'} ne $sudom) {
612: $form{'udom'}=$sudom;
613: }
614: }
615: }
616: }
617: }
618: } else {
619: &Apache::lonnet::logthis('Non-privileged user attempting switch user');
620: }
621: }
622:
623: my ($is_balancer,$otherserver);
624:
625: unless ($hosthere) {
626: ($is_balancer,$otherserver) =
627: &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
628: if ($is_balancer) {
629: # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
630: my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
631: if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
632: $otherserver = $found_server;
633: }
634: if ($otherserver eq '') {
635: my $lowest_load;
636: ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
637: if ($lowest_load > 100) {
638: $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
639: }
640: }
641: if ($otherserver ne '') {
642: my @hosts = &Apache::lonnet::current_machine_ids();
643: if (grep(/^\Q$otherserver\E$/,@hosts)) {
644: $hosthere = $otherserver;
645: }
646: }
647: }
648: }
649:
650: if (($is_balancer) && (!$hosthere)) {
651: if ($otherserver) {
652: &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
653: \%form);
654: my $switchto = '/adm/switchserver?otherserver='.$otherserver;
655: if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
656: $switchto .= '&origurl='.$firsturl;
657: }
658: if ($form{'role'}) {
659: $switchto .= '&role='.$form{'role'};
660: }
661: if ($form{'symb'}) {
662: $switchto .= '&symb='.$form{'symb'};
663: }
664: if ($form{'linkprot'}) {
665: $env{'request.linkprot'} = $form{'linkprot'};
666: } elsif ($form{'linkkey'} ne '') {
667: $env{'request.linkkey'} = $form{'linkkey'};
668: }
669: if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
670: &set_deeplink_login(%form);
671: }
672: $r->internal_redirect($switchto);
673: } else {
674: &Apache::loncommon::content_type($r,'text/html');
675: $r->send_http_header;
676: $r->print(&noswitch());
677: }
678: return OK;
679: } else {
680: if (!&check_can_host($r,\%form,$authhost)) {
681: my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
682: if ($otherserver) {
683: &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
684: \%form);
685: my $switchto = '/adm/switchserver?otherserver='.$otherserver;
686: if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
687: $switchto .= '&origurl='.$firsturl;
688: }
689: if ($form{'role'}) {
690: $switchto .= '&role='.$form{'role'};
691: }
692: if ($form{'symb'}) {
693: $switchto .= '&symb='.$form{'symb'};
694: }
695: if ($form{'linkprot'}) {
696: $env{'request.linkprot'} = $form{'linkprot'};
697: } elsif ($form{'linkkey'} ne '') {
698: $env{'request.linkkey'} = $form{'linkkey'};
699: }
700: if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
701: &set_deeplink_login(%form);
702: }
703: $r->internal_redirect($switchto);
704: } else {
705: &Apache::loncommon::content_type($r,'text/html');
706: $r->send_http_header;
707: $r->print(&noswitch());
708: }
709: return OK;
710: }
711:
712: # ------------------------------------------------------- Do the load balancing
713:
714: # ---------------------------------------------------------- Determine own load
715: my $loadlim = $r->dir_config('lonLoadLim');
716: my $loadavg;
717: {
718: my $loadfile=Apache::File->new('/proc/loadavg');
719: $loadavg=<$loadfile>;
720: }
721: $loadavg =~ s/\s.*//g;
722: my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
723: my $userloadpercent=&Apache::lonnet::userload();
724:
725: # ---------------------------------------------------------- Are we overloaded?
726: if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
727: my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});
728: if (!$unloaded) {
729: ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
730: }
731: if ($unloaded) {
732: &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
733: undef,\%form);
734: if ($form{'linkprot'}) {
735: $env{'request.linkprot'} = $form{'linkprot'};
736: } elsif ($form{'linkkey'} ne '') {
737: $env{'request.linkkey'} = $form{'linkkey'};
738: }
739: if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
740: &set_deeplink_login(%form);
741: }
742: $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
743: return OK;
744: }
745: }
746: if (($is_balancer) && ($hosthere)) {
747: $form{'noloadbalance'} = $hosthere;
748: }
749: my $extra_env;
750: if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {
751: if ($sessiondata{'origurl'} ne '') {
752: $firsturl = $sessiondata{'origurl'};
753: $form{'firsturl'} = $sessiondata{'origurl'};
754: my @names = ('role','symb','linkprot','linkkey');
755: foreach my $item (@names) {
756: if ($sessiondata{$item} ne '') {
757: $form{$item} = $sessiondata{$item};
758: }
759: }
760: }
761: }
762: if ($form{'linkprot'}) {
763: my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
764: if ($linkprotector) {
765: $extra_env = {'user.linkprotector' => $linkprotector,
766: 'user.linkproturi' => $uri};
767: }
768: } elsif ($form{'linkkey'} ne '') {
769: $extra_env = {'user.deeplinkkey' => $form{'linkkey'},
770: 'user.keyedlinkuri' => $form{'firsturl'}};
771: }
772: if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
773: &set_deeplink_login(%form);
774: if ($form{'linkprot'}) {
775: if (ref($extra_env) eq 'HASH') {
776: %{$extra_env} = ( %{$extra_env}, 'request.linkprot' => $form{'linkprot'} );
777: } else {
778: $extra_env = {'request.linkprot' => $form{'linkprot'}};
779: }
780: } elsif ($form{'linkkey'} ne '') {
781: if (ref($extra_env) eq 'HASH') {
782: %{$extra_env} = ( %{$extra_env}, 'request.linkkey' => $form{'linkkey'} );
783: } else {
784: $extra_env = {'request.linkkey' => $form{'linkkey'}};
785: }
786: }
787: if ($env{'request.deeplink.login'}) {
788: if (ref($extra_env) eq 'HASH') {
789: %{$extra_env} = ( %{$extra_env}, 'request.deeplink.login' => $form{'firsturl'} );
790: } else {
791: $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
792: }
793: }
794: }
795: &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
796: \%form);
797: return OK;
798: }
799: }
800:
801: sub get_form_items {
802: my ($r) = @_;
803: my $buffer;
804: if ($r->header_in('Content-length') > 0) {
805: $r->read($buffer,$r->header_in('Content-length'),0);
806: }
807: my %form;
808: foreach my $pair (split(/&/,$buffer)) {
809: my ($name,$value) = split(/=/,$pair);
810: $value =~ tr/+/ /;
811: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
812: $form{$name}=$value;
813: }
814: return %form;
815: }
816:
817: sub set_deeplink_login {
818: my (%form) = @_;
819: my $disallow;
820: if ($form{'firsturl'} =~ m{^/tiny/($match_domain)/\w+$}) {
821: my $cdom = $1;
822: my ($cnum,$symb) = &Apache::loncommon::symb_from_tinyurl($form{'firsturl'},'',$cdom);
823: if ($symb) {
824: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
825: my $deeplink;
826: if ($symb =~ /\.(page|sequence)$/) {
827: my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($symb))[2]);
828: my $navmap = Apache::lonnavmaps::navmap->new();
829: if (ref($navmap)) {
830: $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
831: }
832: } else {
833: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
834: }
835: if ($deeplink ne '') {
836: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
837: if (($protect ne 'none') && ($protect ne '')) {
838: my ($acctype,$item) = split(/:/,$protect);
839: if ($acctype =~ /lti(c|d)$/) {
840: unless ($form{'linkprot'} eq $item.$1.':'.$env{'request.deeplink.login'}) {
841: $disallow = 1;
842: }
843: } elsif ($acctype eq 'key') {
844: unless ($form{'linkkey'} eq $item) {
845: $disallow = 1;
846: }
847: }
848: }
849: }
850: unless ($disallow) {
851: $env{'request.deeplink.login'} = $form{'firsturl'};
852: }
853: } else {
854: $env{'request.deeplink.login'} = $form{'firsturl'};
855: }
856: }
857: }
858: if ($disallow) {
859: return;
860: }
861: return 'ok';
862: }
863:
864: sub set_retry_token {
865: my ($form,$lonhost,$querystr) = @_;
866: if (ref($form) eq 'HASH') {
867: my ($firsturl,$token,$extras,@names);
868: @names = ('role','symb','linkprot','linkkey','iptoken');
869: foreach my $name (@names) {
870: if ($form->{$name} ne '') {
871: $extras .= '&'.$name.'='.&escape($form->{$name});
872: last if ($name eq 'linkprot');
873: }
874: }
875: my $firsturl = $form->{'firsturl'};
876: if (($firsturl ne '') || ($extras ne '')) {
877: $extras .= ':retry';
878: $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).
879: $extras,$lonhost);
880: if (($token eq 'con_lost') || ($token eq 'no_such_host')) {
881: return 'fail';
882: } else {
883: if (ref($querystr)) {
884: $$querystr = 'retry='.$token;
885: }
886: return 'ok';
887: }
888: }
889: }
890: return;
891: }
892:
893: sub check_can_host {
894: my ($r,$form,$authhost,$domdesc) = @_;
895: return unless (ref($form) eq 'HASH');
896: my $canhost = 1;
897: my $lonhost = $r->dir_config('lonHostID');
898: my $udom = $form->{'udom'};
899: my @intdoms;
900: my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
901: if (ref($internet_names) eq 'ARRAY') {
902: @intdoms = @{$internet_names};
903: }
904: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
905: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
906: unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
907: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
908: my $hostname = &Apache::lonnet::hostname($lonhost);
909: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
910: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
911: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
912: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
913: my $loncaparev;
914: if ($authhost eq 'no_account_on_host') {
915: $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
916: } else {
917: $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
918: }
919: $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
920: $udomdefaults{'remotesessions'},
921: $defdomdefaults{'hostedsessions'});
922: }
923: unless ($canhost) {
924: if ($authhost eq 'no_account_on_host') {
925: my $checkloginvia = 1;
926: my ($login_host,$hostname) =
927: &Apache::lonnet::choose_server($udom,$checkloginvia);
928: &Apache::loncommon::content_type($r,'text/html');
929: $r->send_http_header;
930: if ($login_host ne '') {
931: my $protocol = $Apache::lonnet::protocol{$login_host};
932: $protocol = 'http' if ($protocol ne 'https');
933: my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);
934: $hostname = $alias if ($alias ne '');
935: my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
936: #FIXME Should preserve where user was going and linkprot by setting ltoken at $login_host
937: $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
938: '<h3>'.&mt('Account creation').'</h3>'.
939: &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
940: '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
941: '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
942: &Apache::loncommon::end_page());
943: } else {
944: $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
945: '<h3>'.&mt('Account creation unavailable').'</h3>'.
946: &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
947: '<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>'.
948: &Apache::loncommon::end_page());
949: }
950: } else {
951: &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
952: $form);
953: if ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
954: $env{'request.deeplink.login'} = $form->{'firsturl'};
955: }
956: if ($form->{'linkprot'}) {
957: $env{'request.linkprot'} = $form->{'linkprot'};
958: } elsif ($form->{'linkkey'} ne '') {
959: $env{'request.linkkey'} = $form->{'linkkey'};
960: }
961: my ($otherserver) = &Apache::lonnet::choose_server($udom);
962: $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
963: }
964: }
965: return $canhost;
966: }
967:
968: sub noswitch {
969: my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
970: '<h3>'.&mt('Session unavailable').'</h3>'.
971: &mt('This LON-CAPA server is unable to host your session.').'<br />'.
972: '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
973: &Apache::loncommon::end_page();
974: return $result;
975: }
976:
977: sub loginhelpdisplay {
978: my ($authdomain) = @_;
979: my $login_help = 1;
980: my $lang = &Apache::lonlocal::current_language();
981: if ($login_help) {
982: my $dom = $authdomain;
983: if ($dom eq '') {
984: $dom = &Apache::lonnet::default_login_domain();
985: }
986: my %domconfhash = &Apache::loncommon::get_domainconf($dom);
987: my $loginhelp_url;
988: if ($lang) {
989: $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
990: if ($loginhelp_url ne '') {
991: return $loginhelp_url;
992: }
993: }
994: $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
995: if ($loginhelp_url ne '') {
996: return $loginhelp_url;
997: } else {
998: return '/adm/loginproblems.html';
999: }
1000: }
1001: return;
1002: }
1003:
1004: 1;
1005: __END__
1006:
1007:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>