Class | User
In: | app/models/user.rb
Parent: | ActiveRecord::Base

### Methods

authenticate authenticate_from_url authenticated? can? can_access? can_change_schedule? can_create? can_edit? can_edit_schedule? can_see_l_schedule? can_see_schedule? editable_schedules_with_create_option editable_schedules_with_radio email_blank encrypt encrypt encrypt_password forget_me generate_random_password_if_empty has_department? has_department_schedule? has_ma_access? has_schedule_permissions? internal_name is_admin? is_official_commenter? is_staff? nullify_url_if_necessary organization_ids password_required? permission? permissions_for_form permissions_for_form_array public_name remember_me remember_me_for remember_me_until remember_token? set_default_status update_permissions

### Constants

STATUS | = | %w(pendiente aprobado vetado)
TYPES | = | {'Person' => 'Registrado', 'Colaborator' => 'Colaborador', 'Admin' => 'Administrador', 'Journalist' => 'Periodista', 'DepartmentEditor' => 'Jefe de prensa', 'StaffChief' => 'Jefe de gabinete', 'StreamingOperator' => 'Operador de streaming', 'DepartmentMember' => 'Miembro de departamento'}
STAFF | = | %w(Admin DepartmentEditor StaffChief)

### Attributes

password | [RW] | Virtual attribute for the unencrypted password

### Public Class methods

authenticate(email, password)

Authenticates a user by their login name and unencrypted password. Returns the user or nil.

[Source]

        # File app/models/user.rb, line 56
    56:   def self.authenticate(email, password)
    57:     u = find_by_email_and_status(email, 'aprobado') # need to get the salt
    58:     u && u.authenticated?(password) ? u : nil
    59:   end

authenticate_from_url(user_id, crypted_password)

Authenticates a user by their login name and encrypted password. Returns the user or nil.

[Source]

        # File app/models/user.rb, line 62
    62:   def self.authenticate_from_url(user_id, crypted_password)
    63:     u = find_by_id_and_status_and_crypted_password(user_id, "aprobado", crypted_password)
    64:   end

encrypt(password, salt)

Encrypts some data with the salt.

[Source]

        # File app/models/user.rb, line 91
    91:   def self.encrypt(password, salt)
    92:     Digest::SHA1.hexdigest("--#{salt}--#{password}--")
    93:   end

### Public Instance methods

authenticated?(password)

Determines wheather the user is authenticated

[Source]

         # File app/models/user.rb, line 101
    101:   def authenticated?(password)
    102:     crypted_password == encrypt(password)
    103:   end

can?(perm_type, doc_type)

[Source]

         # File app/models/user.rb, line 233
    233:   def can?(perm_type, doc_type)
    234:     # Admin tiene permiso para todo
    235:     if self.is_a?(Admin) && !doc_type.eql?("permissions")
    236:       true
    237:     elsif !self.is_a?(DepartmentMember) && doc_type.eql?("events") &&  %w(create_irekia create_agencia create_private).include?(perm_type)
    238:       # Los permisos para publicar noticias en irekia, agencia y privados, solo se ponen para los miembros
    239:       # de departamento. Para los demas, el permiso es el mismo de crear evento
    240:       self.can_create?(doc_type)
    241:     else
    242:       permission?(perm_type, doc_type)
    243:     end
    244:   end

can_access?(doc_type)

Indica si tiene permiso para acceder a la administración de los recursos de tipo `doc_type`. Por defecto, sólo los usuarios de tipo Admin pueden acceder a todos los módulos. En las subclases se concretan los permisos para cada tipo de usuario Ejemplos:

- current_user.can_access?("news")
- current_user.can_access?("photos")

[Source]

         # File app/models/user.rb, line 140
    140:   def can_access?(doc_type)
    141:     [Admin].include?(self.class)
    142:   end

can_change_schedule?(schedule_id)

Indica si el usuario puede traspasar los eventos de la agenda `schedule_id` a la agenda compartida.

[Source]

         # File app/models/user.rb, line 225
    225:   def can_change_schedule?(schedule_id)
    226:     res = false
    227:     if perm = self.schedules_permissions.find_by_schedule_id(schedule_id)
    228:       res = perm.can_change_schedule?
    229:     end
    230:     res
    231:   end

can_create?(doc_type)

Indica si puede crear recursos de tipo `doc_type`. Por defecto, sólo los usuarios de tipo Admin pueden modificar todos los módulos. En las subclases se concretan los permisos para cada tipo de usuario. Ejemplos:

- current_user.can_create?("news")
- current_user.can_create?("photos")

[Source]

         # File app/models/user.rb, line 158
    158:   def can_create?(doc_type)
    159:     [Admin].include?(self.class)
    160:   end

can_edit?(doc_type)

Indica si puede modificar recursos de tipo `doc_type`. Por defecto, sólo los usuarios de tipo Admin pueden modificar todos los módulos. En las subclases se concretan los permisos para cada tipo de usuario. Ejemplos:

- current_user.can_edit?("news")
- current_user.can_edit?("photos")

[Source]

         # File app/models/user.rb, line 149
    149:   def can_edit?(doc_type)
    150:     [Admin].include?(self.class)
    151:   end

can_edit_schedule?(schedule_id)

Indica si el usuario puede modificar los eventos de la agenda `schedule_id`

[Source]

         # File app/models/user.rb, line 216
    216:   def can_edit_schedule?(schedule_id)
    217:     res = false
    218:     if perm = self.schedules_permissions.find_by_schedule_id(schedule_id)
    219:       res = perm.can_edit?
    220:     end
    221:     res
    222:   end

can_see_l_schedule?()

Indica si puede ver los eventos a los que asiste el lehendakari

[Source]

         # File app/models/user.rb, line 208
    208:   def can_see_l_schedule?
    209:     if s = Schedule.lehendakari
    210:       return self.can_see_schedule?(s.id)
    211:     end
    212:     false
    213:   end

can_see_schedule?(schedule_id)

Indica si puede ver la agenda especial `schedule_id`

[Source]

         # File app/models/user.rb, line 203
    203:   def can_see_schedule?(schedule_id)
    204:     self.schedule_ids.include?(schedule_id)
    205:   end

editable_schedules_with_create_option()

Returns the list with schedules for which a separate create event button is shown

[Source]

         # File app/models/user.rb, line 188
    188:   def editable_schedules_with_create_option
    189:     self.editable_schedules.find(:all, :conditions => 'department_id IS NULL')
    190:   end

editable_schedules_with_radio()

[Source]

         # File app/models/user.rb, line 192
    192:   def editable_schedules_with_radio
    193:     self.editable_schedules - self.editable_schedules_with_create_option
    194:   end

encrypt(password)

Encrypts the password with the user salt

[Source]

        # File app/models/user.rb, line 96
    96:   def encrypt(password)
    97:     self.class.encrypt(password, salt)
    98:   end

forget_me()

[Source]

         # File app/models/user.rb, line 124
    124:   def forget_me
    125:     self.remember_token_expires_at = nil
    126:     self.remember_token            = nil
    127:     save(false)
    128:   end

has_department?()

Indica si se debe especificar departamento para este usuario

[Source]

         # File app/models/user.rb, line 178
    178:   def has_department?
    179:     self.respond_to?("department")
    180:   end

has_department_schedule?()

Indica si el usuario existe una agenda privada para el departamento al que pertenece el usuario, si es que pertenece a alguno

[Source]

         # File app/models/user.rb, line 331
    331:   def has_department_schedule?
    332:     self.has_department? && Schedule.exists?(:department_id=> self.department_id)
    333:   end

has_ma_access?()

[Source]

         # File app/models/user.rb, line 167
    167:   def has_ma_access?
    168:     ["Colaborator", "StreamingOperator", "Journalist"].include? self.class.to_s
    169:   end

has_schedule_permissions?()

Permisos para las agendas especiales

[Source]

         # File app/models/user.rb, line 198
    198:   def has_schedule_permissions?
    199:     !self.schedules_permissions.blank?
    200:   end

internal_name()

Nombre interno, principalmente para el "staff" que tiene nombres públicos con los que no se les puede identificar fácilmente

[Source]

        # File app/models/user.rb, line 73
    73:   def internal_name
    74:     internal_name = public_name
    75:     internal_name << " (#{telephone})" unless telephone.blank?
    76:     return internal_name
    77:   end

is_admin?()

[Source]

         # File app/models/user.rb, line 130
    130:   def is_admin?
    131:     self.is_a?(Admin)
    132:   end

is_official_commenter?()

Indica si los comentarios de este usuario se consideran oficiales y, por lo tanto,

     se aprueban automáticamente y se muestran en color destacado

[Source]

         # File app/models/user.rb, line 173
    173:   def is_official_commenter?
    174:     self.is_staff? || self.can?('official', 'comments')
    175:   end

is_staff?()

Indica si el usuario es miembro del "staff"

[Source]

         # File app/models/user.rb, line 163
    163:   def is_staff?
    164:     User::STAFF.include?(self.class.to_s)
    165:   end

nullify_url_if_necessary()

[Source]

        # File app/models/user.rb, line 84
    84:   def nullify_url_if_necessary
    85:     self.url = nil if self.url.eql?("http://")
    86:     return true
    87:   end

organization_ids()

Devuelve un array de los organismos a los que está suscrito. Sólo relevante para periodistas

[Source]

         # File app/models/user.rb, line 183
    183:   def organization_ids
    184:     []
    185:   end

permission?(perm_type, doc_type)

     Indica si el usuario tiene permiso de tipo <tt>perm_type</tt> en el modulo <tt>doc_type</tt>.

Para ver los valores posibles de estas dos variables, ver el comentario inicial de la clase Permission

[Source]

         # File app/models/user.rb, line 248
    248:   def permission?(perm_type, doc_type)
    249:     conditions = ["module=?", doc_type]
    250:     case
    251:     when perm_type.eql?("edit")
    252:       # El permiso de crear lleva consigo el de modificar
    253:       conditions[0] << " AND action IN ('edit', 'create')"
    254:     when !perm_type.eql?("access")
    255:       # access significa cualquier tipo de permiso sobre el modulo
    256:       conditions[0] << " AND action=?"
    257:       conditions << perm_type
    258:     end
    259:     permissions.exists?(conditions)
    260:   end

permissions_for_form()

Devuelve todos los permisos que tiene un usuario para el formulario de app/views/admin/permissions/edit. Incluye:

- Los permisos heredados del tipo de usuario
- Los permisos dados manualmene a través de la clase Permission
- Los permisos dados manualmente a través de la clase SchedulesPermission. Solo se incluyen los permisos sobre la agenda del departamento al que pertenece el usuario (si es que pertenece a alguno) porque son los únicos que se pueden modificar a través de ese formulario

[Source]

         # File app/models/user.rb, line 269
    269:   def permissions_for_form
    270:     fp = self.permissions.dup
    271:
    272:     if self.has_department_schedule?
    273:       schedules_permissions.find(:all, :conditions => "schedule_id=#{self.department.schedule.id}").each do |sp|
    274:         if sp.can_edit?
    275:           fp << Permission.new(:user_id => self.id, :module => "schedule_events", :action => "can_edit", :not_editable => false)
    276:         end
    277:         if sp.can_change_schedule?
    278:           fp << Permission.new(:user_id => self.id, :module => "schedule_events", :action => "can_change_schedule", :not_editable => false)
    279:         end
    280:       end
    281:     end
    282:
    283:     if self.class.respond_to?("inherited_permissions")
    284:       self.class.inherited_permissions.each do |perm|
    285:         fp << Permission.new(perm.merge(:not_editable => true, :user_id => self.id))
    286:       end
    287:     end
    288:     return fp
    289:   end

permissions_for_form_array()

Devuelve los mismos permisos que `permissions_for_form` pero en el siguiente formato, adecuado para los campos del formulario [perm[news][create], perm[events][create_private]]

[Source]

         # File app/models/user.rb, line 294
    294:   def permissions_for_form_array
    295:     output = self.permissions_for_form.collect {|p| "perm[#{p.module}][#{p.action}]"}
    296:     # logger.info "permissions_for_form_array #{output.inspect}"
    297:     return output
    298:   end

public_name()

Nombre tal y como aparecerá en las páginas públicas

[Source]

        # File app/models/user.rb, line 67
    67:   def public_name
    68:     "#{name} #{last_names}"
    69:   end

remember_me()

These create and unset the fields required for remembering users between browser closes

[Source]

         # File app/models/user.rb, line 110
    110:   def remember_me
    111:     remember_me_for 2.weeks
    112:   end

remember_me_for(time)

[Source]

         # File app/models/user.rb, line 114
    114:   def remember_me_for(time)
    115:     remember_me_until time.from_now.utc
    116:   end

remember_me_until(time)

[Source]

         # File app/models/user.rb, line 118
    118:   def remember_me_until(time)
    119:     self.remember_token_expires_at = time
    120:     self.remember_token            = encrypt("#{email}--#{remember_token_expires_at}")
    121:     save(false)
    122:   end

remember_token?()

[Source]

         # File app/models/user.rb, line 105
    105:   def remember_token?
    106:     remember_token_expires_at && Time.now.utc < remember_token_expires_at
    107:   end

update_permissions(new_permissions)

[Source]

         # File app/models/user.rb, line 300
    300:   def update_permissions(new_permissions)
    301:     self.transaction do
    302:       logger.info "Nuevos permisos..... #{new_permissions.inspect}"
    303:       if schedules_permissions = new_permissions.delete(:schedule_events)
    304:           logger.info "Schedules permissions......... #{schedules_permissions.inspect}"
    305:           # Con esta interfaz simplificada, solo podemos asignar permisos en agendas especiales
    306:           # en el departamento al que pertenece el usuario. El resto hay que hacerlo a mano en SQL
    307:           if has_department_schedule?
    308:             # Mantenemos los permisos que le hemos dado fuera de su departamento
    309:             self.schedules_permissions = self.schedules_permissions.find(:all, :conditions => "schedule_id <>#{self.department.schedule.id}")
    310:             if schedules_permissions.length == 2
    311:               self.schedules_permissions.build(:schedule_id => self.department.schedule.id, :can_edit => true, :can_change_schedule => true)
    312:             else
    313:               self.schedules_permissions.build({:schedule_id => self.department.schedule.id, :can_edit => false, :can_change_schedule => false}.merge(schedules_permissions.keys[0].to_sym => true))
    314:             end
    315:           end
    316:         end
    317:
    318:       self.permissions.clear
    319:       logger.info "Resto de permisos......... #{new_permissions.inspect}"
    320:       new_permissions.each do |mod, permissions|
    321:         permissions.each do |perm|
    322:           self.permissions.build(:module => mod, :action => perm[0]) if perm[1].to_i == 1
    323:         end
    324:       end
    325:       self.save
    326:     end
    327:   end

### Protected Instance methods

email_blank()

[Source]

         # File app/models/user.rb, line 357
    357:     def email_blank
    358:       self.email.blank?
    359:     end

encrypt_password()

before filter

[Source]

         # File app/models/user.rb, line 337
    337:     def encrypt_password
    338:
    339:       if self.is_a?(Journalist) && self.new_record?
    340:         generate_random_password_if_empty
    341:       end
    342:
    343:       return if password.blank?
    344:       self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{email}--") if new_record?
    345:       self.crypted_password = encrypt(password)
    346:       self.plain_password = password
    347:     end

generate_random_password_if_empty()

[Source]

         # File app/models/user.rb, line 361
    361:     def generate_random_password_if_empty
    362:       self.password = Journalist.random_password if self.password.blank?
    363:     end

password_required?()

[Source]

         # File app/models/user.rb, line 353
    353:     def password_required?
    354:       !type.eql?('Journalist') && (crypted_password.blank? || !password.blank?)
    355:     end

set_default_status()

[Source]

         # File app/models/user.rb, line 349
    349:     def set_default_status
    350:       self.status = 'aprobado' unless self.status
    351:     end

[Validate]