Ejemplo n.º 1
0
 def get_marshaller():
     return {
         'id':
         fields.Integer,
         'time_created':
         fields.DateTime,
         'time_updated':
         fields.DateTime,
         'start_time':
         fields.DateTime,
         'end_time':
         fields.DateTime,
         'owner':
         fields.Nested(UserModel.get_marshaller()),
         'community':
         fields.Nested(CommunityModel.get_marshaller()),
         'start_km':
         fields.String,
         'end_km':
         fields.String,
         'parking_position':
         fields.String,
         'comment':
         fields.String,
         'is_force_finished':
         fields.Boolean,
         'force_finished_by':
         fields.Nested(UserModel.get_marshaller(), allow_null=True),
         'is_open':
         fields.Boolean,
         'passengers':
         fields.Nested(UserModel.get_marshaller())
     }
Ejemplo n.º 2
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('resetPasswordHash', help='This field cannot be blank', required=True, type=str)
     parser.add_argument('newPassword', help='This field cannot be blank', required=True, type=str)
     data = parser.parse_args()
     user = UserModel.find_by_reset_password_hash(data['resetPasswordHash'])
     if not user:
         abort(401, message=RESET_PASSWORD_HASH_INVALID)
     now = datetime.now()
     hash_age = now - user.reset_password_hash_created
     # Hash must be younger then 24 hours
     if divmod(hash_age.total_seconds(), 60 * 60 * 24)[0] > 0.0:
         abort(401, message=RESET_PASSWORD_HASH_INVALID)
     if len(data['newPassword']) < 8:
         abort(400, message=PASSWORD_TOO_SHORT)
     user.password = UserModel.generate_hash(data['newPassword'])
     user.reset_password_hash = None
     user.reset_password_hash_created = None
     user.persist()
     access_token = create_access_token(identity=user.username)
     refresh_token = create_refresh_token(identity=user.username)
     return AuthResponse(PASSWORD_RESET,
                         user,
                         access_token=access_token,
                         refresh_token=refresh_token), 202
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
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
Ejemplo n.º 5
0
Archivo: user.py Proyecto: 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
Ejemplo n.º 6
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
Ejemplo n.º 7
0
 def put(self):#altera senha
     args=self.parser.parse_args()
     user=UserModel.find_one(get_jwt_identity())
     if(not user):
         return "Not Found", 404
     elif(check(args['password'],user['password'])):
         UserModel.update(get_jwt_identity(),args['new_password'])
         return "Ok",200
     else:
         return "Unauthorized",401
Ejemplo n.º 8
0
 def get_marshaller():
     return {
         'id': fields.Integer,
         'time_created': fields.DateTime,
         'time_updated': fields.DateTime,
         'debtee': fields.Nested(UserModel.get_marshaller()),
         'recepient': fields.Nested(UserModel.get_marshaller()),
         'is_settled': fields.Boolean,
         'amount': fields.Float
     }
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
0
    def delete(self):
        args=User.parser.parse_args()
        user=UserModel.find_one(get_jwt_identity())

        if(not user):
            return "Not Found", 404
        elif(check(args['password'],user['password'])):
            if(UserModel.delete(user.username)):
                return "Deleted",200
            else:
                return "not Deleted",500
Ejemplo n.º 12
0
    def post(self):
        data = UserRegister.parser.parse_args()

        user = UserModel.find_by_email(data['email'])

        if user:
            return {'message': "User already exists"}, 400

        user = UserModel(data['email'], data['password'])
        user.save()

        return {'message': 'User is created'}, 201
Ejemplo n.º 13
0
    def post(self):
        args=User.parser.parse_args()
        user=UserModel.find_one(args['username'])

        if(not user):
            try:
                UserModel.create(args['username'],args['password'])
                return "Criated", 201
            except ValueError:
                return ValueError,500
        else: 
            return "Exists",409
Ejemplo n.º 14
0
def crear_usuario():
    if request.method == 'GET':
        return render_template('usuarios/crear.html')
    nombre = request.form.get('nombre')
    apellido = request.form.get('apellido')
    celular = request.form.get('celular')
    email = request.form.get('email')
    password = request.form.get('password')

    usuariosModel = UserModel()
    usuariosModel.crear_usuario(nombre, apellido, celular, email, password)

    return redirect(url_for('usuarios'))
Ejemplo n.º 15
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
Ejemplo n.º 16
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
Ejemplo n.º 17
0
 def put(self):
     password_parser = reqparse.RequestParser()
     password_parser.add_argument('old_password', help='This field cannot be blank', required=True, type=str)
     password_parser.add_argument('new_password', help='This field cannot be blank', required=True, type=str)
     data = password_parser.parse_args()
     user = UserModel.find_by_username(get_jwt_identity())
     if UserModel.verify_hash(data['old_password'], user.password):
         if len(data['new_password']) < 8:
             abort(400, message=PASSWORD_TOO_SHORT)
         user.password = UserModel.generate_hash(data['new_password'])
         user.persist()
         return SimpleMessage(PASSWORD_CHANGED), 201
     else:
         abort(401, message=OLD_PASSWORD_INCORRECT)
Ejemplo n.º 18
0
async def create_user(user: UserRequest,
                      db: Session = Depends(database.get_db_session),
                      current_user: LoginSchema = Depends(
                          oauth.get_current_user)):
    created = datetime(datetime.today().year,
                       datetime.today().month,
                       datetime.today().day)
    password = Hash.bcrypt(user.password)

    new_user = UserModel(username=user.username,
                         password=password,
                         name=user.name,
                         lastname=user.lastname,
                         email=user.email,
                         enabled=user.enabled,
                         created=created)

    db.add(new_user)
    db.commit()
    db.refresh(new_user)

    if not new_user:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            detail='Error trying to create blog!')

    return new_user
Ejemplo n.º 19
0
    def delete(cls, user_id):
        user = UserModel.find_by_id(user_id)
        if not user:
            return {'message': 'User not found'}, 404

        user.delete_from_db()
        return {'message': 'User deleted successfully.'}, 200
Ejemplo n.º 20
0
    def put(self, community_id, id):
        data = finish_tour_parser.parse_args()

        tour = TourModel.find_by_id(id)
        user = UserModel.find_by_username(get_jwt_identity())
        community: CommunityModel = CommunityModel.find_by_id(community_id)
        community_member_ids = [m.id for m in community.users]

        if not tour:
            abort(404, message=TOUR_NOT_FOUND)

        if not user.id == tour.owner.id:
            abort(401, message=UNAUTHORIZED)

        if tour.end_km:
            abort(400, message=TOUR_HAS_ALREADY_BEEN_FINISHED)

        passengers = []
        if data['passengers']:
            for passenger_id in set(data['passengers']):
                if passenger_id not in community_member_ids:
                    abort(400, message=PASSENGERS_MUST_BE_COMMUNITY_MEMBERS)
                else:
                    passengers.append([u for u in community.users if u.id == passenger_id][0])

        tour.end_time = datetime.datetime.now(pytz.utc)
        tour.passengers = passengers
        tour.end_km = data['end_km']
        tour.comment = data['comment']
        tour.parking_position = data['parking_position']
        tour.persist()

        create_km_triggered_task_instances(community_id, tour.end_km)

        return tour, 200
Ejemplo n.º 21
0
    def post(self, community_id):
        data = parser.parse_args()

        owner = UserModel.find_by_username(get_jwt_identity())
        community: CommunityModel = CommunityModel.find_by_id(community_id)

        if not community:
            abort(400, message=COMMUNIY_DOESNT_EXIST)

        if owner.id not in [u.id for u in community.users]:
            abort(401, message=UNAUTHORIZED)

        new_refuel = RefuelModel(
            owner=owner,
            community=community,
            costs=round(data['costs'], 2),
            liters=data['liters'],
            gas_station_name=data['gas_station_name'],
        )

        try:
            new_refuel.persist()
            return new_refuel, 201
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Ejemplo n.º 22
0
    def post(self, username):
        data = self.parser.parse_args()
        required_access = 3
        current_user = current_identity  # type: UserModel
        admin = AdminModel.find_by_id(current_user.id)
        if not admin:
            return {'message': 'No admin access.'}, 400

        if admin.access_level < required_access:
            return {
                'message': f'Access level {required_access} required.'
            }, 400

        other_user = UserModel.find_by_username(username)

        if not other_user:
            return {'message': f'User {username} doesn\'t exist.'}, 400

        if other_user.is_admin():
            return {'message': f'User {username} is already admin.'}, 400

        access_level = data['access_level']
        if admin.access_level <= access_level:
            return {'message': 'Access level must be lower than self.'}, 400

        if access_level < 1:
            return {'message' 'Invalid access level.'}, 400

        new_admin = AdminModel(other_user.id, access_level)
        new_admin.save()
        return {'admin': new_admin.json()}, 201
Ejemplo n.º 23
0
    def put(self, event_id):
        data = parser.parse_args()

        owner = UserModel.find_by_username(get_jwt_identity())
        event: EventModel = EventModel.find_by_id(event_id)

        if not event:
            abort(400, message=EVENT_DOESNT_EXIST)

        if owner != event.owner:
            abort(401, message=UNAUTHORIZED)

        if not data['end'] > data['start']:
            abort(400, message=END_MUST_BE_AFTER_START)

        event.title = data['title']
        event.description = data['description']
        event.start = data['start']
        event.end = data['end']

        try:
            event.persist()
            return event, 200
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Ejemplo n.º 24
0
    def post(self, community_id):
        data = parser.parse_args()

        owner = UserModel.find_by_username(get_jwt_identity())
        community: CommunityModel = CommunityModel.find_by_id(community_id)
        community_member_ids = [m.id for m in community.users]

        if not community:
            abort(400, message=COMMUNIY_DOESNT_EXIST)

        if owner.id not in community_member_ids:
            abort(401, message=UNAUTHORIZED)

        if not data['end'] > data['start']:
            abort(400, message=END_MUST_BE_AFTER_START)

        new_event = EventModel(owner=owner,
                               title=data['title'],
                               description=data['description'],
                               start=data['start'],
                               end=data['end'],
                               community_id=community.id)

        try:
            new_event.persist()
            return new_event, 201
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Ejemplo n.º 25
0
 def get_marshaller():
     return {
         'message': fields.String,
         'access_token': fields.String,
         'refresh_token': fields.String,
         'user': fields.Nested(UserModel.get_marshaller())
     }
Ejemplo n.º 26
0
def create_tables():
    print('Creating all application tables')
    db.create_all()
    if (seed_database):
        print('Seeding database')

        characters = [
            CharacterModel(name='Aragorn Segundo Elessar',
                           race='men', age='210'),
            CharacterModel(name='Gandalf', race='Maia', age=''),
            CharacterModel(name='Sauron', race='Maia', age=''),
            CharacterModel(name='Bilbo Baggins', race='	Hobbit', age=''),
        ]

        for character in characters:
            character.save_to_db()

        users = [
            UserModel(
                username='******',
                password='******'
            ),
        ]

        for user in users:
            user.save_to_db()
Ejemplo n.º 27
0
    def post(self):
        data = post_parser.parse_args()

        founder = UserModel.find_by_username(get_jwt_identity())
        car = CarModel.find_by_id(data['car'])

        if not car:
            abort(404, message=CAR_DOESNT_EXIST)

        if not car.owner.id == founder.id:
            abort(400, message=CANNOT_CREATE_COMMUNITY_WITH_FOREIGN_CAR)

        if CommunityModel.find_by_car_id(car.id):
            abort(400, message=COMMUNIY_WITH_THIS_CAR_ALREADY_EXISTS)

        new_community = CommunityModel(name=data['name'],
                                       car=car,
                                       users=[founder])

        try:
            new_community.persist()
            faved_community: CommunityUserLinkModel = assure_favourite_community(
                founder.id)
            if faved_community and faved_community.community_id == new_community.id:
                new_community.is_favourite = faved_community.is_favourite
            return new_community, 201
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Ejemplo n.º 28
0
    def post(self):
        data = invitation_parser.parse_args()

        user = UserModel.find_by_username(data['user'])
        community = CommunityModel.find_by_id(data['community'])

        if not user:
            abort(404, message=USER_DOESNT_EXIST)

        if not community:
            abort(404, message=COMMUNIY_DOESNT_EXIST)

        if user in community.users:
            abort(400, message=USER_ALREADY_INVITED)

        new_community_user_link = CommunityUserLinkModel(
            user_id=user.id,
            community_id=community.id,
            invitation_accepted=False,
            is_owner=False)

        try:
            new_community_user_link.persist()
            return SimpleMessage(COMMUNIY_INVITATION_SENT), 200
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Ejemplo n.º 29
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
Ejemplo n.º 30
0
 def post(cls):
     # TODO: NOT PERFECT
     jti = get_raw_jwt()["jti"]
     username = UserModel.find_by_sha_token(get_jwt_identity()).username
     BLACKLIST.add(jti)
     return {
         "message": response_quote("user_logged_out").format(username)
     }, 200