Beispiel #1
0
def login():
    try:
        if current_user.is_authenticated:
            user = User.query.filter(User.id == current_user.id).first()
            return make_response(
                jsonify(to_dict(user, exclude=User.getExclude())))

        form_data = json.loads(request.get_data().decode('utf-8'))

        if ('email' in form_data) and ('password' in form_data):
            user = User.query.filter(
                User.email == form_data['email'],
                User.password == HashValidator.hash(
                    form_data['password'])).first()
            if user is None:
                raise Error(name='Failed login',
                            message='Combinatie email/wachtwoord is onbekend')

            login_user(user)

            return make_response(
                jsonify(to_dict(user, exclude=User.getExclude())))

        else:
            raise Error(
                name='Failed login',
                message='Kan niet inloggen, email en/of wachtwoord ontbreekt')
    except Error as e:
        return make_response(jsonify({e.name: e.message}), 400)
Beispiel #2
0
    async def post(self, request):
        user = User(request.json, strict=True)
        try:
            user.validate()
        except BaseError as ex:
            raise InvalidUsage(f'Error in data: {ex.to_primitive()}')

        user = await db_api.add_user(user.to_native())
        return json(user, status=201)
Beispiel #3
0
 def test_encode_auth_token(self):
     user = User(first_name='First Name',
                 last_name='Last Name',
                 email='*****@*****.**',
                 password='******')
     db.session.add(user)
     db.session.commit()
     auth_token = user.encode_auth_token(user.id)
     self.assertTrue(isinstance(auth_token, bytes))
Beispiel #4
0
    async def put(self, request, user_id):
        user_id = UserById({'user_id': user_id}).user_id
        user = User(request.json, strict=True)
        try:
            user.validate()
        except BaseError as ex:
            raise InvalidUsage(f'Error in data: {ex.to_primitive()}')

        user = db_api.update_user_by_id(user_id, user.to_native())
        return json(user, status=200)
Beispiel #5
0
 def put(self):
     """Updates current user profile info"""
     logger.info("UserProfile.put() user_id: %s", str(current_user().id))
     try:
         user_id = current_user().id
         content = json.loads(request.form['data'])
         photo = request.files.get('photo', None)
         photo_url = cloudinary_uploader.upload(
             photo)['url'] if photo else None
         User.update_user_profile_info(user_id, content, photo_url)
         return 'User profile info has been updated', 200
     except Exception as e:
         logger.exception("UserProfile.put(): %s", str(e))
         return "Couldn't update user profile info", 500
Beispiel #6
0
    def test_get_user_with_other_jwt(self):
        user = User(
            username='******',
            password='******',
            email='*****@*****.**',
        )
        role = Roles({'username': user.username, 'roles': user.is_admin})
        save_user(user)
        save_user(role)

        me = User(
            username='******',
            password='******',
            email='*****@*****.**',
        )
        role_me = Roles({'username': me.username, 'roles': me.is_admin})
        save_user(me)
        save_user(role_me)

        with self.client:
            res_login = self.client.post('/v1/login',
                                         headers={
                                             'Content-Type':
                                             'application/json',
                                             'Accept': 'application/json'
                                         },
                                         data=json.dumps({
                                             'username': '******',
                                             'password': '******'
                                         }))
            data_login = json.loads(res_login.data.decode())

            response = self.client.get('/v1/users/{}'.format(user.username),
                                       headers={
                                           'Content-Type':
                                           'application/json',
                                           'Accept':
                                           'application/json',
                                           'Authorization':
                                           'Bearer {}'.format(
                                               data_login['access_token'])
                                       })
            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == True)
            self.assertTrue(
                data['msg'] == 'Accessed to {} page.'.format(user.username))
            self.assertTrue(data['is_user'] == False)
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 200)
Beispiel #7
0
def register_user():
    try:
        username = request.get_json()['username']
        email = request.get_json()['email']
        password = request.get_json()['password']
        user = User('user_id',
                    username=username,
                    email=email,
                    password=password)
        new_user = User.insert_user_data(user)
        print(new_user)
        return new_user
    except Exception as e:
        logging.error(e)
        return make_response(jsonify({'message': str(e)}), 500)
Beispiel #8
0
def ensure_user(user_id):
    user = User.get_by_id(user_id)
    if not user:
        raise GulDanException().with_code(404).with_message(
            u"找不到用户(id:{})".format(user_id))

    return user
Beispiel #9
0
def init_admin_user():
    from app.api.mod_misc.register import create_user
    from app.api.models.user import User

    user = User.get_user_by_name("admin")
    if not user.name:
        create_user("admin", "123456")
Beispiel #10
0
def login_user():
    """ Allows users to log into their accounts"""
    try:
        with DatabaseConnection() as cursor:
            if not request.get_json():
                return make_response(
                    jsonify({"message": "Request should be json"}), 400)
            email = request.get_json()['email']
            password = request.get_json()['password']
            sql = "select user_id, email, password from users where email = %s and password = %s"
            cursor.execute(sql, (email, password))
            user_id = cursor.fetchone()
            if user_id:
                token = User.encode_auth_token(user_id)
                if token:
                    response = {
                        'user_id': user_id[0],
                        'message': 'You logged in successfully',
                        'token': token,
                        'email': email
                    }
                    return make_response(jsonify(response))
                return make_response(jsonify({"message": "Please log in"}))

            else:
                return make_response(
                    jsonify({"message":
                             "wrong password or email credentials"}))

    except Exception as e:
        logging.error(e)
        return make_response(jsonify({'message': str(e)}), 401)
Beispiel #11
0
    def post(self):
        post_data = request.get_json()
        name = post_data.get("firstName")
        surname = post_data.get("lastName")
        email = post_data.get("email")
        password = post_data.get("password")

        user = get_user_by_email(email)
        if user:
            auth_namespace.abort(400, "Sorry. That email already exists.")

        user = User.add_user(name, surname, email, password)

        # msg = Message("Testing email", recipients=[email])
        # mail.send(msg)
        try:
            with open('./templates/registration_email.html') as file:
                template = file.read()
            guard.send_registration_email(email,
                                          user=user,
                                          confirmation_sender='SchabCoin',
                                          template=template)
        except Exception as e:
            logger.exception(e)
            return "Failed to send registration email", 500

        ret = {
            'message': f'successfully sent registration email to user {email}'
        }
        return ret, 200
Beispiel #12
0
    def test_get_all_users_with_unauthorized_jwt(self):
        user = User(
            username='******',
            password='******',
            email='*****@*****.**',
        )
        role = Roles({'username': user.username, 'roles': user.is_admin})
        admin = User(
            username='******',
            password='******',
            email='*****@*****.**',
        )
        admin_r = Roles({'username': admin.username, 'roles': admin.is_admin})
        save_user(user)
        save_user(role)
        save_user(admin)
        save_user(admin_r)

        with self.client:
            res_login = self.client.post('/v1/login',
                                         headers={
                                             'Content-Type':
                                             'application/json',
                                             'Accept': 'application/json'
                                         },
                                         data=json.dumps({
                                             'username': '******',
                                             'password': '******'
                                         }))
            data_login = json.loads(res_login.data.decode())

            response = self.client.get('/v1/users',
                                       headers={
                                           'Content-Type':
                                           'application/json',
                                           'Accept':
                                           'application/json',
                                           'Authorization':
                                           'Bearer {}'.format(
                                               data_login['access_token'])
                                       })
            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == False)
            self.assertTrue(data['msg'] == 'Sorry, page not found.')
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 404)
Beispiel #13
0
def get_users_from_audits(audits):
    user_ids = {audit.user_id for audit in audits}
    users = User.get_by_ids(user_ids)
    result = {}
    for u in users:
        result[u.id] = u.name

    return result
Beispiel #14
0
def get_one_modifier(resource_type, resource_id):
    priv = Privilege.get_one_user_for_resource(resource_id, resource_type,
                                               Privilege.Type.MODIFIER)
    user_id = priv[0]
    user = User.get_by_id(user_id)
    if not user:
        raise GulDanException().with_code(404).with_message(u"找不到指定的用户")
    return {"user_id": user.id, "user_name": user.name}
Beispiel #15
0
def current():
    if current_user.is_authenticated:
        user = User.query.filter(User.id == current_user.id).first()
        return make_response(
            jsonify(to_dict(user, deep={"cook": []},
                            exclude=User.getExclude())))
    else:
        return make_response(jsonify([]))
Beispiel #16
0
    def post(self):
        """
        Allows users to create accounts
        """
        args = self.reqparse.parse_args()
        new_user = User(args['username'], args['email'],
                        args['password'], args['phone'])

        if args['username'].strip() == "" or len(args['username'].strip()) < 2:
            return make_response(jsonify({"message":
                                          "invalid, Enter name please"}), 400)

        if re.compile('[!@#$%^&*:;?><.0-9]').match(args['username']):
            return make_response(jsonify({"message":
                                          "Invalid characters not allowed"}
                                         ), 400)

        if not re.match(r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+$)", args['email']):
            return make_response(jsonify({"message":
                                          "Enter valid email"}), 400)

        if args['password'].strip() == "":
            return make_response(jsonify({"message": "Enter password"}), 400)

        if len(args['password']) < 5:
            return make_response(jsonify({"message":
                                          "Password is too short, < 5"}), 400)

        if len(args['phone']) < 10:
            return make_response(jsonify({"message":
                                          "Phone number is too short"}), 400)

        print(new_user)

        USERS.append(new_user)
        for user in USERS:
            print(user.username)
        # print(USERS)

        return make_response(jsonify({
            'message': 'User successfull created with id: ' + new_user.get_id()
        }), 201)
Beispiel #17
0
def get_users_for_privileges(privileges):
    user_ids = set()
    for p in privileges:
        user_ids.add(p.user_id)

    users = User.get_by_ids(user_ids)
    user_dict = {}
    for u in users:
        user_dict[u.id] = u

    return user_dict
Beispiel #18
0
 def get(self):
     """Returns user profile info"""
     try:
         args = parser.parse_args()
         user_id = args['user-id']
         if not user_id:
             user_id = current_user().id
         logger.info("UserProfile.get() user_id: %s", str(user_id))
         return User.get_user_profile_info(user_id), 200
     except Exception as e:
         logger.exception("UserProfile.get(): %s", str(e))
         return "Couldn't load user profile info", 500
Beispiel #19
0
def login():
    try:
        if current_user.is_authenticated:
            user = User.query.filter(User.id == current_user.id).first()
            return make_response(jsonify(to_dict(user, exclude=User.getExclude())))

        form_data = json.loads(request.get_data().decode('utf-8'))

        if ('email' in form_data) and ('password' in form_data):
            user = User.query.filter(User.email == form_data['email'], User.password == HashValidator.hash(form_data['password'])).first()
            if user is None:
                raise Error(name='Failed login', message='Combinatie email/wachtwoord is onbekend')

            login_user(user)

            return make_response(jsonify(to_dict(user, exclude=User.getExclude())))

        else:
            raise Error(name='Failed login', message='Kan niet inloggen, email en/of wachtwoord ontbreekt')
    except Error as e:
        return make_response(jsonify({e.name: e.message}), 400)
Beispiel #20
0
    def post(self):
        print("HEREEEEEEEEEEEEEEEEEEE") # DOESN'T PRINT. WHY?
        # get the post data
        post_data = request.get_json()
        # check if user already exists
        user = User.query.filter_by(email=post_data.get('email')).first()
        if not user:
            try:
                user = User(
		            first_name=post_data.get('first_name'),
		            last_name=post_data.get('last_name'),
                    email=post_data.get('email'),
                    password=post_data.get('password')
                )

                # insert the user
                db.session.add(user)
                db.session.commit()
                # generate the auth token
                auth_token = user.encode_auth_token(user.id)
                responseObject = {
                    'status': 'success',
                    'message': 'Successfully registered.',
                    'auth_token': auth_token.decode()
                }
                return make_response(jsonify(responseObject)), 201
            except Exception as e:
                responseObject = {
                    'status': 'fail',
                    'message': 'Some error occurred. Please try again.'
                }
                return make_response(jsonify(responseObject)), 401
        else:
            responseObject = {
                'status': 'fail',
                'message': 'User already exists. Please Log in.',
            }
            return make_response(jsonify(responseObject)), 202
Beispiel #21
0
def load_data():

    # load user table
    db.session.add(
        User(username='******', email="*****@*****.**", password="******"))
    db.session.add(
        User(username='******',
             email="*****@*****.**",
             password="******"))
    db.session.add(
        User(username='******',
             email="*****@*****.**",
             password="******"))
    db.session.add(
        User(username='******', email="*****@*****.**", password="******"))
    db.session.add(
        User(username='******',
             name="Jan",
             surname="Gargas",
             email="*****@*****.**",
             password="******",
             phone="668-760-600"))
    db.session.add(
        User(username='******',
             name="Kinga",
             surname="Wierchomska",
             email="*****@*****.**",
             password="******",
             phone="668-760-600"))
    db.session.add(
        User(username='******',
             name="Michał",
             surname="Kurleto",
             email="Michał@Kurleto.com",
             password="******",
             phone="668-760-600"))
    db.session.add(
        User(username='******',
             name="Mateusz",
             surname="Mastalerczyk",
             email="*****@*****.**",
             password="******",
             phone="668-760-600"))

    print("user table loaded")

    db.session.commit()
Beispiel #22
0
def is_user_logged_in(user_hash, session_id):
    user = User.get_user_by_user_hash(user_hash)
    if not user:
        raise GulDanException().with_code(404).with_message(u"找不到用户")

    user_login = UserLogin.get_user_login_by_user_id(user.id)
    if not user_login.user_id:
        return False

    if not session_id or session_id == UserLogin.DEFAULT_SESSION_ID:
        return False

    if user_login.login_token == session_id:
        return user.id, user.name

    return False
Beispiel #23
0
    def test_update_email_by_user(self):
        user = User(
            username='******',
            password='******',
            email='*****@*****.**'
        )
        user_r = Roles({
            'username': user.username,
            'roles': user.is_admin
        })

        save_user(user)
        save_user(user_r)

        with self.client:
            res_login = self.client.post(
                '/v1/login',
                headers={
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                data=json.dumps({
                    'username': '******',
                    'password': '******'
                })
            )

            data_login = json.loads(res_login.data.decode())
            response = self.client.put(
                f'/v1/users/{user.username}',
                headers={
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Authorization': 'Bearer {}'.format(data_login['access_token'])
                },
                data=json.dumps({
                    'username': '******',
                    'email': '*****@*****.**'
                })
            )

            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == True)
            self.assertTrue(data['msg'] == 'Updated successfully')
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 200)
    def test_post_non_admin_user_with_admin_role(self):
        user = User(
            username='******',
            password='******',
            email='*****@*****.**',
        )
        user_r = Roles({'username': user.username, 'roles': 'admin'})
        save_user(user)
        save_user(user_r)
        with self.client:
            res_login = self.client.post('/v1/login',
                                         headers={
                                             'Content-Type':
                                             'application/json',
                                             'Accept': 'application/json'
                                         },
                                         data=json.dumps({
                                             'username': '******',
                                             'password': '******'
                                         }))
            data_login = json.loads(res_login.data.decode())

            response = self.client.post('/v1/users',
                                        headers={
                                            'Content-Type':
                                            'application/json',
                                            'Accept':
                                            'application/json',
                                            'Authorization':
                                            'Bearer {}'.format(
                                                data_login['access_token'])
                                        },
                                        data=json.dumps({
                                            'username':
                                            '******',
                                            'password':
                                            '******',
                                            'email':
                                            '*****@*****.**',
                                        }))
            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == True)
            self.assertTrue(data['msg'] == 'Registered successfully')
            self.assertTrue(response.content_type == 'application/json')
            self.assertTrue(response.status_code == 201)
Beispiel #25
0
    def test_login(self):
        user = User(username='******', password='******', email='*****@*****.**')
        save_user(user)
        with self.client:
            response = self.client.post('/v1/login',
                                        data=json.dumps({
                                            'username': '******',
                                            'password': '******'
                                        }),
                                        content_type='application/json')
            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == True)
            self.assertTrue(data['msg'] == 'Logged in.')
            self.assertTrue(data['access_token'])
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 200)
Beispiel #26
0
def login_user(user_name, password):
    computed_secret_hash, computed_user_hash = user.get_user_info_hash(
        user_name, password)
    user_in_store = User.get_user_by_name(user_name)

    if user_in_store.secret_hash == computed_secret_hash:
        session_id = user.gen_session_id_for_user(user_name)
        new_token = mark_user_as_login(user_in_store.id, session_id)
        if new_token:
            session_id = new_token

        return {
            "session_id": session_id,
            "hash": user_in_store.user_hash,
            "name": user_name,
            "id": user_in_store.id,
        }
    else:
        raise GulDanException().with_code(400).with_message(u"用户名或密码不正确")
Beispiel #27
0
    def test_login_with_unactive_user(self):
        user = User(username='******', password='******', email='*****@*****.**')
        save_user(user)
        update_user(user_obj=user, data={'is_active': False})
        with self.client:
            response = self.client.post('/v1/login',
                                        data=json.dumps({
                                            'username': '******',
                                            'password': '******'
                                        }),
                                        content_type='application/json')

            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == False)
            self.assertTrue(
                data['msg'] == 'User is currently banned! Please recover.')
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 403)
Beispiel #28
0
    def test_login_with_wrong_pwd(self):
        user = User(username='******', password='******', email='*****@*****.**')
        save_user(user)
        with self.client:
            response = self.client.post('/v1/login',
                                        data=json.dumps({
                                            'username': '******',
                                            'password': '******'
                                        }),
                                        content_type='application/json')

            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == False)
            self.assertTrue(
                data['msg'] ==
                'Incorrect username or password. Please try again.')
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 400)
Beispiel #29
0
    def test_register_with_duplicated_email(self):
        user = User(username='******', password='******', email='*****@*****.**')
        save_user(user)

        with self.client:
            response = self.client.post('/v1/register',
                                        data=json.dumps({
                                            'username':
                                            '******',
                                            'password':
                                            '******',
                                            'email':
                                            '*****@*****.**'
                                        }),
                                        content_type='application/json')

            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == False)
            self.assertTrue(data['msg'] == 'User has existed already')
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 400)
Beispiel #30
0
    def test_get_admin_users_with_no_jwt(self):
        user = User(
            username='******',
            password='******',
            email='*****@*****.**',
        )
        role = Roles({'username': user.username, 'roles': user.is_admin})
        save_user(user)
        save_user(role)

        with self.client:
            response = self.client.get('/v1/users/admin',
                                       headers={
                                           'Content-Type': 'application/json',
                                           'Accept': 'application/json',
                                       })
            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == False)
            self.assertTrue(data['msg'] == 'Sorry, page not found.')
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 404)
Beispiel #31
0
api_manager.create_api(
    TransactionLog,
    url_prefix="/api/v1",
    collection_name="transactionlogs",
    methods=["GET"],
    exclude_columns=TransactionLog.getExclude(),
    validation_exceptions=[Error, ProcessingException],
)

api_manager.create_api(
    User,
    url_prefix="/api/v1",
    collection_name="users",
    methods=["GET", "POST", "PATCH", "PUT", "DELETE"],
    exclude_columns=User.getExclude(),
    validation_exceptions=[Error, ProcessingException],
    preprocessors={
        "GET_SINGLE": [User.get_single_preprocessor],
        "POST": [User.post_single_preprocessor],
        "PATCH_SINGLE": [User.patch_single_preprocessor],
    },
)

from app import main
from app.api.views.login import mod as loginModule
from app.api.views.search import mod as searchModule

app.register_blueprint(loginModule)
app.register_blueprint(searchModule)
Beispiel #32
0
def current():
    if current_user.is_authenticated:
        user = User.query.filter(User.id == current_user.id).first()
        return make_response(jsonify(to_dict(user, deep={"cook": [] }, exclude=User.getExclude())))
    else:
        return make_response(jsonify([]))
Beispiel #33
0
    def test_update_invalid_fields_by_admin(self):
        admin = User(
            username='******',
            password='******',
            email='*****@*****.**'
        )
        admin_r = Roles({
            'username': admin.username,
            'roles': admin.is_admin
        })

        save_user(admin)
        save_user(admin_r)

        with self.client:
            res_login = self.client.post(
                '/v1/login',
                headers={
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                data=json.dumps({
                    'username': '******',
                    'password': '******'
                })
            )
            data_login = json.loads(res_login.data.decode())

            res_test = self.client.post(
                '/v1/users',
                headers={
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Authorization': 'Bearer {}'.format(data_login['access_token'])
                },
                data=json.dumps({
                    'username': '******',
                    'password': '******',
                    'email': '*****@*****.**'
                })
            )

            data_test = json.loads(res_test.data.decode())

            response = self.client.put(
                '/v1/users/test',
                headers={
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Authorization': 'Bearer {}'.format(data_login['access_token'])
                },
                data=json.dumps({
                    'username': '******',
                    'email': '*****@*****.**',
                    'is_admin': True
                })
            )

            data = json.loads(response.data.decode())

            self.assertTrue(data['ok'] == False)
            self.assertTrue(data['msg'])
            self.assertTrue(response.content_type == 'application/json')
            self.assertEqual(response.status_code, 400)