Advertisement
Guest User

Untitled

a guest
May 3rd, 2016
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.41 KB | None | 0 0
  1. @login_manager.user_loader
  2. def user_loader(user_id):
  3. """Given *user_id*, return the associated User object.
  4.  
  5. :param unicode user_id: user_id (email) user to retrieve
  6. """
  7. print('within user loader')
  8. print('user_id:')
  9. print(user_id)
  10. # try:
  11. # return User.query.get(user_id)
  12. # except:
  13. user = User(email=user_id)
  14. print('the user:')
  15. print(user)
  16. return user
  17.  
  18.  
  19. @login_manager.request_loader
  20. def request_loader(request):
  21. print('within request_loader')
  22. email = request.form.get('email')
  23. try:
  24. user = User.query.get(email)
  25. except:
  26. return
  27.  
  28. # DO NOT ever store passwords in plaintext and always compare password
  29. # hashes using constant-time comparison!
  30. try:
  31. user.is_authenticated = request.form['password'] == user.password
  32. except:
  33. pass
  34. return user
  35.  
  36.  
  37. class CRUDMixin(object):
  38. """Mixin that adds convenience methods for CRUD (create, read, update, delete)
  39. operations.
  40. """
  41.  
  42. @classmethod
  43. def create(cls, **kwargs):
  44. """Create a new record and save it the database."""
  45. instance = cls(**kwargs)
  46. return instance.save()
  47.  
  48. def update(self, commit=True, **kwargs):
  49. """Update specific fields of a record."""
  50. for attr, value in kwargs.iteritems():
  51. setattr(self, attr, value)
  52. return commit and self.save() or self
  53.  
  54. def save(self, commit=True):
  55. """Save the record."""
  56. # with application.app_context():
  57. db.session.add(self)
  58. if commit:
  59. db.session.commit()
  60. return self
  61.  
  62. def delete(self, commit=True):
  63. """Remove the record from the database."""
  64. # with application.app_context():
  65. db.session.delete(self)
  66. return commit and db.session.commit()
  67.  
  68.  
  69. class Model(CRUDMixin, db.Model):
  70. """Base model class that includes CRUD convenience methods."""
  71. __abstract__ = True
  72.  
  73. def __init__(self, **kwargs):
  74. db.Model.__init__(self, **kwargs)
  75.  
  76.  
  77. # From Mike Bayer's "Building the app" talk
  78. # https://speakerdeck.com/zzzeek/building-the-app
  79. class SurrogatePK(object):
  80. """A mixin that adds a surrogate integer 'primary key' column named
  81. ``id`` to any declarative-mapped class.
  82. """
  83. __table_args__ = {'extend_existing': True}
  84.  
  85. id = db.Column(db.Integer, primary_key=True)
  86.  
  87. @classmethod
  88. def get_by_id(cls, id):
  89. _id = to_int(id)
  90. if _id is not None:
  91. return cls.query.get(_id)
  92. return None
  93.  
  94.  
  95. class Website(Model, SurrogatePK):
  96. __tablename__ = 'websites'
  97.  
  98. name = db.Column(db.String(100), unique=True)
  99. url = db.Column(db.String(250), unique=True)
  100. user_id = db.Column(db.Integer, db.ForeignKey('users.email'))
  101. # def __init__(self, name, url):
  102. # self.name = name
  103. # self.url = url
  104.  
  105. def __repr__(self):
  106. return "{}: {}".format(self.name, self.url)
  107.  
  108.  
  109. class User(Model):
  110. """
  111. :param str email: email address of user
  112. :param str password: encrypted password for the user
  113. """
  114. __tablename__ = 'users'
  115.  
  116. email = db.Column(db.String, primary_key=True)
  117. password = db.Column(db.String)
  118. authenticated = db.Column(db.Boolean, default=False)
  119. approved = db.Column(db.Boolean, default=False)
  120. websites = db.relationship('Website', backref='websites', lazy='dynamic')
  121.  
  122.  
  123. def is_active(self):
  124. """True, as all users are active."""
  125. return True
  126.  
  127. def is_authenticated(self):
  128. """Return True if the user is authenticated."""
  129. return self.authenticated
  130.  
  131. def is_anonymous(self):
  132. """False, as anonymous users aren't supported."""
  133. return False
  134.  
  135. def get_id(self):
  136. """Return the email address to satisfy Flask-Login's requirements."""
  137. return self.email
  138.  
  139. @application.route('/login', methods=['GET', 'POST'])
  140. def login():
  141. form = LoginForm(request.form)
  142. if request.method == 'POST':
  143. if form.validate_on_submit():
  144. email = form.email.data
  145. password = form.password.data
  146. user = User.query.filter_by(email=email, password=password).first()
  147. if user:
  148. login_user(user)
  149. current_user.authenticated = True
  150. print(current_user.authenticated)
  151. flash('Logged in successfully.')
  152. return redirect(url_for('main'))
  153. handle_login_form(form)
  154. return render_template('login.html', form=form)
  155.  
  156. within user loader
  157. user_id:
  158. cchilder@mail.usf.edu
  159. the user:
  160. <app.User object at 0x7f4de90f1990>
  161.  
  162. @application.route('/')
  163. @login_required
  164. def main():
  165. print('nnIn main')
  166. print(current_user.is_authenticated())
  167. print(current_user.approved)
  168. print(current_user)
  169. if not current_user:
  170. return "still having login issue"
  171.  
  172. if current_user.is_authenticated and not current_user.approved:
  173. return redirect(url_for('awaiting_approval'))
  174.  
  175. statuses = gather_statuses()
  176. length = len(statuses['system_statuses']) + len(statuses['website_statuses'])
  177. is_empty = length == 0
  178. return render_template('status.html', is_empty=is_empty, **statuses)
  179.  
  180. In main
  181. None
  182. None
  183. <app.User object at 0x7f4de90f1990>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement