~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/webapp/admin/user.py

  • Committer: William Grant
  • Date: 2010-02-11 05:09:56 UTC
  • Revision ID: grantw@unimelb.edu.au-20100211050956-t5i2z6b8iulxteza
Unbreak existing tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
# Author: Matt Giuca, Will Grant
19
19
 
 
20
import formencode
 
21
import formencode.validators
 
22
from genshi.filters import HTMLFormFiller
 
23
 
 
24
from ivle.webapp import ApplicationRoot
20
25
from ivle.webapp.base.rest import JSONRESTView, require_permission
21
26
from ivle.webapp.base.xhtml import XHTMLView
22
27
from ivle.webapp.base.plugins import ViewPlugin, MediaPlugin
23
 
from ivle.webapp.errors import NotFound, Unauthorized
 
28
from ivle.webapp.admin.publishing import root_to_user, user_url
 
29
from ivle.database import User
24
30
import ivle.database
 
31
import ivle.date
25
32
import ivle.util
26
33
 
 
34
 
 
35
class UsersView(XHTMLView):
 
36
    """A list of all IVLE users."""
 
37
    template = 'templates/users.html'
 
38
    tab = 'users'
 
39
    breadcrumb_text = 'Users'
 
40
 
 
41
    def authorize(self, req):
 
42
        return req.user.admin
 
43
 
 
44
    def populate(self, req, ctx):
 
45
        ctx['req'] = req
 
46
        ctx['users'] = req.store.find(User).order_by(User.login)
 
47
 
 
48
 
27
49
# List of fields returned as part of the user JSON dictionary
28
50
# (as returned by the get_user action)
29
51
user_fields_list = (
30
52
    "login", "state", "unixid", "email", "nick", "fullname",
31
 
    "rolenm", "studentid", "acct_exp", "pass_exp", "last_login",
 
53
    "admin", "studentid", "acct_exp", "pass_exp", "last_login",
32
54
    "svn_pass"
33
55
)
34
56
 
36
58
    """
37
59
    A REST interface to the user object.
38
60
    """
39
 
    def __init__(self, req, login):
40
 
        super(UserRESTView, self).__init__(self, req, login)
41
 
        self.context = ivle.database.User.get_by_login(req.store, login)
42
 
        if self.context is None:
43
 
            raise NotFound()
44
61
 
45
62
    @require_permission('view')
46
63
    def GET(self, req):
54
71
        user['local_password'] = self.context.passhash is not None
55
72
        return user
56
73
 
57
 
    @require_permission('edit')
58
 
    def PATCH(self, req, data):
59
 
        # XXX Admins can set extra fields
60
 
        # Note: Cannot change password here (use change_password named op)
61
 
 
62
 
        for f in user_fields_list:
63
 
            try:
64
 
                field = data[f]
65
 
                if isinstance(field, str):
66
 
                    field = unicode(field)
67
 
                setattr(self.context, f, field)
68
 
            except KeyError:
69
 
                continue
70
 
 
71
 
class UserSettingsView(XHTMLView):
72
 
    template = 'user-settings.html'
73
 
    appname = 'settings'
74
 
    permission = 'edit'
75
 
 
76
 
    def __init__(self, req, login):
77
 
        self.context = ivle.database.User.get_by_login(req.store, login)
78
 
        if self.context is None:
79
 
            raise NotFound()
80
 
 
81
 
    def populate(self, req, ctx):
82
 
        self.plugin_scripts[Plugin] = ['settings.js']
83
 
        req.scripts_init = ['revert_settings']
84
 
 
85
 
        ctx['login'] = self.context.login
 
74
class UserEditSchema(formencode.Schema):
 
75
    nick = formencode.validators.UnicodeString(not_empty=True)
 
76
    email = formencode.validators.Email(not_empty=False,
 
77
                                        if_missing=None)
 
78
 
 
79
class UserEditView(XHTMLView):
 
80
    """A form to change a user's details."""
 
81
    template = 'templates/user-edit.html'
 
82
    tab = 'users'
 
83
    permission = 'edit'
 
84
 
 
85
    def filter(self, stream, ctx):
 
86
        return stream | HTMLFormFiller(data=ctx['data'])
 
87
 
 
88
    def populate(self, req, ctx):
 
89
        if req.method == 'POST':
 
90
            data = dict(req.get_fieldstorage())
 
91
            try:
 
92
                validator = UserEditSchema()
 
93
                data = validator.to_python(data, state=req)
 
94
                self.context.nick = data['nick']
 
95
                self.context.email = unicode(data['email']) if data['email'] \
 
96
                                     else None
 
97
                req.store.commit()
 
98
                req.throw_redirect(req.uri)
 
99
            except formencode.Invalid, e:
 
100
                errors = e.unpack_errors()
 
101
        else:
 
102
            data = {'nick': self.context.nick,
 
103
                    'email': self.context.email
 
104
                   }
 
105
            errors = {}
 
106
 
 
107
        ctx['format_datetime'] = ivle.date.make_date_nice
 
108
        ctx['format_datetime_short'] = ivle.date.format_datetime_for_paragraph
 
109
 
 
110
        ctx['req'] = req
 
111
        ctx['user'] = self.context
 
112
        ctx['data'] = data
 
113
        ctx['errors'] = errors
 
114
 
 
115
class UserAdminSchema(formencode.Schema):
 
116
    admin = formencode.validators.StringBoolean(if_missing=False)
 
117
    fullname = formencode.validators.UnicodeString(not_empty=True)
 
118
    studentid = formencode.validators.UnicodeString(not_empty=False,
 
119
                                                    if_missing=None
 
120
                                                    )
 
121
 
 
122
class UserAdminView(XHTMLView):
 
123
    """A form for admins to change more of a user's details."""
 
124
    template = 'templates/user-admin.html'
 
125
    tab = 'users'
 
126
 
 
127
    def authorize(self, req):
 
128
        """Only allow access if the requesting user is an admin."""
 
129
        return req.user.admin
 
130
 
 
131
    def filter(self, stream, ctx):
 
132
        return stream | HTMLFormFiller(data=ctx['data'])
 
133
 
 
134
    def populate(self, req, ctx):
 
135
        if req.method == 'POST':
 
136
            data = dict(req.get_fieldstorage())
 
137
            try:
 
138
                validator = UserAdminSchema()
 
139
                data = validator.to_python(data, state=req)
 
140
 
 
141
                self.context.admin = data['admin']
 
142
                self.context.fullname = data['fullname'] \
 
143
                                        if data['fullname'] else None
 
144
                self.context.studentid = data['studentid'] \
 
145
                                         if data['studentid'] else None
 
146
                req.store.commit()
 
147
                req.throw_redirect(req.uri)
 
148
            except formencode.Invalid, e:
 
149
                errors = e.unpack_errors()
 
150
        else:
 
151
            data = {'admin': self.context.admin,
 
152
                    'fullname': self.context.fullname,
 
153
                    'studentid': self.context.studentid,
 
154
                   }
 
155
            errors = {}
 
156
 
 
157
        ctx['req'] = req
 
158
        ctx['user'] = self.context
 
159
        ctx['data'] = data
 
160
        ctx['errors'] = errors
 
161
 
 
162
class PasswordChangeView(XHTMLView):
 
163
    """A form to change a user's password, with knowledge of the old one."""
 
164
    template = 'templates/user-password-change.html'
 
165
    tab = 'users'
 
166
    permission = 'edit'
 
167
 
 
168
    def authorize(self, req):
 
169
        """Only allow access if the requesting user holds the permission,
 
170
           and the target user has a password set. Otherwise we might be
 
171
           clobbering external authn.
 
172
        """
 
173
        return super(PasswordChangeView, self).authorize(req) and \
 
174
               self.context.passhash is not None
 
175
 
 
176
    def populate(self, req, ctx):
 
177
        error = None
 
178
        if req.method == 'POST':
 
179
            data = dict(req.get_fieldstorage())
 
180
            if data.get('old_password') is None or \
 
181
               not self.context.authenticate(data.get('old_password')):
 
182
                error = 'Incorrect password.'
 
183
            elif data.get('new_password') != data.get('new_password_again'):
 
184
                error = 'New passwords do not match.'
 
185
            elif not data.get('new_password'):
 
186
                error = 'New password cannot be empty.'
 
187
            else:
 
188
                self.context.password = data['new_password']
 
189
                req.store.commit()
 
190
                req.throw_redirect(req.uri)
 
191
 
 
192
        ctx['req'] = req
 
193
        ctx['user'] = self.context
 
194
        ctx['error'] = error
 
195
 
 
196
class PasswordResetView(XHTMLView):
 
197
    """A form to reset a user's password, without knowledge of the old one."""
 
198
    template = 'templates/user-password-reset.html'
 
199
    tab = 'users'
 
200
 
 
201
    def authorize(self, req):
 
202
        """Only allow access if the requesting user is an admin."""
 
203
        return req.user.admin
 
204
 
 
205
    def populate(self, req, ctx):
 
206
        error = None
 
207
        if req.method == 'POST':
 
208
            data = dict(req.get_fieldstorage())
 
209
            if data.get('new_password') != data.get('new_password_again'):
 
210
                error = 'New passwords do not match.'
 
211
            elif not data.get('new_password'):
 
212
                error = 'New password cannot be empty.'
 
213
            else:
 
214
                self.context.password = data['new_password']
 
215
                req.store.commit()
 
216
                req.throw_redirect(req.uri)
 
217
 
 
218
        ctx['user'] = self.context
 
219
        ctx['error'] = error
86
220
 
87
221
class Plugin(ViewPlugin, MediaPlugin):
88
222
    """
89
223
    The Plugin class for the user plugin.
90
224
    """
91
 
    # Magic attribute: urls
92
 
    # Sequence of pairs/triples of
93
 
    # (regex str, handler class, kwargs dict)
94
 
    # The kwargs dict is passed to the __init__ of the view object
95
 
    urls = [
96
 
        ('~:login/+settings', UserSettingsView),
97
 
        ('api/~:login', UserRESTView),
 
225
 
 
226
    forward_routes = (root_to_user,)
 
227
    reverse_routes = (user_url,)
 
228
    views = [(ApplicationRoot, 'users', UsersView),
 
229
             (ivle.database.User, '+index', UserEditView),
 
230
             (ivle.database.User, '+admin', UserAdminView),
 
231
             (ivle.database.User, '+changepassword', PasswordChangeView),
 
232
             (ivle.database.User, '+resetpassword', PasswordResetView),
 
233
             (ivle.database.User, '+index', UserRESTView, 'api'),
 
234
             ]
 
235
 
 
236
    tabs = [
 
237
        ('users', 'Users', 'Display and edit all users',
 
238
         'users.png', 'users', 0, True)
98
239
    ]
99
240
 
 
241
    public_forward_routes = forward_routes
 
242
    public_reverse_routes = reverse_routes
 
243
 
100
244
    media = 'user-media'