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