Exemple #1
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for("home"))

    if request.method == "GET":
        return render_template("auth/register.html", user=current_user)

    username = request.form.get("username")
    password = request.form.get("password")
    if not (username and len(username) >= 3 and password
            and len(password) >= 4):
        return render_template(
            "auth/register.html",
            error_text="Username has to be at least 3 symbols and pass min 5",
            user=current_user,
        )
    if Session.query(User).filter_by(username=username).count():
        return render_template(
            "auth/register.html",
            error_text=f"Username {username!r} already exists!",
            user=current_user,
        )

    user = User(username, password)
    Session.add(user)

    try:
        Session.commit()
    except Exception as e:
        logger.exception("Error creating user!")
        raise InternalServerError(f"Could not create new user! Error: {e}")

    login_user(user)
    return redirect(url_for("home"))
Exemple #2
0
class BaseHandler(tornado.web.RequestHandler, SessionMixin):
    def get_current_user(self):
        return self.session.get('username_session')

    def initialize(self):
        self.db_session = Session()
        self.orm = OrmHandler(self.db_session)

    def on_finish(self):
        self.db_session.close()
Exemple #3
0
 def get(self, user_id):
     session = Session()
     rows = session.query(User).filter_by(id=user_id).first()
     session.delete(rows)
     session.commit()
     session.close()
     self.redirect('/administrator')
Exemple #4
0
 def get(self, quote_id):
     session = Session()
     rows = session.query(Quotes).filter_by(id=quote_id).first()
     session.delete(rows)
     session.commit()
     session.close()
     self.redirect('/quotes')
Exemple #5
0
def registration():
    form = RegistrationForm()
    if request.method == "POST" and form.validate():
        user = User(username=form.username.data, password=form.password.data)
        Session.add(user)
        Session.commit()

        flash(message=f'Пользователь {user.username} успешно зарегистрирован',
              category='success')
        return redirect(url_for("auth_app.login"))
    return render_template("auth/registration.html", form=form)
Exemple #6
0
def update_post(post_id):
    post = Session.query(Post).filter_by(id=post_id).first()
    form = PostForm(obj=post)
    if request.method == "POST" and form.validate():
        post.title = request.form.get('title')
        post.text = request.form.get('text')
        post.image_url = request.form.get('image_url')

        Session.commit()
        return redirect(url_for("main"))
    return render_template("posts/update.html", form=form, post_id=post.id)
Exemple #7
0
class BaseHandler(tornado.web.RequestHandler, SessionMixin):
    def get_current_user(self):
        return self.session.get('tudo_user', None)

    def prepare(self):
        self.db_session = Session()
        logger.info('db_session instance {}'.format(self))
        self.orm = HandlerORM(self.db_session)

    def on_finish(self):
        self.db_session.close()
        logger.info('db_session close')
Exemple #8
0
def add_post(img_url, thumb_url, username):
    session = Session()
    user = session.query(User).filter_by(username=username).first()
    post = Post(image_url=img_url, thumb_url=thumb_url, user_id=user.id)
    session.add(post)
    session.commit()
    post_id = post.id
    session.close()
    return post_id
Exemple #9
0
def create_post():
    form = PostForm()
    if request.method == "POST" and form.validate():
        post = Post(
            title=request.form.get('title'),
            text=request.form.get('text'),
            image_url=request.form.get('image_url'),
            user_id=current_user.id
        )
        Session.add(post)
        Session.commit()
        return redirect(url_for("main"))
    return render_template("posts/create.html", form=form)
Exemple #10
0
def new_post():
    if not current_user.is_authenticated:
        return redirect(url_for("index.html"))
    if request.method == "GET":
        return render_template("new_post.html")
    form = request.form
    post_text = form['post_text']
    post = Post(post_text, current_user.id)
    Session.add(post)
    try:
        Session.commit()
    except Exception as e:
        logger.exception("Error creating post!")
        raise InternalServerError(f"Could not create new post! Error: {e}")
    return redirect(url_for("index"))
Exemple #11
0
class UserManager:

    _DB = Session()

    @classmethod
    def find(cls, user_id: int) -> User:
        return cls._DB.query(User).get(user_id)

    @classmethod
    def get(cls) -> List[User]:
        return cls._DB.query(User).all()

    @classmethod
    def get_by_email(cls, email: str) -> User:
        return cls._DB.query(User).filter_by(email=email).first()

    @classmethod
    def save(cls, data) -> User:
        password = Crypt.hash(data.password)
        user = User(email=data.email, password=password)
        cls._DB.add(user)
        cls._DB.commit()
        return user

    @classmethod
    def delete(cls, user_id: int) -> bool:
        user = cls.get_user(user_id)
        if not user:
            return False
        cls._DB.delete(user)
        cls._DB.commit()
        return True
Exemple #12
0
def get_all_posts(username=None):
    '''
    查询获取所有图片或者是特定的用户
    :param username:如果没做,就是获取全部图片
    :return:
    '''
    session = Session()
    if username:
        user = session.query(User).filter_by(username=username).first()
        posts = session.query(Post).filter_by(user=user).all()

    else:
        posts = session.query(Post).all()
    if posts:
        return posts
    else:
        return []
Exemple #13
0
def login():
    form = LoginForm()
    if request.method == "POST" and form.validate():
        user = Session.query(User).filter_by(
            username=form.username.data).first()
        login_user(user)
        return redirect(url_for("main"))
    return render_template("auth/login.html", form=form)
Exemple #14
0
def sign_in():
    if current_user.is_authenticated:
        return redirect(url_for("index"))

    if request.method == "GET":
        return render_template("sign_in.html")

    username, password = get_username_and_password_from_form(request.form)
    validate_username_unique(username)
    user = User(username, password)
    Session.add(user)

    try:
        Session.commit()
    except Exception as e:
        logger.exception("Error creating user!")
        raise InternalServerError(f"Could not create new user! Error: {e}")
    login_user(user)
    return redirect(url_for("index"))
Exemple #15
0
 def post(self, quote_id):
     author = self.get_argument('author', '')
     country = self.get_argument('country', '')
     content = self.get_argument('content', '')
     session = Session()
     session.query(Quotes).filter_by(id=int(quote_id)).update({Quotes.author: author, Quotes.country: country,Quotes.quotes_content: content})
     session.commit()
     self.redirect('/quotes')
Exemple #16
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("index.html"))
    if request.method == "GET":
        return render_template("login.html")
    username, password = get_username_and_password_from_form(request.form)
    user = Session.query(User).filter_by(username=username).one_or_none()
    if not user:
        return render_template("login.html", error_text="User not found")
    if user.password != User.hash_password(password):
        return render_template("login.html",
                               error_text="Invalid username or password!")
    login_user(user)
    print("Uid:", user.id)
    return redirect(url_for("index"))
Exemple #17
0
def add_post():

    if request.method == "GET":
        return render_template("post/add_post.html", user=current_user)

    title = request.form["title"]
    text = request.form["text"]
    if not title:
        return render_template(
            "post/add_post.html", error_text="Title can't be empty", user=current_user
        )
    if not text:
        return render_template(
            "post/add_post.html", error_text="Text can't be empty", user=current_user
        )
    new_post = Post(title, text, current_user.id)
    Session.add(new_post)
    try:
        Session.commit()
    except Exception as e:
        logger.exception("Error creating post!")
        raise InternalServerError(f"Could not create new post! Error: {e}")

    return redirect(url_for("home"))
Exemple #18
0
def register(username, password1, password2):
    ret = {'msg': 'other error', 'user_id': None}
    if username and password1 and password2:
        if password1 == password2:
            session = Session()
            user = session.query(User).filter_by(username=username).all()
            if user:
                msg = 'username is exists'
            else:
                new_user = User(username=username, password=hash(password1))
                session.add(new_user)
                session.commit()
                ret['user_id'] = new_user.id
                session.close()
                msg = 'ok'
        else:
            msg = 'password1 != password2'
    else:
        msg = 'username or password is empty'
    ret['msg'] = msg
    return ret
Exemple #19
0
 def post(self, user_id):
     username = self.get_argument('username', '')
     password = self.get_argument('password', '')
     email = self.get_argument('email', '')
     gender = self.get_argument('gender', '')
     age = self.get_argument('age', ' ')
     power = self.get_argument('power', '')
     session =Session()
     session.query(User).filter_by(id=int(user_id)).update({User.username: username, User.password: password, User.emial: email, User.gender: gender, User.age: age,User.power: int(power)})
     session.commit()
     self.redirect('/administrator')
Exemple #20
0
 def post(self):
     username = self.get_argument('username', '')
     username1 = self.get_argument('username1', '')
     password = self.get_argument('password', '')
     email = self.get_argument('email', '')
     gender = self.get_argument('gender', '')
     age = self.get_argument('age', ' ')
     session = Session()
     dict_data = {User.username:username1,User.password:password, User.emial:email,User.gender:gender,User.age:age}
     session.query(User).filter_by(username=username).update(dict_data)
     session.commit()
     self.redirect('/')
Exemple #21
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("home"))

    if request.method == "GET":
        return render_template("auth/login.html", user=current_user)

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

    user = Session.query(User).filter_by(username=username).one_or_none()

    if not user:
        return render_template("auth/login.html", error_text="User not found")

    if user.password != User.hash_password(password):
        return render_template(
            "auth/login.html",
            error_text="Invalid username or password!",
            user=current_user,
        )

    login_user(user)
    return redirect(url_for("home"))
Exemple #22
0
 def is_exists(cls, username, password):
     session = Session()
     ret = session.query(exists().where(
         and_(User.name == username, User.password == password))).scalar()
     session.close()
     return ret
Exemple #23
0
 def validate_username(self, field):
     if len(field.data) < 6:
         field.errors.append('Логин должен быть не менее 6 символов')
     if Session.query(User).filter_by(username=field.data).first():
         field.errors.append(
             'Пользователь с таким логином уже зарегистрирован')
Exemple #24
0
 def get_user(self, username):
     return Session.query(User).filter_by(username=username).first()
Exemple #25
0
def remove_session(*args):
    Session.remove()
Exemple #26
0
def main():
    posts = Session.query(Post).order_by(Post.created)
    return render_template("index.html", posts=posts)
Exemple #27
0
def load_user(user_id):
    return Session.query(User).filter_by(id=user_id).one_or_none()
Exemple #28
0
from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import exists

from models.db import Base, Session

session = Session()


class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), unique=True, nullable=False)
    password = Column(String(50))
    creatime = Column(DateTime, default=datetime.now)
    email = Column(String(80))

    def __repr__(self):
        return "<User表:id:{},username:{}>".format(self.id, self.username)

    @classmethod
    # 定义一个查询用户是否存在的方法
    def is_exists(cls, username):
        return session.query(exists().where(cls.username == username)).scalar()

    @classmethod
    def get_password(cls, username):
        user = session.query(cls).filter_by(username=username).first()
        if user:
            return user.password
Exemple #29
0
 def initialize(self):
     self.db_session = Session()
     self.orm = OrmHandler(self.db_session)
Exemple #30
0
import hashlib
from models.auth import User, Post, Like
from models.db import Session

db_session = Session()


def hashed(text):
    """
    密码md5加密
    :param text: password
    :return:
    """
    return hashlib.md5(text.encode('utf8')).hexdigest()


def authenticate(username, password):
    """
    验证密码
    :param username:
    :param password:
    :return:
    """
    return User.get_password(username) == hashed(password)  # 返回bool值


class HandlerORM:
    """
    辅助操作数据库的工具类, 综合 RequestHandler使用
    """
    def __init__(self, db_session):