web.user.model

Package web :: Package user :: Module model |
[hide private]
[frames] | no frames]

# Source Code for Module web.user.model

      1  from db import Base
      2  from hashlib import sha1
      3  from sqlalchemy import Column, Integer, String, Unicode, ForeignKey, Boolean, DateTime, Table
      4  from sqlalchemy.orm import relation, backref
      5  from gettext import gettext as _
      6  import string
      7  from random import Random
      8  import datetime
      9  import config
     10  import web
     11
     12  metadata = Base.metadata
     13
     14 -class User(Base):
     15      __tablename__ = 'user'
     16
     17      id = Column(Integer, primary_key=True)
     18      name = Column(Unicode(60), unique=True)
     19      password = Column(String(128))
     20      email = Column(Unicode(256))
     21      super_user = Column(Boolean)
     22      creation_date = Column(DateTime())
     23      # state can be either active or inactive
     24      state = Column(Unicode(30))
     25      # Unicode used for password recovery and for activating the user
     26      temp_token = Column(String(50))
     27      temp_token_valid_until = Column(DateTime(50))
     28
     29      user_organizative_unit = Table('user_organizative_unit', metadata,
     30          Column('user_id', Integer, ForeignKey('user.id')),
     31          Column('organizative_unit_id', Integer, ForeignKey('organizative_unit.id'))
     32      )
     33      organizative_units = relation('OrganizativeUnit', secondary=user_organizative_unit)
     34
     35
     36 -    def __init__(self, name=u'', password='', email=u''):
     37          self.name = name
     38          if password:
     39              self.set_password(password)
     40          self.email = email
     41          self.super_user = False
     42          self.state = u'inactive'
     43          self.creation_date = datetime.datetime.now()
     44          self.generate_temp_token()
     45
     46 -    def generate_temp_token(self):
     47          '''
     48          Generates a new temporal token valid for 48 hours
     49          '''
     50          self.temp_token_valid_until = datetime.timedelta(days = 2)+datetime.datetime.now()
     51          self.temp_token = ''.join(Random().sample(string.letters + string.digits, 50))
     52
     53 -    def send_activation_mail(self):
     54          title = _('Welcome to %s, %s') % (config.sitename, self.name)
     55          text = _("""
     56  Welcome to %s, %s!
     57
     58  You can activate you account using the URL below:
     59  %suser/confirmemail/%s/%s
     60
     61  If you didn't request the creation of this user, you should ignore this email.
     62
     63  Thanks for joining us,
     64  %s
     65              """) % (config.sitename, self.name, config.siteurl, self.name, self.temp_token, config.sitename)
     66          print text
     67          try:
     68              web.sendmail(config.system_email, self.email, title, text)
     69          except:
     70              print " ** CAN'T SEND EMAIL ** "
     71
     72 -    def send_recover_password_mail(self):
     73          self.generate_temp_token()
     74          title = _('Reset password for %s, %s') %  (config.sitename, self.name)
     75          text = _("""
     76  To recover your password in %s for the user %s, use the following URL:
     77
     78  %suser/recoverpassword/%s/%s
     79
     80  If you didn't request the recovery of your password, you should ignore this email.
     81
     82  Regards,
     83  %s
     84              """) % (config.sitename, self.name, config.siteurl, self.name, self.temp_token, config.sitename)
     85          print text
     86          web.sendmail(config.system_email, self.email, title, text)
     87
     88 -    def validate_temp_token(self, token):
     89          '''
     90          Returns whether the given token is valid or not
     91          '''
     92          now = datetime.datetime.now()
     93          if now >= self.temp_token_valid_until:
     94              return False
     95
     96          if self.temp_token != token:
     97              return False
     98
     99          self.temp_token_valid_until = datetime.datetime.min # this invalidates the temp token
    100          self.temp_token = ''
    101          self.state = u'active'
    102          return True
    103
    104 -    def set_password(self, password):
    105          self.password = sha1(password).hexdigest()
    106
    107 -    def auth(self, password):
    108          return self.state == u'active' and self.password == sha1(password).hexdigest()
    109
    110 -    def is_super_user(self):
    111          return self.super_user
    112
    113 -    def is_active(self):
    114          return self.state == u'active'
    115
    116 -    def __repr__(self):
    117          return self.name
    118
    119      @classmethod
    120 -    def current(self):
    121          '''
    122          Returns current user. If there's no user logged in, returns anonymous user.
    123          '''
    124          import web
    125          if not web.ctx.session.has_key('loggedin'):
    126              return web.ctx.orm.query(User).filter(User.name == u'anonymous').first()
    127
    128          username = web.ctx.session.get('username', '')
    129          user_object = web.ctx.orm.query(User).filter(User.name == username).first()
    130          if user_object is None:
    131              return web.ctx.orm.query(User).filter(User.name == u'anonymous').first()
    132
    133          return user_object
    134
    135      #################
    136      # dbadmin stuff #
    137      #################
    138
    139      @classmethod
    140 -    def fields(self):
    141          return ('name', 'email', 'super_user', 'state')
    142
    143
    144 -class Role(Base):
    145      __tablename__ = 'role'
    146
    147      id = Column(Integer, primary_key=True)
    148      name = Column(Unicode(60), unique=True)
    149
    150      user_role = Table('user_role', metadata,
    151          Column('user_id', Integer, ForeignKey('user.id')),
    152          Column('role_id', Integer, ForeignKey('role.id'))
    153      )
    154      users = relation('User', secondary=user_role, backref='roles')
    155
    156 -    def __init__(self, name=u'', users=None):
    157          self.name = name
    158          if users is None: users = []
    159          self.users = users
    160
    161 -    def __repr__(self):
    162          return self.name
    163
    164      @classmethod
    165 -    def fields(self):
    166          return ('name', )
    167
    168
    169 -class Action(Base):
    170      __tablename__ = 'action'
    171      permissions = Table('permissions', metadata,
    172          Column('role_id', Integer, ForeignKey('role.id')),
    173          Column('action_id', Integer, ForeignKey('action.id'))
    174      )
    175
    176      id = Column(Integer, primary_key=True)
    177      name = Column(Unicode(120), unique=True)
    178      roles = relation('Role', secondary=permissions, backref='actions')
    179
    180 -    def __init__(self, name=u'', roles=None):
    181          self.name = name
    182          if roles is None: roles = []
    183          self.roles = roles
    184
    185 -    def __repr__(self):
    186          return self.name
    187
    188      @classmethod
    189 -    def fields(self):
    190          return ('name', )
    191