コード例 #1
0
ファイル: auth.py プロジェクト: monstercode/flask-framework
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        parser.add_argument('password',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        data = parser.parse_args()

        if not re.match(UserModel.USERNAME_FORMAT, data['username']):
            return {'message': 'User not found'}

        current_user = UserModel.find_by_username(username=data['username'],
                                                  exclude_deleted=True)
        if not current_user or current_user.deleted_at != None:
            return {'message': 'User {} not found'.format(data['username'])}

        if UserModel.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(current_user.jwt_serialize())
            refresh_token = create_refresh_token(current_user.jwt_serialize())
            return {
                'message': 'Logged in as {}'.format(current_user.username),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        else:
            return {'message': 'Wrong credentials'}
コード例 #2
0
    def create_test_note1_and_note2_by_user1(self):
        user_data = {
            "username": '******',
            'password': '******'
        }

        user = UserModel(**user_data)
        user.save()
        res = self.client.get("/users")
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data[0]["username"], user_data["username"])

        notes_data = [
            {
                "note": 'test note 1'
            },
            {
                "note": 'test note 2'
            },
        ]
        ids = []
        for note_data in notes_data:
            note = NoteModel(author_id=user.id, **note_data)
            note.save()
            ids.append(note.id)

        return user, user_data
コード例 #3
0
    def post(self):
        """Handles registration of user
                Handles native user signup and sends authToken back in the
                response

                Request Body:
                    user (LoginRequestParams) -- LoginRequestParams data.

                200 Response:
                    status (SuccessResponse) -- success
                    authToken ([jwt]) -- jwtToken
                Error Responses:
                    400 () -- Bad Request
                    500 () -- Internal Server Error
            """
        model = UserModel(db=self.db)
        (status, _) = yield model.login(self.args)
        if status:
            authToken = yield self.authorize(_)
            self.write(
                json.dumps({
                    'status': 'success',
                    'auth_token': authToken
                }))
        else:
            self.set_status(400)
            self.write(json.dumps(_))
            self.finish()
コード例 #4
0
ファイル: test.py プロジェクト: Nickolai-Myasnicov/NotesApi
    def test_get_note_by_id(self):
        user_data = {"username": '******', "password": '******'}

        user = UserModel(**user_data)
        user.save()
        notes_data = [
            {
                "text": 'Text note 1',
            },
            {
                "text": 'Text note 2',
            },
        ]
        ids = []
        for note_data in notes_data:
            note = NoteModel(author_id=user.id, **note_data)
            note.save()
            ids.append(note.id)

        headers = {
            'Authorization':
            'Basic ' +
            b64encode(f"{user_data['username']}:{user_data['password']}".
                      encode('ascii')).decode('utf-8')
        }
        res = self.client.get('/notes', headers=headers)
        self.assertEqual(res.status_code, 200)
        data = json.loads(res.data)
        self.assertEqual(len(data), 2)
コード例 #5
0
    def create_test_user1_note1_tag1_tag1(self):
        user_data = {
            "username": '******',
            'password': '******'
        }

        user = UserModel(**user_data)
        user.save()
        res = self.client.get("/users")
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data[0]["username"], user_data["username"])

        note_data1 = {
            "note": 'test note 1'
        }

        note = NoteModel(author_id=user.id, **note_data1)
        note.save()

        tags_data = [
            {
                "name": 'test1 tag'
            },
            {
                "name": 'test2 tag'
            }
        ]
        for tag_data in tags_data:
            tag = TagModel(author_id=user.id, **tag_data)
            tag.save()

        return user, note, user_data, tags_data
コード例 #6
0
 def post(self, **kwargs):
     user = UserModel(**kwargs)
     try:
         user.save()
         return user, 201
     except:
         abort(404, error=f"An error occurred while adding new user" \
                          "or a user with such name is already exist. " \
                          "You can only add a unique name")
コード例 #7
0
ファイル: test.py プロジェクト: Nickolai-Myasnicov/NotesApi
 def test_user_get_by_id(self):
     user_data = {"username": '******', 'password': '******'}
     user = UserModel(**user_data)
     user.save()
     user_id = user.id
     response = self.client.get(f'/users/{user_id}')
     data = json.loads(response.data)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(data["username"], user_data["username"])
コード例 #8
0
def mock_user_model(mocker):
    # so that we don't actually save to the db
    mocker.patch("api.models.user.UserModel.save_to_db")
    mocker.patch(
        "api.models.user.UserModel.find_all",
        return_value=[
            UserModel(name="john smith"),
            UserModel(name="mary jane")
        ],
    )
コード例 #9
0
ファイル: test_tags.py プロジェクト: UshakovAleksandr/Blog
    def create_test_user1(self):
        user_data = {"username": '******', 'password': '******'}

        user = UserModel(**user_data)
        user.save()
        res = self.client.get("/users")
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data[0]["username"], user_data["username"])
        return user_data
コード例 #10
0
    def post(self):
        # make sure all required fields are present
        user_data = self.parser.parse_args()

        try:
            user = UserModel(**user_data)
            user.save_to_db()
        except Exception:
            return {"message": "Unable to create user"}, 500
        return {"message": "successfully created user", "payload": user.json()}, 201
コード例 #11
0
 def test_register_duplicate_user(self):
     user = UserModel('test', 'password')
     user.save_to_db()
     response = self.client.post(
         '/register',
         data=json.dumps({
             'username': '******',
             'password': '******'
         }),
         headers={'Content-Type': 'application/json'})
     self.assertEqual(response.status_code, 400)
     expected = {"message": "A user with that username already exists"}
     self.assertDictEqual(expected, json.loads(response.data))
コード例 #12
0
ファイル: auth.py プロジェクト: monstercode/flask-framework
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        parser.add_argument('password',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        parser.add_argument('email',
                            help='This field cannot be blank',
                            location='json',
                            required=True)
        data = parser.parse_args()

        if not re.match(UserModel.USERNAME_FORMAT, data['username']):
            return {
                'message':
                'Username must consist of letters, numbers, hyphens and underscores'
            }

        if UserModel.find_by_username(username=data['username'],
                                      exclude_deleted=False):
            return {
                'message':
                'Username {} already exists'.format(data['username'])
            }

        if UserModel.find_by_email(email=data['email'], exclude_deleted=False):
            return {
                'message':
                'User with email {} already exists'.format(data['email'])
            }

        new_user = UserModel(
            username=data['username'],
            password=UserModel.generate_hash(data['password']),
            email=data['email'],
            deleted_at=None,
        )

        try:
            new_user.save_to_db()
            access_token = create_access_token(new_user.jwt_serialize())
            refresh_token = create_refresh_token(new_user.jwt_serialize())
            return {
                'message': 'User {} was created'.format(data['username']),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        except:
            return {'message': 'Something went wrong'}, 400
コード例 #13
0
ファイル: test_tags.py プロジェクト: UshakovAleksandr/Blog
    def create_test_tag1_by_user1(self):
        user_data1 = {"username": '******', 'password': '******'}

        user1 = UserModel(**user_data1)
        user1.save()
        res = self.client.get("/users")
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data[0]["username"], user_data1["username"])

        tag_data1 = {"name": 'test tag'}

        tag1 = TagModel(author_id=user1.id, **tag_data1)
        tag1.save()

        return tag1, user1, user_data1
コード例 #14
0
    def get(self):
        """
        Returns user Profile

        HTTP Header:
            Authorization (str) -- Required

        200 Response:
            status (ProfileSchema) -- success
        :return:
        """

        model = UserModel(user=self._user, db=self.db)
        profile = model.get_profile()

        self.write(dumps(profile))
コード例 #15
0
ファイル: user.py プロジェクト: mmint-kanban/kanban
 def get(self):
     # Search user
     users = UserModel.search(
         keyword=request.args.get('keyword'),
         fields=('username', '_id')
     )
     return {'users': users}
コード例 #16
0
    def isUserExist(self, userid):
        user = UserModel.get_by_id(userid)

        # print user
        if user is not None:
            return True
        else:
            return False
コード例 #17
0
ファイル: test_user.py プロジェクト: lciamp/flask-test
    def test_create_user(self):
        user = UserModel('Test', 'password')

        self.assertIsNotNone(user)

        self.assertEqual(user.username, 'Test')

        self.assertEqual(user.password, 'password')
コード例 #18
0
    def addUser(self, user):
        # currentuser = UserModel(parent=self.getUserKey()) #User is a parent and has username as the key

        if self.isUserExist(user['username']) is not True:
            currentuser = UserModel()
            currentuser.key = ndb.Key(UserModel, user['username'])
            currentuser.username = user['username']
            currentuser.realname = user['realname']
            currentuser.password = user['password']
            currentuser.group = user['group']
            currentuser.put()
            return True
        else:
            return False
コード例 #19
0
def create_test_user1_and_user2(db_create):
    users_data = [
        {
            "username": '******',
            'password': '******'
        },
        {
            "username": '******',
            'password': '******'
        },
    ]
    users_lst = []
    for user_data in users_data:
        user = UserModel(**user_data)
        user.save()
        users_lst.append(user)

    return users_lst
コード例 #20
0
ファイル: user.py プロジェクト: RusksTeam/db-generator
 def post(cls):
     data = _user_parser.parse_args()
     user = UserModel.find_by_username(data['username'])
     data_password_hashed = sha512(
         data['password'].encode('utf-8')).hexdigest()
     if user and safe_str_cmp(data_password_hashed, user.password):
         access_token = create_access_token(identity=user.id)
         return {'access_token': access_token}
     return {'message': 'Invalid credentials'}, 401
コード例 #21
0
def load_tables():
    if len(DryBreadModel.find_all()) == 0:
        print('Database does not exist/is empty. Creating from file...')
        data = dict()
        with open('tmp_database.json', 'r', encoding='utf-8') as f:
            data = json.loads(f.read())

        for e in data['suchary']:
            if e['type'] <= cfg['JOKE_TYPE']:
                db = DryBreadModel(e['q'], e['a'])
                db.save_to_db()

        print('drybreads loaded:', [x.json() for x in db.find_all()])

####users database
    from api.models.user import UserModel
    admin = UserModel('admin', 'admin', UserModel.ROLE_ADMIN)
    admin.save_to_db()
コード例 #22
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument("username", required=True)
     parser.add_argument("password", required=True)
     user_data = parser.parse_args()
     user = UserModel(**user_data)
     db.session.add(user)
     db.session.commit()
     return user_schema.dump(user), 201
コード例 #23
0
 def test_register_and_login(self):
     UserModel('test', 'password').save_to_db()
     auth_response = self.client.post(
         '/auth',
         data=json.dumps({
             'username': '******',
             'password': '******'
         }),
         headers={'Content-Type': 'application/json'})
     self.assertIn('access_token', json.loads(auth_response.data).keys())
コード例 #24
0
    def on_post(self, req, resp):

        data = req.context.get("json")

        if UserModel.find_by_username(data.get("username")):
            payload = {
                "message":
                f"User with username:{data.get('username')} already exists"
            }
            resp.body = json.dumps(payload, ensure_ascii=False)
            resp.status = falcon.HTTP_400
        else:

            user = UserModel(**data)
            user.save_to_db()

            payload = {"message": "User created sucessfully"}
            resp.body = json.dumps(payload, ensure_ascii=False)
            resp.status = falcon.HTTP_201
コード例 #25
0
    def post(self):
        args = self.reqparse.parse_args()
        user = UserModel(args.name, args.state)

        db.session.add(user)
        db.session.commit()

        response = UserSchema().dump(user)

        return response, 201
コード例 #26
0
ファイル: __init__.py プロジェクト: MyGodIsHe/Blog
def verify_password(username_or_token, password):
    from api.models.user import UserModel
    #print("username_or_token = ", username_or_token)
    user = UserModel.verify_auth_token(username_or_token)
    if not user:
        user = UserModel.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True
コード例 #27
0
ファイル: test_tags.py プロジェクト: UshakovAleksandr/Blog
    def create_test_tag1_and_tag2_by_user1(self):
        user_data1 = {"username": '******', 'password': '******'}

        user1 = UserModel(**user_data1)
        user1.save()
        res = self.client.get("/users")
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data[0]["username"], user_data1["username"])

        tags_data = [{"name": 'test1 tag'}, {"name": 'test2 tag'}]

        ids = []
        for tag_data in tags_data:
            tag = TagModel(author_id=user1.id, **tag_data)
            tag.save()
            ids.append(tag.id)

        return user1, user_data1, tags_data
コード例 #28
0
ファイル: test_item.py プロジェクト: lciamp/flask-test
 def setUp(self):
     super(ItemTest, self).setUp()
     UserModel('test', 'password').save_to_db()
     auth_response = self.client.post(
         '/auth',
         data=json.dumps({
             'username': '******',
             'password': '******'
         }),
         headers={'Content-Type': 'application/json'})
     self.token = 'JWT {}'.format(
         json.loads(auth_response.data).get('access_token'))
コード例 #29
0
ファイル: test.py プロジェクト: Nickolai-Myasnicov/NotesApi
    def test_users_get(self):
        users_data = [
            {
                "username": '******',
                'password': '******'
            },
            {
                "username": '******',
                'password': '******'
            },
        ]
        for user_data in users_data:
            user = UserModel(**user_data)
            user.save()

        res = self.client.get('/users')
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        print(data)
        self.assertEqual(data[0]["username"], users_data[0]["username"])
        self.assertEqual(data[1]["username"], users_data[1]["username"])
コード例 #30
0
 def test_register_user(self):
     response = self.client.post(
         '/register',
         data=json.dumps({
             'username': '******',
             'password': '******'
         }),
         headers={'Content-Type': 'application/json'})
     self.assertEqual(response.status_code, 201)
     self.assertIsNotNone(UserModel.find_by_username('test'))
     expected = {"message": "User created successfully."}
     self.assertDictEqual(expected, json.loads(response.data))
コード例 #31
0
    def create_test_user1_note1_by_user1(self):
        user_data1 = {
            "username": '******',
            'password': '******'
        }

        user1 = UserModel(**user_data1)
        user1.save()
        res = self.client.get("/users")
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data[0]["username"], user_data1["username"])

        note_data1 = {
            "note": 'test note 1'
        }

        note1 = NoteModel(author_id=user1.id, **note_data1)
        note1.save()

        return note1, user1, user_data1
コード例 #32
0
ファイル: user.py プロジェクト: mmint-kanban/kanban
 def post(self, _id=None):
     UserModel.register(request.form)
     return 'ok'