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