from werkzeug.security import generate_password_hash, check_password_hash
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext import login

import config
db = SQLAlchemy(config.app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String, unique=True)
    password = db.Column(db.String)

    def __init__(self, email, password):
        self.email = email
        self.password = self.hash_password(password)

    def hash_password(self, password):
        return generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def is_authenticated(self):
        return self.id is not None

    def is_anonymous(self):
        return False

    def is_active(self):
        return self.is_authenticated()

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return '<User: %s>' % self.email

    def key_for_service(self, alias):
        return self.keys.filter_by(service_alias=alias).first()


class Key(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    service_alias = db.Column(db.String)
    key = db.Column(db.String)
    secret = db.Column(db.String)
    expires = db.Column(db.DateTime)

    user = db.relationship('User', backref=db.backref('keys', lazy='dynamic'))

    @property
    def service(self):
        if self.service_alias:
            for service in config.services:
                if self.service_alias == service.alias:
                    return service
        else:
            raise AttributeError('No service specified.')
        raise AttributeError('%r is not a valid service.' % self.service_alias)


login_manager = login.LoginManager()
login_manager.setup_app(config.app)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)



@@ -1453,32 +1453,36 @@
 lf):%0A        if 
+not 
 self.service_ali
@@ -1501,95 +1501,53 @@
     
-for service in config.services:%0A                if self.service_alias == service.alias:
+raise AttributeError('No service specified.')
 %0A   
@@ -1543,32 +1543,37 @@
 fied.')%0A        
+try:%0A
             retu
@@ -1579,88 +1579,73 @@
 urn 
-service%0A        else:%0A            raise AttributeError('No service specified.')%0A
+config.services%5Bself.service_alias%5D%0A        except KeyError:%0A    
     

Use a faster service lookup