def post(self, data): password = data.get("password", "") customer: Customer = Manager(Customer).get(email=self.kwargs["email"]) if customer.verify_password(password): token = Token(customer=customer.pk, token=str(uuid4())) token.save() return self.response({"token": token.token}) else: return self.response({"error": "Invalid password"})
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 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 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 test_login_required_view_with_token(self): path = "/website" customer = Customer(name="test", password="******", email="test", subscription=None, plan=None) customer.save() token_str = "token" token = Token(token=token_str, customer=customer.pk) token.save() view = router.router(path, token_str) self.assertIsInstance(view, WebsiteView) self.assertEqual(view.customer.pk, customer.pk)
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 setUp(self): no_name_app.configure_app('confs/test.cfg') self.app = no_name_app.app.test_client() User.drop_collection() Token.drop_collection()
def test_empty_mongo(self): self.assertEquals(User.objects().count(), 0) self.assertEquals(Token.objects().count(), 0)