예제 #1
0
def register():
    # verify if user is already logged in.
    # if he is, redirect home. otherwise continue showing login page.
    try:
        displayname = session['displayname']
        if displayname is not None:
            return redirect(url_for('home'))

    except KeyError as error:
        # User is not logged in. continue on this page.
        pass

    userform = UserForm()
    if userform.validate_on_submit():
        # if the request.method == POST and the form is valid,
        # register the user and redirect to home
        displayname = userform.displayname.data
        password = userform.password.data

        # check if user is already registered
        try:
            user = User(displayname=displayname, password=None)
            i = users.index(user)
            userform.displayname.errors.append('Display name already taken')

        except ValueError as e:
            # Display name available to use.
            # Create the user.
            newuser = User(displayname=displayname, password=password)
            users.append(newuser)
            session['displayname'] = displayname
            return redirect(url_for('home'))

    return render_template('register.html', form=userform)
예제 #2
0
파일: routes.py 프로젝트: jilir/vulncode-db
def load_user():
    user = None

    # Ignore all non-admin users for now.
    if not is_admin():
        g.user = None
        return

    # Ignore all non-admin users during maintenance mode.
    if current_app.config["MAINTENANCE_MODE"]:
        return

    if is_authenticated():
        data = session["user_info"]
        email = data["email"]

        user = User.query.filter_by(email=email).one_or_none()
        if not user:
            user = User(email=email,
                        full_name=data["name"],
                        profile_picture=data["picture"])
        else:
            user.full_name = data["name"]
            user.profile_picture = data["picture"]
        db.session.add(user)
        db.session.commit()

    g.user = user
예제 #3
0
def register():
    """
    用户注册
    """
    if request.method == 'POST':
        username = request.form.get("username")
        password = request.form.get("password")
        password2 = request.form.get("password2")
        if not all([username, password, password2]):
            return render_template('login.html', error="用户名或密码不允许为空")
        user = db.query(User).filter(User.username == username).one_or_none()
        if user:
            return render_template('register.html', error="该用户名已注册")
        if password2 != password:
            return render_template('register.html', error="两次输入的密码不匹配")
        token = create_token()
        user = User(username=username,
                    password=generate_password_hash(password),
                    active=True,
                    token=token)
        db.session.add(user)
        db.session.commit()
        response = make_response(redirect('/'))
        response.set_cookie("token", token)
        return response
    return render_template('register.html')
예제 #4
0
파일: dao.py 프로젝트: jgabrielgv/cgistore
 def username_email_exists(self, username, email):
     """Validates if a user exists by username or email"""
     self.__open_connection()
     cursor = self.__db.cursor()
     result = {}
     try:
         sql_query = """select user_id, username, email, entry_date from user where username = %s or email = %s"""
         cursor.execute(sql_query, (
             username,
             email,
         ))
         dataset = cursor.fetchall()
         for user_id, user_name, email, entry_date in dataset:
             result = User(user_id, user_name, email, '', '', entry_date)
         if not result:
             return {}
         values = {}
         if result.username == username:
             values['username'] = True
         if result.email == email:
             values['email'] = True
         return values
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
     finally:
         self.__close_connection(cursor)
     return result
예제 #5
0
def registration():
    form = RegisterForm()
    if form.validate_on_submit():
        # Проверка правильности повторного ввода пароля
        if form.password.data != form.password_again.data:
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают")

        # Проверка наличия в системе такого пользователя
        session = db_session.create_session()
        if session.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")

        # Создание пользователя
        user = User(surname=form.surname.data,
                    name=form.name.data,
                    age=form.age.data,
                    email=form.email.data)

        # Добавление пользователя в БД
        user.set_password(form.password.data)
        session.add(user)
        session.commit()

        return redirect('/login')
    return render_template('register.html', title='Регистрация', form=form)
예제 #6
0
파일: moo.py 프로젝트: kcvrgopal/Pinit
def register_user():
    """
    This method registers a user with the data provided and returns corresponding response
    """
    fmt = __format(request)
    if request.content_type == "application/json":
        username = request.json['username']
        name = request.json['name']
        password = request.json['password']
    else:
        username = request.forms.get("username")
        name = request.forms.get("name")
        password = request.forms.get("password")
    user = User(name=name, username=username, password=password)
    result = db.insert_registration(user)
    if result:
        response._status_line = "201 Created"
        response_to_user = {
            "status": response._status_line,
            "success": True,
            "message": "Created",
            "user_id": result
        }
        return format_checker(response_to_user, fmt)
    else:
        response._status_line = "500 Internal Server Error"
        response_to_user = {
            "status": response._status_line,
            "success": False,
            "message": "Could Not Process Request!!!"
        }
        return format_checker(response_to_user, fmt)
예제 #7
0
def get_user_language(user_id=None, update=None, short=False):
    # If passed update, not user_id
    if update:
        user_id = update.message.from_user.id

    # Create database session
    session = db_session.create_session()

    # Get user information
    user = session.query(User).filter(User.telegram_id == user_id).first()

    # If user doesn't exist
    if not user:
        # Create new object for user with standard parameters
        new_user = User()
        new_user.telegram_id = user_id
        new_user.language_id = 0
        session.add(new_user)
        session.commit()
        user = new_user

    # Get user language
    language_id = user.language_id
    language = LANGUAGES[language_id]

    # Close database session
    session.close()

    # If passed "short"=True parameter, return short language
    if short:
        return language["short"]

    # Return language
    return language
예제 #8
0
파일: dao.py 프로젝트: jgabrielgv/cgistore
 def fetch_user(self, user_name, passwd):
     """Fetch an specific user by username"""
     self.__open_connection()
     cursor = self.__db.cursor()
     result = {}
     try:
         error_message = "Usuario y contraséa no coinciden."
         sql_query = """select user_id, username, email, password, salt, entry_date from user where username = %s"""
         cursor.execute(sql_query, (user_name, ))
         dataset = cursor.fetchall()
         if not dataset:
             self.__log(error_message)
             return result
         for user_id, user_name, email, password, salt, entry_date in dataset:
             user = User(user_id, user_name, email, password, salt,
                         entry_date)
         if not check_password(user, passwd):
             self.__log(error_message)
             user = result
         return user
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
     finally:
         self.__close_connection(cursor)
     return result
예제 #9
0
def handle_send_message_event(data):
    sender = User(username=data['username'], user_id=data['user_id'])
    user_type = data['user_type']
    current_room = get_room(data['room_id'])
    last_sender = None
    prev_msg = None
    if len(current_room.messages) > 0:
        index = len(current_room.messages) - 1
        prev_msg = current_room.messages[index]
        last_sender = prev_msg.sender

    if user_type == "BOT":
        sender.personality = data['personality']
        sender.user_type = user_type
        bot = assign_bot(personality=sender.personality)
        prev_content = prev_msg.content.message if prev_msg else None
        message = bot(prev_content)
    else:
        message = Message(sender=sender, content=Content(message=data['msg']))
        data['ok'] = "DIN TUR"

    if last_sender is None or last_sender.user_id != sender.user_id:
        data['message'] = asdict(message)
        current_room.messages.append(message)
        socket.emit('receive_message', data, to=current_room.room_id)
예제 #10
0
파일: dao.py 프로젝트: jgabrielgv/cgistore
 def get_cookie_id(self, cookie_id, cursor):
     """Validate product properties bofore save, for example, that the code_id does not exists yet"""
     response = None
     data = None
     try:
         response = '403'
         #cursor1 = cursor(buffered=True)
         sql_query_user = """SELECT user_session_history_id, user_id FROM user_session__history WHERE cookie_id = %s limit 1"""
         test = cursor.execute(sql_query_user, (cookie_id, ))
         rows = cursor.fetchall()
         results = len(rows)
         result = results
         if results > 0:
             row = rows[0]
             sql_query_user = """SELECT user_id, name, email FROM user WHERE user_id = %s limit 1"""
             cursor.execute(sql_query_user, (row[1], ))
             rows = cursor.fetchall()
             results = len(rows)
             if results > 0:
                 row = rows[0]
                 user = User(row[0], '', row[2], '', '', row[1])
                 return user
         return response
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
         return response
     finally:
         self.__close_connection(cursor)
     return True
예제 #11
0
def registration():
    form = RegistrationForm()
    response = requests.get(f'{HOST_PORT}/api/token/departament').json()
    form.departament.choices = \
        [(val['id'], val['organization']['title'] + ', ' + val['title']) for val in response['departament']]
    auth_error = ''

    if request.method == 'POST' and form.validate_on_submit():
        session = db_session.create_session()
        result = session.query(User).filter(
            User.email == request.form.get('email')).first()
        if request.form.get('password') == request.form.get('repeat_password'):
            if result == 0:
                user = User(name=request.form.get('name'),
                            email=request.form.get('email'),
                            hashed_password=request.form.get('password'),
                            departament_id=request.form.get('departament'))
                session.add(user)
                session.commit()
                session.close()
                return render_template('status.html',
                                       status=True,
                                       message='Вы успешно зарегистрированы!')
            else:
                auth_error = 'Такой пользователь уже существует'
        else:
            auth_error = 'Пароли не совпадают'
    return render_template('registration.html',
                           title='Регистрация',
                           form=form,
                           auth_error=auth_error)
예제 #12
0
def register_user(login, password, mail, name) -> User:
    session = db_session.create_session()
    user = User()
    auth = Auth()

    user.is_approved = False
    user.name = name
    user.role = 'user'
    user.key = geherate_key()
    auth.login = login
    auth.password = password
    auth.email = mail
    user.auth.append(auth)

    session.add(user)
    session.flush()

    application = Applications()
    application.user_id = user.id
    application.login = login
    session.add(application)

    session.commit()
    session.close()
    return user
예제 #13
0
파일: main.py 프로젝트: DimeraCejz/animals
def registration():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(form.login.data, form.password.data)
        session = db_session.create_session()
        try:
            session.add(user)
            session.commit()
        except IntegrityError:
            return render_template(
                'registration.html',
                title='Регистрация',
                form=form,
                message='Такой пользователь уже существует.')
        except Exception as e:
            print(e)
            return render_template(
                'registration.html',
                title='Регистрация',
                form=form,
                message='Произошла ошибка. Пожалуйста, повторите попытку позже.'
            )
        finally:
            session.close()
        return redirect('/login')
    return render_template('registration.html', title='Регистрация', form=form)
예제 #14
0
def auth_registration():
    data = request.get_json()
    username = data.get('username')
    first_name = data.get('first_name')
    last_name = data.get('last_name')
    email = data.get('email')
    pass1 = data.get('password1')
    pass2 = data.get('password2')

    no_exist = User.query.filter_by(email=email).first() is None
    pass_equiv = pass1 == pass2

    xhr = MakeResponse()

    if not pass_equiv:
        xhr.set_error(422, "Paswords do not match.")
    elif not no_exist:
        xhr.set_error(409, "Email address is not available for use.")
    else:
        user = User({
            "username": username,
            "first_name": first_name,
            "last_name": last_name,
            "email": email,
            "password": pass1
        })
        user.save()
        xhr.set_status(200)

    return xhr.response
예제 #15
0
def login():
    userf = UserForm()
    admin = AdminForm()

    if userf.validate_on_submit():

        comand = userf.comand_name.data
        username = userf.username.data
        password = userf.password.data
        db_sess = db_session.create_session()
        team = db_sess.query(Teams).filter(Teams.name == comand).filter(
            Teams.name != 'Admins').first()

        if team and check_password_hash(team.password_hash, password):
            users = db_sess.query(
                User.username).filter(User.team == team.name).all()
            users_names = [x[0] for x in users]

            if username in users_names:
                login_user(
                    db_sess.query(User).filter(User.team == team.name).filter(
                        User.username == username).first())
                return redirect("/user")

            else:
                if len(users) < 6:
                    us = User()
                    us.username = username
                    us.team = comand
                    db_sess.add(us)
                    db_sess.commit()
                    login_user(us)
                    return redirect("/user")

                else:
                    return render_template('login.html',
                                           form=userf,
                                           adm_form=admin)
        return render_template('login.html', form=userf, adm_form=admin)

    if admin.validate_on_submit():

        name = admin.ad_username.data
        password = admin.ad_password.data
        db_sess = db_session.create_session()
        admins = db_sess.query(User).filter(User.username == name).filter(
            User.role == 1).first()
        team = db_sess.query(Teams).filter(Teams.name == 'Admins').first()

        if admins and check_password_hash(team.password_hash, password):
            login_user(admins)
            return redirect('/admin')

        else:
            return render_template('login.html', form=userf, adm_form=admin)
    return render_template('login.html',
                           title='Авторизация',
                           form=userf,
                           adm_form=admin)
예제 #16
0
def create_fake_user():
    user = User(
        username="******",
        password=generate_password_hash("testword"),
        email="*****@*****.**",
    )
    db.session.add(user)
    db.session.commit()
예제 #17
0
def get_all():
    users = []

    cursor = users_collection.find({})

    for document in cursor:
        users.append(User(document['chat_id'], document['year']))

    return users
예제 #18
0
def api_displayname_available(displayname):
    try:
        user = User(displayname=displayname, password="")
        i = users.index(user)
        # Display Name already exists
        return 'Not Available', 404

    except ValueError as e:
        # Display name available to use
        return 'Available', 200
예제 #19
0
 def create_user(self,
                 user_id,
                 user_name,
                 first_name,
                 last_name,
                 is_bot=False):
     user = User(user_id, user_name, first_name, last_name, is_bot)
     self._context.get_context().add(user)
     self._context.get_context().flush()
     self._context.get_context().refresh(user)
     return user
예제 #20
0
def displayfunc(request):
    pro1 = Product(
        title="Float Recliner",
        price_reg="Rs 750/month",
        description=
        "Rent our Float, a neutral fabric recliner, which merges seamlessly with any decor in your home.",
        qauntity=8,
        image="ridada",
        weight=40,
        depth=90,
        width=80,
        height=110,
        price_sale="Rs 550/month",
        bestseller="yes",
        status="available",
        productlink="/sofa/bcde/",
        category="sofa")

    pro = User(name="Rishab",
               email="*****@*****.**",
               password="******",
               number=9971775086,
               pincode=110032,
               city="Delhi",
               address="1/757 West rohtash nagar shahdara",
               state="Delhi")

    # Product.objects.all().delete()
    # for xyz in range(1,20):
    #    Product.objects.filter(id=xyz).delete()
    design = ""

    # design ='Printing all Dreamreal entries in the DB : <br>'
    # a = Product.objects.get(title="Dhyanachand Bed (Brown)")
    # design +=a.price_sale + "<br>"
    # list1=["1000","899","899","800","750","750",]
    # i=0
    b = User.objects.get(email="*****@*****.**")
    c = b.id

    objects = UserPurchase.objects.filter(email=c)
    for a in objects:
        # xyz.price_reg=list1[i]
        design += a.productid + "<br>"

    # objects = TestModels.objects.all()
    # for xyz in objects:
    #     p=xyz.price
    #     p= str(p)
    #     p = p + "<br>"
    #     design += p
    return HttpResponse(design)
예제 #21
0
def user_add():
    """
        添加用户
    """
    data = request.get_json()
    username = data.get('username')
    password = data.get("password")
    if db.session.query(User).filter(User.username == username).one_or_none():
        return make_response(jsonify({"msg": "用户名已存在"}), 400)
    safe_password = generate_password_hash(password)
    db.session.add(User(username=username, password=safe_password))
    db.session.commit()
    return jsonify({})
예제 #22
0
def join():
    """
    Register user with given credentials if user with that username doesnt exist
    Otherwise redirect on /join page again
    :return:
    """
    title = 'Join us'
    session = db_session.create_session()
    # Registration form
    form = forms.RegistrationForm()
    if form.validate_on_submit():
        # Creating Database Session
        session = db_session.create_session()

        # checking if user already registered
        if session.query(User).filter(
                User.username == form.username.data).all():
            session.close()
            logger.info(
                f'user with username {form.username.data} already registered, redirecting on /join with'
                f' the flash')
            flash('User with this username already registered',
                  'alert alert-danger')
            return render_template('join.html', form=form)

        # User object for database
        user = User()

        # Hashing password here
        password_hash = hashlib.new('md5',
                                    bytes(form.password.data, encoding='utf8'))
        # Filling database with user data
        user.username = form.username.data
        # Here we use not password but its hash
        user.hashed_password = password_hash.hexdigest()
        user.reg_ip = request.remote_addr
        user.last_ip = request.remote_addr

        # Adding user to database
        session.merge(user)
        # Commiting changes
        session.commit()
        session.close()
        logger.info(
            f'User {form.username.data} with IP {request.remote_addr} just registered, redirecting on /index'
        )
        flash('Your account has been created and now you are able to log in',
              'alert alert-primary')
        return redirect(url_for('index'))
    session.close()
    return render_template('join.html', title=title, form=form)
예제 #23
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
예제 #24
0
파일: start.py 프로젝트: m3nd0r/geo_bot
def registration(update, context):
    name = update.message.text
    user_id = update.message.chat_id

    if not name_exists(name):
        db.session.add(User(user_id=user_id, user_name=name, user_score=0))
        db.session.commit()
        update.message.reply_text(
            f'Спасибо! Теперь Вы известны как {name}!\nМожно начинать игру.',
            reply_markup=StartgameKeyboard().generate_keyboard_markup())
        return ConversationHandler.END
    else:
        update.message.reply_text(
            'Прошу прощения, но имя уже занято. Попробуйте другое.')
        return REG
예제 #25
0
def create_user(data: dict):
    user = User()
    user.login = data.get("login")
    user.password = data.get("password")
    try:
        with db.atomic() as transaction:
            try:
                user.save()
            except peewee.InternalError:
                transaction.rollback()
            else:
                transaction.commit()
    except peewee.IntegrityError:
        print(f"{data.get('login')}: Already exist.")
    return user.id
예제 #26
0
def register_admin(login, password, mail, name) -> User:
    session = db_session.create_session()
    user = User()
    auth = Auth()
    user.is_approved = True
    user.name = name
    user.role = 'admin'
    user.key = geherate_key()
    auth.login = login
    auth.password = password
    auth.email = mail
    user.auth.append(auth)
    session.add(user)
    session.commit()
    session.close()
예제 #27
0
def __process_request():
    if not helpers.request_method() == 'POST':
        return False
    parser = helpers.FormParser()
    parser.discover_values()
    name = parser.get_value("name", "")
    username = parser.get_value("username", "")
    password = parser.get_value("password", "", False)
    email = parser.get_value("email", "")
    if __validate_properties(name, username, password, email) or \
     __validate_custom_functions(username, email):
        return False
    else:
        user = User(0, username, email, password, '', name)
        return __CONN.create_account(user)
    return True
예제 #28
0
파일: views.py 프로젝트: rishabswalia/shops
def saveModel(name, email1, pincode, password, number, city, address, state):
    if name != None:
        try:
            a = User.objects.get(email=email1)
            dict.update({print: "User exits already try different email"})
        except User.DoesNotExist:
            pro1 = User(name=name,
                        email=email1,
                        pincode=pincode,
                        password=password,
                        number=number,
                        city=city,
                        address=address,
                        state=state)
            pro1.save()
            return True
예제 #29
0
파일: dao.py 프로젝트: jgabrielgv/cgistore
 def fetch_user_by_user_id(self, user_id):
     """Fetch an specific user by user id"""
     self.__open_connection()
     cursor = self.__db.cursor()
     result = None
     try:
         sql_query = """select user_id, username, email, entry_date from user where user_id = %s"""
         cursor.execute(sql_query, (user_id, ))
         dataset = cursor.fetchall()
         for user_id, user_name, email, entry_date in dataset:
             result = User(user_id, user_name, email, '', '', entry_date)
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
     finally:
         self.__close_connection(cursor)
     return result
예제 #30
0
def store(request):

    # if form.is_valid():
    if request.POST:
        role = request.POST.get('role')
        if role == 'p':
            form1 = Publisher()
        elif role == 'a':
            form1 = Advertiser()

        form1.name = request.POST.get('name')
        form1.contact = request.POST.get('contact_number')
        form1.email = request.POST.get('email')
        form1.avatar = request.FILES['image']

        form1.company_name = request.POST.get('company_name')
        form1.company_address = request.POST.get('company_address')
        form1.state = request.POST.get('state')
        form1.city = request.POST.get('city')
        created_at = datetime.datetime.now()
        form1.save()

        if role == 'p':
            record = Publisher.objects.all().order_by('-id')[0]
        elif role == 'a':
            record = Advertiser.objects.all().order_by('-id')[0]

        form_user = User()
        form_user.username = request.POST.get('username')
        form_user.password = request.POST.get('password')
        created_at = datetime.datetime.now()
        form_user.role = request.POST.get('role')
        form_user.uid = form1.id
        form_user.save()
        # instance = form.save(commit=False)
        # instance.save()
        # form = ImageUploadForm(request.POST, request.FILES)
        # if form.is_valid():
        #     if role == 'p':
        #         m = Publisher()
        #     elif role == 'a':
        #         m = Advertiser()
        #
        #     m.avatar = form.cleaned_data['image']
        #     m.save()

    return render(request, 'navigation.html')