Beispiel #1
0
 def get(self):
     if not self.current_user:
         self.redirect("/login")
         return
     user = User()
     user_list = user.get_by_username(self.current_user)
     self.render("index.html", user=user_list[0])
Beispiel #2
0
    def post(self):
        '''Register user'''
        try:
            data = api.payload
            username = data['username']
            hashed_password = generate_password_hash(data['password'],
                                                     method='sha256')
            new_user = User(username=username, password=hashed_password)
            new_user.insert_record()
            user = user_schema.dump(data)
            this_user = User.fetch_by_user(username)

            access_token = create_access_token(identity=this_user.id,
                                               expires_delta=False)
            return {
                'status': 'User added',
                'access token': access_token,
                'user': user
            }, 201
        except KeyError as e:
            api.abort(500,
                      e.__doc__,
                      status="Could not perform this action",
                      statusCode="500")
        except Exception as e:
            api.abort(400,
                      e.__doc__,
                      status="Could not perform this action",
                      statusCode="400")
Beispiel #3
0
    def post(self, *args, **kwargs):
        error_list = {"usererror": False, "pswerror": False, "message": ""}
        username = self.get_body_argument("username")
        password = self.get_body_argument("password")

        if username.strip() == "":
            error_list = {"usererror": True, "pswerror": False, "message": "User name cannot be empty."}
            self.render("sign-in.html", error=error_list)

        if password.strip() == "":
            error_list = {"usererror": False, "pswerror": True, "message": "Password cannot be empty."}
            self.render("sign-in.html", error=error_list)

        user = User()
        user_list = user.get_by_username(username)

        if not (len(user_list) == 1):
            error_list = {"usererror": True, "pswerror": False, "message": "User is not existed."}
            self.render("sign-in.html", error=error_list)

        _user = user_list[0]

        if not (_user.password == password):
            error_list = {"usererror": False, "pswerror": True, "message": "Password is not correct."}
            self.render("sign-in.html", error=error_list)
        else:
            self.set_secure_cookie("myinfo_user", _user.username)
            self.redirect("/home")
Beispiel #4
0
def factory(username="******",
            email="*****@*****.**",
            password="******"):
    hashed_pw = auth_logic.hash_password(password)
    user = User(username=username, email=email, password=hashed_pw)
    user.save()
    return user
Beispiel #5
0
def register_user(form):
    encoded_pw = form.password.data.encode('utf-8')
    hashed_password = auth_logic.hash_password(encoded_pw)
    user = User(username=form.username.data,
                email=form.email.data,
                password=hashed_password)
    user.save()
    return unicode(user.pk)
Beispiel #6
0
def create_db():
    """Creates database with some data populated."""
    db.drop_all()
    db.create_all()
    User.add_user_td()
    response_text = '{ "message": "Database created" }'
    response = Response(response_text, 200, mimetype='application/json')
    return response
Beispiel #7
0
 def can_close(self, user: User):
     if not user.is_banned() and not self.is_closed:
         if user.is_admin() or self.user_id == user.id:
             return True
         else:
             return False
     else:
         return False
Beispiel #8
0
def get_by_username(username):
    if User.get_user(username):
        return Response(str(User.get_user(username)),
                        200,
                        mimetype="application/json")
    else:
        return Response(error_message_helper("User not found"),
                        404,
                        mimetype="application/json")
Beispiel #9
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if User.find_by_username(data['username']):
            return {"message": "username already taken"}, 400

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

        return {"message": "user created"}, 201
Beispiel #10
0
    def post(self):
        data = request.get_json()

        if User.find_by_username(data['username']):
            return {"message": "User already exists"}

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

        return {"message": "User Created"}
Beispiel #11
0
def send_welcome(message):
    User.get_or_create_user(message)
    lng = get_lang(message)
    message_keyboard = ReplyKeyboardMarkup(one_time_keyboard=True,
                                           resize_keyboard=True,
                                           row_width=2)
    message_keyboard.add(*WORDS[lng]['start_keyboard'].values())
    bot.send_message(message.chat.id,
                     Texts.get_text('Greetings', lng),
                     reply_markup=message_keyboard)
Beispiel #12
0
    def get(self):
        if not self.current_user:
            self.redirect("/login")
            return

        _uid = self.get_argument("uid")
        user = User()
        user_list = user.get_by_uid(_uid)

        self.render("user.html", user=user_list[0])
    def test_verify_user(self):
        login = "******" + str(randint(-1000, 1000))

        password = "******"
        user = User(fullname="New user service user.",
                    login=login,
                    password=password)
        self.user_service.create_new_user(user)
        user2 = User(login=login, password=password)
        assert self.user_service.verify_user(user2) is not None
Beispiel #14
0
    def post(self, *args, **kwargs):

        error_list = {"usernameerror": False, "firstnameerror": False, "lastnameerror": False,
                      "emailerror": False, "passworderror": False, "message": ""}

        if self.current_user:
            self.redirect("/home")
            return

        _username = self.get_body_argument("username")
        _firstname = self.get_body_argument("firstname")
        _lastname = self.get_body_argument("lastname")
        _email = self.get_body_argument("email")
        _password = self.get_body_argument("password")

        if _firstname == "" or len(_firstname) > 20:
            error_list = {"usernameerror": False, "firstnameerror": True, "lastnameerror": False,
                      "emailerror": False, "passworderror": False, "message": "Firstname cannot be empty or length over 20."}
            self.render("sign-up.html", error=error_list)

        if _lastname == "" or len(_lastname) > 20:
            error_list = {"usernameerror": False, "firstnameerror": False, "lastnameerror": True,
                      "emailerror": False, "passworderror": False, "message": "Last name cannot be empty or length over 20."}
            self.render("sign-up.html", error=error_list)

        if _email == "" or len(_email) > 50:
            error_list = {"usernameerror": False, "firstnameerror": False, "lastnameerror": False,
                      "emailerror": True, "passworderror": False, "message": "Email cannot be empty or length over 50."}
            self.render("sign-up.html", error=error_list)

        if _password == "" or len(_password) > 50:
            error_list = {"usernameerror": False, "firstnameerror": False, "lastnameerror": False,
                      "emailerror": False, "passworderror": True, "message": "Password cannot be empty or length over 20."}
            self.render("sign-up.html", error=error_list)

        if _username == "" or len(_username) > 20:
            error_list = {"usernameerror": True, "firstnameerror": False, "lastnameerror": False,
                      "emailerror": False, "passworderror": False, "message": "Username cannot be empty or length over 20."}
            self.render("sign-up.html", error=error_list)

        user = User()
        user_list = user.get_by_username(_username)

        if len(user_list) > 0:
            error_list = {"usernameerror": True, "firstnameerror": False, "lastnameerror": False,
                      "emailerror": False, "passworderror": False, "message": "User name has already existed."}
            self.render("sign-up.html", error=error_list)
        else:
            r = user.insert(username=_username, first_name=_firstname, last_name=_lastname, password=_password,
                            email=_email)
            if r:
                self.redirect("/login")
            else:
                self.render("sign-up.html", error=error_list)
Beispiel #15
0
 def can_post(self, user: User):
     if user.is_banned():
         return False
     if self.is_writeable and not self.is_closed:
         return True
     elif not self.is_writeable and (
             self.user_id == user.id
             or user.is_admin()) and not self.is_closed:
         return True
     else:
         return False
Beispiel #16
0
        def wrap(*args, **kwargs):

            # If allow_user_permission is True, make sure the user has the appropriate permissions.
            if allow_user_permission and _check_user_permission(required_access_tokens, current_user):
                return func(*args, **kwargs)

            # Check and obtain API key from DB
            try:
                key = ApiKey.objects(key=request.headers['ApiKey']).first()
            except KeyError:
                return {'error': [{'message': "no/invalid ApiKey header provided", 'identifier': "apikey_not_provided"}]}, 403
            if key is None:
                return {'error': [{'message': "no/invalid ApiKey header provided", 'identifier': "apikey_not_provided"}]}, 403
            for access in required_access_tokens:
                if access not in key.access:
                    return {'error': [{'message': "api key doesn't have access to '%s'" % access, 'identifier': "permission#%s" % access}]}, 403

            # Check for the AsUser header, apply stuff to context
            if 'AsUser' in request.headers or 'AsPlayer' in request.headers:
                if 'api.as_user' not in key.access:
                    return {'error': [{'message': "api key doesn't have access to 'api.as_user', required for using the AsUser and AsPlayer headers", 'identifier': "permission#api.as_user"}]}, 403

                if 'AsUser' in request.headers:
                    username = request.headers['AsUser']

                    # Obtain user from db
                    user = User.get_user_by_name(username)
                    if user is None and asuser_must_be_registered:
                        return {'error': [{'message': "the user specified in the AsUser header wasn't found", 'identifier': "asuser_not_found"}]}, 403

                    request.api_user_method = 'as_user'
                    request.api_user = user
                    request.api_user_name = username
                elif 'AsPlayer' in request.headers:
                    uuid = request.headers['AsPlayer']

                    player = MinecraftPlayer.find_player(uuid)
                    if player is None:
                        return {'error': [{'message': "player uuid specified in AsPlayer header is not registered in database (has not logged in?)", 'identifier': "player_uuid_not_found"}]}, 403

                    user = User.get_user_by_uuid(player)
                    if user is None and asuser_must_be_registered:
                        return {'error': [{'message': "the uuid specified in the AsPlayer field is not owned by a website user", 'identifier': "asuser_not_found"}]}, 403

                    request.api_user_method = 'as_player'
                    request.api_user = user
                    request.api_user_name = user.name if user is not None else None
                    request.api_player = player
            else:
                request.api_user_method = 'key_owner'
                request.api_user = key.owner
                request.api_user_name = key.owner.name

            return func(*args, **kwargs)
def send_greetings(message):
    User.get_or_create_user(message)
    keyboard = ReplyKeyboardMarkup(resize_keyboard=True)
    keyboard.row('Категории', 'Корзина', 'История заказов')
    # keyboard.row(*config.START_KEYBOARD.values())
    if message.from_user.language_code == 'ru':
        bot.send_message(message.chat.id, Text.get_text('Ru greetings'),
                         reply_markup=keyboard)
    elif message.from_user.language_code == 'de':
        bot.send_message(message.chat.id, Text.get_text('Greetings'),
                         reply_markup=keyboard)
Beispiel #18
0
def update_email(username):
    request_data = request.get_json()
    try:
        jsonschema.validate(request_data, update_email_schema)
        # username is coming from url param, and email from json request body
        User.update_email(username, request_data['email'])
        response = Response('', 204, mimetype="application/json")
    except jsonschema.exceptions.ValidationError as exc:
        response = Response(error_message_helper(exc.message),
                            400,
                            mimetype="application/json")
    return response
    def post(self):
        user_info = request.get_json(force=True)
        existing_user = UserModel.query.filter_by(
            email=user_info['email']).first()
        if existing_user:
            return error_response(message="This email address" +
                                  " has been taken",
                                  status=409)
        new_user = UserModel(**user_info)
        new_user.save()

        return success_response(
            message="Your account has been created successfully",
            data=UserSchema(exclude=['password']).dump(new_user),
            status=201)
Beispiel #20
0
def send_welcome(message):
    try:
        # If who trigger the bot already triggered it, i just show the keyboard,
        # in case is a new user, i send it to a "welcome page" to get language and timezone
        if User.exist(user_id=message.chat.id):
            utilities_interaction_module(bot, User(
                message.chat.id)).show_keyboard(message)
        else:
            send_welcome_interaction_module(bot).send_welcome(message)

    except Exception as e:
        logging.error("-----------------------------------")
        logging.error("Error: " + str(e))
        logging.error("Message:" + str(message))
        logging.error("Function: send_welcome")
Beispiel #21
0
    def get(self, *args, **kwargs):
        if self.current_user:
            self.redirect("/home")
            return

        uid = self.get_argument("uid")
        if uid == "":
            print "error"
        else:
            _user = User()
            result = _user.delete_by_uid(uid)
            if result == "OK":
                self.redirect("/home")
            else:
                pass
Beispiel #22
0
def stats(origin_id, command_stack):
    try:
        origin_user = User(user_id=origin_id)

        if not pipocoin_util.does_user_exists_by_id(origin_user):
            return messages.stats.fail_not_registered_user()

        user = user_DAO.fetch_user_by_id(
            origin_user.get_id()
        )

        return messages.stats.success_get_stats(user)
    except Exception as e:
        print(e)
        return messages.stats.fail_error_occurred()
Beispiel #23
0
def language_or_greetings(message):
    if User.objects(user_id=message.from_user.id):
        language = User.objects.get(user_id=message.from_user.id).get_user_language
        Storage.language = language
        start_keyboard = START_KEYBOARD[language]
        s = u'\U0000270C'
        hello = s + Texts.objects.get(title='Greetings', language=language).text + f', {message.chat.first_name}'
        kb = ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(*start_keyboard.values())
        bot.send_message(message.chat.id, hello, reply_markup=kb)
    else:
        Storage.language = 'uk'
        User.get_or_create_user(message, 'uk')
        kb = ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(*START_KEYBOARD['uk'].values())
Beispiel #24
0
def add_user():
    request_data = request.get_json()
    try:
        jsonschema.validate(request_data, add_user_schema)
        User.add_user(request_data['username'], request_data['email'])
        response = Response(json.dumps(request_data),
                            201,
                            mimetype="application/json")
        response.headers['Location'] = "users/v1/" + str(
            request_data['username'])
    except jsonschema.exceptions.ValidationError as exc:
        response = Response(error_message_helper(exc.message),
                            400,
                            mimetype="application/json")
    return response
    def delete(self, id):
        '''Delete User'''
        my_user = User.fetch_by_id(id)
        user = user_schema.dump(my_user)
        if len(user) == 0:
            abort(400, 'User does not exist')

        claims = get_jwt_claims()
        authorised_user = get_jwt_identity()
        if claims['is_admin'] or id == authorised_user['id']:
            User.delete_by_id(id)
            return {'message': 'User deleted successfuly'}, 200

        abort(400,
              'You do not have the required permissions to delete this user!')
 def test_delete_user(self):
     userA = User(fullname='UserA',
                  login="******" + str(randint(-1000, 1000)),
                  password="******")
     self.repo.create_user(userA)
     self.repo.delete_user(userA)
     assert self.repo.get_user_by_id(userA.id) is None
Beispiel #27
0
def reset(what):
    if not current_user.has_permission('reset.{}'.format(what)):
        abort(403)

    form = ResetForm(request.form)
    user = User.objects(name=form.who.data).first()
    if user is None:
        abort(401)

    if form.validate():
        if what == 'password':
            password = ''.join(
                random.choice(
                    '0123456789abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
                ) for i in range(16))
            user.hash = bcrypt.hashpw(password, bcrypt.gensalt())
            user.save()
            return render_template('profile_reset_password_successful.html',
                                   user=user,
                                   password=password)
        elif what == 'tfa':
            user.tfa = False
            user.tfa_secret = ''
            user.save()
            return render_template('profile_reset_tfa_successful.html',
                                   user=user)
        else:
            abort(401)

    flash(
        'Error in reset form. Make sure you are typing the confirmation token correctly.',
        category='alert')
    return redirect(user.get_profile_url()), 303
Beispiel #28
0
def fetch_user_by_name(user_name):
    db_cursor = db_query(sql_queries.SQL_FETCH_USER_BY_NAME, (user_name,))
    row = db_cursor.fetchone()
    user = None
    if row:
        user = User(row["twitter_id"], row["user_name"], row["balance"])
    return user
Beispiel #29
0
def delete_user(username):
    resp = token_validator(request.headers.get('Authorization'))
    if "expired" in resp:
        return Response(error_message_helper(resp),
                        401,
                        mimetype="application/json")
    elif "Invalid token" in resp:
        return Response(error_message_helper(resp),
                        401,
                        mimetype="application/json")
    else:
        user = User.query.filter_by(username=resp).first()
        if user.admin:
            if bool(User.delete_user(username)):
                responseObject = {
                    'status': 'success',
                    'message': 'User deleted.'
                }
                return Response(json.dumps(responseObject),
                                200,
                                mimetype="application/json")
            else:
                return Response(error_message_helper("User not found!"),
                                404,
                                mimetype="application/json")
        else:
            return Response(
                error_message_helper("Only Admins may delete users!"),
                401,
                mimetype="application/json")
Beispiel #30
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = None
        user_data = user_db_conn.execute(
            "SELECT * FROM Users WHERE Username = ?",
            (form.username.data.lower(), )).fetchall()
        if user_data:
            user = User(user_data[0][0], user_data[0][1], user_data[0][2],
                        user_data[0][3], user_data[0][4])
        if user and bcrypt.check_password_hash(user.password,
                                               form.password.data):
            login_user(user, remember=form.remember.data)
            flash(f'Login successful for user {form.username.data}!',
                  'success')
            return redirect(url_for('home'))
        else:
            flash("Login failed- please check username and password", 'danger')
    elif request.method == 'POST' and form.errors:
        for error in form.errors:
            for str in form.errors[error]:
                flash(f"{error.capitalize()} error, {str}", 'danger')
    return render_template("login.html", form=form)
Beispiel #31
0
def profile_text_edit(name):
    if current_user.name != name and not current_user.has_permission(
            'profile.admin'):
        abort(404)
    user = User.objects(name=name).first()
    if user is None:
        abort(404)
    profile = get_profile(user)
    form = ProfileTextEditForm(request.form)

    if request.method == 'POST':
        if not form.validate():
            return render_template('profile_edit_text.html',
                                   profile=profile,
                                   form=form)

        profile.profile_text = form.text.data
        profile.save()
        return redirect(user.get_profile_url())

    form.text.data = profile.profile_text
    return render_template('profile_edit_text.html',
                           profile=profile,
                           form=form,
                           user=user,
                           title="Edit Profile - " + name + " - Profile")
Beispiel #32
0
    def post(self, *args, **kwargs):

        account = str(self.get_json_argument("account"))
        password = str(self.get_json_argument("password"))

        user = User.get_user_with_account(account)

        if user != None:
            if user.password == password:
                data = {
                    'code': '200',
                    'message': 'Success',
                    'user_info': {
                        'user_id': user.user_id,
                        'account': user.account,
                        'password': user.password,
                        'gender': user.gender,
                        'birthday': user.birthday,
                        'height': user.height,
                        'weight': user.weight
                    }
                }
                self.write(json.dumps(data))
            else:
                data = {'code': '300', 'message': 'wrong password'}
                self.write(json.dumps(data))
        else:
            data = {'code': '300', 'message': 'unexisted account'}
            self.write(json.dumps(data))
Beispiel #33
0
async def login(user: UserLogin):
    """
    Valida el acceso del usuario al sistema.
    :param user Usuario que se quiere conectar,  tiene atributos rut y password
    @return:  User que contiene la información requerida y el tokn correspondiente.
    """
    session = next(get_db())
    r = user.rut.strip().replace(".", "").replace("-", "")
    r = r.rjust(10, '0')
    vendedor = session.query(t_MSOVENDEDOR).filter(
        t_MSOVENDEDOR.c.rut == r, t_MSOVENDEDOR.c.tipo == 1).all()
    clave = session.query(t_EOS_USUARIOS).filter(
        t_EOS_USUARIOS.c.rut == r).all()

    if vendedor and clave:
        password_bytes = base64.b64decode(user.password)
        password = password_bytes.decode('ascii')
        m = hashlib.sha1(password.encode('utf-8'))
        if m.digest() == clave[0].password:
            upd = t_EOS_USUARIOS.update().where(
                t_EOS_USUARIOS.c.rut == r).values(
                    lastlogin=datetime.datetime.now())
            session.execute(upd)
            return User(code=vendedor[0].codigo,
                        name=vendedor[0].nombre,
                        rut=r,
                        token="123")
        else:
            raise HTTPException(status_code=400, detail="Clave incorrecta")

    raise HTTPException(status_code=400, detail="Usuario No encontrado")
Beispiel #34
0
def verify():
    form = VerifyForm(request.form)

    if request.method == "POST" and form.validate():
        # verify otp
        if session.get('tfa-logged-in', False) is not True:
            return redirect(url_for('auth.login'))

        user = User.objects(name=session['tfa-user']).next()

        ok, drift = accept_totp(format='dec6',
                                key=binascii.hexlify(base64.b32decode(user.tfa_secret)),
                                response=form.code.data,
                                drift=user.tfa_info.get('drift', 0))

        if not ok:
            form.errors['verify'] = ["Incorrect verification code."]
            return render_template('verify.html', form=form, title="Verify Login")

        if login_user(user, remember=session['tfa-remember']):
            user.tfa_info['drift'] = drift
            user.save()
            flash("Logged in!", category="success")
            return redirect(request.args.get("next", '/'))

    return render_template("verify.html", form=form, title="Verify Login")
Beispiel #35
0
def reset(what):
    if not current_user.has_permission('reset.{}'.format(what)):
        abort(403)

    form = ResetForm(request.form)
    user = User.objects(name=form.who.data).first()
    if user is None:
        abort(401)

    if form.validate():
        if what == 'password':
            password = ''.join(random.choice('0123456789abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(16))
            user.hash = bcrypt.hashpw(password, bcrypt.gensalt())
            user.save()
            return render_template('profile_reset_password_successful.html', user=user, password=password)
        elif what == 'tfa':
            user.tfa = False
            user.tfa_secret = ''
            user.save()
            return render_template('profile_reset_tfa_successful.html', user=user)
        else:
            abort(401)

    flash('Error in reset form. Make sure you are typing the confirmation token correctly.', category='alert')
    return redirect(user.get_profile_url()), 303
Beispiel #36
0
def delete_user(username):
    if User.delete_user(username):
        response = Response('', 204)
    else:
        response = Response(json.dumps(invalid_delete_error_msg_users),
                            404,
                            mimetype="application/json")
    return response
    def view(self, session: Session, **kwargs):
        if self.form.validate_on_submit():
            user = User(
                login=self.form.login.data,
                email=self.form.email.data,
                nickname=self.form.nickname.data,
                sex=self.form.sex.data,
            )
            user.set_password(self.form.password.data)
            status = DataBaseWorker.add_user(session, user)
            if status == "ok":
                return redirect("/login")
            else:
                return super(RegisterController, self).view(form=self.form, error=status)

        else:
            return super(RegisterController, self).view(form=self.form)
Beispiel #38
0
def authenticate_user(username, password, message="Invalid username or password."):
    user = User.objects(name__iexact=username).first()
    if user is None:
        raise LoginException(message)
    if user.hash == bcrypt.hashpw(password, user.hash):
        return user
    else:
        raise LoginException(message)
Beispiel #39
0
    def get(self):
        users = User.objects(Q(role_groups__exists=True) & Q(role_groups__not__size=0)).scalar('name', 'role_groups')

        user_groups = dict()
        for name, groups in users:
            user_groups[name] = dict(groups=map(lambda group: group.name, groups))

        return {'users': user_groups}
Beispiel #40
0
def fetch_all_users():
    db_cursor = db_query(sql_queries.SQL_FETCH_ALL_USERS)
    rows = db_cursor.fetchall()
    users = []
    for row in rows:
        user = User(row["twitter_id"], row["user_name"], row["balance"])
        users.append(user)
    return users
Beispiel #41
0
def check_username(username):
    if len(username) < 4:
        return False, error_messages.value_too_short

    username_taken = len(User.objects(username=username)) > 0
    if username_taken:
        return False, error_messages.username_taken

    return True, None
def view_staff():
    listings_data = dict()
    for listing in listings:
        data = User.objects(role_groups__in=[Role_Group.objects(name=listing["id"]).first()]).only('name')
        data = list(data)
        shuffle(data)
        listings_data[listing["id"]] = data

    return render_template('staff_view_staff.html', data=listings_data, listings=listings, title="Staff")
Beispiel #43
0
def add_role(username, role):
    from models.user_model import User

    user = User.objects(name=username).first()
    if user is None:
        print("no user was found with that name")

    user.roles.append(role)
    user.save()

    print("success!")
Beispiel #44
0
def login():
    form = LoginForm(request.form)
    if request.method == "POST" and form.validate():
        user = User.get_by_login_credentials(form.username_or_email.data, form.password.data)
        if user:
            login_user(user)
            return redirect(url_for("index"))
        else:
            message = "Username or password incorrect."
            return message

    return "Login: %s" % str(form.errors)
Beispiel #45
0
def profile_view(name):
    user = User.objects(name=name).first()
    if user is None:
        abort(404)

    forum_info = ForumInfo(user)

    profile = get_profile(user)

    reset_form = ResetForm()

    return render_template('profile_view.html', user=user, forum_info=forum_info, profile=profile, render_badges=render_badges, title="{} - Profile".format(user.name), reset_form=reset_form)
Beispiel #46
0
def check_email(email):
    if len(email) < 6:
        return False, error_messages.value_too_short

    email_valid = validate_email(email)
    if not email_valid:
        return False, error_messages.email_invalid

    email_exists = len(User.objects(email=email)) > 0
    if email_exists:
        return False, error_messages.email_taken

    return True, None
Beispiel #47
0
def register_pool(username):
    if current_user.is_authenticated():
        flash("You are already logged in. Log out to register another account.", category="alert")
        return redirect(url_for('static_pages.landing_page'))

    if User.objects(name=username).first() is not None:
        flash("This user is already registered.", category="alert")
        return redirect(url_for('auth.login'))

    #Is verified
    auth_check = check_authenticated_ip(request.remote_addr, username=username)
    if auth_check:
        form = RegistrationForm(request.form)

        if request.method == "GET":
            return render_template('register_3.html', username=username, form=form, title="Step 3 - Register")

        elif request.method == "POST":
            if form.validate():
                uuid = auth_check.uuid.hex
                player = MinecraftPlayer.find_or_create_player(uuid, auth_check.username)
                user = User(
                    name=username,
                    hash=bcrypt.hashpw(form.password.data, bcrypt.gensalt()),
                    mail=form.mail.data,
                    minecraft_player=player)
                user.save()
                flash("Registration complete!", category="success")
                return redirect(url_for('auth.login'))
            return render_template('register_3.html', username=username, form=form, title="Step 3 - Register")

    #Is not verified
    else:
        if request.method == "GET":
            return render_template('register_2.html', username=username, title="Waiting... - Step 2 - Register")
        else:
            abort(405)
 def initialize(self, *args, **kwargs):
     RequestHandler.initialize(self, *args, **kwargs)
     uid = self.read_secure_cookie('user_id')
     self.user = uid and User.by_id(int(uid))
     self.url = self.request.route_args[0] if len(self.request.route_args) > 0 else '/'
     v = self.request.get('v')
     if v and v.isdigit():
         self.v = int(v)
         p = Page.by_id(int(self.v), self.url)
         if p:
             self.page = p
         else:
             self.error(404)
     else:
         self.page = Page.by_url(self.url)
    def post(self):
        prev_url = str(self.request.get('prev_url'))
        if not prev_url or prev_url.startswith('/login'):
            prev_url = '/'
        user_name = self.request.get('username')
        user_pass = self.request.get('password')

        user = User.login(user_name, user_pass)

        if user:
            self.login(user)
            self.redirect(prev_url)
        else:
            error = 'Either the username or the password wasn\'t valid'
            self.render_page(name=user_name, error=error)
Beispiel #50
0
 def task(self, task, full = False):
     line = '  '
     username = str(User.find(task.assignedUser).username)
     if task.status == 0:
         line += self.RED+''
         color = self.RED
     elif task.status == 1:
         line += self.YELLOW+''
         color = self.YELLOW
     elif task.status == 2:
         line += self.GREEN+''
         color = self.GREEN
     line += ' #'+str(task._id) +'  '+str(task.title) +self.BOLD+'  @'+username+self.END_FORMAT
     if full:
         line += color+'\n   type: task\t   status: '+task.getStatus(True)+'\n  '
         line += str(task.details)+self.END_FORMAT+'\n'
     print line
Beispiel #51
0
 def bug(self, bug, full = False):
     line = '  '
     username = str(User.find(bug.assignedUser).username)
     if bug.status == 0:
         line += self.RED+''
         color = self.RED
     elif bug.status == 1:
         line += self.YELLOW+''
         color = self.YELLOW
     elif bug.status == 2:
         line += self.GREEN+''
         color = self.GREEN
     line += ' #'+str(bug._id) +'  '+str(bug.title) +self.BOLD+'  @'+username+self.END_FORMAT
     if full:
         line += color+'\n   type: bug\t   status: '+bug.getStatus(True)+'\n  '
         line += str(bug.details)+self.END_FORMAT+'\n'
     print line
Beispiel #52
0
def profile_text_edit(name):
    if current_user.name != name and not current_user.has_permission('profile.admin'):
        abort(404)
    user = User.objects(name=name).first()
    if user is None:
        abort(404)
    profile = get_profile(user)
    form = ProfileTextEditForm(request.form)

    if request.method == 'POST':
        if not form.validate():
            return render_template('profile_edit_text.html', profile=profile, form=form)

        profile.profile_text = form.text.data
        profile.save()
        return redirect(user.get_profile_url())

    form.text.data = profile.profile_text
    return render_template('profile_edit_text.html', profile=profile, form=form, user=user, title="Edit Profile - " + name + " - Profile")
    def post(self):
        prev_url = str(self.request.get('prev_url'))
        if not prev_url or prev_url.startswith('/login'):
            prev_url = '/'
        error_msg = ''
        user_name = self.request.get('username')
        user_pass = self.request.get('password')
        user_verify = self.request.get('verify')
        user_email = self.request.get('email')

        valid_user, valid_pass, valid_email, in_use = (
            self.valid_username(user_name),
            self.valid_password(user_pass),
            self.valid_email(user_email),
            self.username_in_use(user_name)
        )

        if not valid_user:
            error_msg += 'Please enter a 3-20 character username of alphanumeric characters, dashes or underscores.<br>'
        if in_use:
            error_msg += 'Username already in use, choose another.<br>'
        if valid_pass and not (user_pass == user_verify):
            error_msg += 'Both passwords do not match.<br>'
        if not valid_pass:
            error_msg += 'Please enter a password at least 8 characters long.<br>'
        if not valid_email:
            error_msg += 'Please enter a valid email address.<br>'

        if len(error_msg) > 0:
            self.render_page(name=user_name, email=user_email,
                             error=error_msg, prev_url=prev_url)
        else:
            user = User.register(name=user_name, password=user_pass,
                                 email=user_email)
            user.put()
            if user:
                self.login(user)
                self.redirect(prev_url)
 def username_in_use(self, username):
     return User.by_name(username)
Beispiel #55
0
 def run(self):
     arg = ''
     if len(self.argq) > 0:
         arg = self.argq.popleft()
     if arg == '' or arg == 'all':
         bugs = Bug.all()
         for bug in bugs:
             w.bug(bug)
     elif arg == '+' or arg == 'add':
         if len(self.argq) > 0:
             # Si se pasaron los datos de manera directa
             pass
         title = raw_input('Ingrese título >>> ')
         details = raw_input('Ingrese detalles\n>>> ')
         bug = Bug()
         bug.title = title
         bug.details = details
         bug.status = 0
         users = User.all()
         for user in users:
             #print '\t'+str(user)
             w.user(user)
         assignedUser = raw_input('Ingrese ID del usuario asignado (Por defecto, su usuario)\n#')
         if assignedUser == '':
             bug.assignedUser = User.find(Config.getUser().username, False)._id
         else:
             bug.assignedUser = assignedUser
         # Pendiente el manejo de errores de ingreso
         bug.AsignedUser = 2
         if bug.save():
             #w.success('')
             pass
         else:
             w.error("Error al guardar")
     elif arg == 'del' or arg == '-d':
         if len(self.argq) < 1:
             w.error('No eligió ningun elemento para borrar. Pruebe alguno de los siguientes comandos')
             w.warning('  track -t -d \#1', True, '\t#1 para el elemento cuyo id es 1')
         else:
             arg = self.argq.popleft()
             if arg.find('#') > -1:
                 _id = int(arg[1:])
             else:
                 _id = int(arg)
             bug = Bug.find(_id)
             if bug == None:
                 w.error('No existe el elemento: '+str(arg))
                 exit()
             if bug.delete():
                 w.success(' '+bug.title, True, ' eliminado')
     elif arg == 'me' or arg == '-m':
         #tareas asignadas a mí
         user = User.find(Config.getUser().username, False)
         bugs = user.bugs()
         for bug in bugs:
             w.bug(bug)
         pass
     elif arg == 'list' or arg == '-l':
         # Mostrar lista de comandos con ejemplo
         self.showCommandsList()
     elif arg == '-h' or arg == 'help':
         # Mostrar ayuda
         self.showHelp()
     else:
         if arg.find('#') > -1:
             #Si se quiere ver una tarea en especifico
             bug = Bug.find(int(arg[1:]))
             w.bug(bug, True)
         elif arg.find('@')  > -1:
             # Las tareas de un usuario en especifico
             user = User.find(arg[1:], False)
             if user == None:
                 w.error('No existe el usuario: '+str(arg))
                 exit()
             bugs = user.bugs()
             if len(bugs) < 1:
                 w.success(arg+' no tiene elementos "bug" asignados')
                 exit()
             for bug in bugs:
                 w.bug(bug, True)
         else:
             print 'Parámetro desconocido. Puede probar los siguientes:'
             print '\ttracker bugs [-b] list [-l]\tLista de comandos'
             print '\ttracker bugs [-b] help [-h]\tAyuda'
             print 'Si se omite el parámetro, se listan todos los elementos'
def resolve_user(doc):
    user = User.objects(minecraft_player=doc.player).first()

    if doc.user != user:
        doc.user = user
Beispiel #57
0
def user_loader(id):
    user = User.objects(name__iexact=id).first()
    return user
Beispiel #58
0
    def run(self):
        arg = ''
        if len(self.argq) > 0:
            arg = self.argq.popleft()
        if arg == '' or arg == 'all':
            users = User.all()
            for user in users:
                w.user(user)
        elif arg == '+' or arg == 'add':
            if len(self.argq) > 0:
                # Si se pasaron los datos de manera directa
                pass
            name = raw_input('Ingrese nombre>>> ')
            username = raw_input('Ingrese nombre de usuario>>> ')
            email = raw_input('Ingrese email>>> ')
            user = User()
            user.name = name
            user.username = username
            user.email = email
            if user.save():
                #w.success('')
                pass
            else:
                w.error("Error al guardar")
        elif arg == 'del' or arg == '-d':
            if len(self.argq) < 1:
                w.error('No eligió ningun elemento para borrar. Pruebe alguno de los siguientes comandos')
                w.warning('  track -u -d \#1', True, '\t#1 para el elemento cuyo id es 1')
                w.warning('  track -u -d @username', True, '\t@username para borrar a @username')
            else:
                arg = self.argq.popleft()
                if arg.find('#') > -1:
                    user = User.find(int(arg[1:]))
                    if user == None:
                        w.error('No existe el usuario: '+str(arg))
                        exit()
                elif arg.find('@')  > -1:
                    user = User.find(arg[1:], False)
                    if user == None:
                        w.error('No existe el usuario: '+str(arg))
                        exit()
                if user.delete():
                    w.success('@'+user.username, True, ' eliminado')

        elif arg == 'me' or arg == '-m':
            #tareas asignadas a mí
            user = User.find(Config.getUser().username, False)
            if user != None:
                w.user(user, True)
        elif arg == 'list' or arg == '-l':
            # Mostrar lista de comandos con ejemplo
            self.showCommandsList()
        elif arg == '-h' or arg == 'help':
            # Mostrar ayuda
            self.showHelp()
        else:
            if arg.find('#') > -1:
                #Si se quiere ver una tarea en especifico
                user = User.find(int(arg[1:]))
                if user != None:
                    w.user(user, True)
                    exit()
            elif arg.find('@')  > -1:
                # Las tareas de un usuario en especifico
                user = User.find(arg[1:], False)
                if user == None:
                    w.error('No existe el usuario: '+str(arg))
                    exit()
                w.user(user, True)
            else:
                print 'Parámetro desconocido. Puede probar los siguientes:'
                print '\ttracker users [-u] list [-l]\tLista de comandos'
                print '\ttracker users [-u] help [-h]\tAyuda'
                print 'Si se omite el parámetro, se listan todos los elementos'