Example #1
0
def generate():
    if roles_required(["admin", "registrar"]) == 400:
        return jsonify({"msg": "no access"}), 400

    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400
    try:

        num = request.json['number']

        users_model = UsersModel(PostgresConnection().get_connection())
        notarius_model = NotariusModel(PostgresConnection().get_connection())
        blank_model = BlankModel(PostgresConnection().get_connection())
        usages_register_model = UsagesRegisterModel(
            PostgresConnection().get_connection())
        journal_actions_model = JournalActionsModel(
            PostgresConnection().get_connection())
        verifications_register_model = VerificationsRegisterModel(
            PostgresConnection().get_connection())
        code_usages_blank_model = CodeUsagesBlankModel(
            PostgresConnection().get_connection())

        users_model.generate_data(num)
        notarius_model.generate_data(num)
        blank_model.generate_data(num)
        usages_register_model.generate_data(num)
        journal_actions_model.generate_data(num)
        verifications_register_model.generate_data(num)
        code_usages_blank_model.generate_data(num)

    except Exception as e:
        return jsonify({"msg": str(e)}), 400

    return jsonify({"msg": "data generated"}), 200
Example #2
0
    def test_create_user(self):
        users_model = UsersModel()
        user_model = UserModel()

        user = '******'
        passwd = 'fakepass'
        group = 'unit_test_fake_group'
        profile = 'unit_test_fake_profile'

        common_users = users_model.get_list()
        params = {'name': user, 'password': passwd,
                  'group': group, 'profile': profile}
        with RollbackContext() as rollback:

            users_model.create(params)
            rollback.prependDefer(user_model.delete, user)

            new_users = users_model.get_list()
            self.assertEqual(len(new_users), len(common_users) + 1)

            enc_passwd = spwd.getspnam(user)[1]
            invalid_passwd = [None, "NP", "!", "!!",  "", "LK", "*"]
            self.assertNotIn(enc_passwd, invalid_passwd)

            self.assertEqual(crypt.crypt(passwd, enc_passwd), enc_passwd)
Example #3
0
 def post(self):
     self.parser.add_argument("id",
                              type=int,
                              required=True,
                              location="json",
                              help='id is required')
     self.parser.add_argument(
         "email",
         type=inputs.regex(
             r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)'),
         required=True,
         location="json",
         help='email format is incorrect')
     self.parser.add_argument("password",
                              type=password_len,
                              location="json",
                              trim=True)
     args = self.parser.parse_args()
     userEmailInfo = UsersModel.query.filter_by(email=args.email).all()
     for item in userEmailInfo:
         if item.id != args.id:
             return pretty_result(code.ERROR, msg='该邮箱已经被注册!')
     userInfo = UsersModel.query.filter_by(id=args.id).first()
     userInfo.email = args.email
     if args.password:
         userInfo.password = UsersModel.set_password(
             UsersModel, args.password)
     UsersModel.update(userInfo)
     return pretty_result(code.OK, msg='用户信息更新成功!')
class Controller(object):
    def __init__(self):
        self._connection = PostgresConnection().get_connection()
        self._cursor = self._connection.cursor(cursor_factory=DictCursor)
        self._create_tables()

        self._code_usages_blank_model = CodeUsagesBlankModel(self._connection)
        self._notarius_model = NotariusModel(self._connection)
        self._blank_model = BlankModel(self._connection)
        self._usages_register_model = UsagesRegisterModel(self._connection)
        self._users_model = UsersModel(self._connection)
        self._journal_actions_model = JournalActionsModel(self._connection)
        self._verifications_register_model = VerificationsRegisterModel(
            self._connection)

        self._users_model.generate_data(5000)
        self._notarius_model.generate_data(5000)
        self._blank_model.generate_data(5000)
        self._usages_register_model.generate_data(5000)
        self._journal_actions_model.generate_data(5000)
        self._verifications_register_model.generate_data(5000)
        self._code_usages_blank_model.generate_data(5000)
        # self._users_model.generate_data(100)

    @property
    def connection(self):
        return self._connection

    def _create_tables(self):
        file_path = path.join(path.dirname(path.abspath(__file__)),
                              '../create_tables.sql')
        with open(file_path, 'r') as f:
            sql = f.read()
        self._cursor.execute(sql)
        self._connection.commit()
def authenticate(username, password):
    # user = username_mapping.get(username,None)

    if len(username) == 10 and username.isdigit():
        user = UsersModel.find_by_phone(username)
    else:
        user = UsersModel.find_by_email(username)
    if user and safe_str_cmp(user.password, password):
        return user
Example #6
0
 def delete(self):
     self.parser.add_argument("ids",
                              type=list,
                              required=True,
                              location="json",
                              help='ids is required')
     args = self.parser.parse_args()
     UsersModel.delete(UsersModel, args.ids)
     return pretty_result(code.OK, msg='用户信息删除成功!')
Example #7
0
 def get(self):
     """
     获取用户列表信息
     :return: json
     """
     self.parser.add_argument("pageNo",
                              type=int,
                              required=True,
                              location="args",
                              help='pageNo is required')
     self.parser.add_argument("pageSize",
                              type=int,
                              required=True,
                              location="args",
                              help='pageSize is required')
     self.parser.add_argument("username",
                              type=str,
                              required=True,
                              location="args",
                              help='username is required')
     args = self.parser.parse_args()
     user_list = UsersModel.paginate(UsersModel, args.pageNo, args.pageSize)
     items = []
     totalCount = user_list.total
     user_list = user_list.items
     if args.username:
         user_list = UsersModel.filter_by_username(UsersModel,
                                                   args.username)
         totalCount = len(user_list)
     for user in user_list:
         if user.permission == "SuperAdmin":
             continue
         items.append({
             'id':
             user.id,
             'username':
             user.username,
             'email':
             user.email,
             'permission':
             user.permission,
             'avatar':
             user.avatar,
             'login_time':
             user.login_time,
             'update_time':
             user.update_time.strftime("%m/%d/%Y %H:%M:%S")
         })
     data = {
         'pageNo': args.pageNo,
         'pageSize': args.pageSize,
         'totalCount': totalCount,
         'items': items
     }
     return pretty_result(code.OK, data=data, msg='用户信息获取成功!')
    def post(self):
        data = request.get_json(force=True)
        if UsersModel.find_by_username(data['username']):
            return {
                'message': 'Username is existed, please use another name.'
            }, 400
        data['_id'] = 0
        user = UsersModel(data)
        user.insert_to_db()

        return {'message': 'user has been created successfully.'}, 201
Example #9
0
 def post(self):
     # register interface
     req_data = request.get_json()
     user_name = req_data.get('username', None)
     user_pass = req_data.get('password', None)
     if not user_name or not user_pass:
         return StandardResponse(403, 1, 'Forbidden')
     user = UsersModel(user_name, user_pass)
     try:
         user.add(user)
     except Exception, e:
         return StandardResponse(500, 1, e.message)
Example #10
0
 def post(self):
     """
     用户注册
     :return: json
     """
     self.parser.add_argument(
         "email",
         type=inputs.regex(
             r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)'),
         required=True,
         location="json",
         help='email format is incorrect')
     self.parser.add_argument("username",
                              type=str,
                              required=True,
                              location="json",
                              help='username is required')
     # self.parser.add_argument("permission", type=str, choices=['test', 'guest', 'user', 'admin', 'superAdmin'], required=True, location="json",
     #                          help='permission is required and only (test,user,admin,superAdmin)')
     self.parser.add_argument("permission",
                              type=str,
                              required=True,
                              location="json",
                              help='permission is required')
     self.parser.add_argument("password",
                              type=password_len,
                              required=True,
                              location="json",
                              trim=True)
     args = self.parser.parse_args()
     userEmailInfo = UsersModel.query.filter_by(email=args.email).all()
     for item in userEmailInfo:
         if item.id != args.id:
             return pretty_result(code.ERROR, msg='该邮箱已经被注册!')
     user = UsersModel(email=args.email,
                       username=args.username,
                       password=UsersModel.set_password(
                           UsersModel, args.password),
                       permission=args.permission)
     result = UsersModel.add(UsersModel, user)
     if user.id:
         returnUser = {
             'id': user.id,
             'username': user.username,
             'email': user.email,
             'login_time': user.login_time
         }
         return pretty_result(code.OK, data=returnUser, msg='用户注册成功')
     else:
         return pretty_result(code.ERROR, data='', msg='用户注册失败(用户名或邮箱已存在)')
Example #11
0
    def put(self, token):
        try:
            data = self.parser.parse_args()
            validateObj = UsersModel.validateData(data, request)
            if type(validateObj) is dict:
                return {"success": False, "errors": validateObj}, 400

            user_id = decodeID(token)
            user = UsersModel.find_by_id(user_id)
            if not user or user.token != token:
                return {"success": False, 'message': 'Record Not Found'}, 404

            user.modified_on = datetime.now()
            user.modified_by = 1
            user.password = data['password']
            user.user_type_id = data['user_type_id']
            user.company_name = data['company_name']
            user.first_name = data['first_name']
            user.last_name = data['last_name']
            user.phone = data['phone']
            user.title = data['title']
            user.owner_manager = data['owner_manager']
            user.yearly_budget = data['yearly_budget']
            user.logo = data['logo']
            user.city = data['city']
            user.country_id = data['country_id']
            user.address = data['address']
            user.timezone = data['timezone']
            user.level = data['level']
            user.permission = data['permission']
            user.assigned_brands = data['assigned_brands']
            user.assigned_products = data['assigned_products']
            user.assigned_services = data['assigned_services']
            user.parent_user_id = data['parent_user_id']
            name = data['email']
            if name.strip():
                user.save_to_db()
            else:
                return {
                    "success": False,
                    "message": "String Should not be empty"
                }

            return {
                "success": True,
                "message": "Record updated successfully."
            }, 200
        except Exception as e:
            return {"success": False, "message": str(e)}
Example #12
0
def login():

    data = request.get_json(silent=True)
    email = data["email"]
    password = data["password"]

    user = UsersModel().authenticate(email=email, password=password)
    if not user:
        return jsonify({
            'message': 'Invalid Credentials',
            'authenticated': False
        })

    # set the session of the user
    login_session["user_id"] = str(user["_id"])
    print(f"user id: {login_session}")
    response = jsonify({
        "token":
        jwt.encode(
            {
                'sub': user['email'],
                'iat': datetime.utcnow(),
                'exp': datetime.utcnow() + timedelta(minutes=30)
            }, app.config['SECRET_KEY']).decode('UTF-8'),
        "user": {
            "id": str(user['_id']),
            "username": user['username'],
            "email": user['email']
        },
        'authenticated':
        'true'
    })
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
Example #13
0
    def find_last_rentals_info(cls, moto, num_rentals, associated_rentals):
        """
        Finds n last rentals from a moto
        Param: moto id and rentals num
        Return: Json
        """
        final_list = [moto.json()]
        count = 0

        associated_rentals_json = [
            rental.json() for rental in associated_rentals
        ]
        sorted_associated_rentals = sorted(associated_rentals_json,
                                           key=lambda k: k['id'])
        sorted_associated_rentals.reverse()

        for rental in sorted_associated_rentals:
            if (count < num_rentals):
                count += 1
                user = UsersModel.find_by_id(rental['user_id'])
                final_list.append([rental, user.json()])
            else:
                break

        return final_list
Example #14
0
    def delete(self, user_id):
        """
        DELETE method
        Removes an account
        Param: string id
        Return: dict (message ok / message)
        """

        data = parser.parse_args()

        user = UsersModel.find_by_id(user_id=user_id)

        if user:
            try:
                user.delete_from_db()
                return {
                    'message':
                    "User with id [{}] and all associated info deleted".format(
                        user_id)
                }, 200
            except:
                return {"message": "Error Description"}, 500
        else:
            return {
                'message': "User with id [{}] Not found".format(user_id)
            }, 404
Example #15
0
    def put(self, email):
        data = self.parser.parse_args()

        user = UsersModel.find_by_Email(email)

        if user:
            user.modified_on = datetime.now()
            user.modified_by = 1
            user.password = data['password']
            user.user_type_id = data['user_type_id']
            user.company_name = data['company_name']
            user.first_name = data['first_name']
            user.last_name = data['last_name']
            user.phone = data['phone']
            user.title = data['title']
            user.owner_manager = data['owner_manager']
            user.yearly_budget = data['yearly_budget']
            user.logo = data['logo']
            user.city = data['city']
            user.country_id = data['country_id']
            user.address = data['address']
            user.timezone = data['timezone']
            user.level = data['level']
            user.permission = data['permission']
            user.assigned_brands = data['assigned_brands']
            user.assigned_products = data['assigned_products']
            user.assigned_services = data['assigned_services']
            user.parent_user_id = data['parent_user_id']
            user.save_to_db()
            return user.json()
        else:
            return {'message': 'User not found.'}, 404
Example #16
0
def getpass():
    user_id = request.args.get('userid')
    identity = get_jwt_identity()
    target_id = int(user_id)
    entries = PassesModel.get_string_pass_by_user_id(target_id)
    is_fav = UsersModel.is_fav(identity, target_id)
    return jsonify(success=True, entries=entries, isFav=is_fav), 200
Example #17
0
    def post(self):
        """
        POST method
        Login, Generates a token if is all okay
        Return: dict
        """
        data = parser.parse_args()

        if not data['mail']:
            return {'message': {"mail": "Mail cant be empty"}}, 400

        if not data['google_token']:
            return {
                'message': {
                    "google_token": "Google token cant be empty"
                }
            }, 400

        user = UsersModel.find_by_mail(mail=data['mail'])

        if not user:
            return {
                'message':
                "Account with mail [{}] Not found".format(data['mail'])
            }, 404

        valid_password = user.verify_password(data['google_token'])

        if not valid_password:
            return {'message': "Invalid google token"}, 400

        token = user.generate_auth_token()
        return {'token': token.decode('ascii')}, 200
Example #18
0
 def identify(self, request):
     """
     用户鉴权
     :return: list
     """
     data = ''
     msg = ''
     status = code.AUTHORIZATION_ERROR
     auth_header = request.headers.get('Authorization')
     if (auth_header):
         auth_tokenArr = auth_header.split(" ")
         if (not auth_tokenArr or auth_tokenArr[0] != 'JWT'
                 or len(auth_tokenArr) != 2):
             msg = '请传递正确的验证头信息'
         else:
             auth_token = auth_tokenArr[1]
             payload = self.decode_auth_token(auth_token)
             if not isinstance(payload, str):
                 user = UsersModel.get(UsersModel, payload['data']['id'])
                 if (user is None):
                     msg = '找不到该用户信息'
                 else:
                     if (user.login_time == payload['data']['login_time']):
                         status = code.OK
                         data = user.id
                         msg = '请求成功'
                     else:
                         msg = 'Token已更改,请重新登录获取'
             else:
                 msg = payload
     else:
         msg = '没有提供认证token'
     return pretty_result(status, data=data, msg=msg)
Example #19
0
def register():
    data = request.get_json(silent=True)
    username = data["username"]
    print(f"inside reg function")
    email = data["email"]
    password = data["password"]
    password_confirmation = data["password_confirmation"]

    # Check that user doesn't exist already
    if not UsersModel.check_user(email):
        print(f"This email is used")
        return jsonify({
            'message': 'A user with that email already exists',
            'authenticated': False
        })
    print(f"The email is ok")

    # Check password confirmation
    if password != password_confirmation:
        return jsonify({
            'message': 'Password not equal to password confirmation',
            'authenticated': False
        })

    user, user_id = UsersModel.register(username=username,
                                        email=email,
                                        password=password)

    # login user after registration
    response = jsonify({
        "token":
        jwt.encode(
            {
                'sub': user['email'],
                'iat': datetime.utcnow(),
                'exp': datetime.utcnow() + timedelta(minutes=30)
            }, app.config['SECRET_KEY']).decode('UTF-8'),
        "user": {
            "id": str(user_id),
            "username": user['username'],
            "email": user['email']
        },
        'authenticated':
        'true'
    })
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
Example #20
0
def result():
    identity = get_jwt_identity()
    content = request.json
    new_password = content['newPassword']
    user = UsersModel.find_user_by_id(identity)
    user.password = hashlib.sha256(new_password.encode("utf-8")).hexdigest()
    db.session.commit()
    return jsonify(success=True), 200
 def delete(self):
     data = request.get_json(force=True)
     user = UsersModel.find_by_username(data['username'])
     if user:
         user.delete_from_db()
         return {
             'message': 'user {} has been deleted'.format(data['username'])
         }
Example #22
0
    def test_creating_existing_user_fails(self):
        users_model = UsersModel()
        user_model = UserModel()

        user = '******'
        passwd = 'fakepass'
        group = 'unit_test_fake_group'
        profile = 'unit_test_fake_profile'

        params = {'name': user, 'password': passwd,
                  'group': group, 'profile': profile}

        with RollbackContext() as rollback:
            users_model.create(params)
            rollback.prependDefer(user_model.delete, user)

            with self.assertRaises(OperationFailed):
                users_model.create(params)
Example #23
0
 def get(cls, token):
     try:
         user_id = decodeID(token)
         user = UsersModel.find_by_id(user_id)
         if not user or user.token != token:
             return {"success": False, 'message': 'Record Not Found'}, 404
         return user.json(), 200
     except Exception as e:
         return {"success": False, "message": str(e)}
Example #24
0
 def get(self):
     # search interface
     try:
         user_instance = UsersModel.find_by_id(current_identity.id)
         user_dump, errors = UsersSchema().dump(user_instance)
         if errors:
             return StandardResponse(404, 1, u'Resource Not Found')
     except Exception, e:
         return StandardResponse(500, 1, u'SQLAlchemy Error')
Example #25
0
    def post(self, email):
        if UsersModel.find_by_Email(email):
            return {'message': "An user with email '{}' already exists.".format(email)}, 400

        data = self.parser.parse_args()

        user = UsersModel(email, **data)

        try:
            user.created_by=1
            user.created_on = datetime.now()
            user.modified_by = 0
            user.deleted_by = 0
            user.save_to_db()

        except:
            return {"message": "An error occurred while inserting the user."}, 500

        return user.json(), 201
Example #26
0
 def authenticate(self, username, password):
     """
     用户登录,登录成功返回token,写将登录时间写入数据库;登录失败返回失败原因
     :param password:
     :return: json
     """
     userInfo = UsersModel.query.filter_by(username=username).first()
     if (userInfo is None):
         return pretty_result(code.OK, data='', msg='找不到用户')
     else:
         if (UsersModel.check_password(UsersModel, userInfo.password,
                                       password)):
             login_time = int(time.time())
             userInfo.login_time = login_time
             UsersModel.update(UsersModel)
             token = self.encode_auth_token(userInfo.id, login_time)
             return pretty_result(code.OK, data=token.decode(), msg='登录成功')
         else:
             return pretty_result(code.OK, data='', msg='密码不正确')
Example #27
0
    def delete(self, Email):
        claims = get_jwt_claims()
        if not claims['is_admin']:
            return {'message': 'Admin privilege required.'}, 401

        user = UsersModel.find_by_Email(Email)
        if user:
            user.delete_from_db()
            return {'message': 'User deleted.'}
        return {'message': 'User not found.'}, 404
Example #28
0
    def get(self):
        """
        GET method
        Return: dict (users)
        """
        data = parser.parse_args()

        users = UsersModel.all_users()

        return {'users': [user.json() for user in users]}, 200
	def put(self, user_id, alt_phone_number):

		user = UsersModel.find_by_id(user_id)

		if user:
			user.alt_phone_number = alt_phone_number
			user.save_to_db()
			return {'data':{'status': True, 'user': user.json()}}

		else:
			return {"data": {"status": False}}
Example #30
0
 def post(self):
     user = UsersModel.get(UsersModel, g.user_id)
     returnUser = {
         'id': user.id,
         'username': user.username,
         'email': user.email,
         'permission': user.permission,
         'avatar': user.avatar,
         'login_time': user.login_time
     }
     return pretty_result(code.OK, data=returnUser)
Example #31
0
    def get(self, phone_number, password):

        user_phone = UsersModel.find_by_phone(phone_number)
        if user_phone:
            if user_phone.password == password:

                user_phone.save_to_db()
                # return user_phone.json()
                return {'status': True, 'user': user_phone.json()}

        return {'status': False}, 200
	def get(self, phone_number):


		user = UsersModel.find_by_phone(phone_number)
		if user:
			password = user.password
			r = requests.get('http://roundsms.com/api/sendhttp.php?authkey=NGUwNDYxZmNiY2N&mobiles='+str(phone_number)+'&Your password for KM NORTH '+password+'.&sender=KMNORT&type=1&route=2')
			return {"data": {"status": True, "res": r.json()}}
		else:

			return {"data": {"status": False}}
Example #33
0
 def __init__(self):
     super(Users, self).__init__()
     self._data = UsersModel()
Example #34
0
class Users(Controller):
    # constructor
    def __init__(self):
        super(Users, self).__init__()
        self._data = UsersModel()

    # login
    def login(self):
        if self.logged():
            return write("Well done")

        email = request.values.get("email")
        password = request.values.get("password")

        if email is not None and \
           password is not None and \
           self._data.valid(email, sha512(password)):
            session["email"] = email
            return write("Well done")
        else:
            return error("Incorrect login or password")

    # logout
    def logout(self):
        if not self.logged():
            return error("You not logged")

        session.pop('email', None)
        return write("Well done")

    # entered
    def entered(self):
        if self.logged():
            return write("Yes")
        else:
            return write("No")

    # register new user
    def register(self):
        if self.logged():
            return error("You are already logged")

        email = request.values.get("email")
        password = request.values.get("password")
        fname = request.values.get("fname")
        lname = request.values.get("lname")
        role = request.values.get("role")
        avatar = request.values.get("avatar")
        status = request.values.get("status")

        if (not (type(email) is unicode)) or (len(email) < 5):
            return error("Incorrect e-mail")

        if (not (type(password) is unicode)) or (len(password) < 5):
            return error("Incorrect password")

        if self._data.exists(email):
            return error("User with this e-mail already exists")

        try:
            self._data.add({"email": email,
                            "password": sha512(password),
                            "fname": fname,
                            "lname": lname,
                            "role": role,
                            "avatar": avatar,
                            "status": status})
            return write("Well done")
        except:
            return error("Registration failed")

    # delete user
    def delete(self):
        if not self.logged():
            return error("You not logged")

        try:
            id = int(request.values.get("id"))
            self._data.delete(id)
            return write("Well done")
        except:
            return error("Invalid request")

    # get user info
    def get(self, param):
        if not self.logged():
            return error("You not logged")

        try:
            if type(param) is int:
                return write(self._data.get(param))
            elif type(param) is unicode:
                return write(self._data.get(param))
            else:
                return write(self._data.get(session["email"]))
        except:
            return error("Invalid request")

    # change user info
    def change(self):
        if not self.logged():
            return error("You not logged")

        user = {"email": request.values.get("email"),
                "password": request.values.get("password"),
                "fname": request.values.get("fname"),
                "lname": request.values.get("lname"),
                "role": request.values.get("role"),
                "avatar": request.values.get("avatar"),
                "status": request.values.get("status")}

        try:
            id = int(request.values.get("id"))
            self._data.edit(id, user)
            return write("Well done")
        except:
            return error("Invalid request")

    # get all user list
    def all(self):
        if not self.logged():
            return error("You not logged")

        try:
            return write(self._data.all())
        except:
            return error("Invalid request")


    def fetch(self, **kwargs):
        action = kwargs.get("action")
        param = kwargs.get("param")

        if action == "login":
            return self.login()
        elif action == "logout":
            return self.logout()
        elif action == "entered":
            return self.entered()
        elif action == "register":
            return self.register()
        elif action == "delete":
            return self.delete()
        elif action == "get" or action is None:
            return self.get(param)
        elif action == "change":
            return self.change()
        elif action == "all":
            return self.all()
        else:
            return error("Invalid request")
Example #35
0
 def test_get_users_list(self):
     model = UsersModel()
     users = model.get_list()
     self.assertGreaterEqual(len(users), 0)