示例#1
0
    def mutate(
        root,
        info,
        password: str,
        email: Optional[str] = None,
        username: Optional[str] = None,
    ):
        logger.debug(
            f"username: {username}, email: {email}, password: {password}")
        # get user info
        if email is not None:
            user = crud.get_user(db, key="email", query=email)
        elif username is not None:
            user = crud.get_user(db, key="username", query=username)
        else:
            raise GraphQLError("Username or Email Fields is need")

        if user is None:
            raise GraphQLError("Username not existed")
        # check password
        is_password_correct = crud.check_password(db=db,
                                                  username=username,
                                                  password=password)

        if is_password_correct is None:
            raise GraphQLError("Password is not correct")

        access_token = create_access_token_with_username(username)

        return AuthenUser(token=access_token, username=user.username)
示例#2
0
def calcScore(email, loc):
    total_points = 0
    for crit in crud.get_user(email).criteria:
        yelp_endpoint = yelp(crit, loc)
        matches = get_matches(yelp_endpoint, crit, loc)
        loccrit = recordLocCrit(matches, crit, loc)
        total_points += loccrit.points
    index = (total_points / crud.get_user(email).get_max_pts()) * 100
    score = Score(index=index, latlong=loc.latlong, email=email)
    db.session.add(score)
    db.session.commit()
    return score
示例#3
0
def unblock(user_ip, domain=None, app_name=None):
    if app_name != None:
        user = get_user(ip=user_ip).fetchone()
        app = get_app(name=app_name).fetchone()
        if user and app:
            return delete_block(user_id=user[0], app_id=app[0])
        elif user and not app:
            print("App not exist")
        else:
            return f"User {user_ip} has no locks."
    elif domain != None:
        user = get_user(ip=user_ip).fetchone()
        return delete_block(user_id=user[0], domain=domain)
示例#4
0
def login():
    form = LoginForm(request.form)
    if request.method == "POST" and form.validate():
        username = form.username.data
        password = form.password.data

        result = get_user(username)
        if result:
            if sha256_crypt.verify(password, result.password):
                flash("Giriş İşlemi Başarılı", "success")

                session["logged_in"] = True
                session["id"] = result.id
                session["username"] = username
                session["name_lastname"] = f"{result.name} {result.last_name}"

                return redirect(url_for("index"))
            else:
                flash("Girilen Şifre Hatalı", "danger")
                return redirect(url_for("login"))
        else:
            flash("Kullanıcı Adı ve Şifre Hatalı", "danger")
            return redirect(url_for("login"))
    else:
        return render_template("login.html", form=form)
示例#5
0
def add_freight():
    if request.method == "POST":
        freight_type = request.form.get("freight_type")
        departure_city = request.form.get("departure_city")
        incoterms = request.form.get("incoterms")
        weight = request.form.get("weight")
        height = request.form.get("height")
        width = request.form.get("width")
        length = request.form.get("length")
        radio_extra = request.form.get("freight_type")
        freight_number = get_freight_number()

        user = get_user(session["username"])

        data = {
            "user_id": user.id,
            "freight_type": freight_type,
            "departure_city": departure_city,
            "incoterms": incoterms,
            "weight": weight,
            "height": height,
            "width": width,
            "length": length,
            "radio_extra": radio_extra,
            "freight_number": freight_number
        }
        create_freight(data)

        flash("Gönderi Kaydınız Başarıyla Oluşturulmuştur.", "success")
        flash(f"Gönderi Numaranız: {freight_number}.", "danger")

        return redirect(url_for("index"))

    return render_template("add_freight.html")
示例#6
0
def update_user_image(user: schemas.UserUpdate, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user.id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    if not is_valid_image(user.image):
        raise HTTPException(status_code=422, detail="Invalid image data")
    return crud.update_user(db=db, user=user)
def login_user(
    user: schemas.UserLogIn,
    db: Session = Depends(deps.get_db)) -> JSONResponse:
    """ Login user and Return Access Token"""
    db_user = get_active_user(email=user.email, db=db)
    if db_user is None:
        return JSONResponse(status_code=400,
                            content={"message": "Invalid Credentials"})
    else:
        is_password_correct = crud_login.check_username_password(
            email=user.email, password=user.password, db=db)
        if is_password_correct is False:
            return JSONResponse(status_code=400,
                                content={"message": "Invalid Credentials"})
        else:
            uid = str(uuid.uuid4().hex)
            crud_login.login_user(user=user, session_id=uid, db=db)
            access_token_expires = timedelta(
                minutes=ProjectSettings.ACCESS_TOKEN_EXPIRE_MINUTES)
            token = access_token.create_access_token(
                data={"sub": user.email}, expires_delta=access_token_expires)
            return JSONResponse(status_code=200,
                                content={
                                    "access_token":
                                    token,
                                    "token_type":
                                    "Bearer",
                                    "session_id":
                                    uid,
                                    "user":
                                    jsonable_encoder(
                                        get_user(email=user.email, db=db))
                                })
def update_contact(
    *,
    db: Session = Depends(get_db),
    contact_id: int,
    item_in: schemas.ContactBase,
    owner_id: int,
) -> any:
    """
    Update an item.

    """
    user = crud.get_user(db, user_id=owner_id)
    if user:
        contacts = crud.get_contact(db,
                                    owner_id=owner_id,
                                    contact_id=contact_id)
        if contacts:
            # can also use jsonable_encoder()
            contact = {
                "name": item_in.name,
                "email": item_in.email,
                "phone": item_in.phone
            }
            db.query(models.Contact).filter(
                owner_id == owner_id, models.Contact.id == contact_id).update(
                    contact, synchronize_session="fetch")
            db.commit()
            return {"Contact Updated Successfully": True}
        else:
            raise HTTPException(status_code=404, detail="Contact not found")
    else:
        raise HTTPException(status_code=404, detail=" User doesn't exist")
def del_user(owner_id: int, db: Session = Depends(get_db)):
    user = crud.get_user(db, user_id=owner_id)
    if user:
        crud.del_user(db, user_id=owner_id)
        return "successfully deleted"
    else:
        raise HTTPException(status_code=404, detail=" User doesn't exist")
示例#10
0
def user_login():
    """Allow user to log in to their existing account"""

    # username = request.args["username"]

    # password = request.args["password"]

    username = request.form.get("username")

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

    user = crud.get_user(username, password)

    if user:
        session["logged_in"] = True
        session["user"] = username
        session["password"] = password
        session["user_id"] = user.user_id

        return jsonify({
            'user': username,
            'password': password,
            'user_id': user.user_id,
            'logged_in': True,
            "favoriteTopics": ['Wellness', 'Yoga']
        })
示例#11
0
    def check_username_password(self, email: str, password: str,
                                db: Session) -> Any:
        """ Verify Password"""
        db_user_info = get_user(email=email, db=db)

        return passutil.verify_password(str(password),
                                        str(db_user_info.password))
示例#12
0
def authenticate_user(db, username: str, password: str):
    """
    First gets the user with get_user function, then
    verifies its password woth the password entered at the front end.

    Parameters
    ----------
    username : str
        The username that the user entered.
    password : str
        The password entered by the user.

    Returns
    -------
    user : UserInDB
        The user info.
    """
    user = crud.get_user(db, username).first()
    print(user.__dict__)

    if not user:
        return False
    if not verify_password(password, user.password):
        return False
    return user
示例#13
0
async def get_user(user_id: int,
                   db: database.session = Depends(database.get_db)):
    db_user = crud.get_user(db, user_id)

    if not db_user:
        raise HTTPException(status_code=404, detail='User not found!')

    return await db_user
示例#14
0
def unblock(user_ip, domain):
    user = get_user(ip=user_ip)
    url = get_url(domain=domain)
    if hasattr(user, "id") and hasattr(url, "id"):
        blocking = get_block(user_id=user.id, url_id=url.id)
        return delete_block(blocking.id)
    elif hasattr(user, "id") and not hasattr(url, "id"):
        return f"This domain does not exist, maybe you meant:\n {maybe_sites(domain, blocked_sites(user_ip))}"
    else:
        return f"User {user_ip} has no locks."
示例#15
0
def sign_up():
    """Create new user."""

    user = crud.get_user(session.get('user_id'))

    if 'user_id' in session:
        return redirect('/past_entries')

    else:
        return render_template('sign_up.html')
示例#16
0
def show_all_users():
    """if user is logged in show them all user who is not their friend otherwise redirect to index.html"""
    if session.get("id", None):
        allusers = crud.get_alluser()
        friends = crud.get_friend(session['id'])
        user = [crud.get_user(session['id'])
                ]  #getting user object convert it to list for set subtration
        users = list(set(allusers) - set(friends) - set(user))
        return render_template("users.html", users=users)
    else:
        return redirect("/")
def show_profile(email):
    """Render user profile page if logged in. Otherwise, redirect to homepage"""
    if session.get('user') == email and session['logged_in'] == 'yes':
        user = crud.get_user(email)
        criteria, scores = user.get_criteria, user.get_scores()
        return render_template('profile.html', 
                                user=user,
                                criteria=criteria,
                                scores=scores,
                                )
    return redirect('/')
def login_user():
    """Provided correct email and password, log-in user"""
    email = request.form.get('email')
    password = request.form.get('password')
    if crud.get_user(email) is None or crud.verify_password(email, password) is False:
        return jsonify(({'success': False, 'err': "Incorrect email or password"}))
    else: 
        session['user'] = email
        first_name = crud.get_user_info(email)
        session['logged_in'] = 'yes'
        return jsonify(({'success': True, 'first_name': first_name, 'email': session['user']}))
示例#19
0
def read_contacts(user_id: int, db: Session = Depends(get_db)):
    user = crud.get_user(db, user_id=user_id)
    if user:
        contacts = crud.get_contacts_by_user(db, owner_id=user_id)
        if contacts:
            return contacts
        else:
            raise HTTPException(status_code=404, detail="No contacts added ")
    else:
        raise HTTPException(status_code=404,
                            detail="Create User first , User doesn't exist")
示例#20
0
def block(user_ip, domain=None, app_name=None):
    if app_name != None:
        user = get_user(ip=user_ip).fetchone()
        app = get_app(name=app_name).fetchone()
        if user and app:
            return create_block(user_id=user[0], app_id=app[0])
        elif user and not app:
            app = create_app(name=app_name).fetchone()
            return create_block(user_id=user[0], app_id=app[0])
        elif not user and app:
            user = create_user(user_ip).fetchone()
            return reate_block(user_id=user[0], app_id=app[0])
        else:
            user = create_user(user_ip).fetchone()
            app = create_app(name=app_name).fetchone()
            return create_block(user_id=user[0], app_id=app[0])
    elif domain != None:
        user = get_user(ip=user_ip).fetchone()
        if not user:
            user = create_user(user_ip).fetchone()
        return create_block(user_id=user[0], domain=domain)
示例#21
0
def user_profile():
    """user profile and return his favorite and suggested book """
    if session.get("id") is not None:
        user = crud.get_user(session['id'])
        name = user.fname
        img_url = user.img_url
        return render_template("userProfile.html",
                               name=name,
                               email=user.email,
                               img_url=img_url)
    else:
        return redirect("/")
示例#22
0
def read_contact_by_name(owner_id: str,
                         name: str,
                         db: Session = Depends(get_db)):
    user = crud.get_user(db, user_id=owner_id)
    if user:
        contacts = crud.get_contact_by_name(db, name=name, owner_id=owner_id)
        if contacts is None:
            raise HTTPException(status_code=404, detail="Contact not found")
        else:
            return contacts
    else:
        raise HTTPException(status_code=404,
                            detail="Create User first , User doesn't exist")
示例#23
0
def del_con(owner_id: int, contact_id: int, db: Session = Depends(get_db)):
    user = crud.get_user(db, user_id=owner_id)
    if user:
        contacts = crud.get_contact(db,
                                    owner_id=owner_id,
                                    contact_id=contact_id)
        if contacts is None:
            raise HTTPException(status_code=404, detail="Contact not found")
        else:
            crud.del_contact(db, owner_id=owner_id, contact_id=contact_id)
            return "successfully deleted"
    else:
        raise HTTPException(status_code=404, detail=" User doesn't exist")
示例#24
0
async def get_user(userId: int,
                   response: Response,
                   db: Session = Depends(get_db)):
    db_user = crud.get_user(db, userId)
    if db_user is None:
        response.status_code = status.HTTP_404_NOT_FOUND
        return None
    user = User(id=db_user.id,
                username=db_user.username,
                firstName=db_user.firstname,
                lastName=db_user.lastname,
                email=db_user.email,
                phone=db_user.phone)
    return user.dict()
示例#25
0
async def user_register(message: types.Message, allowed: bool):
    if allowed:
        if not message.from_user.is_bot:
            user = crud.get_user(message.from_user.id)
            if user:
                await message.answer("User already registered")
            else:
                # register user
                crud.create_user(
                    telegram_id=message.from_user.id,
                    username=message.from_user.username,
                    first_name=message.from_user.first_name,
                    last_name=message.from_user.last_name,
                )
                user = crud.get_user(message.from_user.id)
                if user:
                    await message.answer("User successfully registered")
                else:
                    await message.answer(
                        f"Some error registering user {message.from_user}")
    else:
        logging.warning("NOT ALLOWED")
        send_admin_message(f"NOT ALLOWED: {message}")
def register_user():
    """Register new user."""
    email = request.form.get('email')
    first_name = request.form.get('firstName')
    last_name = request.form.get('lastName')
    password = request.form.get('password')
    #If user does not yet exist in database, create new user.  
    if crud.get_user(email):
        # return jsonify({'success': False})
        return redirect(f'/profile/${email}')
    else:
        crud.create_user(email, first_name, last_name, password)
        session['user'] = email
        session['logged_in'] = 'yes'
        return jsonify({'success': True})
def save_password_changes():
    """Save password changes"""

    password = request.form.get('edit-password')

    username = session['user']
    user = crud.get_user(username)

    if user.password != password:
        user.update_password(password)
        flash('Password changed')
    else:
        flash('No change')

    return redirect(f'/profile/{username}')
示例#28
0
def block(user_ip, domain):
    user = get_user(ip=user_ip)
    url = get_url(domain=domain)
    if hasattr(user, "id") and hasattr(url, "id"):
        return create_block(user.id, url.id)
    elif hasattr(user, "id") and not hasattr(url, "id"):
        url = create_url(domain)
        return create_block(user.id, url.id)
    elif not hasattr(user, "id") and hasattr(url, "id"):
        user = create_user(user_ip)
        return create_block(user.id, url.id)
    else:
        user = create_user(user_ip)
        url = create_url(domain)
        return create_block(user.id, url.id)
示例#29
0
def SignIn():
    if request.method == "POST":
        username = request.form["uname"]
        password = request.form["psw"]

        results = crud.get_user(username)
        if results != -1:
            if username == results["username"] and password == results[
                    "password"]:
                session["SIGNED_IN"] = True
                session["Username"] = username

    if "SIGNED_IN" in session and session["SIGNED_IN"] == True:
        return redirect(url_for('index'))
    else:
        return render_template("templateIndexBody2.html")
示例#30
0
def adminFind():
    if request.method == "POST":
        username = request.form["uname"]
        results = crud.get_user(username)
        if results == -1:
            found = "No users found for username: "******"templateAdminNoResult.html", found=found)
        else:
            found = "Contact Details:"
            return render_template("templateAdminFindResult.html",
                                   found=found,
                                   results=results)

    if "ADMIN_SIGNED_IN" in session and session["ADMIN_SIGNED_IN"] == True:
        return render_template("templateAdminFind.html")
    else:
        return render_template("adminSignIn.html")