def post(self):
     user_data = UserRegister.parser.parse_args()
     if UserModel.find_by_username(username=user_data['username']):
         return {'message': 'A user with username already exists'}, 400
     user = UserModel(user_data['username'], user_data['password'])
     user.save_to_db()
     return {"message": "user created successfully"}, 201
Example #2
0
 def post(cls):
     data = request.get_json()
     if UserModel.find_by_email(data["email"]):
         return {
             "message": response_quote("user_email_taken")
         }, 400  # TODO:
     user = UserModel(username=data["username"],
                      password=b_crypt.generate_password_hash(
                          data["password"]).decode("utf-8"),
                      email=data["email"],
                      sha_private=hashlib.sha256(str.encode(
                          data["email"])).hexdigest())
     try:
         user.save_to_db()
         confirmation = ConfirmationModel(user.id)
         confirmation.save_to_db()
         user.confirm()
         return {"message": response_quote("user_been_created")}, 201
     except MailGunException as e:
         user.delete_from_db()  # rollback
         return {"message": str(e)}, 500
     except:
         traceback.print_exc()
         user.delete_from_db()
         return {"message": response_quote("operation_fatal_error")}, 500
Example #3
0
    def post(args):

        if not safe_str_cmp(args['password'], args['password_confirmation']):
            return {
                'success': False,
                'errors': {
                    'password':
                    ['Password and password confirmation do not match']
                }
            }, 409

        user = UserModel.find_by_email(args['email'])
        if user:
            return {
                'success': False,
                'error': 'Email has already been taken'
            }, 409

        is_admin = False
        if UserModel.count_all() < 1:
            is_admin = True

        phone = None

        if 'phone' in args:
            phone = args['phone']

        hashed_password = UserModel.generate_hash(args['password'])

        user = UserModel(args['name'], hashed_password, args['email'], phone,
                         is_admin)
        user.save_to_db()

        return {'success': True, 'user': user_summary.dump(user).data}, 201
Example #4
0
    def post(self):
        data = _user_parser.parse_args()
        if UserModel.find_by_username(data['username']):
            return {'message': 'username is already exists'}, 400

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

        return {'message': 'User created successully.'}, 201
Example #5
0
    def post(self):
        data = request.json
        if UserModel.find_by_username(data['username']):
            return {'message': 'A user with that username already exists'}, 400

        user = UserModel(data['username'], data['password'])
        user.save_to_db()

        return 201
Example #6
0
File: user.py Project: cvioan/itlaw
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {"message": "Un utilizator cu acest nume deja exista"}, 400

        user = UserModel(**data)
        user.save_to_db()
        return {"message": "Utilizatorul a fost creat."}, 201
Example #7
0
    def put(self, username):
        # gets current identity (username, password, admin, super_user)
        identity = current_identity
        # loads json data and parses looking for args
        data = User.parser.parse_args()

        # existing user needed to query if a change being made to username already exists
        existing_user = UserModel.find_by_username(data['username'])

        # looks for current username passed in '/user/<name>' exists and if not create
        user = UserModel.find_by_username(username)
        if identity.super_user == 0 and identity.username != username:
            return {'message': 'You are not authorized.'}, 403
        if user is None:
            user = UserModel(data['username'].lower(), data['password'],
                             data['site_location'].lower(), data['admin'],
                             data['super_user'], identity.username.lower())
        else:
            # it existed, now we must check a few other things to update a record
            # user is admin and no existing user
            if identity.super_user == 1 and existing_user is None:
                user.username = data['username'].lower()
                user.password = data['password']
                user.site_location = data['site_location'].lower()
                user.admin = data['admin']
                user.super_user = data['super_user']

                user.created_by = identity.username.lower()
            # user is updating his record but changing his username
            elif identity.username == username and existing_user is None:
                user.username = data['username'].lower()
                user.password = data['password']
                user.site_location = data['site_location'].lower()
                user.admin = user.admin
                user.super_user = user.super_user

                user.created_by = identity.username.lower()
            # user is updating his user record without a name change
            elif identity.username == existing_user.username:
                user.username = data['username'].lower()
                user.password = data['password']
                user.site_location = data['site_location'].lower()
                if identity.super_user == 1:
                    user.admin = data['admin']
                    user.super_user = data['super_user']
                else:
                    user.admin = user.admin
                    user.super_user = user.super_user

                user.created_by = identity.username.lower()
            else:
                return {'message': 'Username is already in use'}, 400

        user.save_to_db()

        return user.json()
Example #8
0
    def post(self):
        data = UserRegister.parser.parse_args()
        if UserModel.find_by_username(data['username']) is not None:
            return {"message": "User with this name already exists!"}, 400

        password_hash = generate_password_hash(data['password'])
        user = UserModel(data['username'], password_hash)
        user.save_to_db()

        return {"message": "User created successfully"}, 201
Example #9
0
    def post(self):
        data = _user_parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(data['username'], data['password'])
        user.save_to_db()

        return {"message": "User created successfully."}, 201
Example #10
0
def add_users():
    data = request.get_json()
    newUser = UserModel(username=data['username'],
                        password=UserModel.generate_hash(data['password']))

    try:
        newUser.save_to_db()
        return jsonify(
            {'message': 'User {} was created'.format(data['username'])})
    except SQLException.IntegrityError:
        return jsonify({'message': 'This username is already in use'}), 409
    except Exception as e:
        print('Exception: ', e)
        return jsonify({'message': 'Something went wrong'}), 500
Example #11
0
 def post(cls):
     data = UserRegister.parser.parse_args()
     is_valid, msg = cls.validate_username_input(data['username'])
     if not is_valid:
         return {'message': msg}, 400
     is_valid, msg = cls.validate_password_input(data['password'])
     if not is_valid:
         return {'message': msg}, 400
     if UserModel.find_by_username(data['username']) is not None:
         return {'message': MSG.EXISTED.format(data['username'])}, 400
     data['hashed_password'], data['salt'] = encoder(data['password'])
     user = UserModel(**data)
     user.save_to_db(user)
     return {'message': MSG.REGISTERED.format(data['username'])}, 201
Example #12
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data["username"]):
            return {
                "message": "User with this name is already registered"
            }, 400

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

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

        return {"message": "User created successfully."}, 201
Example #13
0
    def post(self):
        data = request.get_json()

        if UserModel.find_by_username(data['username']):
            return {"message": "Username already exists"}, 400

        user = UserModel(**data)
        user.save_to_db()
        # connection = sqlite3.connect('mydata.db')
        # cursor = connection.cursor()
        #
        # query = "insert into users values (NULL,?,?)"
        # cursor.execute(query,(data['username'],data['password']))
        #
        # connection.commit()
        # connection.close()

        return {"message": "user created successfully"}, 201
Example #14
0
    def post(self):
        data = UserRegister.parser.parse_args()
        if data['username'] is "" or data['password'] is "":
            return {
                "message": "Username or Password field cannot be blank"
            }, 400
        elif data['username'] is " " or data['password'] is " ":
            return {
                "message": "Username or Password field cannot be blank"
            }, 400
        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(data['username'].lower(), data['password'],
                         data['site_location'].lower(), False, False,
                         data.username.lower())
        user.save_to_db()

        return {"messgae": "User created successfully."}, 201
Example #15
0
    def test_crud(self):
        with self.app_context():
            user = UserModel('test_username', 'A12345678')

            self.assertIsNone(
                UserModel.find_by_username('test_username'),
                "Found an user with name 'test_username' before save_to_db")
            self.assertIsNone(UserModel.find_by_id(1),
                              "Found an user with id '1' before save_to_db")

            user.save_to_db()

            self.assertIsNotNone(
                UserModel.find_by_username('test_username'),
                "Did not find an user with name 'test_username' after save_to_db"
            )
            self.assertIsNotNone(
                UserModel.find_by_id(1),
                "Did not find an user with id '1' after save_to_db")
Example #16
0
    def get(cls):
        response = github.authorized_response()
        g.access_token = response['access_token']
        github_user = github.get('user')
        github_username = github_user.data['login']

        user = UserModel.find_by_username(github_username)
        if not user:
            user = UserModel(
                username=github_username,
                password="******",
                email="*********",
                sha_private=hashlib.sha256(str.encode(github_username)).hexdigest()
            )
            user.save_to_db()
        access_token = create_access_token(identity=user.sha_private, expires_delta=EXPIRES_DELTA)
        refresh_token = create_refresh_token(identity=user.sha_private)
        return {
            "access_token": access_token,
            "refresh_token": refresh_token
        }, 200
Example #17
0
 def post(cls):
     data = request.get_json()
     if UserModel.find_by_email(data["email"]):
         return {"message": response_quote("user_email_taken")}, 400
     password_salt, password_hash = PassCrypt.generate_password_hash(
         data["password"])
     user = UserModel(username=data["username"],
                      password_hash=password_hash,
                      password_salt=password_salt,
                      email=data["email"])
     try:
         user.save_to_db()
         confirmation = ConfirmationModel(user.id)
         confirmation.save_to_db()
         user.confirm()
         return {"message": response_quote("user_been_created")}, 201
     except MailGunException as e:
         user.delete_from_db()  # rollback
         return {"message": str(e)}, 500
     except:
         traceback.print_exc()
         user.delete_from_db()
         return {"message": response_quote("operation_fatal_error")}, 500
Example #18
0
    def post(cls) -> tuple:
        """
        Add a new user to the data base.

        :return: {json_message}, status code
        """
        data = cls.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {
                "message":
                "A user '{}' already exists!".format(data['username'])
            }, 400

        # Hashing: incl. 16-byte salt (auto) + 29.000 iterations (default)
        data['password'] = pbkdf2_sha256.hash(data['password'])

        user = UserModel(**
                         data)  # UserModel(data['username'], data['password'])
        user.save_to_db(
        )  # Because we use a parser we can use **data! Its never gonna have more/less arguments

        return {"message": "User created successfully."}, 201