views.py 9.14 KB
Newer Older
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
1
2
3
4
5
6
7
8
9
10
11
12
"""cube-specific forms/views/actions/components

:organization: Logilab
:copyright: 2001-2010 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
"""

import random
import string
from datetime import datetime, timedelta

13
14
15
16
from yams import ValidationError

from cubicweb.web import (Redirect, controller, form, formwidgets as wdg,
                          formfields as ff)
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
17
18
19
20
21
22
23
24
from cubicweb.web.views import forms, urlrewrite, basetemplates
from cubicweb.view import StartupView
from cubicweb.server.repository import Repository

from cubes.registration.views import CaptchaWidget, encrypt, decrypt

from logilab.mtconverter import xml_escape

25
26
_ = unicode

Charles Hebert's avatar
0.1.0  
Charles Hebert committed
27
28
29
30
31
32
# Login form
# ----------

class LogFormTemplateForgotPassword(basetemplates.LogFormTemplate):

    def login_form(self, id):
33
34
        super(LogFormTemplateForgotPassword, self).login_form(id)
        self.req.add_css('cubes.forgotpwd.css')
35
36
        self.w(u'<p style="text-align:center"><a href="%s">%s</a></p>' % (
            self.build_url('forgottenpassword'), self.req._('Forgotten your password ?')))
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

# First form, send an email
# -------------------------

class ForgottenPasswordForm(forms.FieldsForm):
    id = 'forgottenpassword'

    form_buttons = [wdg.SubmitButton()]
    @property
    def action(self):
        return self.req.build_url(u'forgottenpassword_sendmail')

    use_email = ff.StringField(widget=wdg.TextInput(), required=True, label=_(u'your email'))
    captcha = ff.StringField(widget=CaptchaWidget(), required=True,
                             label=_('captcha'),
                             help=_('please copy the letters from the image'))

class ForgottenPasswordFormView(form.FormViewMixIn, StartupView):
    id = 'forgottenpassword'

    def call(self):
        form = self.vreg['forms'].select('forgottenpassword', self.req)
        self.w(u'<p>%s</p>' % self.req._(u'Forgot your password ?'))
        self.w(form.render())

class ForgottenPasswordSendMailController(controller.Controller):
    id = 'forgottenpassword_sendmail'

    subject = _(u'Password request on %(base_url)s')

    def publish(self, rset=None):
        data = self.checked_data()
69
70
71
72
73
74
75
76
77
        try:
            self.appli.repo.forgotpwd_send_email(data)
        except ValidationError:
            raise
        except Exception, exc:
            msg = str(exc)
        else:
            msg = self.req._(u'An email has been sent, follow instructions in there to change your password.')
        raise Redirect(self.build_url('pwdsent', __message=msg))
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

    def checked_data(self):
        '''only basic data check here (required attributes and password
        confirmation check)
        '''
        fieldsform = self.vreg['forms'].select('forgottenpassword', self.req)
        data = {}
        errors = {}
        for field in fieldsform._fields_:
            value = self.req.form.get(field.name, u'').strip()
            if not value:
                if field.required:
                    errors[field.name] = self.req._('required attribute')
            data[field.name] = value
        captcha = self.req.get_session_data('captcha', None, pop=True)
        if captcha is None:
            errors[None] = self.req._('unable to check captcha, please try again')
        elif data['captcha'].lower() != captcha.lower():
            errors['captcha'] = self.req._('incorrect captcha value')
        if errors:
            raise ValidationError(None, errors)
        return data

101
102
103
104
105
106
107

class PasswordSentView(StartupView):
    id = 'pwdsent'

    def call(self):
        self.wview('index', self.rset)

Charles Hebert's avatar
0.1.0  
Charles Hebert committed
108
109
110
111
112
113
114
115
116
# Second form, ask for a new password
# -----------------------------------

class ForgottenPasswordRequestForm(forms.FieldsForm):
    id = 'forgottenpasswordrequest'

    form_buttons = [wdg.SubmitButton()]
    @property
    def action(self):
117
        return self.req.build_url(u'forgottenpassword-requestconfirm')
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
118
119
120

    upassword = ff.StringField(widget=wdg.PasswordInput(), required=True)

121

Charles Hebert's avatar
0.1.0  
Charles Hebert committed
122
123
124
class ForgottenPasswordRequestView(form.FormViewMixIn, StartupView):
    id = 'forgottenpasswordrequest'

125
    def check_key(self):
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
126
        try:
127
            return decrypt(self.req.form['key'], self.vreg.config['cypher-seed'])
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
128
129
130
        except:
            msg = self.req._(u'Invalid link. Please try again.')
            raise Redirect(self.req.build_url(u'forgottenpassword', __message=msg))
131
132
133

    def call(self):
        key = self.check_key()
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
134
135
136
137
138
139
140
        form = self.vreg['forms'].select('forgottenpasswordrequest', self.req)
        form.form_add_hidden('use_email', key['use_email'])
        form.form_add_hidden('revocation_id', key['revocation_id'])
        self.w(u'<p>%s</p>' % self.req._(u'Update your password:'))
        self.w(form.render())

class ForgottenPasswordRequestConfirm(controller.Controller):
141
    id = 'forgottenpassword-requestconfirm'
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
142
143
144

    def publish(self, rset=None):
        data = self.checked_data()
145
146
        msg = self.appli.repo.forgotpwd_change_passwd(data)
        raise Redirect(self.build_url('', __message=msg))
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
147
148
149
150
151
152
153
154
155
156
157

    def checked_data(self):
        fieldsform = self.vreg['forms'].select('forgottenpasswordrequest', self.req)
        data = {}
        errors = {}
        for field in fieldsform._fields_:
            value = self.req.form.get(field.name, u'').strip()
            if not value:
                if field.required:
                    errors[field.name] = self.req._('required attribute')
            data[field.name] = value
158
159
        data['use_email'] = self.req.form.get('use_email', '').strip()
        data['revocation_id'] = self.req.form.get('revocation_id', '').strip()
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
160
161
162
163
164
165
        if data['upassword'] != self.req.form.get('upassword-confirm'):
            errors['upassword'] = _('passwords are different')
        if errors:
            raise ValidationError(None, errors)
        return data

166

Charles Hebert's avatar
0.1.0  
Charles Hebert committed
167
168
169
170
171
172
173
# Monkey Patching
# ---------------

from cubicweb.server.repository import Repository
from logilab.common.decorators import monkeypatch
from cubicweb.common.mail import format_mail

174

Charles Hebert's avatar
0.1.0  
Charles Hebert committed
175
176
177
178
179
180
181
@monkeypatch(Repository)
def forgotpwd_send_email(self, data):
    session = self.internal_session()
    revocation_limit = self.config['revocation-limit']
    revocation_id = u''.join([random.choice(string.letters+string.digits) for x in range(10)])
    revocation_date = datetime.now() + timedelta(minutes=revocation_limit)
    try:
182
183
184
185
186
187
188
189
190
        existing_requests = session.execute('Any F WHERE U primary_email E, E address %(e)s, U has_fpasswd F',
                                            {'e': data['use_email']})
        if existing_requests:
            raise ValidationError(None, {None: session._('You have already asked for a new password.')})
        rset = session.execute('INSERT Fpasswd X: X revocation_id %(a)s, X revocation_date %(b)s, '
                               'U has_fpasswd X WHERE U primary_email E, E address %(e)s',
                               {'a':revocation_id, 'b':revocation_date, 'e': data['use_email']})
        if not rset:
            raise ValidationError(None, {None: session._(u'An error occured, this email address is unknown.')})
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
191
192
193
        data['revocation_id'] = revocation_id
        key = encrypt(data, session.vreg.config['cypher-seed'])
        url = session.build_url('forgottenpasswordrequest', key=key)
194
195
196
        session.set_shared_data('resetlink', url)
        # mail is sent on commit
        session.commit()
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    finally:
        session.close()

@monkeypatch(Repository)
def forgotpwd_change_passwd(self, data):
    session = self.internal_session()
    try:
        rset = session.execute('Any F, U WHERE U is CWUser, U primary_email E, E address %(email)s, EXISTS(U has_fpasswd F, F revocation_id %(revid)s)',
                               {'email': data['use_email'], 'revid':data['revocation_id']})
        if rset:
            forgotpwd = rset.get_entity(0,0)
            revocation_date = forgotpwd.revocation_date
            user = rset.get_entity(0,1)
            if revocation_date > datetime.now():
                session.execute('SET U upassword %(newpasswd)s WHERE U is CWUser, U eid %(usereid)s',
                                {'newpasswd':data['upassword'].encode('UTF-8'), 'usereid':user.eid})
                session.execute('DELETE Fpasswd F WHERE F eid %(feid)s',
                                {'feid':forgotpwd.eid})
                session.commit()
                msg = session._(u'Your password has been changed !')
            else:
                msg = session._(u'That link has either expired or is not valid.')
        else:
            msg = session._(u'You already changed your password. This link has expired.')
221
        return msg
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
    finally:
        session.close()

# Registration
# ------------

def registration_callback(vreg):
    vreg.register_all(globals().values(), __name__, (LogFormTemplateForgotPassword,))
    vreg.register_and_replace(LogFormTemplateForgotPassword,
                              basetemplates.LogFormTemplate)

# URL rewriting
# -------------

class RegistrationSimpleReqRewriter(urlrewrite.SimpleReqRewriter):
    rules = [
        ('/forgottenpassword', dict(vid='forgottenpassword')),
239
240
        ('/forgottenpasswordrequest', dict(vid='forgottenpasswordrequest')),
        ('/pwdsent', dict(vid='pwdsent')),
Charles Hebert's avatar
0.1.0  
Charles Hebert committed
241
        ]