Changesets can be listed by changeset number.
The Git repository is here.
- Revision:
- 157
- Log:
Configuration of secure cookie's path now done via environment
variable HUB_COOKIE_PATH rather than being hard-coded. Added
gem reinstallation script for ROOL site.
- Author:
- rool
- Date:
- Sun Dec 10 18:54:08 +0000 2006
- Size:
- 46539 Bytes
1 | ####################################################################### |
2 | # Module: HubSsoLib # |
3 | # By Hipposoft, 2006 # |
4 | # # |
5 | # Purpose: Cross-application same domain single sign-on support. # |
6 | # # |
7 | # Author: A.D.Hodgkinson # |
8 | # # |
9 | # History: 20-Oct-2006 (ADH): First version of stand-alone library, # |
10 | # split from Hub application. # |
11 | # 08-Dec-2006 (ADH): DRB URI, path prefix and random file # |
12 | # path come from environment variables. # |
13 | ####################################################################### |
14 | |
15 | module HubSsoLib |
16 | |
17 | require 'drb' |
18 | |
19 | # DRb connection |
20 | HUBSSOLIB_DRB_URI = ENV['HUB_CONNECTION_URI'] |
21 | |
22 | # Location of Hub application root. |
23 | HUB_PATH_PREFIX = ENV['HUB_PATH_PREFIX'] |
24 | |
25 | # Time limit, *in seconds*, for the account inactivity timeout. |
26 | # If a user performs no Hub actions during this time they will |
27 | # be automatically logged out upon their next action. |
28 | HUBSSOLIB_IDLE_TIME_LIMIT = 60 * 60 |
29 | |
30 | # Random file location. |
31 | HUBSSOLIB_RND_FILE_PATH = ENV['HUB_RANDOM_FILE'] |
32 | |
33 | # Shared cookie name and path. |
34 | HUBSSOLIB_COOKIE_NAME = 'hubapp_shared_id' |
35 | HUBSSOLIB_COOKIE_PATH = ENV['HUB_COOKIE_PATH'] |
36 | |
37 | ####################################################################### |
38 | # Class: Crypto # |
39 | # By Hipposoft, 2006 # |
40 | # # |
41 | # Purpose: Encryption and decryption utilities. # |
42 | # # |
43 | # Author: A.D.Hodgkinson # |
44 | # # |
45 | # History: 28-Aug-2006 (ADH): First version. # |
46 | # 20-Oct-2006 (ADH): Integrated into HubSsoLib, renamed to # |
47 | # 'Crypto' from 'HubSsoCrypto'. # |
48 | ####################################################################### |
49 | |
50 | # Encryption and decryption utility object. Once instantiated with the |
51 | # filename of a file that holds at least 1K of pseudo-random data, a |
52 | # HubSsoLib::Crypto object is used to encrypt and decrypt data with the |
53 | # AES-256-CBC cipher. A single passphrase is used for both operations. |
54 | # A SHA-256 hash of that passphrase is used as the encryption key. |
55 | # |
56 | # CBC operation requires an initialization vector for the first block of |
57 | # data during encryption and decryption. The file of random data is used |
58 | # for this in conjunction with the passphrase used to generate the key. By |
59 | # so doing, the initialization vector is not revealed to third parties, |
60 | # even though the source code of the object is available. The weakness is |
61 | # that for a given passphrase and random data pool the same initialization |
62 | # vector will always be generated - indeed, this is relied upon, to allow |
63 | # callers themselves to only have to remember the passphrase. See private |
64 | # method obtain_iv() for more details. |
65 | # |
66 | class Crypto |
67 | |
68 | require 'openssl' |
69 | require 'digest/sha2' |
70 | require 'digest/md5' |
71 | |
72 | # Initialize the HubSsoLib::Crypto object. Must pass a pathname to a file |
73 | # of effectively random data of at least 1K in length. If the data is |
74 | # larger than 16K in size, everything after the first 16K will be |
75 | # ignored. The data is cached internally when the object starts. |
76 | # |
77 | def initialize(rnd_file) |
78 | # Check the file size and find out how much data to read - at least 1K, |
79 | # no more than 16K. Store the size in @rnd_size and read the data into |
80 | # @rnd_data, both for use later. |
81 | |
82 | @rnd_size = File.size(rnd_file) |
83 | @rnd_size = 16384 if (@rnd_size > 16384) |
84 | |
85 | if @rnd_size < 1024 |
86 | raise "HubSsoLib::Crypto objects need at least 1024 bytes of random data - file '#{rnd_file}' is too small" |
87 | else |
88 | @rnd_data = File.open(rnd_file, 'rb').read(@rnd_size) |
89 | end |
90 | end |
91 | |
92 | # Generate a series of pseudo-random bytes of the given length. |
93 | # |
94 | def self.random_data(size) |
95 | data = '' |
96 | size.times { data << rand(256) } |
97 | data |
98 | end |
99 | |
100 | def random_data(size) |
101 | HubSsoLib::Crypto.random_data(size) |
102 | end |
103 | |
104 | # Encode some given data in base-64 format with no line breaks. |
105 | # |
106 | def self.pack64(data) |
107 | [data].pack('m1000000') # Stupid long number to avoid "\n" in the output |
108 | end |
109 | |
110 | def pack64(data) |
111 | HubSsoLib::Crypto.pack64(data) |
112 | end |
113 | |
114 | # Decode some given data from base-64 format with no line breaks. |
115 | # |
116 | def self.unpack64(data) |
117 | data.unpack('m').first |
118 | end |
119 | |
120 | def unpack64(data) |
121 | HubSsoLib::Crypto.unpack64(data) |
122 | end |
123 | |
124 | # Encrypt the given data with the AES-256-CBC algorithm using the |
125 | # given passphrase. Returns the encrypted result in a string. |
126 | # Distantly based upon: |
127 | # |
128 | # http://www.bigbold.com/snippets/posts/show/576 |
129 | # |
130 | # In the context of Hub, the passphrase tends to be fixed per IP |
131 | # address (albeit unknown to the public) and the IV is derived from |
132 | # it. This means the same data will encode to the same result. With |
133 | # the source data having some parts which are invariant, security |
134 | # is compromised. To avoid this, data is prefixed by a quantity of |
135 | # random bytes, effectively supplementing the IV and ensuring that |
136 | # different size and content data is generated each time. |
137 | # |
138 | def encrypt(data, passphrase) |
139 | cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") |
140 | cipher.encrypt |
141 | |
142 | cipher.key = Digest::SHA256.digest(passphrase) |
143 | cipher.iv = obtain_iv(passphrase) |
144 | |
145 | rsize = rand(32) |
146 | data = '' << rsize << random_data(rsize) << data |
147 | |
148 | encrypted = cipher.update(data) |
149 | encrypted << cipher.final |
150 | |
151 | return encrypted |
152 | end |
153 | |
154 | # Decrypt the given data with the AES-256-CBC algorithm using the |
155 | # given passphrase. Returns 'nil' if there is any kind of error in |
156 | # the decryption process. Distantly based upon: |
157 | # |
158 | # http://www.bigbold.com/snippets/posts/show/576 |
159 | # |
160 | def decrypt(data, passphrase) |
161 | cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") |
162 | cipher.decrypt |
163 | |
164 | cipher.key = Digest::SHA256.digest(passphrase) |
165 | cipher.iv = obtain_iv(passphrase) |
166 | |
167 | decrypted = cipher.update(data) |
168 | decrypted << cipher.final |
169 | |
170 | rsize = decrypted[0] |
171 | return decrypted[rsize + 1..-1] |
172 | rescue |
173 | return nil |
174 | end |
175 | |
176 | # Encrypt and base-64 encode the given data with the given passphrase. |
177 | # Returns the encoded result. |
178 | # |
179 | def encode(data, passphrase) |
180 | pack64(encrypt(data, passphrase)) |
181 | end |
182 | |
183 | # Decrypt and base-64 decode the given data with the given passphrase. |
184 | # Returns the decoded result or 'nil' on error. |
185 | # |
186 | def decode(data, passphrase) |
187 | decrypt(unpack64(data), passphrase) |
188 | rescue |
189 | return nil |
190 | end |
191 | |
192 | # Class method that takes an object and passphrase and encrypts |
193 | # the result. The passphrase is scrambled internally using data |
194 | # not available to the public, the object serialised (so it must |
195 | # support serialisation), encrypted and base-64 encoded, and the |
196 | # 7-bit safe string result returned. On failure, exceptions will |
197 | # be raised (failure is not expected). |
198 | # |
199 | def self.encode_object(object, passphrase) |
200 | crypto = HubSsoLib::Crypto.new(HUBSSOLIB_RND_FILE_PATH) |
201 | passphrase = crypto.scramble_passphrase(passphrase) |
202 | |
203 | return crypto.encode(Marshal.dump(object), passphrase) |
204 | end |
205 | |
206 | def encode_object(object, passphrase) |
207 | HubSsoLib::Crypto.encode_object(object, passphrase) |
208 | end |
209 | |
210 | # Class method that takes output from Crypto.encode_object and |
211 | # decodes it, returning an object reference. Since failure may |
212 | # result from invalid data input and this can be a common case, |
213 | # rather than raise an exception as with Crypto.encode_object, |
214 | # this method returns 'nil' should there be any decode problems. |
215 | # |
216 | def self.decode_object(data, passphrase) |
217 | crypto = HubSsoLib::Crypto.new(HUBSSOLIB_RND_FILE_PATH) |
218 | passphrase = crypto.scramble_passphrase(passphrase) |
219 | object = nil |
220 | |
221 | if (data && !data.empty?) |
222 | object = Marshal.load(crypto.decode(data, passphrase)) |
223 | end |
224 | |
225 | return object |
226 | rescue |
227 | return nil |
228 | end |
229 | |
230 | def decode_object(data, passphrase) |
231 | HubSsoLib::Crypto.decode_object(data, passphrase) |
232 | end |
233 | |
234 | # "Scramble" a passphrase. Cookie data encryption is done purely so that |
235 | # some hypothetical malicious user cannot easily examine or modify the |
236 | # cookie contents for some nefarious purpose. Encryption is done at the |
237 | # head end. We need to be able to decrypt in the absence of any other |
238 | # information. A fixed passphrase thus needs to be used, but it cannot be |
239 | # included in the source code or anyone can read the cookie contents! To |
240 | # work around this, transform the passphrase into 32 bytes of data from |
241 | # the random pool if asked. The random pool is not known to the outside |
242 | # world so security is improved (albeit far from perfect, but this is all |
243 | # part of little more than an anti-spam measure - not Fort Knox!). |
244 | # |
245 | def scramble_passphrase(passphrase) |
246 | |
247 | # Generate a 16-byte hash of the passphrase using the MD5 algorithm. Get |
248 | # this as a string of hex digits and convert that into an integer. Strip |
249 | # off the top bits (since we've no more reason to believe that the top |
250 | # bits contain more randomly varying data than the bottom bits) so that |
251 | # the number is bound to between zero and the random pool size, minus |
252 | # 33, thus providing an offset into the file from which we can safely |
253 | # read 32 bytes of data. |
254 | |
255 | offset = Digest::MD5.hexdigest(passphrase).hex % (@rnd_size - 32) |
256 | |
257 | # Return 32 bytes of data from the random pool at the calculated offset. |
258 | |
259 | return @rnd_data[offset..offset + 31] |
260 | end |
261 | |
262 | private |
263 | |
264 | # Obtain an initialization vector (IV) of 32 bytes (256 bits) length based |
265 | # on external data loaded when the object was created. Since the data |
266 | # content is unknown, the IV is unknown. This is important; see: |
267 | # |
268 | # http://www.ciphersbyritter.com/GLOSSARY.HTM#CipherBlockChaining |
269 | # |
270 | # Weakness: An offset into the supplied data is generated from the given |
271 | # passphrase. Since the data is cached internally, the same IV will be |
272 | # produced for any given passphrase (this is as much a feature as it is a |
273 | # weakness, since the encryption and decryption routines rely on it). |
274 | # |
275 | # The passphrase scrambler is used to do the back-end work. Since the |
276 | # caller may have already scrambled the passphrase once, scrambled data is |
277 | # used as input; we end up scrambling it twice. This is a desired result - |
278 | # we don't want the IV being the data that's actually also used for the |
279 | # encryption passphrase. |
280 | # |
281 | def obtain_iv(passphrase) |
282 | return scramble_passphrase(passphrase) |
283 | end |
284 | |
285 | end # Crypto class |
286 | |
287 | ####################################################################### |
288 | # Class: Roles # |
289 | # By Hipposoft, 2006 # |
290 | # # |
291 | # Purpose: Shared methods for handling user account roles. # |
292 | # # |
293 | # Author: A.D.Hodgkinson # |
294 | # # |
295 | # History: 17-Oct-2006 (ADH): Adapted from Clubhouse. # |
296 | # 20-Oct-2006 (ADH): Integrated into HubSsoLib. # |
297 | ####################################################################### |
298 | |
299 | class Roles |
300 | |
301 | # Association of symbolic role names to display names, in no |
302 | # particular order. |
303 | # |
304 | ROLES = { |
305 | :admin => 'Administrator', |
306 | :webmaster => 'Webmaster', |
307 | :privileged => 'Advanced user', |
308 | :normal => 'Normal user' |
309 | } |
310 | |
311 | ADMIN = :admin |
312 | NORMAL = :normal |
313 | |
314 | # Return the display name of a given role symbol. Class method. |
315 | # |
316 | def self.get_display_name(symbol) |
317 | ROLES[symbol] |
318 | end |
319 | |
320 | # Return all display names in an array. Class method. |
321 | |
322 | def self.get_display_names |
323 | ROLES.values |
324 | end |
325 | |
326 | # Return an array of known role symbols. They can be used with |
327 | # methods like get_display_name. Class method. |
328 | |
329 | def self.get_role_symbols |
330 | ROLES.keys |
331 | end |
332 | |
333 | # Initialize a new Roles object. Pass 'true' if this is for |
334 | # an admin user account, else 'false'. Default is 'false'. Note |
335 | # that further down in this file, the String, Symbol and Array |
336 | # classes are extended with to_authenticated_roles methods, which |
337 | # provide other ways of creating Roles objects. |
338 | # |
339 | def initialize(admin = false) |
340 | if (admin) |
341 | @role_array = [ ADMIN ] |
342 | else |
343 | @role_array = [ NORMAL ] |
344 | end |
345 | end |
346 | |
347 | # Adds a role, supplied as a string or symbol, to the internal list. |
348 | # A non-nil return indicates that the role was already present. |
349 | # |
350 | def add(role) |
351 | @role_array.push(role.to_s.intern).uniq! |
352 | end |
353 | |
354 | # Deletes a role, supplied as a string or symbol, from the internal |
355 | # list. A nil return indicates that the role was not in the list. |
356 | # |
357 | def delete(role) |
358 | @role_array.delete(role.to_s.intern) |
359 | end |
360 | |
361 | # Delete all roles from the internal list. |
362 | # |
363 | def clear |
364 | @role_array.clear |
365 | end |
366 | |
367 | # Return a copy of the internal roles list as a string. |
368 | # |
369 | def to_s |
370 | return @role_array.join(',') |
371 | end |
372 | |
373 | # Return a copy of the internal roles list as an array. |
374 | # |
375 | def to_a |
376 | return @role_array.dup |
377 | end |
378 | |
379 | # Return a copy of the intenal roles list as a human readable string. |
380 | # |
381 | def to_human_s |
382 | human_names = [] |
383 | |
384 | @role_array.each do |role| |
385 | human_names.push(HubSsoLib::Roles.get_display_name(role)) |
386 | end |
387 | |
388 | if (human_names.length == 0) |
389 | return '' |
390 | elsif (human_names.length == 1) |
391 | return human_names[0] |
392 | else |
393 | return human_names[0..-2].join(', ') + ' and ' + human_names.last |
394 | end |
395 | end |
396 | |
397 | # Do nothing - this is just useful for polymorphic code, where a function |
398 | # can take a String, Array, Symbol or Roles object and make the |
399 | # same method call to return a Roles object in return. |
400 | # |
401 | def to_authenticated_roles |
402 | return self |
403 | end |
404 | |
405 | # Does the internal list of roles include the supplied role or roles? |
406 | # The roles can be given as an array of individual role symbols or |
407 | # equivalent strings, or as a single symbol or single equivalent |
408 | # symbol, or as a string containing equivalents of role symbols in a |
409 | # comma-separated list (no white space or other spurious characters). |
410 | # Returns 'true' if the internal list of roles includes at least one |
411 | # of the supplied roles, else 'false'. |
412 | # |
413 | def include?(roles) |
414 | return false if roles.nil? |
415 | |
416 | # Ensure we've an array of roles, one way or another |
417 | roles = roles.to_s if roles.class == Symbol |
418 | roles = roles.split(',') if roles.class == String |
419 | |
420 | roles.each do |role| |
421 | return true if @role_array.include?(role.to_s.intern) |
422 | end |
423 | |
424 | return false |
425 | end |
426 | |
427 | # Synonym for 'include?'. |
428 | # |
429 | alias includes? include? |
430 | |
431 | # Validate the list of roles. Validation means ensuring that all |
432 | # roles in this object are found in the internal ROLES hash. Returns |
433 | # true if the roles validate or false if unknown roles are found. |
434 | # |
435 | def validate |
436 | return false if @role_array.empty? |
437 | |
438 | @role_array.each do |role| |
439 | return false unless ROLES[role] |
440 | end |
441 | |
442 | return true |
443 | end |
444 | |
445 | end # Roles class |
446 | |
447 | ####################################################################### |
448 | # Class: Permissions # |
449 | # By Hipposoft, 2006 # |
450 | # # |
451 | # Purpose: Methods to help, in conjunction with Roles, determine the # |
452 | # access permissions a particular user is granted. # |
453 | # # |
454 | # Author: A.D.Hodgkinson # |
455 | # # |
456 | # History: 17-Oct-2006 (ADH): Adapted from Clubhouse. # |
457 | # 20-Oct-2006 (ADH): Integrated into HubSsoLib. # |
458 | ####################################################################### |
459 | |
460 | class Permissions |
461 | |
462 | # Initialize a permissions object. The map is a hash which maps action |
463 | # names, expressed as symbols, to roles, expressed as individual symbols, |
464 | # equivalent strings, or arrays of multiple strings or symbols. Use 'nil' |
465 | # to indicate permission for the general public - no login required - or |
466 | # simply omit the action (unlisted actions are permitted). |
467 | # |
468 | # Example mapping for a generic controller: |
469 | # |
470 | # { |
471 | # :new => [ :admin, :webmaster, :privileged, :normal ], |
472 | # :create => [ :admin, :webmaster, :privileged, :normal ], |
473 | # :edit => [ :admin, :webmaster, :privileged, :normal ], |
474 | # :update => [ :admin, :webmaster, :privileged, :normal ], |
475 | # :delete => [ :admin, :webmaster, :privileged ], |
476 | # :list => nil, |
477 | # :show => nil |
478 | # } |
479 | # |
480 | def initialize(pmap) |
481 | @permissions = pmap |
482 | end |
483 | |
484 | # Does the given Roles object grant permission for the given action, |
485 | # expressed as a string or symbol? Returns 'true' if so, else 'false'. |
486 | # |
487 | # If a role is given as some other type, an attempt is made to convert |
488 | # it to a Roles object internally (so you could pass a role symbol, |
489 | # string, array of symbols or strings, or comma-separated string). |
490 | # |
491 | # Passing an empty roles string will tell you whether or not the |
492 | # action requires login. Only actions not in the permissions list or |
493 | # those with a 'nil' list of roles will generate a result 'true', |
494 | # since any other actions will require your empty roles string to |
495 | # include at least one role (which it obviously doesn't). |
496 | # |
497 | def permitted?(roles, action) |
498 | action = action.to_s.intern |
499 | roles = roles.to_authenticated_roles |
500 | |
501 | return true unless @permissions.include?(action) |
502 | return true if @permissions[action].nil? |
503 | return roles.include?(@permissions[action]) |
504 | end |
505 | end # Permissions class |
506 | |
507 | ####################################################################### |
508 | # Class: User # |
509 | # By Hipposoft, 2006 # |
510 | # # |
511 | # Purpose: A representation of the Hub application's User Model in # |
512 | # terms of a simple set of properties, so that applications # |
513 | # don't need User access to understand user attributes. # |
514 | # # |
515 | # Author: A.D.Hodgkinson # |
516 | # # |
517 | # History: 21-Oct-2006 (ADH): Created. # |
518 | ####################################################################### |
519 | |
520 | class User |
521 | include DRb::DRbUndumped |
522 | |
523 | attr_accessor :user_salt |
524 | attr_accessor :user_roles |
525 | attr_accessor :user_updated_at |
526 | attr_accessor :user_activated_at |
527 | attr_accessor :user_real_name |
528 | attr_accessor :user_crypted_password |
529 | attr_accessor :user_remember_token_expires_at |
530 | attr_accessor :user_activation_code |
531 | attr_accessor :user_member_id |
532 | attr_accessor :user_id |
533 | attr_accessor :user_password_reset_code |
534 | attr_accessor :user_remember_token |
535 | attr_accessor :user_email |
536 | attr_accessor :user_created_at |
537 | attr_accessor :user_password_reset_code_expires_at |
538 | |
539 | def initialize |
540 | @user_salt = nil |
541 | @user_roles = nil |
542 | @user_updated_at = nil |
543 | @user_activated_at = nil |
544 | @user_real_name = nil |
545 | @user_crypted_password = nil |
546 | @user_remember_token_expires_at = nil |
547 | @user_activation_code = nil |
548 | @user_member_id = nil |
549 | @user_id = nil |
550 | @user_password_reset_code = nil |
551 | @user_remember_token = nil |
552 | @user_email = nil |
553 | @user_created_at = nil |
554 | @user_password_reset_code_expires_at = nil |
555 | end |
556 | end # User class |
557 | |
558 | ####################################################################### |
559 | # Class: Session # |
560 | # By Hipposoft, 2006 # |
561 | # # |
562 | # Purpose: Session support object, used to store session metadata in # |
563 | # an insecure cross-application cookie. # |
564 | # # |
565 | # Author: A.D.Hodgkinson # |
566 | # # |
567 | # History: 22-Oct-2006 (ADH): Created. # |
568 | ####################################################################### |
569 | |
570 | class Session |
571 | include DRb::DRbUndumped |
572 | |
573 | attr_accessor :session_last_used |
574 | attr_accessor :session_return_to |
575 | attr_accessor :session_flash |
576 | attr_accessor :session_user |
577 | |
578 | def initialize |
579 | @session_last_used = Time.now.utc |
580 | @session_return_to = nil |
581 | @session_flash = {} |
582 | @session_user = HubSsoLib::User.new |
583 | end |
584 | end # Session class |
585 | |
586 | ####################################################################### |
587 | # Class: SessionFactory # |
588 | # By Hipposoft, 2006 # |
589 | # # |
590 | # Purpose: Build Session objects for DRb server clients. Maintains a # |
591 | # hash of Session objects. # |
592 | # # |
593 | # Author: A.D.Hodgkinson # |
594 | # # |
595 | # History: 26-Oct-2006 (ADH): Created. # |
596 | ####################################################################### |
597 | |
598 | class SessionFactory |
599 | def initialize |
600 | @sessions = {} |
601 | end |
602 | |
603 | def get_session(key) |
604 | unless (@sessions.has_key? key) |
605 | @sessions[key] = HubSsoLib::Session.new |
606 | end |
607 | |
608 | return @sessions[key] |
609 | end |
610 | end |
611 | |
612 | ####################################################################### |
613 | # Module: Server # |
614 | # By Hipposoft, 2006 # |
615 | # # |
616 | # Purpose: DRb server to provide shared data across applications. # |
617 | # Thanks to RubyPanther, rubyonrails IRC, for suggesting # |
618 | # this after a cookie-based scheme failed. # |
619 | # # |
620 | # Include the module then call hubssolib_launch_server. The # |
621 | # call will not return as the server runs indefinitely. # |
622 | # # |
623 | # Author: A.D.Hodgkinson # |
624 | # # |
625 | # History: 26-Oct-2006 (ADH): Created. # |
626 | ####################################################################### |
627 | |
628 | module Server |
629 | def hubssolib_launch_server |
630 | DRb.start_service(HUBSSOLIB_DRB_URI, HubSsoLib::SessionFactory.new) |
631 | DRb.thread.join |
632 | end |
633 | end # Server module |
634 | |
635 | ####################################################################### |
636 | # Module: Core # |
637 | # Various authors # |
638 | # # |
639 | # Purpose: The barely recognisable core of acts_as_authenticated's # |
640 | # AuthenticatedSystem module, modified to work with the # |
641 | # other parts of HubSsoLib. You should include this module # |
642 | # to use its facilities. # |
643 | # # |
644 | # Author: Various; adaptation by A.D.Hodgkinson # |
645 | # # |
646 | # History: 20-Oct-2006 (ADH): Integrated into HubSsoLib. # |
647 | ####################################################################### |
648 | |
649 | module Core |
650 | |
651 | # Returns true or false if the user is logged in. |
652 | # |
653 | # Preloads @hubssolib_current_user with user data if logged in. |
654 | # |
655 | def hubssolib_logged_in? |
656 | !!self.hubssolib_current_user |
657 | end |
658 | |
659 | # Check if the user is authorized to perform the current action. If calling |
660 | # from a helper, pass the action name and class name; otherwise by default, |
661 | # the current action name and 'self.class' will be used. |
662 | # |
663 | # Override this method in your controllers if you want to restrict access |
664 | # to a different set of actions. Presently, the current user's roles are |
665 | # compared against the caller's permissions hash and the action name. |
666 | # |
667 | def hubssolib_authorized?(action = action_name, classname = self.class) |
668 | |
669 | # Classes with no permissions object always authorise everything. |
670 | # Otherwise, ask the permissions object for its opinion. |
671 | |
672 | if (classname.respond_to? :hubssolib_permissions) |
673 | return classname.hubssolib_permissions.permitted?(hubssolib_get_user_roles, action) |
674 | else |
675 | return true |
676 | end |
677 | end |
678 | |
679 | # Is the current user privileged? Anything other than normal user |
680 | # privileges will suffice. Can be called if not logged in. Returns |
681 | # 'false' for logged out or normal user privileges only, else 'true'. |
682 | # |
683 | def hubssolib_privileged? |
684 | return false unless hubssolib_logged_in? |
685 | |
686 | pnormal = HubSsoLib::Roles.new(false).to_s |
687 | puser = hubssolib_get_user_roles.to_s |
688 | |
689 | return (puser && !puser.empty? && puser != pnormal) |
690 | end |
691 | |
692 | # Log out the user. Very few applications should ever need to call this, |
693 | # though Hub certainly does and it gets used internally too. |
694 | # |
695 | def hubssolib_log_out |
696 | # Causes the "hubssolib_current_[foo]=" methods to run, which |
697 | # deal with everything else. |
698 | self.hubssolib_current_user = nil |
699 | self.hubssolib_current_session = nil |
700 | end |
701 | |
702 | # Accesses the current user, via the DRb server if necessary |
703 | # |
704 | def hubssolib_current_user |
705 | hubssolib_get_user_data |
706 | end |
707 | |
708 | # Store the given user data in the cookie |
709 | # |
710 | def hubssolib_current_user=(new_user) |
711 | hubssolib_set_user_data(new_user) |
712 | end |
713 | |
714 | # Accesses the current session from the cookie. Creates a new |
715 | # session object if need be. |
716 | # |
717 | def hubssolib_current_session |
718 | @hubssolib_current_session ||= hubssolib_get_session_data |
719 | end |
720 | |
721 | # Store the given session data. |
722 | # |
723 | def hubssolib_current_session=(new_session) |
724 | @hubssolib_current_session = new_session |
725 | end |
726 | |
727 | # Public read-only accessor methods for common user activities: |
728 | # return the current user's roles as a Roles object, or nil if |
729 | # there's no user. |
730 | # |
731 | def hubssolib_get_user_roles |
732 | user = self.hubssolib_current_user |
733 | user ? user.user_roles.to_authenticated_roles : nil |
734 | end |
735 | |
736 | # Public read-only accessor methods for common user activities: |
737 | # return the current user's name as a string, or nil if there's |
738 | # no user. See also hubssolib_unique_name. |
739 | # |
740 | def hubssolib_get_user_name |
741 | user = self.hubssolib_current_user |
742 | user ? user.user_real_name : nil |
743 | end |
744 | |
745 | # Public read-only accessor methods for common user activities: |
746 | # return the Hub database ID of the current user account, or |
747 | # nil if there's no user. See also hubssolib_unique_name. |
748 | # |
749 | def hubssolib_get_user_id |
750 | user = self.hubssolib_current_user |
751 | user ? user.user_id : nil |
752 | end |
753 | |
754 | # Public read-only accessor methods for common user activities: |
755 | # return the current user's e-mail address, or nil if there's |
756 | # no user. |
757 | # |
758 | def hubssolib_get_user_address |
759 | user = self.hubssolib_current_user |
760 | user ? user.user_email : nil |
761 | end |
762 | |
763 | # Return a human-readable unique ID for a user. We don't want to |
764 | # have e-mail addresses all over the place, but don't want to rely |
765 | # on real names as unique - they aren't. Instead, produce a |
766 | # composite of the user's account database ID (which must be |
767 | # unique by definition) and their real name. See also |
768 | # hubssolib_get_name. |
769 | # |
770 | def hubssolib_unique_name |
771 | user = hubssolib_current_user |
772 | user ? "#{user.user_real_name} (#{user.user_id})" : 'Anonymous' |
773 | end |
774 | |
775 | # Main filter method to implement HubSsoLib permissions management, |
776 | # session expiry and so-on. Call from controllers only, always as a |
777 | # before_fitler. |
778 | # |
779 | def hubssolib_beforehand |
780 | |
781 | # Does this action require a logged in user? |
782 | |
783 | if (self.class.respond_to? :hubssolib_permissions) |
784 | login_is_required = !self.class.hubssolib_permissions.permitted?('', action_name) |
785 | else |
786 | login_is_required = false |
787 | end |
788 | |
789 | # If we require login but we're logged out, redirect to Hub login. |
790 | |
791 | logged_in = hubssolib_logged_in? |
792 | |
793 | if (login_is_required and logged_in == false) |
794 | hubssolib_store_location |
795 | return hubssolib_must_login |
796 | end |
797 | |
798 | # If we reach here the user is either logged, or the method does |
799 | # not require them to be. In the latter case, if we're not logged |
800 | # in there is no more work to do - exit early. |
801 | |
802 | return true unless logged_in # true -> let action processing continue |
803 | |
804 | # So we reach here knowing we're logged in, but the action may or |
805 | # may not require authorisation. |
806 | |
807 | unless (login_is_required) |
808 | |
809 | # We have to update session expiry even for actions that don't |
810 | # need us to be logged in, since we *are* logged in and need to |
811 | # maintain that state. If, though, the session expires, we just |
812 | # quietly log out and let action processing carry on. |
813 | |
814 | if (hubssolib_session_expired?) |
815 | hubssolib_log_out |
816 | hubssolib_set_flash(:attention, 'Your session timed out, so you are no longer logged in.') |
817 | else |
818 | hubssolib_set_last_used(Time.now.utc) |
819 | end |
820 | |
821 | return true # true -> let action processing continue |
822 | |
823 | else |
824 | |
825 | # Login *is* required for this action. If the session expires, |
826 | # redirect to Hub's login page via its expiry action. Otherwise |
827 | # check authorisation and allow action processing to continue |
828 | # if OK, else indicate that access is denied. |
829 | |
830 | if (hubssolib_session_expired?) |
831 | hubssolib_store_location |
832 | hubssolib_log_out |
833 | hubssolib_set_flash(:attention, 'Sorry, your session timed out; you need to log in again to continue.') |
834 | |
835 | # We mean this: redirect_to :controller => 'account', :action => 'login' |
836 | # ...except for the Hub, rather than the current application (whatever |
837 | # it may be). |
838 | redirect_to HUB_PATH_PREFIX + '/account/login' |
839 | else |
840 | hubssolib_set_last_used(Time.now.utc) |
841 | return hubssolib_authorized? ? true : hubssolib_access_denied |
842 | end |
843 | |
844 | end |
845 | end |
846 | |
847 | # Main after_filter method to tidy up after running state changes. |
848 | # |
849 | def hubssolib_afterwards |
850 | # Nothing to do right now; maybe in future... |
851 | end |
852 | |
853 | # Store the URI of the current request in the session, or store the |
854 | # optional supplied specific URI. |
855 | # |
856 | # We can return to this location by calling #redirect_back_or_default. |
857 | # |
858 | def hubssolib_store_location(uri_str = request.request_uri) |
859 | |
860 | if (uri_str && !uri_str.empty?) |
861 | uri_str = hubssolib_promote_uri_to_ssl(uri_str, request.host) |
862 | hubssolib_set_return_to(uri_str) |
863 | else |
864 | hubssolib_set_return_to(nil) |
865 | end |
866 | |
867 | end |
868 | |
869 | # Redirect to the URI stored by the most recent store_location call or |
870 | # to the passed default. |
871 | def hubssolib_redirect_back_or_default(default) |
872 | url = hubssolib_get_return_to |
873 | hubssolib_set_return_to(nil) |
874 | |
875 | url ? redirect_to_url(url) : redirect_to(default) |
876 | end |
877 | |
878 | # Take a URI and pass an optional host parameter. Decomposes the URI, |
879 | # sets the host you provide (or leaves it alone if you omit the |
880 | # parameter), then forces the scheme to 'https'. Returns the result |
881 | # as a flat string. |
882 | |
883 | def hubssolib_promote_uri_to_ssl(uri_str, host = nil) |
884 | uri = URI.parse(uri_str) |
885 | uri.host = host if host |
886 | uri.scheme = 'https' |
887 | return uri.to_s |
888 | end |
889 | |
890 | # Ensure the current request is carried out over HTTPS by redirecting |
891 | # back to the current URL with the HTTPS protocol if it isn't. Returns |
892 | # 'true' if not redirected (already HTTPS), else 'false'. |
893 | # |
894 | def hubssolib_ensure_https |
895 | unless request.ssl? |
896 | # This isn't reliable: redirect_to({ :protocol => 'https://' }) |
897 | redirect_to (hubssolib_promote_uri_to_ssl(request.request_uri, request.host)) |
898 | return false |
899 | else |
900 | return true |
901 | end |
902 | end |
903 | |
904 | # Public methods to set some data that would normally go in @session, |
905 | # but can't because it needs to be accessed across applications. It is |
906 | # put in an insecure support cookie instead. There are some related |
907 | # private methods for things like session expiry too. |
908 | # |
909 | def hubssolib_get_flash() |
910 | f = self.hubssolib_current_session ? self.hubssolib_current_session.session_flash : nil |
911 | return f || {} |
912 | end |
913 | |
914 | def hubssolib_set_flash(symbol, message) |
915 | return unless self.hubssolib_current_session |
916 | f = hubssolib_get_flash |
917 | f[symbol] = message |
918 | self.hubssolib_current_session.session_flash = f |
919 | end |
920 | |
921 | def hubssolib_clear_flash |
922 | return unless self.hubssolib_current_session |
923 | self.hubssolib_current_session.session_flash = {} |
924 | end |
925 | |
926 | # Helper methods to output flash data. It isn't merged into the standard |
927 | # application flash with a filter because the rather daft and difficult |
928 | # to manage lifecycle model of the standard flash gets in the way. |
929 | # |
930 | # First, return tags for a flash using the given key, clearing the |
931 | # result in the flash hash now it has been used. |
932 | # |
933 | def hubssolib_flash_tag(key) |
934 | value = hubssolib_get_flash[key] |
935 | |
936 | if (value) |
937 | hubssolib_set_flash(key, nil) |
938 | return "<h2 align=\"left\" class=\"#{key}\">#{value}</h2><p />" |
939 | else |
940 | return '' |
941 | end |
942 | end |
943 | |
944 | # Next, return tags for a standard application flash using the given key. |
945 | # |
946 | def hubssolib_standard_flash_tag(key) |
947 | value = flash[key] if defined?(flash) |
948 | |
949 | if (value) |
950 | flash.delete(key) |
951 | return "<h2 align=\"left\" class=\"#{key}\">#{value}</h2><p />" |
952 | else |
953 | return '' |
954 | end |
955 | end |
956 | |
957 | # Return flash tags for known keys, then all remaining keys, from both |
958 | # the cross-application and standard standard flash hashes. |
959 | # |
960 | def hubssolib_flash_tags |
961 | # These known key values are used to guarantee an order in the output |
962 | # for cases where multiple messages are defined. |
963 | |
964 | tags = hubssolib_flash_tag(:notice) << |
965 | hubssolib_flash_tag(:attention) << |
966 | hubssolib_flash_tag(:alert) |
967 | |
968 | tags << hubssolib_standard_flash_tag(:notice) << |
969 | hubssolib_standard_flash_tag(:attention) << |
970 | hubssolib_standard_flash_tag(:alert) |
971 | |
972 | # Now pick up anything else. |
973 | |
974 | hubssolib_get_flash.each do |key, value| |
975 | tags << hubssolib_flash_tag(key) if (value and !value.empty?) |
976 | end |
977 | |
978 | flash.each do |key, value| |
979 | tags << hubssolib_standard_flash_tag(key) if (value and !value.empty?) |
980 | end if defined?(flash) |
981 | |
982 | return tags |
983 | end |
984 | |
985 | # Retrieve the message of an exception stored as an object in the given |
986 | # string. |
987 | # |
988 | def hubssolib_get_exception_message(id_data) |
989 | hubssolib_get_exception_data(id_data) |
990 | end |
991 | |
992 | # Inclusion hook to make various methods available as ActionView |
993 | # helper methods. |
994 | # |
995 | def self.included(base) |
996 | base.send :helper_method, |
997 | :hubssolib_current_user, |
998 | :hubssolib_unique_name, |
999 | :hubssolib_logged_in?, |
1000 | :hubssolib_authorized?, |
1001 | :hubssolib_privileged?, |
1002 | :hubssolib_flash_tags |
1003 | rescue |
1004 | # We're not always included in controllers... |
1005 | nil |
1006 | end |
1007 | |
1008 | private |
1009 | |
1010 | # Indicate that the user must log in to complete their request. |
1011 | # Returns false to enable a before_filter to return through this |
1012 | # method while ensuring that the previous action processing is |
1013 | # halted (since the overall return value is therefore 'false'). |
1014 | # |
1015 | def hubssolib_must_login |
1016 | # If HTTP, redirect to the same place, but HTTPS. Then we can store the |
1017 | # flash and return-to in the session data. We'll have the same set of |
1018 | # before-filter operations running and they'll find out we're either |
1019 | # authorised after all, or come back to this very function, which will |
1020 | # now be happily running from an HTTPS connection and will go on to set |
1021 | # the flash and redirect to the login page. |
1022 | |
1023 | if hubssolib_ensure_https |
1024 | hubssolib_set_flash(:alert, 'You must log in before you can continue.') |
1025 | redirect_to HUB_PATH_PREFIX + '/account/login' |
1026 | end |
1027 | |
1028 | return false |
1029 | end |
1030 | |
1031 | # Indicate access is denied for a given logged in user's request. |
1032 | # Returns false to enable a before_filter to return through this |
1033 | # method while ensuring that the previous action processing is |
1034 | # halted (since the overall return value is therefore 'false'). |
1035 | # |
1036 | def hubssolib_access_denied |
1037 | # See hubsso_must_login for the reason behind the following call. |
1038 | |
1039 | if hubssolib_ensure_https |
1040 | hubssolib_set_flash(:alert, 'You do not have permission to carry out that action on this site.') |
1041 | redirect_to HUB_PATH_PREFIX + '/' |
1042 | end |
1043 | |
1044 | return false |
1045 | end |
1046 | |
1047 | # Check conditions for session expiry. Returns 'true' if session's |
1048 | # last_used date indicates expiry, else 'false'. |
1049 | # |
1050 | def hubssolib_session_expired? |
1051 | |
1052 | # 23-Oct-2006 (ADH): |
1053 | # |
1054 | # An exception, which is also a security hole of sorts. POST requests |
1055 | # cannot be redirected because HTTP doesn't have that concept. If a user |
1056 | # is editing a Wiki page, say, then goes away, comes back later and now |
1057 | # finishes their edits, their session may have timed out. They submit |
1058 | # the page but it's by POST so their submission details are lost. If they |
1059 | # are lucky their browser might remember the form contents if they go |
1060 | # back but not all do and not all users would think of doing that. |
1061 | # |
1062 | # To work around this, don't enforce a timeout for POST requests. Should |
1063 | # a user on a public computer not log out, then a hacker arrive *after* |
1064 | # the session expiry time (if they arrive before it expires then the |
1065 | # except for POSTs is irrelevant), they could recover the session by |
1066 | # constructing a POST request. It's a convoluted path, requires a user to |
1067 | # have not logged out anyway, and the Hub isn't intended for Fort Knox. |
1068 | # At the time of writing the trade-off of usability vs security is |
1069 | # considered acceptable, though who knows, the view may change in future. |
1070 | |
1071 | last_used = hubssolib_get_last_used |
1072 | (request.method != :post && last_used && Time.now.utc - last_used > HUBSSOLIB_IDLE_TIME_LIMIT) |
1073 | end |
1074 | |
1075 | # Retrieve data from a given cookie with encrypted contents. |
1076 | # |
1077 | def hubssolib_get_secure_cookie_data(name) |
1078 | return HubSsoLib::Crypto.decode_object(cookies[name], request.remote_ip) |
1079 | end |
1080 | |
1081 | # Set the given cookie to a value of the given data, which |
1082 | # will be encrypted. |
1083 | # |
1084 | def hubssolib_set_secure_cookie_data(name, value) |
1085 | if (@hubssolib_have_written_cookie) |
1086 | raise "HubSsoLib: Attmept to set cookie '#{name}' more than once" |
1087 | end |
1088 | |
1089 | @hubssolib_have_written_cookie = true |
1090 | |
1091 | # Using cookies.delete *should* work but doesn't. Set the |
1092 | # cookie with nil data instead. |
1093 | |
1094 | data = value.nil? ? nil : HubSsoLib::Crypto.encode_object(value, request.remote_ip) |
1095 | |
1096 | # No expiry time; to aid security, use session cookies only. |
1097 | |
1098 | cookies[name] = { |
1099 | :value => data, |
1100 | :path => HUBSSOLIB_COOKIE_PATH, |
1101 | :secure => true |
1102 | } |
1103 | end |
1104 | |
1105 | # Retrieve user data from the DRb server. |
1106 | # |
1107 | def hubssolib_get_user_data |
1108 | user = self.hubssolib_current_session ? self.hubssolib_current_session.session_user : nil |
1109 | |
1110 | if (user && user.user_id) |
1111 | return user |
1112 | else |
1113 | return nil |
1114 | end |
1115 | end |
1116 | |
1117 | def hubssolib_set_user_data(user) |
1118 | self.hubssolib_current_session.session_user = user |
1119 | end |
1120 | |
1121 | def hubssolib_get_session_data |
1122 | |
1123 | # If we're not using SSL, forget it |
1124 | return nil unless request.ssl? |
1125 | |
1126 | # If we've no cookie, we need a new session ID |
1127 | key = hubssolib_get_secure_cookie_data(HUBSSOLIB_COOKIE_NAME) |
1128 | |
1129 | unless (key) |
1130 | key = HubSsoLib::Crypto.pack64(HubSsoLib::Crypto.random_data(48)) |
1131 | hubssolib_set_secure_cookie_data(HUBSSOLIB_COOKIE_NAME, key) |
1132 | end |
1133 | |
1134 | DRb.start_service() |
1135 | |
1136 | factory = DRbObject.new_with_uri(HUBSSOLIB_DRB_URI) |
1137 | return factory.get_session(key) |
1138 | |
1139 | rescue Exception => e |
1140 | |
1141 | # At this point there tends to be no Session data, so we're |
1142 | # going to have to encode the exception data into the URI... |
1143 | |
1144 | suffix = '/' + CGI::escape(hubssolib_set_exception_data(e)) |
1145 | new_path = HUB_PATH_PREFIX + '/tasks/service' |
1146 | redirect_to new_path + suffix unless request.path.include?(new_path) |
1147 | return nil |
1148 | end |
1149 | |
1150 | def hubssolib_set_session_data(session) |
1151 | # Nothing to do presently - DRb handles everything |
1152 | end |
1153 | |
1154 | # Encode exception data into a string suitable for using in a URL |
1155 | # if CGI escaped first. Pass the exception object; stores only the |
1156 | # message. |
1157 | # |
1158 | def hubssolib_set_exception_data(e) |
1159 | HubSsoLib::Crypto.encode_object(e.message, request.remote_ip) |
1160 | end |
1161 | |
1162 | # Decode exception data encoded with hubssolib_set_exception_data. |
1163 | # Returns the originally stored message string or 'nil' if there |
1164 | # are any decoding problems. Pass the encoded data. |
1165 | # |
1166 | def hubssolib_get_exception_data(data) |
1167 | HubSsoLib::Crypto.decode_object(data, request.remote_ip) |
1168 | end |
1169 | |
1170 | # Various accessors that ultimately run through the DRb server if |
1171 | # the session data is available, else return default values. |
1172 | |
1173 | def hubssolib_get_last_used |
1174 | session = self.hubssolib_current_session |
1175 | session ? session.session_last_used : Time.now.utc |
1176 | end |
1177 | |
1178 | def hubssolib_set_last_used(time) |
1179 | return unless self.hubssolib_current_session |
1180 | self.hubssolib_current_session.session_last_used = time |
1181 | end |
1182 | |
1183 | def hubssolib_get_return_to |
1184 | session = self.hubssolib_current_session |
1185 | session ? session.session_return_to : nil |
1186 | end |
1187 | |
1188 | def hubssolib_set_return_to(uri) |
1189 | return unless self.hubssolib_current_session |
1190 | self.hubssolib_current_session.session_return_to = uri |
1191 | end |
1192 | |
1193 | end # Core module |
1194 | end # HubSsoLib module |
1195 | |
1196 | ####################################################################### |
1197 | # Classes: Standard class extensions for HubSsoLib Roles operations. # |
1198 | # By Hipposoft, 2006 # |
1199 | # # |
1200 | # Purpose: Extensions to standard classes to support HubSsoLib. # |
1201 | # # |
1202 | # Author: A.D.Hodgkinson # |
1203 | # # |
1204 | # History: 20-Oct-2006 (ADH): Integrated into HubSsoLib. # |
1205 | ####################################################################### |
1206 | |
1207 | # Method to return a Roles object created from the |
1208 | # contents of the String the method is invoked upon. The |
1209 | # string may contain a single role or a comma-separated list |
1210 | # with no white space. |
1211 | # |
1212 | class String |
1213 | def to_authenticated_roles |
1214 | roles = HubSsoLib::Roles.new |
1215 | array = self.split(',') |
1216 | |
1217 | roles.clear |
1218 | array.each { |role| roles.add(role) } |
1219 | |
1220 | return roles |
1221 | end |
1222 | end # String class |
1223 | |
1224 | # Method to return a Roles object created from the |
1225 | # contents of the Symbol the method is invoked upon. |
1226 | # |
1227 | class Symbol |
1228 | def to_authenticated_roles |
1229 | return self.to_s.to_authenticated_roles |
1230 | end |
1231 | end # Symbol class |
1232 | |
1233 | # Method to return a Roles object created from the |
1234 | # contents of the Array the method is invoked upon. The array |
1235 | # contents will be flattened. After that, each entry must be |
1236 | # a single role symbol or string equivalent. Comma-separated |
1237 | # lists are not currently allowed (improvements to the roles |
1238 | # class could easily give this, but the bloat isn't needed). |
1239 | # |
1240 | class Array |
1241 | def to_authenticated_roles |
1242 | roles = HubSsoLib::Roles.new |
1243 | roles.clear |
1244 | |
1245 | self.flatten.each { |entry| roles.add(entry.to_s) } |
1246 | |
1247 | return roles |
1248 | end |
1249 | end # Array class |