Shotca avatar Shotca committed 4992a2a

Removed mongo model as it was not supported anymore, cleaned up some code, added comments

Comments (0)

Files changed (7)

 *egg-info
 .*
 _build
+*.orig

examples/mongoalchemy_model.py

-from flask import Flask, request, redirect, url_for
-from flaskext.mongoalchemy import MongoAlchemy
-from flaskext.auth import Auth, login_required, logout
-from flaskext.auth.models.mongo import get_user_class 
-
-app = Flask(__name__)
-app.config['MONGOALCHEMY_DATABASE'] = 'library'
-db = MongoAlchemy(app)
-auth = Auth(app, login_url_name='index')
-
-User = get_user_class(db)
-
-@login_required()
-def admin():
-    return 'Admin! Excellent!'
-
-def index():
-    if request.method == 'POST':
-        username = request.form['username']
-        user = User.query.filter(User.username==username).first()
-        if user is not None:
-            # Authenticate and log in!
-            if user.authenticate(request.form['password']):
-                return redirect(url_for('admin'))
-        return 'Failure :('
-    return '''
-            <form method="POST">
-                Username: <input type="text" name="username"/><br/>
-                Password: <input type="password" name="password"/><br/>
-                <input type="submit" value="Log in"/>
-            </form>
-        '''
-
-def user_create():
-    if request.method == 'POST':
-        username = request.form['username']
-        if User.query.filter(User.username==username).first():
-            return 'User already exists.'
-        password = request.form['password']
-        user = User(username=username)
-        user.set_and_encrypt_password(password)
-        user.save()
-        return redirect(url_for('index'))
-    return '''
-            <form method="POST">
-                Username: <input type="text" name="username"/><br/>
-                Password: <input type="password" name="password"/><br/>
-                <input type="submit" value="Create"/>
-            </form>
-        '''
-
-def logout_view():
-    user = logout()
-    if user is None:
-        return 'No user to log out.'
-    return 'Logged out user {0}.'.format(user.username)
-
-# URLs
-app.add_url_rule('/', 'index', index, methods=['GET', 'POST'])
-app.add_url_rule('/admin/', 'admin', admin)
-app.add_url_rule('/users/create/', 'user_create', user_create, methods=['GET', 'POST'])
-app.add_url_rule('/logout/', 'logout', logout_view)
-
-# Secret key needed to use sessions.
-app.secret_key = 'N4BUdSXUzHxNoO8g'
-
-if __name__ == '__main__':
-    app.run(debug=True)

examples/permissions.py

 }
 
 def load_role(role_name):
+    """
+    Function that has to be defined to be able to retrieve the actual role
+    object from the user.role attribute. In this simple case, we could
+    actually assign the role object directly to user.role, in which this
+    function would simply be the identity function (lambda x: x). This extra
+    step becomes needed however in case the role object is more complex
+    and it can't be simply pickled anymore.
+    """
     return roles.get(role_name)
 
 auth.load_role = load_role
     user.set_and_encrypt_password('password', salt='123')
     # Setting role of the user.
     user.role = 'userview'
+
+    # Doing the same for the admin
+    admin = AuthUser(username='admin')
+    admin.set_and_encrypt_password('admin')
+    admin.role = 'admin'
+
     # Persisting users for this request.
-    g.users = {'user': user}
+    g.users = {'user': user, 'admin': admin, }
 
 @permission_required(resource='user', action='view')
 def user_view():
             if g.users[username].authenticate(request.form['password']):
                 return '''
                         <a href="{0}">View users</a><br/>
-                        <a href="{1}">Create users</a>
-                        '''.format(url_for('user_view'), url_for('user_create'))
+                        <a href="{1}">Create users</a><br/>
+                        <a href="{2}">Logout</a>
+                        '''.format(url_for('user_view'), 
+                                   url_for('user_create'),
+                                   url_for('logout'),)
         return 'Failure :('
     return '''
             <form method="POST">
 
 # URLs
 app.add_url_rule('/', 'index', index, methods=['GET', 'POST'])
-app.add_url_rule('/user/view/', 'user_view', user_view)
-app.add_url_rule('/user/create/', 'user_create', user_create)
+app.add_url_rule('/users/view/', 'user_view', user_view)
+app.add_url_rule('/users/create/', 'user_create', user_create)
 app.add_url_rule('/logout/', 'logout', logout_view)
 
 # Secret key needed to use sessions.

flaskext/auth/__init__.py

     flaskext.auth
     ~~~~~~~~~~~~~
 
-    Flask extension for role-based user administration and authentication. Designed to be DB agnostic and still fairly
-    plug-and-play.
+    Flask extension for role-based user administration and authentication. 
+    Designed to be DB agnostic and still fairly plug-and-play.
 
     :copyright: (c) 2011 by Lars de Ridder.
     :license: BSD, see LICENSE for more details.

flaskext/auth/auth.py

         return None
     return user_data
 
-def _not_logged_in(callback, *args, **kwargs):
+def not_logged_in(callback, *args, **kwargs):
+    """
+    Executes not logged in callback. Not for external use.
+    """
     if callback is None:
         return current_app.auth.not_logged_in_callback(*args, **kwargs)
     else:
     def wrap(func):
         def decorator(*args, **kwargs):
             if get_current_user_data() is None:
-                return _not_logged_in(callback, *args, **kwargs)
+                return not_logged_in(callback, *args, **kwargs)
             return func(*args, **kwargs)
         return decorator
     return wrap

flaskext/auth/models/mongo.py

-import datetime
-from flaskext.auth import AuthUser, get_current_user_data
-
-def now():
-    return datetime.datetime.utcnow()
-
-def get_user_class(db):
-    class User(db.Document, AuthUser):
-        """
-        Implementation of User for SQLAlchemy.
-        """
-        username = db.StringField()
-        password = db.StringField()
-        salt = db.StringField()
-        role = db.StringField(required=False)
-        created = db.DateTimeField(default=now())
-        modified = db.DateTimeField(default=now())
-
-        def save(self):
-            self.modified = now()
-            super(User, self).save()
-
-        def __getstate__(self):
-            return {
-                'id': self.id,
-                'username': self.username,
-                'role': self.role,
-                'created': self.created,
-                'modified': self.modified,
-            }
-
-        @classmethod
-        def load_current_user(cls, apply_timeout=True):
-            data = get_current_user_data(apply_timeout)
-            if not data:
-                return None
-            return cls.query.filter(cls.username==data['username']).one()
-
-    return User

flaskext/auth/permissions.py

 """
 
 from flask import current_app
-from flaskext.auth.auth import get_current_user_data, _not_logged_in
+from flaskext.auth.auth import get_current_user_data, not_logged_in
 
 def has_permission(role, resource, action):
     """Function to check if a user has the specified permission."""
         def decorator(*args, **kwargs):
             user_data = get_current_user_data()
             if user_data is None:
-                return _not_logged_in(callback, *args, **kwargs)
+                return not_logged_in(callback, *args, **kwargs)
             if not has_permission(user_data.get('role'), resource, action):
                 if callback is None:
                     return current_app.auth.not_permitted_callback(*args, **kwargs)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.