Ejemplo n.º 1
0
    def post(self):
        """ Create a new user """

        if not current_user.has_admin():
            return {"success": False, "message": "Access denied"}, 401

        args = register.parse_args()
        username = args.get('username')

        if UserModel.objects(username__iexact=username).first():
            return {
                'success': False,
                'message': 'Username already exists.'
            }, 400

        user = UserModel()
        user.username = args.get('username')
        user.password = generate_password_hash(args.get('password'),
                                               method='sha256')
        user.name = args.get('name', "")
        user.email = args.get('email', "")
        user.is_admin = args.get('isAdmin', False)
        user.save()

        user_json = fix_ids(current_user)
        del user_json['password']

        return {'success': True, 'user': user_json}
Ejemplo n.º 2
0
    def post(self):
        """ Creates user """

        users = UserModel.objects.count()

        if not Config.ALLOW_REGISTRATION and users != 0:
            return {'success': False, 'message': 'Registration of new accounts is disabled.'}, 400

        args = register.parse_args()
        username = args.get('username')

        if UserModel.objects(username__iexact=username).first():
            return {'success': False, 'message': 'Username already exists.'}, 400

        user = UserModel()
        user.username = args.get('username')
        user.password = generate_password_hash(args.get('password'), method='sha256')
        user.name = args.get('name')
        user.email = args.get('email')
        if users == 0:
            user.is_admin = True
        user.save()

        login_user(user)

        user_json = fix_ids(current_user)
        del user_json['password']

        return {'success': True, 'user': user_json}
Ejemplo n.º 3
0
def load_user_from_request(request):

    logger.info(f'Trying login')
    api_key = request.args.get('api_key')
    if api_key and len(api_key) == 24:
        logger.info(f'Trying login with api key')
        user = UserModel.objects(id=api_key).first()
        if user:
            logger.info(f'{user.username} logged in with api key')
            return user

    auth = request.authorization
    if not auth:
        return None
    user = UserModel.objects(username__iexact=auth.username).first()

    # if not user.api_key:
    #     logger.info(f'api key generating')
    #     new_api_key = uuid4()
    #     user.update(api_key=new_api_key)
    #     user = UserModel.objects(username__iexact=auth.username).first()

    if user and check_password_hash(user.password, auth.password):
        # login_user(user)
        return user
    return None
Ejemplo n.º 4
0
    def create(self, username, password, name, email):
        if self.can_not_register():
            return Result.failure(
                ['Registration of new accounts is disabled.'])

        if UserModel.user_already_exists(username):
            user = UserModel.find_by_username(username)
            return Result.success(user.id)

        user = self.create_user(username, password, name, email)
        return Result.success(user.id)
 def create_admin_user(self, username, password, name, email):
     user = UserModel()
     user.username = username
     user.password = self.encryption_service.hash_password(password)
     user.name = name
     user.email = email
     user.is_admin = True
     user.save()
     return user
Ejemplo n.º 6
0
    def post(self):
        """ Logs user in """
        args = login.parse_args()
        username = args.get('username')

        user = UserModel.objects(username__iexact=username).first()
        if user is None:
            return {
                'success': False,
                'message': 'Could not authenticate user'
            }, 400

        if check_password_hash(user.password, args.get('password')):
            login_user(user)
            user._update_last_seen()
            # user_api_key = user.api_key
            # if user_api_key == '':
            #     user_api_key = uuid4()
            #     user.update(api_key=user_api_key)
            user_json = fix_ids(current_user)
            del user_json['password']

            logger.info(f'User {current_user.username} has LOGIN')

            return {'success': True, 'user': user_json}

        return {
            'success': False,
            'message': 'Could not authenticate user'
        }, 400
Ejemplo n.º 7
0
Archivo: app.py Proyecto: ByK95/Crowley
def register():
    """Register user"""
    if request.method == "POST":

        form = {"username": None, "email": None, "password": None}
        for i in form:
            if request.form.get(i) is None or request.form.get(i) == "":
                return "Must Provide {}".format(i)
            form[i] = request.form.get(i)

        passhash = generate_password_hash(request.form.get("password"))

        new_user = UserModel(username=form["username"],
                             emailAddress=form["email"],
                             passwordHash=passhash)

        try:
            db.session.add(new_user)
            db.session.commit()
        except exc.IntegrityError:
            return render_template("error.html",
                                   errTitle='User exists!',
                                   redir="/register")

        return redirect("/")
    else:
        return render_template("register.html")
Ejemplo n.º 8
0
 def mutate(self, context, **kwargs):
     user = UserModel(name=kwargs.get('name'),
                      email=kwargs.get('email'),
                      username=kwargs.get('username'))
     db_session.add(user)
     db_session.commit()
     ok = True
     return createUser(user=user, ok=ok)
Ejemplo n.º 9
0
 def mutate(cls, _, args, context, info):
     user = UserModel(name=args.get('name'),
                      email=args.get('email'),
                      username=args.get('username'))
     db_session.add(user)
     db_session.commit()
     ok = True
     return createUser(user=user, ok=ok)
Ejemplo n.º 10
0
def load_user_from_request(request):
    auth = request.authorization
    if not auth:
        return None
    user = UserModel.objects(username__iexact=auth.username).first()
    if user and check_password_hash(user.password, auth.password):
        # login_user(user)
        return user
    return None
Ejemplo n.º 11
0
    def get(self, username):
        """ Get a users """

        if not current_user.has_admin():
            return {"success": False, "message": "Access denied"}, 401

        user = UserModel.objects(username__iexact=username).first()
        if user is None:
            return {"success": False, "message": "User not found"}, 400

        return fix_ids(user)
Ejemplo n.º 12
0
    def delete(self, username):
        """ Delete a user """

        if not current_user.has_admin():
            return {"success": False, "message": "Access denied"}, 401

        user = UserModel.objects(username__iexact=username).first()
        if user is None:
            return {"success": False, "message": "User not found"}, 400

        user.delete()
        return {"success": True}
Ejemplo n.º 13
0
def register():
    if request.method == 'POST':
        name = request.form['name']
        surname = request.form['surname']
        email = request.form['email']
        username = request.form['username']
        password = request.form['password']
        #user details are requested from the form
        if UserModel.query.filter_by(
                email=email).first():  #If email is already used error occurs.
            return ('Email already Present')

        user = UserModel(name=name,
                         surname=surname,
                         email=email,
                         username=username)
        user.set_password(password)
        current_user.name = name
        current_user.surname = surname
        db.session.add(user)
        db.session.commit()  #details are committed to the database
        return redirect('/profile1')  #patient home page is returned
    return render_template('register.html')  #register home page is returned
Ejemplo n.º 14
0
    def get(self, username):
        args = user_images.parse_args()
        date = args.get('date')
        status = args.get('status')
        if status is None:
          status = 'completed'
        logger.info(status)

        args = page_data.parse_args()
        limit = args['limit']
        page = args['page']

        user = UserModel.objects(username=username).first()
        if user is None:
            return {'success': False, 'message': 'Could not find user'}, 404
        
        if date:
            start = datetime.datetime.strptime(date, '%Y-%m-%d')
            end = datetime.datetime.strptime(date, '%Y-%m-%d') + datetime.timedelta(days=1)
            images = user.images.filter(
                      annotated=True,
                      # status__completed=True,
                      # status__rejected=True,
                      status__completedBy=user.id,
                      status__completedDate__gte=start,
                      status__completedDate__lte=end,
                      **{'{}__{}'.format('status', status): True}
                    ).only(
                      'id', 'dataset_id', 'path', 'file_name', 'annotating', 'annotated', 'num_annotations', 'status'
                    )
        else:
            images = user.images.filter(
                annotated=True,
                # status__completed=True, 
                status__completedBy=user.id,
                **{'{}__{}'.format('status', status): True}
              ).only(
                'id', 'dataset_id', 'path', 'file_name', 'annotating', 'annotated', 'num_annotations', 'status'
              )
        pagination = Pagination(len(images), limit, page)
        images = fix_ids(images[pagination.start:pagination.end])
        return {
            "pagination": pagination.export(),
            "page": page,
            "images": images,
            "status": status,
            "formatted_status": '{}__{}'.format('status' , status),
            "date": date,
        }
Ejemplo n.º 15
0
def register():

    form = RegisterForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        confirm = form.confirm.data

        if (password == confirm):
            newUser = UserModel(username, password)
            db.session.add(newUser)
            db.session.commit()
            return redirect(url_for("index"))
        else:
            flash("Passwords must match", "error")

    return render_template("register.html", form=form)
Ejemplo n.º 16
0
 def get(self):
     user = UserModel.objects(
         username__iexact=current_user.username).first()
     user.update(last_seen=datetime.datetime.utcnow())
     user_model = UserModel.objects
     present_time = datetime.datetime.utcnow()
     live_count = 0
     for user in user_model:
         user_last_seen = user.last_seen
         if user_last_seen is not None:
             if present_time > user_last_seen:
                 td = present_time - user_last_seen
             else:
                 td = user_last_seen - present_time
             td_mins = int(round(td.total_seconds() / 60))
             if td_mins <= 3:
                 live_count += 1
     return {'success': True, 'live_count': live_count}
    def execute(self, username, password, name, email):
        if self.can_not_register():
            return {
                'success': False,
                'message': 'Registration of new accounts is disabled.'
            }, 400

        if UserModel.user_already_exists(username):
            return {
                'success': False,
                'message': 'Username already exists.'
            }, 400

        user = self.create_user(username, password, name, email)

        return {
            'success': True,
            'user': self.json_prepare.prepare_user_json(user)
        }
Ejemplo n.º 18
0
 def get(self):
     users = UserModel.objects().only('id', 'username', 'name', 'online', 'is_admin', 'last_seen').all()
     
     stats = []
     for user in users:
         user['completed_images_total'] = user.images.filter(
                             annotated=True,
                             status__completed=True,
                             status__completedBy=user.id).count()
         user['verified_images_total'] = user.images.filter(
                             annotated=True,
                             status__verified=True,
                             status__completedBy=user.id).count()
         user['rejected_images_total'] = user.images.filter(
                             annotated=True,
                             status__rejected=True,
                             status__completedBy=user.id).count()
         stats.append(fix_ids(user))
     
     return stats
Ejemplo n.º 19
0
    def patch(self, username):
        """ Edit a user """

        if not current_user.has_admin():
            return {"success": False, "message": "Access denied"}, 401

        user = UserModel.objects(username__iexact=username).first()
        if user is None:
            return {"success": False, "message": "User not found"}, 400

        args = create_user.parse_args()
        name = args.get('name')
        if len(name) > 0:
            user.name = name

        password = args.get('password')
        if len(password) > 0:
            user.password = generate_password_hash(password, method='sha256')

        user.save()

        return fix_ids(user)
Ejemplo n.º 20
0
    def get(self, username):
        user = UserModel.objects(username=username).only('id', 'name', 'username', 'is_admin', 'last_seen').first()
        if user is None:
            return {'success': False, 'message': 'Could not find user'}, 404
        
        args = user_stats.parse_args()
        start_date = args.get('start_date')
        end_date = args.get('end_date')
        
        start = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        end = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        images = user.images.filter(
          annotated=True,
          # status__completed=True,
          status__completedBy=user.id,
          status__completedDate__gte=start,
          status__completedDate__lte=end)

        user['stats'] = {}
        for image in images:
          day = image.status['completedDate'].strftime('%Y%m%d')
          if not day in user['stats']:
            user['stats'][day] = {
              'completedCount': 0,
              'verifiedCount': 0,
              'rejectedCount': 0,
              'day': image.status['completedDate'].strftime('%Y-%m-%d')
            }
          if image.status['completedDate']:
            user['stats'][day]['completedCount'] += 1
          if 'verifiedDate' in image.status:
            user['stats'][day]['verifiedCount'] += 1
          if 'rejectedDate' in image.status:
            user['stats'][day]['rejectedCount'] += 1

        # user.images.filter(annotated=True, status__completed=True, status__completedBy=user.id)

        return fix_ids(user)
Ejemplo n.º 21
0
def load_user(user_id):
    return UserModel.objects(id=user_id).first()
Ejemplo n.º 22
0
 def find_user():
     return UserModel.objects().first()
 def mutate(cls, root, info, **args):
     user = UserModel(name=args.get('name'), age=args.get('age'))
     db_session.add(user)
     db_session.commit()
     ok = True
     return CreateUser(user=user, ok=ok)
Ejemplo n.º 24
0
 def create_user(username, password):
     user = UserModel(
         username=username,
         password=password
     ).save()
     return user.id
Ejemplo n.º 25
0
 def create_user_model(self, username, password, name, email):
     hash_password = self.encryption_service.hash_password(password)
     return UserModel.create(username, hash_password, name, email)
Ejemplo n.º 26
0
 def find_user_by_username(self, username):
     user = UserModel.objects(username__iexact=username).first()
     return user
Ejemplo n.º 27
0
def load_user(request):
    return UserModel.objects(username=user_credential.get_user_name()).first()