Skip to content

Instantly share code, notes, and snippets.

@psykidellic
Created June 10, 2014 17:39
Show Gist options
  • Save psykidellic/db57c046ea5a852b216b to your computer and use it in GitHub Desktop.
Save psykidellic/db57c046ea5a852b216b to your computer and use it in GitHub Desktop.
auth = Blueprint("auth", __name__)
@auth.route("/login", methods=["POST"])
def login():
"""
Logs the user in
"""
if current_user is not None and current_user.is_authenticated():
return jsonify({'username': current_user.username})
data = request.get_json(force=True)
user, authenticated = User.authenticate(data["login"],
data["password"])
if user and authenticated:
login_user(user)
return jsonify({'username': user.username})
return make_response(jsonify({'err': 'Error'}), 401)
@auth.route("/logout", methods=["POST"])
@login_required
def logout():
logout_user()
return jsonify({'success': 'ok'})
class User(db.Model, UserMixin):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True, nullable=False)
email = db.Column(db.String(63), unique=True, nullable=False)
_password = db.Column('password', db.String(80), nullable=False)
date_joined = db.Column(db.DateTime, default=datetime.utcnow())
# Properties
@property
def last_post(self):
"""Returns the latest post from the user"""
return Post.query.filter(Post.user_id == self.id).\
order_by(Post.date_created.desc()).first()
@property
def url(self):
"""Returns the url for the user"""
return url_for("user.profile", username=self.username)
# Methods
def __repr__(self):
"""Set to a unique key specific to the object in the database.
Required for cache.memoize() to work across requests.
"""
return "Username: %s" % self.username
def _get_password(self):
"""Returns the hashed password"""
return self._password
def _set_password(self, password):
"""Generates a password hash for the provided password"""
self._password = generate_password_hash(password)
# Hide password encryption by exposing password field only.
password = db.synonym('_password',
descriptor=property(_get_password,
_set_password))
@classmethod
def authenticate(cls, login, password):
"""A classmethod for authenticating users
It returns true if the user exists and has entered a correct password
:param login: This can be either a username or a email address.
:param password: The password that is connected to username and email.
"""
user = cls.query.filter(db.or_(User.username == login,
User.email == login)).first()
if user:
authenticated = user.check_password(password)
else:
authenticated = False
return user, authenticated
def _make_token(self, data, timeout):
s = Serializer(current_app.config['SECRET_KEY'], timeout)
return s.dumps(data)
def _verify_token(self, token):
s = Serializer(current_app.config['SECRET_KEY'])
data = None
expired, invalid = False, False
try:
data = s.loads(token)
except SignatureExpired:
expired = True
except Exception:
invalid = True
return expired, invalid, data
def make_reset_token(self, expiration=3600):
"""Creates a token. The duration can be configured through the
expiration parameter.
:param expiration: The time in seconds how long the token is valid.
"""
return self._make_token({'id': self.id, 'op': 'reset'}, expiration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment