1: # The LearningOnline Network
2: # User Authentication Module
3: #
4: # $Id: lonauth.pm,v 1.72 2005/11/15 17:55:03 www 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 Apache::Constants qw(:common);
33: use Apache::File;
34: use CGI qw(:standard);
35: use CGI::Cookie();
36: use DynaLoader; # for Crypt::DES version
37: use Crypt::DES;
38: use Apache::loncommon();
39: use Apache::lonnet;
40: use Apache::lonmenu();
41: use Fcntl qw(:flock);
42: use Apache::lonlocal;
43: use POSIX qw(strftime);
44:
45: my %FORM;
46:
47: # ------------------------------------------------------------ Successful login
48:
49: sub success {
50: my ($r, $username, $domain, $authhost,$lowerurl) = @_;
51: my $lonids=$r->dir_config('lonIDsDir');
52:
53: my $public=($username eq 'public' && $domain eq 'public');
54:
55: # See if old ID present, if so, remove
56:
57: my ($filename,$cookie,$userroles);
58: my $now=time;
59:
60: if ($public) {
61: my $max_public=100;
62: my $oldest;
63: my $oldest_time=0;
64: for(my $next=1;$next<=$max_public;$next++) {
65: if (-e $lonids."/publicuser_$next.id") {
66: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
67: if ($mtime<$oldest_time || !$oldest_time) {
68: $oldest_time=$mtime;
69: $oldest=$next;
70: }
71: } else {
72: $cookie="publicuser_$next";
73: last;
74: }
75: }
76: if (!$cookie) { $cookie="publicuser_$oldest"; }
77: } else {
78: opendir(DIR,$lonids);
79: while ($filename=readdir(DIR)) {
80: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
81: unlink($lonids.'/'.$filename);
82: }
83: }
84: closedir(DIR);
85:
86: # Give them a new cookie
87:
88: $cookie="$username\_$now\_$domain\_$authhost";
89:
90: # Initialize roles
91:
92: $userroles=Apache::lonnet::rolesinit($domain,$username,$authhost);
93: }
94: # ------------------------------------ Check browser type and MathML capability
95:
96: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
97: $clientunicode,$clientos) = &Apache::loncommon::decode_user_agent($r);
98:
99: # -------------------------------------- Any accessibility options to remember?
100: if (($FORM{'interface'}) && ($FORM{'remember'} eq 'true')) {
101: foreach ('imagesuppress','appletsuppress',
102: 'embedsuppress','fontenhance','blackwhite') {
103: if ($FORM{$_} eq 'true') {
104: &Apache::lonnet::put('environment',{$_ => 'on'},
105: $domain,$username);
106: } else {
107: &Apache::lonnet::del('environment',[$_],$domain,$username);
108: }
109: }
110: }
111: # ------------------------------------------------------------- Get environment
112:
113: my $userenv;
114: my %userenv=Apache::lonnet::dump('environment',$domain,$username);
115: my ($tmp) = keys(%userenv);
116: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
117: foreach my $key (keys(%userenv)) {
118: $userenv.="environment.$key=$userenv{$key}\n";
119: }
120: }
121: if (($userenv{'interface'}) && (!$FORM{'interface'})) {
122: $FORM{'interface'}=$userenv{'interface'};
123: }
124: $env{'environment.remote'}=$userenv{'remote'};
125: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
126:
127: # --------------- Do not trust query string to be put directly into environment
128: foreach ('imagesuppress','appletsuppress',
129: 'embedsuppress','fontenhance','blackwhite',
130: 'interface','localpath','localres') {
131: $FORM{$_}=~s/[\n\r\=]//gs;
132: }
133: # --------------------------------------------------------- Write first profile
134:
135: {
136: my $idf=Apache::File->new(">$lonids/$cookie.id");
137: unless (flock($idf,LOCK_EX)) {
138: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
139: 'Could not obtain exclusive lock in lonauth: '.$!);
140: $idf->close();
141: return 'error: '.$!;
142: }
143: if ($userenv ne '') { print $idf "$userenv\n"; }
144: print $idf "user.name=$username\n";
145: print $idf "user.domain=$domain\n";
146: print $idf "user.home=$authhost\n";
147: print $idf "browser.type=$clientbrowser\n";
148: print $idf "browser.version=$clientversion\n";
149: print $idf "browser.mathml=$clientmathml\n";
150: print $idf "browser.unicode=$clientunicode\n";
151: print $idf "browser.os=$clientos\n";
152: if ($FORM{'localpath'}) {
153: print $idf "browser.localpath=$FORM{'localpath'}\n";
154: print $idf "browser.localres=$FORM{'localres'}\n";
155: }
156: print $idf "server.domain=".$r->dir_config('lonDefDomain')."\n";
157: my $timezone=POSIX::strftime("%Z",localtime(time));
158: print $idf "server.timezone=$timezone\n";
159: print $idf "request.course.fn=\n";
160: print $idf "request.course.uri=\n";
161: print $idf "request.course.sec=\n";
162: print $idf "request.role=cm\n";
163: print $idf "request.role.adv=$env{'user.adv'}\n";
164: print $idf "request.host=$ENV{'REMOTE_ADDR'}\n";
165: if ($public) {
166: print $idf "environment.remote=off\n";
167: }
168: if ($FORM{'interface'}) {
169: $FORM{'interface'}=~s/\W//gs;
170: print $idf "browser.interface=$FORM{'interface'}\n";
171: $env{'browser.interface'}=$FORM{'interface'};
172: foreach ('imagesuppress','appletsuppress',
173: 'embedsuppress','fontenhance','blackwhite') {
174: if (($FORM{$_} eq 'true') ||
175: ($userenv{$_} eq 'on')) {
176: print $idf "browser.$_=on\n";
177: }
178: }
179: }
180: if ($userroles ne '') { print $idf "$userroles"; }
181: $idf->close();
182: }
183: $env{'request.role'}='cm';
184: $env{'request.role.adv'}=$env{'user.adv'};
185: $env{'browser.type'}=$clientbrowser;
186: # -------------------------------------------------------------------- Log this
187:
188: &Apache::lonnet::log($domain,$username,$authhost,
189: "Login $ENV{'REMOTE_ADDR'}");
190:
191: # ------------------------------------------------- Check for critical messages
192:
193: my @what=&Apache::lonnet::dump('critical',$domain,$username);
194: if ($what[0]) {
195: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
196: $lowerurl='/adm/email?critical=display';
197: }
198: }
199:
200: # ------------------------------------------------------------ Get cookie ready
201:
202: if ($public or $lowerurl eq 'noredirect') { return $cookie; }
203:
204: $cookie="lonID=$cookie; path=/";
205: # -------------------------------------------------------- Menu script and info
206: my $windowinfo=&Apache::lonmenu::open($clientos);
207: my $startupremote=&Apache::lonmenu::startupremote($lowerurl);
208: my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);
209: my $setflags=&Apache::lonmenu::setflags();
210: my $maincall=&Apache::lonmenu::maincall();
211: my $bodytag=&Apache::loncommon::bodytag('Successful Login');
212: my $add=&addcontent();
213: my $continuelink;
214: if (($env{'browser.interface'} eq 'textual') ||
215: ($env{'environment.remote'} eq 'off')) {
216: $continuelink="<a href=\"$lowerurl\">".&mt('Continue')."</a>";
217: }
218: # ------------------------------------------------- Output for successful login
219:
220: $r->send_cgi_header(<<ENDHEADER);
221: Content-type: text/html$add
222: Set-cookie: $cookie
223:
224: ENDHEADER
225: my %lt=&Apache::lonlocal::texthash(
226: 'wel' => 'Welcome',
227: 'mes' => 'Welcome to the Learning<i>Online</i> Network with CAPA. Please wait while your session is being set up',
228: 'pro' => 'Problems',
229: 'log' => 'loginproblems.html',
230: );
231: $r->print(<<ENDSUCCESS);
232: <html>
233: <head>
234: <title>Successful Login to the LearningOnline Network with CAPA</title>
235: $startupremote
236: </head>
237: $bodytag
238: $setflags
239: $windowinfo
240: <h1>$lt{'wel'}</h1>
241: $lt{'mes'}.<p>
242: <a href="/adm/$lt{'log'}">$lt{'pro'}?</a></p>
243: $remoteinfo
244: $maincall
245: $continuelink
246: </body>
247: </html>
248: ENDSUCCESS
249: }
250:
251: # --------------------------------------------------------------- Failed login!
252:
253: sub failed {
254: my ($r,$message) = @_;
255: my $bodytag=&Apache::loncommon::bodytag('Unsuccessful Login');
256: my $add=&addcontent();
257: $r->send_cgi_header(<<ENDFHEADER);
258: Content-type: text/html$add
259:
260: ENDFHEADER
261: $r->print(<<ENDFAILED);
262: <html>
263: <head>
264: <title>Unsuccessful Login to the LearningOnline Network with CAPA</title>
265: </head>
266: $bodytag
267: <h1>Sorry ...</h1>
268: <p><b>$message</b></p>
269: <p>Please <a href="/adm/login?username=$FORM{'uname'}&domain=$FORM{'udom'}">log in again</a>.</p>
270: <p>
271: <a href="/adm/loginproblems.html">Problems?</a></p>
272: </body>
273: </html>
274: ENDFAILED
275: }
276:
277: # --------------------------------------------------------------------- Charset
278:
279: sub addcontent {
280: my $encoding=&Apache::lonlocal::current_encoding;
281: if ($encoding) {
282: return '; charset='.$encoding;
283: } else {
284: return '';
285: }
286: }
287:
288: # ------------------------------------------------------------------ Rerouting!
289:
290: sub reroute {
291: my $r=shift;
292: my $bodytag=&Apache::loncommon::bodytag('Rerouting');
293: $r->send_cgi_header(<<ENDRFHEADER);
294: Content-type: text/html
295:
296: ENDRFHEADER
297: $r->print(<<ENDRFAILED);
298: <html>
299: <head>
300: <title>Rerouting Login to the LearningOnline Network with CAPA</title>
301: </head>
302: $bodytag
303: <h1>Sorry ...</h1>
304: Please <a href="/">log in again</a>.
305: </body>
306: </html>
307: ENDRFAILED
308: }
309:
310: # ---------------------------------------------------------------- Main handler
311:
312: sub handler {
313: my $r = shift;
314:
315: # Are we re-routing?
316: if (-e '/home/httpd/html/lon-status/reroute.txt') {
317: &reroute($r);
318: return OK;
319: }
320:
321: &Apache::lonlocal::get_language_handle($r);
322:
323: # -------------------------------- Prevent users from attempting to login twice
324: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
325: my $lonid=$cookies{'lonID'};
326: my $cookie;
327: if ($lonid) {
328: my $handle=$lonid->value;
329: $handle=~s/\W//g;
330: my $lonidsdir=$r->dir_config('lonIDsDir');
331: if ((-e "$lonidsdir/$handle.id") && ($handle ne '')) {
332: # Indeed, a valid token is found
333: $r->send_cgi_header(<<ENDFHEADER);
334: Content-type: text/html
335:
336: ENDFHEADER
337: my $bodytag=&Apache::loncommon::bodytag('Already logged in');
338: $r->print(<<ENDFAILED);
339: <html>
340: <head>
341: <title>Already logged in</title>
342: </head>
343: $bodytag
344: <h1>You are already logged in</h1>
345: <p>Please either <a href="/adm/roles">continue the current session</a> or
346: <a href="/adm/logout">logout</a>.</p>
347: <p>
348: <a href="/adm/loginproblems.html">Problems?</a></p>
349: </body>
350: </html>
351: ENDFAILED
352: return OK;
353: }
354: }
355:
356: # ---------------------------------------------------- No valid token, continue
357:
358:
359: my $buffer;
360: $r->read($buffer,$r->header_in('Content-length'),0);
361: my @pairs=split(/&/,$buffer);
362: my $pair; my $name; my $value;
363: undef %FORM;
364: %FORM=();
365: foreach $pair (@pairs) {
366: ($name,$value) = split(/=/,$pair);
367: $value =~ tr/+/ /;
368: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
369: $FORM{$name}=$value;
370: }
371:
372: if ((!$FORM{'uname'}) || (!$FORM{'upass0'}) || (!$FORM{'udom'})) {
373: failed($r,'Username, password and domain need to be specified.');
374: return OK;
375: }
376:
377: # split user logging in and "su"-user
378:
379: ($FORM{'uname'},$FORM{'suname'})=split(/\:/,$FORM{'uname'});
380: $FORM{'uname'} =~ s/\W//g;
381: $FORM{'suname'} =~ s/\W//g;
382: $FORM{'udom'} =~ s/\W//g;
383:
384: my $role = $r->dir_config('lonRole');
385: my $domain = $r->dir_config('lonDefDomain');
386: my $prodir = $r->dir_config('lonUsersDir');
387:
388: # ---------------------------------------- Get the information from login token
389:
390: my $tmpinfo=Apache::lonnet::reply('tmpget:'.$FORM{'logtoken'},
391: $FORM{'serverid'});
392:
393: if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
394: failed($r,'Information needed to verify your login information is missing, inaccessible or expired.');
395: return OK;
396: } else {
397: unless (&Apache::lonnet::reply('tmpdel:'.$FORM{'logtoken'},
398: $FORM{'serverid'}) eq 'ok') {
399: &failed($r,'Session could not be opened.');
400: }
401: }
402: my ($key,$firsturl)=split(/&/,$tmpinfo);
403:
404: my $keybin=pack("H16",$key);
405:
406: my $cipher;
407: if ($Crypt::DES::VERSION>=2.03) {
408: $cipher=new Crypt::DES $keybin;
409: }
410: else {
411: $cipher=new DES $keybin;
412: }
413: my $upass='';
414: for (my $i=0;$i<=2;$i++) {
415: my $chunk=
416: $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},0,16))));
417:
418: $chunk.=
419: $cipher->decrypt(unpack("a8",pack("H16",substr($FORM{'upass'.$i},16,16))));
420:
421: $chunk=substr($chunk,1,ord(substr($chunk,0,1)));
422: $upass.=$chunk;
423: }
424:
425: # ---------------------------------------------------------------- Authenticate
426: my $authhost=Apache::lonnet::authenticate($FORM{'uname'},
427: $upass,
428: $FORM{'udom'});
429:
430: # --------------------------------------------------------------------- Failed?
431:
432: if ($authhost eq 'no_host') {
433: failed($r,'Username and/or password could not be authenticated.');
434: return OK;
435: }
436:
437: if (($firsturl eq '') ||
438: ($firsturl=~/^\/adm\/(logout|remote)/)) {
439: $firsturl='/adm/roles';
440: }
441: # --------------------------------- Are we attempting to login as somebody else?
442: if ($FORM{'suname'}) {
443: # ------------ see if the original user has enough privileges to pull this stunt
444: if (&Apache::lonnet::privileged($FORM{'uname'},$FORM{'udom'})) {
445: # ---------------------------------------------------- see if the su-user exists
446: unless (&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'})
447: eq 'no_host') {
448: &Apache::lonnet::logthis(&Apache::lonnet::homeserver($FORM{'suname'},$FORM{'udom'}));
449: # ------------------------------ see if the su-user is not too highly privileged
450: unless (&Apache::lonnet::privileged($FORM{'suname'},$FORM{'udom'})) {
451: # -------------------------------------------------------- actually switch users
452: &Apache::lonnet::logperm('User '.$FORM{'uname'}.' at '.$FORM{'udom'}.
453: ' logging in as '.$FORM{'suname'});
454: $FORM{'uname'}=$FORM{'suname'};
455: } else {
456: &Apache::lonnet::logthis('Attempted switch user to privileged user');
457: }
458: }
459: } else {
460: &Apache::lonnet::logthis('Non-privileged user attempting switch user');
461: }
462: }
463: &success($r,$FORM{'uname'},$FORM{'udom'},$authhost,$firsturl);
464: return OK;
465: }
466:
467: 1;
468: __END__
469:
470:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>