Annotation of loncom/lti/ltiutils.pm, revision 1.17.2.2
1.1 raeburn 1: # The LearningOnline Network with CAPA
2: # Utility functions for managing LON-CAPA LTI interactions
3: #
1.17.2.2! raeburn 4: # $Id: ltiutils.pm,v 1.17.2.1 2022/01/03 18:35:27 raeburn Exp $
1.1 raeburn 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 LONCAPA::ltiutils;
30:
31: use strict;
32: use Net::OAuth;
33: use Digest::SHA;
1.17.2.2! raeburn 34: use Digest::MD5 qw(md5_hex);
! 35: use LWP::UserAgent();
1.1 raeburn 36: use Apache::lonnet;
37: use Apache::loncommon;
38: use LONCAPA qw(:DEFAULT :match);
39:
40: #
41: # LON-CAPA as LTI Consumer or LTI Provider
42: #
43: # Determine if a nonce in POSTed data has expired.
44: # If unexpired, confirm it has not already been used.
45: #
46: # When LON-CAPA is operating as a Consumer, nonce checking
47: # occurs when a Tool Provider launched from an instance of
48: # an external tool in a LON-CAPA course makes a request to
49: # (a) /adm/service/roster or (b) /adm/service/passback to,
50: # respectively, retrieve a roster or store the grade for
51: # the original launch by a specific user.
52: #
53: # When LON-CAPA is operating as a Provider, nonce checking
54: # occurs when a user in course context in another LMS (the
1.4 raeburn 55: # Consumer) launches an external tool to access a LON-CAPA URL:
1.1 raeburn 56: # /adm/lti/ with LON-CAPA symb, map, or deep-link ID appended.
57: #
58:
59: sub check_nonce {
60: my ($nonce,$timestamp,$lifetime,$domain,$ltidir) = @_;
61: if (($ltidir eq '') || ($timestamp eq '') || ($timestamp =~ /^\D/) ||
62: ($lifetime eq '') || ($lifetime =~ /\D/) || ($domain eq '')) {
63: return;
64: }
65: my $now = time;
66: if (($timestamp) && ($timestamp < ($now - $lifetime))) {
67: return;
68: }
69: if ($nonce eq '') {
70: return;
71: }
72: if (-e "$ltidir/$domain/$nonce") {
73: return;
74: } else {
75: unless (-e "$ltidir/$domain") {
76: unless (mkdir("$ltidir/$domain",0755)) {
77: return;
78: }
79: }
80: if (open(my $fh,'>',"$ltidir/$domain/$nonce")) {
81: print $fh $now;
82: close($fh);
83: return 1;
84: }
85: }
86: return;
87: }
88:
89: #
90: # LON-CAPA as LTI Consumer
91: #
92: # Verify a signed request using the consumer_key and
93: # secret for the specific LTI Provider.
94: #
95:
96: sub verify_request {
1.15 raeburn 97: my ($oauthtype,$protocol,$hostname,$requri,$reqmethod,$consumer_secret,$params,
98: $authheaders,$errors) = @_;
99: unless (ref($errors) eq 'HASH') {
100: $errors->{15} = 1;
101: return;
102: }
103: my $request;
104: if ($oauthtype eq 'consumer') {
105: my $oauthreq = Net::OAuth->request('consumer');
106: $oauthreq->add_required_message_params('body_hash');
107: $request = $oauthreq->from_authorization_header($authheaders,
108: request_url => $protocol.'://'.$hostname.$requri,
109: request_method => $reqmethod,
110: consumer_secret => $consumer_secret,);
111: } else {
112: $request = Net::OAuth->request('request token')->from_hash($params,
113: request_url => $protocol.'://'.$hostname.$requri,
114: request_method => $reqmethod,
115: consumer_secret => $consumer_secret,);
116: }
1.1 raeburn 117: unless ($request->verify()) {
118: $errors->{15} = 1;
119: return;
120: }
121: }
122:
123: #
124: # LON-CAPA as LTI Consumer
125: #
126: # Sign a request used to launch an instance of an external
1.4 raeburn 127: # tool in a LON-CAPA course, using the key and secret supplied
1.1 raeburn 128: # by the Tool Provider.
129: #
130:
131: sub sign_params {
1.17 raeburn 132: my ($url,$key,$secret,$paramsref,$sigmethod,$type,$callback,$post) = @_;
1.1 raeburn 133: return unless (ref($paramsref) eq 'HASH');
1.3 raeburn 134: if ($sigmethod eq '') {
135: $sigmethod = 'HMAC-SHA1';
136: }
1.17 raeburn 137: if ($type eq '') {
138: $type = 'request token';
139: }
140: if ($callback eq '') {
141: $callback = 'about:blank',
142: }
1.9 raeburn 143: srand( time() ^ ($$ + ($$ << 15)) ); # Seed rand.
1.1 raeburn 144: my $nonce = Digest::SHA::sha1_hex(sprintf("%06x%06x",rand(0xfffff0),rand(0xfffff0)));
1.17 raeburn 145: my $request = Net::OAuth->request($type)->new(
1.1 raeburn 146: consumer_key => $key,
147: consumer_secret => $secret,
148: request_url => $url,
149: request_method => 'POST',
1.3 raeburn 150: signature_method => $sigmethod,
1.1 raeburn 151: timestamp => time,
152: nonce => $nonce,
1.17 raeburn 153: callback => $callback,
1.1 raeburn 154: extra_params => $paramsref,
155: version => '1.0',
156: );
1.15 raeburn 157: $request->sign();
1.17 raeburn 158: if ($post) {
159: return $request->to_post_body();
160: } else {
161: return $request->to_hash();
162: }
1.1 raeburn 163: }
164:
165: #
1.6 raeburn 166: # LON-CAPA as LTI Provider
167: #
168: # Use the part of the launch URL after /adm/lti to determine
169: # the scope for the current session (i.e., restricted to a
170: # single resource, to a single folder/map, or to an entire
171: # course).
172: #
173: # Returns an array containing scope: resource, map, or course
174: # and the LON-CAPA URL that is displayed post-launch, including
175: # accommodation of URL encryption, and translation of a tiny URL
176: # to the actual URL
177: #
178:
179: sub lti_provider_scope {
1.10 raeburn 180: my ($tail,$cdom,$cnum,$getunenc) = @_;
181: my ($scope,$realuri,$passkey,$unencsymb);
182: if ($tail =~ m{^/?uploaded/$cdom/$cnum/(?:default|supplemental)(?:|_\d+)\.(?:sequence|page)(|___\d+___.+)$}) {
1.6 raeburn 183: my $rest = $1;
184: if ($rest eq '') {
185: $scope = 'map';
186: $realuri = $tail;
187: } else {
1.13 raeburn 188: my $symb = $tail;
189: $symb =~ s{^/}{};
190: my ($map,$resid,$url) = &Apache::lonnet::decode_symb($symb);
1.6 raeburn 191: $realuri = &Apache::lonnet::clutter($url);
1.7 raeburn 192: if ($url =~ /\.sequence$/) {
193: $scope = 'map';
1.6 raeburn 194: } else {
1.7 raeburn 195: $scope = 'resource';
1.13 raeburn 196: $realuri .= '?symb='.$symb;
197: $passkey = $symb;
1.10 raeburn 198: if ($getunenc) {
1.13 raeburn 199: $unencsymb = $symb;
1.10 raeburn 200: }
1.6 raeburn 201: }
202: }
1.10 raeburn 203: } elsif ($tail =~ m{^/?res/$match_domain/$match_username/.+\.(?:sequence|page)(|___\d+___.+)$}) {
1.8 raeburn 204: my $rest = $1;
205: if ($rest eq '') {
206: $scope = 'map';
207: $realuri = $tail;
208: } else {
1.13 raeburn 209: my $symb = $tail;
210: $symb =~ s{^/?res/}{};
211: my ($map,$resid,$url) = &Apache::lonnet::decode_symb($symb);
1.8 raeburn 212: $realuri = &Apache::lonnet::clutter($url);
213: if ($url =~ /\.sequence$/) {
214: $scope = 'map';
215: } else {
216: $scope = 'resource';
1.13 raeburn 217: $realuri .= '?symb='.$symb;
218: $passkey = $symb;
1.10 raeburn 219: if ($getunenc) {
1.13 raeburn 220: $unencsymb = $symb;
1.10 raeburn 221: }
1.8 raeburn 222: }
223: }
1.6 raeburn 224: } elsif ($tail =~ m{^/tiny/$cdom/(\w+)$}) {
225: my $key = $1;
226: my $tinyurl;
227: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
228: if (defined($cached)) {
229: $tinyurl = $result;
230: } else {
231: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
232: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
233: if ($currtiny{$key} ne '') {
234: $tinyurl = $currtiny{$key};
235: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
236: }
237: }
238: if ($tinyurl ne '') {
239: my ($cnum,$symb) = split(/\&/,$tinyurl,2);
240: my ($map,$resid,$url) = &Apache::lonnet::decode_symb($symb);
241: if ($url =~ /\.(page|sequence)$/) {
242: $scope = 'map';
243: } else {
244: $scope = 'resource';
245: }
1.10 raeburn 246: $passkey = $symb;
1.6 raeburn 247: if ((&Apache::lonnet::EXT('resource.0.encrypturl',$symb) =~ /^yes$/i) &&
248: (!$env{'request.role.adv'})) {
249: $realuri = &Apache::lonenc::encrypted(&Apache::lonnet::clutter($url));
1.7 raeburn 250: if ($scope eq 'resource') {
1.6 raeburn 251: $realuri .= '?symb='.&Apache::lonenc::encrypted($symb);
252: }
253: } else {
254: $realuri = &Apache::lonnet::clutter($url);
1.7 raeburn 255: if ($scope eq 'resource') {
1.6 raeburn 256: $realuri .= '?symb='.$symb;
257: }
258: }
1.10 raeburn 259: if ($getunenc) {
260: $unencsymb = $symb;
261: }
1.6 raeburn 262: }
1.10 raeburn 263: } elsif (($tail =~ m{^/$cdom/$cnum$}) || ($tail eq '')) {
1.6 raeburn 264: $scope = 'course';
265: $realuri = '/adm/navmaps';
1.13 raeburn 266: $passkey = '';
1.10 raeburn 267: }
268: if ($scope eq 'map') {
269: $passkey = $realuri;
270: }
271: if (wantarray) {
272: return ($scope,$realuri,$unencsymb);
273: } else {
274: return $passkey;
275: }
276: }
277:
1.17 raeburn 278: sub setup_logout_callback {
279: my ($uname,$udom,$server,$ckey,$secret,$service_url,$idsdir,$protocol,$hostname) = @_;
280: if ($service_url =~ m{^https?://[^/]+/}) {
281: my $digest_user = &Encode::decode_utf8($uname.':'.$udom);
282: my $loginfile = &Digest::SHA::sha1_hex($digest_user).&md5_hex(&md5_hex(time.{}.rand().$$));
283: if ((-d $idsdir) && (open(my $fh,'>',"$idsdir/$loginfile"))) {
284: print $fh "$uname,$udom,$server\n";
285: close($fh);
286: my $callback = 'http://'.$hostname.'/adm/service/logout/'.$loginfile;
287: my %ltiparams = (
288: callback => $callback,
289: );
290: my $post = &sign_params($service_url,$ckey,$secret,\%ltiparams,
291: '','','',1);
1.17.2.2! raeburn 292:
! 293: my $ua=new LWP::UserAgent;
! 294: $ua->timeout(10);
1.17 raeburn 295: my $request=new HTTP::Request('POST',$service_url);
296: $request->content($post);
1.17.2.2! raeburn 297: my $response=$ua->request($request);
1.17 raeburn 298: }
299: }
300: return;
301: }
302:
1.12 raeburn 303: #
304: # LON-CAPA as LTI Provider
305: #
306: # Create a new user in LON-CAPA. If the domain's configuration
307: # includes rules for format of "official" usernames, those rules
308: # will apply when determining if a user is to be created. In
309: # additional if institutional user information is available that
310: # will be used when creating a new user account.
311: #
312:
1.11 raeburn 313: sub create_user {
314: my ($ltiref,$uname,$udom,$domdesc,$data,$alerts,$rulematch,$inst_results,
315: $curr_rules,$got_rules) = @_;
316: return unless (ref($ltiref) eq 'HASH');
317: my $checkhash = { "$uname:$udom" => { 'newuser' => 1, }, };
318: my $checks = { 'username' => 1, };
319: my ($lcauth,$lcauthparm);
320: &Apache::loncommon::user_rule_check($checkhash,$checks,$alerts,$rulematch,
321: $inst_results,$curr_rules,$got_rules);
322: my ($userchkmsg,$lcauth,$lcauthparm);
323: my $allowed = 1;
324: if (ref($alerts->{'username'}) eq 'HASH') {
325: if (ref($alerts->{'username'}{$udom}) eq 'HASH') {
326: if ($alerts->{'username'}{$udom}{$uname}) {
327: if (ref($curr_rules->{$udom}) eq 'HASH') {
328: $userchkmsg =
329: &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1).
330: &Apache::loncommon::user_rule_formats($udom,$domdesc,
331: $curr_rules->{$udom}{'username'},
332: 'username');
333: }
334: $allowed = 0;
335: }
336: }
337: }
338: if ($allowed) {
339: if (ref($rulematch->{$uname.':'.$udom}) eq 'HASH') {
340: my $matchedrule = $rulematch->{$uname.':'.$udom}{'username'};
341: my ($rules,$ruleorder) =
342: &Apache::lonnet::inst_userrules($udom,'username');
343: if (ref($rules) eq 'HASH') {
344: if (ref($rules->{$matchedrule}) eq 'HASH') {
345: $lcauth = $rules->{$matchedrule}{'authtype'};
346: $lcauthparm = $rules->{$matchedrule}{'authparm'};
347: }
348: }
349: }
350: if ($lcauth eq '') {
351: $lcauth = $ltiref->{'lcauth'};
352: if ($lcauth eq 'internal') {
353: $lcauthparm = &create_passwd();
354: } else {
355: $lcauthparm = $ltiref->{'lcauthparm'};
356: }
357: }
358: } else {
359: return 'notallowed';
360: }
361: my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
362: my (%useinstdata,%info);
363: if (ref($ltiref->{'instdata'}) eq 'ARRAY') {
364: map { $useinstdata{$_} = 1; } @{$ltiref->{'instdata'}};
365: }
366: foreach my $item (@userinfo) {
367: if (($useinstdata{$item}) && (ref($inst_results->{$uname.':'.$udom}) eq 'HASH') &&
368: ($inst_results->{$uname.':'.$udom}{$item} ne '')) {
369: $info{$item} = $inst_results->{$uname.':'.$udom}{$item};
370: } else {
371: if ($item eq 'permanentemail') {
372: if ($data->{'permanentemail'} =~/^[^\@]+\@[^@]+$/) {
373: $info{$item} = $data->{'permanentemail'};
374: }
375: } elsif (($item eq 'firstname') || ($item eq 'lastname')) {
376: $info{$item} = $data->{$item};
377: }
378: }
379: }
380: if (($info{'middlename'} eq '') && ($data->{'fullname'} ne '')) {
381: unless ($useinstdata{'middlename'}) {
382: my $fullname = $data->{'fullname'};
383: if ($info{'firstname'}) {
384: $fullname =~ s/^\s*\Q$info{'firstname'}\E\s*//i;
385: }
386: if ($info{'lastname'}) {
387: $fullname =~ s/\s*\Q$info{'lastname'}\E\s*$//i;
388: }
389: if ($fullname ne '') {
390: $fullname =~ s/^\s+|\s+$//g;
391: if ($fullname ne '') {
392: $info{'middlename'} = $fullname;
393: }
394: }
395: }
396: }
397: if (ref($inst_results->{$uname.':'.$udom}{'inststatus'}) eq 'ARRAY') {
398: my @inststatuses = @{$inst_results->{$uname.':'.$udom}{'inststatus'}};
399: $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
400: }
401: my $result =
402: &Apache::lonnet::modifyuser($udom,$uname,$info{'id'},
403: $lcauth,$lcauthparm,$info{'firstname'},
404: $info{'middlename'},$info{'lastname'},
405: $info{'generation'},undef,undef,
406: $info{'permanentemail'},$info{'inststatus'});
407: return $result;
408: }
409:
1.12 raeburn 410: #
411: # LON-CAPA as LTI Provider
412: #
413: # Create a password for a new user if the authentication
414: # type to assign to new users created following LTI launch is
415: # to be LON-CAPA "internal".
416: #
417:
1.11 raeburn 418: sub create_passwd {
419: my $passwd = '';
1.12 raeburn 420: srand( time() ^ ($$ + ($$ << 15)) ); # Seed rand.
1.11 raeburn 421: my @letts = ("a".."z");
422: for (my $i=0; $i<8; $i++) {
423: my $lettnum = int(rand(2));
424: my $item = '';
425: if ($lettnum) {
426: $item = $letts[int(rand(26))];
427: my $uppercase = int(rand(2));
428: if ($uppercase) {
429: $item =~ tr/a-z/A-Z/;
430: }
431: } else {
432: $item = int(rand(10));
433: }
434: $passwd .= $item;
435: }
436: return ($passwd);
437: }
438:
1.12 raeburn 439: #
440: # LON-CAPA as LTI Provider
441: #
442: # Enroll a user in a LON-CAPA course, with the specified role and (optional)
443: # section. If this is a self-enroll case, i.e., a user launched the LTI tool
444: # in the Consumer, user privs will be added to the user's environment for
445: # the new role.
446: #
447: # If this is a self-enroll case, a Course Coordinator role will only be assigned
448: # if the current user is also the course owner.
449: #
450:
1.11 raeburn 451: sub enrolluser {
1.12 raeburn 452: my ($udom,$uname,$role,$cdom,$cnum,$sec,$start,$end,$selfenroll) = @_;
1.11 raeburn 453: my $enrollresult;
454: my $area = "/$cdom/$cnum";
455: if (($role ne 'cc') && ($role ne 'co') && ($sec ne '')) {
456: $area .= '/'.$sec;
457: }
458: my $spec = $role.'.'.$area;
459: my $instcid;
460: if ($role eq 'st') {
461: $enrollresult =
462: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,
463: undef,undef,$sec,$end,$start,
1.12 raeburn 464: 'ltienroll',undef,$cdom.'_'.$cnum,
465: $selfenroll,'ltienroll','',$instcid);
1.11 raeburn 466: } elsif ($role =~ /^(cc|in|ta|ep)$/) {
467: $enrollresult =
468: &Apache::lonnet::assignrole($udom,$uname,$area,$role,$end,$start,
1.12 raeburn 469: undef,$selfenroll,'ltienroll');
470: }
471: if ($enrollresult eq 'ok') {
472: if ($selfenroll) {
473: my (%userroles,%newrole,%newgroups);
474: &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,
475: $area);
476: &Apache::lonnet::set_userprivs(\%userroles,\%newrole,\%newgroups);
477: $userroles{'user.role.'.$spec} = $start.'.'.$end;
478: &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
479: }
1.11 raeburn 480: }
481: return $enrollresult;
482: }
483:
1.12 raeburn 484: #
485: # LON-CAPA as LTI Provider
486: #
487: # Gather a list of available LON-CAPA roles derived
488: # from a comma separated list of LTI roles.
489: #
490: # Which LON-CAPA roles are assignable by the current user
491: # and how LTI roles map to LON-CAPA roles (as defined in
492: # the domain configuration for the specific Consumer) are
493: # factored in when compiling the list of available roles.
494: #
495: # Inputs: 3
496: # $rolestr - comma separated list of LTI roles.
497: # $allowedroles - reference to array of assignable LC roles
498: # $maproles - ref to HASH of mapping of LTI roles to LC roles
499: #
500: # Outputs: 2
501: # (a) reference to array of available LC roles.
502: # (b) reference to array of LTI roles.
503: #
504:
1.11 raeburn 505: sub get_lc_roles {
506: my ($rolestr,$allowedroles,$maproles) = @_;
507: my (@ltiroles,@lcroles);
508: my @ltiroleorder = ('Instructor','TeachingAssistant','Mentor','Learner');
509: if ($rolestr =~ /,/) {
510: my @possltiroles = split(/\s*,\s*/,$rolestr);
511: foreach my $ltirole (@ltiroleorder) {
512: if (grep(/^\Q$ltirole\E$/,@possltiroles)) {
513: push(@ltiroles,$ltirole);
514: }
515: }
516: } else {
517: my $singlerole = $rolestr;
518: $singlerole =~ s/^\s|\s+$//g;
519: if ($singlerole ne '') {
520: if (grep(/^\Q$singlerole\E$/,@ltiroleorder)) {
521: @ltiroles = ($singlerole);
522: }
523: }
524: }
525: if (@ltiroles) {
526: my %possroles;
527: map { $possroles{$maproles->{$_}} = 1; } @ltiroles;
528: if (keys(%possroles) > 0) {
529: if (ref($allowedroles) eq 'ARRAY') {
530: foreach my $item (@{$allowedroles}) {
531: if (($item eq 'co') || ($item eq 'cc')) {
532: if ($possroles{'cc'}) {
533: push(@lcroles,$item);
534: }
535: } elsif ($possroles{$item}) {
536: push(@lcroles,$item);
537: }
538: }
539: }
540: }
541: }
542: return (\@lcroles,\@ltiroles);
543: }
544:
1.1 raeburn 545: 1;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>