def logout(): """ The logout endpoint Attempt to logout the user and delete its token from mongoDB @return: {'success': true} upon successful logout or a 401 (Unauthorized) response caused by the requires_token wrapper """ Token.objects(id=session['token']).delete() session.pop('token', None) return jsonify(success=True)
def is_valid_token(token_id): """ Check the existence of a token into mongoDB @param token_id: the token's to test id @return: whether the token is valid (exists) or not """ return Token.objects(id=token_id).count() > 0
def decorated(*args, **kwargs): """ The wraps decorator @param args: initial f's args @param kwargs: initial f's kwargs @return: an abortion if unauthorized or f """ if 'token' in session: t = Token.objects(id=session['token']) return f(*args, **kwargs) if t.count > 0 else abort(401) else: return abort(401)
def get_user_info(): """ function to executed before each received request Will test if the user is authenticated and consequently insert its information into the g variable """ if 'token' in session: t = Token.objects(id=session['token']) u = t.first() if u: g.current_user = {'email': u.user.email} else: g.current_user = None
def check_user_token(user): """ Retrieve, update or create a user's token @param user: the user to get a token for @return: a valid token associated with the user """ token = Token.objects(user=user).first() if token: return token else: token = Token(user=user) token.save() return token
def test_empty_mongo(self): self.assertEquals(User.objects().count(), 0) self.assertEquals(Token.objects().count(), 0)