示例#1
0
def reset_password_do(request):
    c = request.tmpl_context

    if SessionUser.get(request): # user already logged in
        return HTTPFound(location=DEFAULT_REDIRECT_TO)

    def passwords_match(node, value):
        if node.get_value(value, 'new_password_1') != node.get_value(value, 'new_password_2'):
            raise colander.Invalid(node, 'Пароли не совпадают')

    password_change_form = SmallForm(validators=[passwords_match])
    StringField(password_change_form, 'login',           required=True)
    StringField(password_change_form, 'new_password_1',  required=True)
    StringField(password_change_form, 'new_password_2',  required=True)

    code = request.matchdict['code']

    try:
        user = settings.user_model.get_by_confirm_code(code)
    except NoResultFound:
        raise HTTPNotFound() # TODO redirect to / ?

    if user.confirm_time is None:
        raise HTTPNotFound() # TODO redirect to / ?

    if datetime.datetime.now() - user.confirm_time > datetime.timedelta(hours=48):
        raise HTTPNotFound() # TODO redirect to / ?

    if request.method == 'GET':
        c.form = password_change_form.from_object()
        return dict()

    if request.method == 'POST':
        c.form = password_change_form.from_submitted(list(request.POST.items()))
        if not c.form.valid:
            # passwords_match
            if c.form.error:
                c.form._errors['new_password_1'] = c.form.error
                c.form._errors['new_password_2'] = c.form.error
            return dict()

        if user.id != c.form.login.value:
            raise HTTPNotFound() # TODO !?

        if user.status == settings.user_model.UNCONFIRMED:
            user.status = settings.user_model.ACTIVE
        user.confirm_code = ''
        user.confirm_time = None
        user.set_new_password(c.form.new_password_1.value)

        return HTTPFound(location=request.route_path('login', _query=dict(reset=user.id)))

    # neither GET nor POST
    return HTTPNotFound()
示例#2
0
def register(request):

    if request.user: # user is already logged in
        return HTTPFound(location='/')

    c = request.tmpl_context

    form = SmallForm(validators=[passwords_match])
    StringField(form, 'login',      required=True, validators=[login_validator, user_login_unique])
    StringField(form, 'email',      required=True, validators=[
        colander.Email('Неправильный формат email адреса'), user_email_unique()
    ])
    StringField(form, 'name',       required=True)
    StringField(form, 'password1',  required=True)
    StringField(form, 'password2',  required=True)

    if request.method == 'GET':
        c.form = form.from_object()
        return dict()

    if request.method == 'POST':
        c.form = form.from_submitted(list(request.POST.items()))
        if not c.form.valid:
            # passwords_match
            if c.form.error:
                c.form._errors['password1'] = c.form.error
                c.form._errors['password2'] = c.form.error
            return dict()

        user = settings.user_model(
            id        = c.form.login.value,
            email     = c.form.email.value,
            real_name = c.form.name.value,
            status    = settings.user_model.UNCONFIRMED
        )
        user.set_new_password(c.form.password1.value)
        user.add() # TODO commit? to avoid sending emails in case of database error

        confirm_code = user.generate_and_set_confirm_code()

        try:
            send_auto_email(user.email, 'user-registered', dict(
                user  = user,
                url   = request.route_url('confirm-user', code=confirm_code)
            ))
            return render_auto_page('user-registered', request, dict(user=user))
        except EmailException as e:
            transaction.doom()
            return render_auto_page('error-sending-email', request, dict(email=c.form.email.value))

    # neither GET nor POST
    return HTTPNotFound()
示例#3
0
def reset_password(request):
    c = request.tmpl_context

    if request.user:  # user already logged in
        return HTTPFound(location=DEFAULT_REDIRECT_TO)

    def user_valid(node, value):
        try:
            user = settings.user_model.get_by_email(value)
            if user.status == settings.user_model.DISABLED:
                raise colander.Invalid(node, 'Пользователь заблокирован.')
        except NoResultFound:
            raise colander.Invalid(node, 'Пользователь с таким email адресом у нас не зарегистрирован.')

    reset_form = SmallForm()
    StringField(reset_form, 'email', required=True, validators=[colander.Email('Неправильный формат email адреса'), user_valid])

    if request.method == 'GET':
        c.form = reset_form.from_object()
        return dict()

    if request.method == 'POST':
        c.form = reset_form.from_submitted(list(request.POST.items()))
        if not c.form.valid:
            if (c.form.email.error or '').find('заблокирован') != -1:
                c.user_blocked = True
            return dict()

        try:
            user = settings.user_model.get_by_email(c.form.email.value)
        except NoResultFound:
            raise HTTPNotFound() # TODO!
        if user.status == settings.user_model.DISABLED:
            raise HTTPNotFound() # TODO!

        confirm_code = user.generate_and_set_confirm_code()

        try:
            send_auto_email(user.email, 'password-reset', dict(
                user = user,
                url = request.route_url('reset-password-do', code=confirm_code)
            ))
            return render_auto_page('reset-email-sent', request, dict(user=user))
        except EmailException as e:
             c.message = 'Ошибка: ' + str(e) # TODO!

    # neither GET nor POST
    return HTTPNotFound()
示例#4
0
def register_with_social_account(request):

    c = request.tmpl_context

    # if user is already logged in, redirect to referer
    if SessionUser.get(request):
        return HTTPFound(location = '/')  # TODO redirect_to('REFERER', request))

    form = SmallForm()
    StringField(form, 'login',  required=True, validators=[login_validator, user_login_unique])
    StringField(form, 'email',  required=True, validators=[colander.Email(u'Неправильный формат email адреса'), user_email_unique])
    StringField(form, 'name',   required=True)

    ##

    if not 'social-session' in request.session:
        log.warn(u'register_with_social_account(): no social account info in user session')
        return HTTPFound(location = '/')
    session = request.session['social-session']

    ##

    if request.method == 'GET':
        c.form = form.from_object(login=session['login'], name=session['real-name'])
        return dict()

    ##

    if request.method == 'POST':
        c.form = form.from_submitted(request.POST.items())
        if not c.form.valid:
            return dict()

        user = models.User(
            login     = c.form.login.value,
            email     = c.form.email.value,
            name      = c.form.name.value,
            status    = models.User.ACTIVE
        )

        if 'twitter' in session:
            s = session['twitter']
            user.save_twitter_session(s['user-id'], s['access-token'], s['secret'])

        if 'facebook' in session:
            s = session['facebook']
            user.save_facebook_session(s['user-id'], s['access-token'], s['expires'])

        if 'vkontakte' in session:
            s = session['vkontakte']
            user.save_vkontakte_session(s['user-id'], s['access-token'])

        user.add()  # TODO errors!

        del request.session['social-session']

        add_flash_message(request, 'logged-in')

        return HTTPFound(
            location = '/', # TODO c.form.came_from.value or DEFAULT_REDIRECT_TO,
            headers = login_user(request, user)
        )

    # neither GET nor POST
    return HTTPNotFound()