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

« back to all changes in this revision

Viewing changes to lib/common/db.py

  • Committer: mattgiuca
  • Date: 2008-02-14 06:34:09 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:465
Added new app: userservice, which is an ajax service for user management
stuff. Currently tries (badly) to speak to usermgt for accepting the TOS
and creating the user's junk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Module: Database
 
19
# Author: Matt Giuca
 
20
# Date:   1/2/2008
 
21
 
 
22
# Code to talk to the PostgreSQL database.
 
23
# (This is the Data Access Layer).
 
24
# All DB code should be in this module to ensure portability if we want to
 
25
# change the DB implementation.
 
26
# This means no SQL strings should be outside of this module. Add functions
 
27
# here to perform the activities needed, and place the SQL code for those
 
28
# activities within.
 
29
 
 
30
# CAUTION to editors of this module.
 
31
# All string inputs must be sanitized by calling _escape before being
 
32
# formatted into an SQL query string.
 
33
 
 
34
import pg
 
35
import conf
 
36
import md5
 
37
 
 
38
def _escape(str):
 
39
    """Wrapper around pg.escape_string. Escapes the string for use in SQL, and
 
40
    also quotes it to make sure that every string used in a query is quoted.
 
41
    If str is None, returns "NULL", which is unescaped and thus a valid SQL
 
42
    value.
 
43
    """
 
44
    # "E'" is postgres's way of making "escape" strings.
 
45
    # Such strings allow backslashes to escape things. Since escape_string
 
46
    # converts a single backslash into two backslashes, it needs to be fed
 
47
    # into E mode.
 
48
    # Ref: http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html
 
49
    # WARNING: PostgreSQL-specific code
 
50
    if str is None:
 
51
        return "NULL"
 
52
    return "E'" + pg.escape_string(str) + "'"
 
53
 
 
54
def _passhash(password):
 
55
    return md5.md5(password).hexdigest()
 
56
 
 
57
class DBException(Exception):
 
58
    """A DBException is for bad conditions in the database or bad input to
 
59
    these methods. If Postgres throws an exception it does not get rebadged.
 
60
    This is only for additional exceptions."""
 
61
    pass
 
62
 
 
63
class DB:
 
64
    """An IVLE database object. This object provides an interface to
 
65
    interacting with the IVLE database without using any external SQL.
 
66
 
 
67
    Most methods of this class have an optional dry argument. If true, they
 
68
    will return the SQL query string and NOT actually execute it. (For
 
69
    debugging purposes).
 
70
 
 
71
    Methods may throw db.DBException, or any of the pg exceptions as well.
 
72
    (In general, be prepared to catch exceptions!)
 
73
    """
 
74
    def __init__(self):
 
75
        """Connects to the database and creates a DB object.
 
76
        Takes no parameters - gets all the DB info from the configuration."""
 
77
        self.db = pg.connect(dbname=conf.db_dbname, host=conf.db_host,
 
78
                port=conf.db_port, user=conf.db_user, passwd=conf.db_password)
 
79
 
 
80
    # USER MANAGEMENT FUNCTIONS #
 
81
 
 
82
    def create_user(self, login, password, unixid, email, nick, fullname,
 
83
        rolenm, studentid, dry=False):
 
84
        """Creates a user login entry in the database.
 
85
        Arguments are the same as those in the "login" table of the schema.
 
86
        The exception is "password", which is a cleartext password. makeuser
 
87
        will hash the password.
 
88
        Also "state" is not given explicitly; it is implicitly set to
 
89
        "no_agreement".
 
90
        Raises an exception if the user already exists.
 
91
        """
 
92
        passhash = _passhash(password)
 
93
        query = ("INSERT INTO login (login, passhash, state, unixid, email, "
 
94
            "nick, fullname, rolenm, studentid) VALUES "
 
95
            "(%s, %s, 'no_agreement', %d, %s, %s, %s, %s, %s);" %
 
96
            (_escape(login), _escape(passhash), unixid, _escape(email),
 
97
            _escape(nick), _escape(fullname), _escape(rolenm),
 
98
            _escape(studentid)))
 
99
        if dry: return query
 
100
        self.db.query(query)
 
101
 
 
102
    def update_user(self, login, password=None, state=None, email=None,
 
103
        nick=None, fullname=None, rolenm=None, dry=False):
 
104
        """Updates fields of a particular user. login is the name of the user
 
105
        to update. The other arguments are optional fields which may be
 
106
        modified. If None or omitted, they do not get modified. login and
 
107
        studentid may not be modified.
 
108
 
 
109
        Note that no checking is done. It is expected this function is called
 
110
        by a trusted source. In particular, it allows the password to be
 
111
        changed without knowing the old password. The caller should check
 
112
        that the user knows the existing password before calling this function
 
113
        with a new one.
 
114
        """
 
115
        # Make a list of SQL fragments of the form "field = 'new value'"
 
116
        # These fragments are ALREADY-ESCAPED
 
117
        setlist = []
 
118
        if password is not None:
 
119
            setlist.append("passhash = " + _escape(_passhash(password)))
 
120
        if state is not None:
 
121
            setlist.append("state = " + _escape(state))
 
122
        if email is not None:
 
123
            setlist.append("email = " + _escape(email))
 
124
        if nick is not None:
 
125
            setlist.append("nick = " + _escape(nick))
 
126
        if fullname is not None:
 
127
            setlist.append("fullname = " + _escape(fullname))
 
128
        if rolenm is not None:
 
129
            setlist.append("rolenm = " + _escape(rolenm))
 
130
        if len(setlist) == 0:
 
131
            return
 
132
        # Join the fragments into a comma-separated string
 
133
        setstring = ', '.join(setlist)
 
134
        # Build the whole query as an UPDATE statement
 
135
        query = ("UPDATE login SET %s WHERE login = %s;"
 
136
            % (setstring, _escape(login)))
 
137
        if dry: return query
 
138
        self.db.query(query)
 
139
 
 
140
    def delete_user(self, login, dry=False):
 
141
        """Deletes a user login entry from the database."""
 
142
        query = "DELETE FROM login WHERE login = %s;" % _escape(login)
 
143
        if dry: return query
 
144
        self.db.query(query)
 
145
 
 
146
    def get_user(self, login, dry=False):
 
147
        """Given a login, returns a dictionary of the user's DB fields,
 
148
        excluding the passhash field.
 
149
 
 
150
        Raises a DBException if the login is not found in the DB.
 
151
        """
 
152
        query = ("SELECT login, state, unixid, email, nick, fullname, "
 
153
            "rolenm, studentid FROM login WHERE login = %s;" % _escape(login))
 
154
        if dry: return query
 
155
        result = self.db.query(query)
 
156
        # Expecting exactly one
 
157
        if result.ntuples() != 1:
 
158
            # It should not be possible for ntuples to be greater than 1
 
159
            assert (result.ntuples() < 1)
 
160
            raise DBException("get_user: No user with that login name")
 
161
        # Return as a dictionary
 
162
        return result.dictresult()[0]
 
163
 
 
164
    def get_users(self, dry=False):
 
165
        """Returns a list of all users. The list elements are a dictionary of
 
166
        the user's DB fields, excluding the passhash field.
 
167
        """
 
168
        query = ("SELECT login, state, unixid, email, nick, fullname, "
 
169
            "rolenm, studentid FROM login")
 
170
        if dry: return query
 
171
        return self.db.query(query).dictresult()
 
172
 
 
173
    def user_authenticate(self, login, password, dry=False):
 
174
        """Performs a password authentication on a user. Returns True if
 
175
        "password" is the correct password for the given login, False
 
176
        otherwise. "password" is cleartext.
 
177
        Also returns False if the login does not exist (so if you want to
 
178
        differentiate these cases, use get_user and catch an exception).
 
179
        """
 
180
        query = ("SELECT login FROM login "
 
181
            "WHERE login = '%s' AND passhash = %s;"
 
182
            % (login, _escape(_passhash(password))))
 
183
        if dry: return query
 
184
        result = self.db.query(query)
 
185
        # If one row was returned, succeed.
 
186
        # Otherwise, fail to authenticate.
 
187
        return result.ntuples() == 1
 
188
 
 
189
    def close(self):
 
190
        """Close the DB connection. Do not call any other functions after
 
191
        this. (The behaviour of doing so is undefined).
 
192
        """
 
193
        self.db.close()