예제 #1
0
 def validator(_node, value):
     User = request.find_model('membership.user')
     user = User.by_employee_id(value)
     if user and str(user.id) != request.params.get('id'):
         raise colander.Invalid(
             _node,
             _(u'User for this employee already exists'),
         )
예제 #2
0
 def validator(_node, value):
     User = request.find_model('membership.user')
     user = User.get_by_email(request.db, value)
     if user and str(user.id) != request.params.get('id'):
         raise colander.Invalid(
             _node,
             _(u'User with the same email exists'),
         )
예제 #3
0
def register_activate(request):
    pid, code = validasi_activation(
        request.matchdict['code'])

    # LOG.debug((pid, code))
    # link = request.route_url(
    #     'register_activate',
    #     code='-'.join(
    #         [text_type(pid),
    #          code]))
    # LOG.debug(link)
    if (pid and code) is not None:
        # cek exist code activation dan cari user berdasarkan nya
        Activation = request.find_model('membership.activation')
        activation = Activation.get_by_code(request.db, code)
        if activation is None:
            request.session.flash(_(
                "We didn't recognize that activation link. "
                "Perhaps you've already activated your account? "
                'If so, try <a href="{url}">signing in</a> using the username '
                'and password that you provided.').format(
                url=request.route_url('_register_view')),
                'error')
            return httpexceptions.HTTPFound(
                location=request.base_url)

        User = request.find_model('membership.user')
        user = User.get_by_activation(request.db, activation)
        if user is None or user.pid != pid:
            raise httpexceptions.HTTPNotFound()

        user.activate()
        request.session.flash(_(
            'Your account has been activated! '
            'You can now <a href="{url}">sign in</a> using the password you '
            'provided.').format(url=request.route_url('_register_view')),
                              'success')

        request.registry.notify(ActivationEvent(request, user))

        return httpexceptions.HTTPFound(
            location=request.base_url)

    return httpexceptions.HTTPNotFound()
예제 #4
0
def activation_email(request, user):
    """Return the data for an 'activate your account' email for the given user.

    :rtype: dict

    """
    link = request.route_url(
        'register_activate',
        code='-'.join(
            [text_type(user.pid),
             user.activation.code]))
    # link = '-'.join(['register.activate', text_type(user.pid), user.activation.code])
    emailtext = _("Please validate your email and activate your account by visiting: {link}")
    body = emailtext.format(link=link)
    return {
        "request": request,
        "subject": _("Please activate your account"),
        "recipients": [user.email],
        "body": body
    }
예제 #5
0
def _register_view(request):

    form = register.RegisterAddForm(request)
    if form.validate():
        user = form.submit()
        LOG.debug(user)
        request.db.add(user)

        # Create a new activation for the user
        Activation = request.find_model('membership.activation')
        activation = Activation()
        request.db.add(activation)
        user.activation = activation

        request.db.flush()

        LOG.debug('')
        # Send the activation email
        message = activation_email(request, user)
        mailer.schedule_email_register(**message)

        request.session.flash(_(
            'Thank you for join Surabaya.py community! '
            "We've sent you an email with an activation link, "
            'before you can sign in <strong>please check your email and open '
            'the link to activate your account</strong>.'), 'success')

        request.registry.notify(
            RegistrationEvent(request, user))

        return {
            'redirect': request.base_url,
            'success_message': _(u'Saved'),
            'response': 0
        }
    else:
        return {
            'error_message': _(u'Please, check errors'),
            'errors': form.errors
        }
예제 #6
0
 def validator(_node, value):
     if value and request.params.get('email') != value:
         raise colander.Invalid(
             _node,
             _(u'Email and confirm is not equal'),
         )
예제 #7
0
class User(Model):

    __tablename__ = u'membership.user'

    STATUS = (('employee', _(u'Employee')), ('student', _(u'Student')),
              ('member', _(u'Member')))

    # Normalised user identifier
    uid = sa.Column(sa.UnicodeText(), nullable=False, unique=True)

    # Username as chosen by the user on registration
    _username = sa.Column('username',
                          sa.UnicodeText(),
                          nullable=False,
                          unique=True)

    # Is this user a admin?
    admin = sa.Column(sa.Boolean,
                      default=False,
                      nullable=False,
                      server_default=sa.sql.expression.false())

    status = sa.Column(
        EnumIntType(STATUS),
        default='employee',
        nullable=False,
    )

    def _get_username(self):
        return self._username

    def _set_username(self, value):
        if not USERNAME_MIN_LENGTH <= len(value) <= USERNAME_MAX_LENGTH:
            raise ValueError('username must be between {min} and {max} '
                             'characters long'.format(min=USERNAME_MIN_LENGTH,
                                                      max=USERNAME_MAX_LENGTH))
        self._username = value
        self.uid = _username_to_uid(value)

    @declared_attr
    def username(self):
        return sa.orm.synonym('_username',
                              descriptor=property(self._get_username,
                                                  self._set_username))

    email = sa.Column(sa.UnicodeText(), nullable=False, unique=True)

    last_login_date = sa.Column(sa.TIMESTAMP(timezone=False),
                                default=datetime.datetime.utcnow,
                                server_default=sa.func.now(),
                                nullable=False)
    registered_date = sa.Column(sa.TIMESTAMP(timezone=False),
                                default=datetime.datetime.utcnow,
                                server_default=sa.func.now(),
                                nullable=False)

    # Activation foreign key
    activation_id = sa.Column(sa.Integer, sa.ForeignKey(Activation.id))
    activation = sa.orm.relationship('Activation', backref='user')

    @sa.orm.validates('email')
    def validate_email(self, key, email):
        if len(email) > EMAIL_MAX_LENGTH:
            raise ValueError('email must be less than {max} characters '
                             'long'.format(max=EMAIL_MAX_LENGTH))
        return email

    @property
    def is_activated(self):
        if self.activation_id is None:
            return True

        return False

    def activate(self):
        """Activate the user by deleting any activation they have."""
        session = sa.orm.object_session(self)
        session.delete(self.activation)

    # Hashed password
    _password = sa.Column('password', sa.UnicodeText(), nullable=False)
    # Password salt
    salt = sa.Column(sa.UnicodeText(), nullable=False)
    # Last password update
    password_updated = sa.Column(sa.DateTime(),
                                 default=datetime.datetime.utcnow,
                                 server_default=sa.func.now(),
                                 nullable=False)

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._set_password(value)

    def _get_password(self):
        return self._password

    def _set_password(self, raw_password):
        if len(raw_password) < PASSWORD_MIN_LENGTH:
            raise ValueError('password must be more than {min} characters '
                             'long'.format(min=PASSWORD_MIN_LENGTH))
        self._password = self._hash_password(raw_password)
        self.password_updated = datetime.datetime.utcnow()

    def _hash_password(self, password):
        if not self.salt:
            self.salt = helper.generate_random_string(24)

        return text_type(CRYPT.encode(password + self.salt))

    @classmethod
    def get_by_email(cls, session, email):
        """Fetch a user by email address."""
        return session.query(cls).filter(
            sa.func.lower(cls.email) == email.lower()).first()

    @classmethod
    def get_by_activation(cls, session, activation):
        """Fetch a user by activation instance."""
        user = session.query(cls).filter(
            cls.activation_id == activation.id).first()

        return user

    @classmethod
    def validate_user(cls, user, password):
        """Validate the passed password for the specified user."""
        if not user:
            return None

        if user.password is None:
            valid = False
        else:
            valid = CRYPT.check(user.password, password + user.salt)

        return valid

    @classmethod
    def get_by_username(cls, session, username):
        """Fetch a user by username."""
        log.debug(username)
        uid = _username_to_uid(username)
        return session.query(cls).filter(cls.uid == uid).first()

    def __repr__(self):
        return '<User: %s>' % self.username
예제 #8
0
 def validator(_node, value):
     if value and request.params.get('password_confirm') != value:
         raise colander.Invalid(
             _node,
             _(u'Password and confirm is not equal'),
         )