Exemplo n.º 1
0
def reg():
    if request.method == "GET":
        return ops_render("member/reg.html")
    req = request.values  # 如果值在里面则取,不在则取空
    login_name = req['login_name'] if "login_name" in req else ""
    login_pwd = req['login_pwd'] if "login_pwd" in req else ""
    login_pwd2 = req['login_pwd2'] if "login_pwd2" in req else ""

    #后端输入验证
    if login_name is None or len(login_name) < 1:
        return ops_renderErrorJSON(msg="请输入正确的管理员账户名")
    if login_pwd is None or len(login_pwd) < 6:
        return ops_renderErrorJSON(msg="请正确输入管理员账户密码,并且不能小于6个字符!")
    if login_pwd != login_pwd2:
        return ops_renderErrorJSON(msg="请确认管理员账户密码!")
    #后端数据库信息验证

    user_info = User.query.filter_by(login_name=login_name).first()
    if user_info:
        return ops_renderErrorJSON(msg="此管理员账户名已存在,请重新输入!")

    model_user = User()  #model实例化
    model_user.login_name = login_name
    model_user.login_salt = UserService.geneSalt(8)
    model_user.login_pwd = UserService.genePwd(login_pwd,
                                               model_user.login_salt)
    model_user.created_time = model_user.updated_time = getCurrentTime()
    db.session.add(model_user)
    db.session.commit()

    return ops_renderJSON(msg="注册提交成功,等待审核!")
Exemplo n.º 2
0
def reg(req):
    back = {'state':'ok'}
    q = req.GET or req.POST
    uname = q.get('uname')
    passwd = q.get('passwd')
    r = User.objects.filter(uname=uname)
    if r:
        back['state'] = 'error'
        back['msg'] = '账号已注册'
        loggerInfo('reg error:'+back['msg'])
    else:
        u = User(uname=uname,passwd=passwd)
        u.save()
        back['msg'] = '注册成功'
        loggerInfo('reg ok:'+back['msg']+':'+str(u.pk))
    return to_json(back)
Exemplo n.º 3
0
    def post_token(self):
        session = Session()
        if session.get("logged_in") == "true":
            session.extend()
            return redirect("/auth/login")

        from utils.format_checker import nyu_email_check
        email = request.form.get("email")
        print("email_received:", email)
        if not nyu_email_check(email):
            logbook.info("[GET EMAIL TOKEN] Wrong email format")
            return {"status": False, "message": "Email is of wrong format. Please provide NYU email"}

        query = User.select().where(User.email == email)
        if request.form.get("reset_password") == "true" and not(query.exists()):
            return {"status": False, "message": "This email has not been registered yet. Please register first"}

        if request.form.get("reset_password") != "true" and query.exists():
            return {"status": False, "message": "This email has been registered"}

        token = TokenGenerator.generate()
        session["token"] = token
        session["email"] = email
        session.expire(600)
        email_helper = EmailHelper(receiver_email=email)
        email_helper.send_token(token)
        return {"status": True, "message": "A token has been sent to your mail box"}
Exemplo n.º 4
0
 def post(self):
     # 创建请求解析器对象
     parser = RequestParser()
     # 添加参数规则
     parser.add_argument('mobile', location='json', required=True)
     parser.add_argument('code', location='json', required=True)
     # 执行解析
     args = parser.parse_args()
     # 获取参数
     mobile = args.mobile
     code = args.code
     from app import redis_client
     key = f'{mobile}'
     # 从redis数据库获取验证码
     r_code = redis_client.get(key)
     # 如果验证码不存在或验证码不相等
     if not r_code or r_code != code:
         return {'message': 'failure', 'data': None}
     user = User.query.options(load_only(User.mobile)).filter(User.mobile == mobile).first()
     # 如果用户存在记录最后一次登陆时间
     if user:
         user.last_login = datetime.now()
     # 如果不存在注册新用户,用户名字为手机号
     else:
         user = User(mobile=mobile, name=mobile, last_login=datetime.now())
         db.session.add(user)
     db.session.commit()
     token = generate_jwt({'user_id': user.id},
                          expiry=datetime.utcnow() + timedelta(days=current_app.config['JWT_EXPIRE_DAYS']))
     return {'token': token}
Exemplo n.º 5
0
def reg():
    if request.method == "GET":
        return render_html("/member/reg.html")

    req = request.values
    login_name = req['log_name'] if 'log_name' in req else ""
    login_pwd = req['log_pwd'] if 'log_pwd' in req else ""
    re_pwd = req['re_pwd'] if 're_pwd' in req else ""

    if len(login_name) < 5:
        return render_error("用户名需长于5个字符")

    if len(login_pwd) < 6:
        return render_error("请输入正确的密码, 不得短于6个字符")

    if login_pwd != re_pwd:
        return render_error("两次密码不一致")

    user_info = User.query.filter_by(login_name=login_name).first()

    if user_info:
        return render_error("用户名已被注册,请更换~")

    now_user = User()
    now_user.login_name = login_name
    now_user.nickname = login_name
    now_user.login_salt = PasswordUtil.gen_salt()
    now_user.login_pwd = PasswordUtil.gen_password(login_pwd,
                                                   now_user.login_salt)
    now_user.created_time = UrlManager.get_current_time()
    db.session.add(now_user)
    db.session.commit()
    return render_json(code=200, msg="注册成功", data={})
Exemplo n.º 6
0
def collect_predictions():
    logger.info("Getting fixture with status `posted_thread`")
    fixture_list = list(Fixture.status_index.query("posted_thread", limit = 1))

    if(len(fixture_list)) > 0:
        f = fixture_list[0]
        logger.info("Fixture: {} found. Checking if it started...".format(f.fixture_id))
        if time.time() > f.start_time:
            try:
                logger.info("Fixture {} started. Getting submission for the fixture".format(f.fixture_id))
                sub = list(Submission.fixture_index.query(f.fixture_id))[0]
                logger.info("Type of sub : {}".format(type(sub)))
                logger.info("Submission `{}` found".format(sub.submission_id))
                user_predictions = bot.crawl_predictions(sub.submission_id)
                logger.info("Gathered `{}` user predictions for fixture: {}".format(len(user_predictions), f.fixture_id))
                new_user_list = list()
                for up in user_predictions:
                    
                    lines = up['body'].split('\n')
                    result = extract_result(lines)
                    if result:
                        prediction = Prediction(fixture=f.fixture_id, result = result, posted_at= up['posted_at'], points = 0)
                        existing_user_result = list(User.query(up['name']))
                        if len(existing_user_result) > 0:
                            existing_user = existing_user_result[0]
                            existing_user.prediction_history.append(existing_user.curr_prediction)
                            existing_user.curr_prediction = prediction
                            existing_user.save()
                        else:
                            new_user = User(user_id=up['name'], total_points=0, points_per_league = dict(), curr_prediction=prediction, prediction_history=list())
                            new_user_list.append(new_user)
                        
                if len(new_user_list) > 0:
                    logger.info("Inserting new user predictions of size: {}".format(len(new_user_list)))
                    for u in new_user_list:
                        u.save()
                        
                logger.info("Changing status of fixture from `posted_thread` to `collected_predictions`")
                f.status = "collected_predictions"
                f.save()
            except Exception:
                logging.exception("Error while collecting predictions for fixture:{}".format(f.fixture_id))

    else:
        logger.info("No fixture found with the status `posted_thread`")
Exemplo n.º 7
0
    def get_reset_password(self):
        session = Session()
        if session.get("logged_in") == " true":
            session.extend()
            return redirect("/homepage")
        if session.get("reset_password_email_verified") != "true":
            return redirect("/auth/reset_password_email_verify")

        email = session.get("email")
        password = request.form.get("password")
        from utils.format_checker import (
            password_checker
        )
        password_check = password_checker(password)
        if not password_check:
            return {"status": False, "message": "Bad password format"}
        hashed_pwd = MD5Helper.hash(password)
        User.update(password=hashed_pwd).where(User.email == email).execute()
Exemplo n.º 8
0
 def get_user_profile(cls, email: str) -> dict:
     user_id = User.select().where(User.email == email).get().id
     profile_ins = Profile.select().where(Profile.user_id == user_id).get()
     result = {
         "username": profile_ins.username,
         "grade": profile_ins.grade,
         "contact_info": profile_ins.contact_info,
         "avatar_id": profile_ins.avatar
     }
     return result
Exemplo n.º 9
0
 def update_user_profile(cls, email: str, data: dict) -> dict:
     print(
         f"[PROFILE SERVICE] Updating profile [email:{email}, data:{data}]")
     user_ins = User.get().where(User.email == email)
     try:
         Profile.update(username=data.get("username"),
                        grade=data.get("grade"),
                        contact_info=data.get("contact_info"),
                        avatar_id=data.get("avatar_id")).where(
                            Profile.id == user_ins.profile_id).execute()
     except:
         return {"status": False, "message": "Profile update failed"}
def registered():
    if request.method == "GET":
        return render_template("Registered_page.html")
    form = Register(request.form)
    if form.validate():
        # 将用户信息注册进数据库
        model_user = User()
        model_user.login_name = form.username.data
        # 使用加密方法存储密码
        model_user._login_pwd = generate_password_hash(form.password.data)
        model_user.created_time = model_user.updated_time = getCurrentTime()
        try:
            db.session.add(model_user)
            db.session.commit()
        except Exception as error:
            return ops_renderErrJSON(msg=str(error))
        else:
            return ops_renderJSON(msg="注册成功~~")
    else:
        # 返回表单验证中的错误信息
        return ops_renderJSON(msg=str(form.errors))
Exemplo n.º 11
0
def reg():
    if request.method == 'GET':
        return ops_render('member/reg.html')

    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''
    login_pwd2 = req['login_pwd2'] if 'login_pwd2' in req else ''

    if not login_name or len(login_name) < 1:
        return ops_renderErrJSON(msg="Please input correct username!")

    if not login_pwd or len(login_pwd) < 6:
        return ops_renderErrJSON(
            msg="Please input correct password! At least 6 characters!")

    if login_pwd != login_pwd2:
        return ops_renderErrJSON(
            msg="Password not match!Please check and input again!")

    user_info = User.query.filter_by(login_name=login_name).first()
    if user_info:
        return ops_renderErrJSON(msg="Username already exist!")

    model_user = User()
    model_user.login_name = login_name
    model_user.nickname = login_name
    model_user.login_salt = UserService.genSalt(8)
    model_user.login_pwd = UserService.genePwd(login_pwd,
                                               model_user.login_salt)
    model_user.created_time = model_user.updated_time = getCurrentTime()
    db.session.add(model_user)
    db.session.commit()
    return ops_renderJSON(msg="Register Success!")
Exemplo n.º 12
0
def reg():
    if request.method == "GET":
        return render_template("member/reg.html")
    else:
        req = request.values
        nickname = req['nickname'] if "nickname" in req else ""
        login_name = req['login_name'] if "login_name" in req else ""
        login_pwd = req['login_pwd'] if "login_pwd" in req else ""
        login_pwd2 = req['login_pwd2'] if "login_pwd2" in req else ""
        if login_name is None or len(login_name) < 1:
            return ops_renderErrJSON(msg="请输入正确的登录用户名~~")

        if login_pwd is None or len(login_pwd) < 6:
            return ops_renderErrJSON(msg="请输入正确的登录密码,并且不能小于6个字符~~")

        if login_pwd != login_pwd2:
            return ops_renderErrJSON(msg="请输入正确的确认登录密码~~")

        # 查询user用户名
        user_info = User.query.filter_by(login_name=login_name).first()
        print(user_info)
        if user_info:
            return ops_renderErrJSON(msg="登录用户名已被注册,请换一个~~")
        model_user = User()
        model_user.login_name = login_name
        model_user.nickname = nickname if nickname is not None else login_name
        model_user.login_salt = UserService.geneSalt(8)
        model_user.login_pwd = UserService.genePwd(login_pwd,
                                                   model_user.login_salt)
        model_user.created_time = model_user.updated_time = getCurrentTime()
        db.session.add(model_user)
        db.session.commit()

        return ops_renderJSON(msg="注册成功~~")
def reg():
    if request.method == "GET":
        return ops_render("member/reg.html")
    elif request.method == "POST":
        req = request.values
        name = req["name"] if "name" in req else ""
        type = req["type"] if "type" in req else ""
        password = req["password"] if "password" in req else ""
        password2 = req["password2"] if "password2" in req else ""

        if name is None or len(name) < 1:
            return ops_renderErrJSON(msg="请输入正确的用户名")
        if type is None or len(type) < 1:
            return ops_renderErrJSON(msg="请选择正确的类型")

        if password is None or len(password) < 6:
            return ops_renderErrJSON(msg="请输入正确的密码")

        if password2 != password2:
            return ops_renderErrJSON(msg="两次密码不一致")

        user_info = User.query.filter_by(name=name).first()
        if user_info:
            return ops_renderErrJSON(msg="用户名已被注册,请更换用户名重新注册")

        model_user = User()
        model_user.name = name
        model_user.type = type
        model_user.password = UserService.gene_pwd(password)
        model_user.regist_time = get_current_time()
        db.session.add(model_user)
        db.session.commit()
        return ops_renderJSON(msg="注册成功~")
Exemplo n.º 14
0
def add(form):
    check_form(form, required_fields)

    if user_loader(form['username']):
        raise FieldExistsError('User', 'username')

    hashed_password = bcrypt.hashpw(form['password'].encode('utf-8'), bcrypt.gensalt())
    user = User(username=form['username'], password=hashed_password, is_authenticated=True)  # login on registration
    db.session.add(user)
    db.session.commit()
    login_user(user, remember=True)  # login on registration

    add_default_settings(user)  # add default settings for user
Exemplo n.º 15
0
    def ensure_from_disco_message(cls, message):
        obj = Message.create(
            message_id=message.id,
            guild_id=(message.guild and message.guild.id),
            channel_id=message.channel_id,
            author_id=message.author.id,
            content=message.content,
            timestamp=message.timestamp,
            edited_timestamp=message.edited_timestamp,
            edit_count=(0 if not message.edited_timestamp else 1),
            mentions=list(message.mentions.keys()),
            emojis=[int(i) for i in EMOJI_RE.findall(message.content)],
            attachments=[i.url for i in message.attachments.values()],
            embeds=[json_dumps(i.to_dict()) for i in message.embeds],
        )

        User.ensure_from_disco_user(message.author)

        for user in message.mentions.values():
            User.ensure_from_disco_user(user)

        return obj
Exemplo n.º 16
0
 def add_avatar(cls, email, content, file_format):
     user_id = User.get().where(User.email == email).id
     query = Image.select().where(
         Image.user_id == user_id & Image.type == "avatar")
     if query.exists():
         image_id = query.get().id
     else:
         image_id = None
     avatar_id = Image.add(user_id=user_id,
                           content=content,
                           type="avatar",
                           image_id=image_id,
                           image_format=file_format)
     return avatar_id
Exemplo n.º 17
0
def auth_discord_callback():
    if request.values.get('error'):
        return request.values['error']

    if 'state' not in session:
        raise APIError('No State', 400)

    discord = make_discord_session(state=session['state'])
    token = discord.fetch_token(
        current_app.config['DISCORD_TOKEN_URL'],
        client_secret=current_app.config['DISCORD_CLIENT_SECRET'],
        authorization_response=request.url)

    discord = make_discord_session(token=token)

    data = discord.get(current_app.config['DISCORD_API_BASE_URL'] +
                       '/users/@me').json()

    user = User.with_id(data['id'])

    if not user:
        User.create(
            user_id=data['id'],
            username=data['username'],
            discriminator=data['discriminator'],
            avatar=data['avatar'],
            bot=False,
        )
    else:
        User.update(
            username=data['username'],
            discriminator=data['discriminator'],
            avatar=data['avatar'],
        ).where(User.user_id == data['id']).execute()

    g.user = user
    return redirect('/')
Exemplo n.º 18
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        data = form.data
        user = User(
            name=data['name'],
            pwd=generate_password(data['pwd'],
                                  generate_salt(len(data['name']))),
            email=data['email'],
        )
        db.session.add(user)
        db.session.commit()
        flash("注册成功", category='ok')
        return redirect(UrlManager.build_url_path("user_page.login"))

    return render_template("register.html", form=form)
Exemplo n.º 19
0
    def on_message_create(self, event):
        if event.author.id == self.bot.client.state.me.id:
            return

        guild_state = self.bot.guild_state.get(event.guild.id)
        if not guild_state:
            return

        content = event.content

        # TODO: pull from config
        prefix = '!'
        if prefix and not content.startswith(prefix):
            return []
        else:
            content = content[len(prefix):]

        if not self.command_matches_re.match(content):
            return []

        options = []
        for command in self.commands:
            match = command.compiled_regex(self.group_abbrev).match(content)
            if match:
                options.append((command, match))
        options = sorted(options, key=lambda obj: obj[0].group is None)
        if not options:
            return

        user = None
        for command, match in options:
            # If this is an admin command, check if the user is an admin
            if command.level == -1:
                if not user:
                    user = User.with_id(event.author.id)

                if not user or not user.admin:
                    log.warning(
                        'User attempted to execute admin-only command %s (%s)',
                        command.name, event.author.id)
                    continue

            # TODO: permissions
            (command_event, kwargs) = command.execute(
                CommandEvent(command, event.message, match))
            gevent.spawn(command.func, guild_state, command_event, **kwargs)
Exemplo n.º 20
0
    def post_register(self):
        session = Session()
        if session.get("logged_in") == " true":
            session.extend()
            return redirect("/homepage")

        if session.get("email_verified") != "true":
            return redirect("/auth/email_verify")

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

        from utils.format_checker import (
            password_checker,
            username_checker
        )
        username_check = username_checker(username)
        password_check = password_checker(password)
        if not username_check["status"]:
            return {"status": False, "message": username_check["error"]}
        if not password_check:
            return {"status": False, "message": "Bad password format"}

        from utils.MD5_helper import MD5Helper
        user_id = User.insert(
            email=email,
            password=MD5Helper.hash(password)
        ).execute()
        Profile.insert(
            username=username,
            user=user_id
        ).execute()
        print(f"[REGISTER] Register Success. username: {username}, email: {email}")
        session["logged_in"] = "true"
        session.extend()
        return redirect("/auth/login")
Exemplo n.º 21
0
    def post_login(self):
        session = Session()
        if session.get("logged_in") == "true":
            session.extend()
            return redirect("/homepage")

        email = request.form.get("email")
        input_password = request.form.get("password")
        query = User.select().where(User.email == email)
        if query.exists():
            stored_password_hash = [ _ for _ in query][0].password
            if MD5Helper.evaluate(input_password, stored_password_hash):
                session["logged_in"] = "true"
                session["email"] = email
                session.extend()
                logbook.info(f"[LOGIN] Login Succeed: [user_email: {email}]")
                print(f"[LOGIN] Login Succeed: [user_email: {email}]")
                return redirect("/homepage")
            else:
                logbook.info("[LOGIN] Login Failed: wrong password.")
                return {"status": False, "message": "wrong password"}
        else:
            logbook.info("[LOGIN] Login Failed: user not found.")
            return {"status": False, "message": "Email not found"}
Exemplo n.º 22
0
def set_():
    default_pwd = '******'
    if request.method == 'GET':
        resp_data = {}
        req = request.args
        uid = int(req.get('id', 0))
        user_info = None
        if uid:
            user_info = User.query.filter_by(uid=uid).first()
        resp_data['user_info'] = user_info
        return ops_render("account/set.html", resp_data)

    resp = {'code': 200, 'msg': '操作成功!', 'data': {}}
    req = request.values

    # 获取参数
    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    mobile = req['mobile'] if 'mobile' in req else ''
    email = req['email'] if 'email' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名!"
        return jsonify(resp)

    if mobile is None or len(mobile) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的手机号码!"
        return jsonify(resp)

    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的邮箱!"
        return jsonify(resp)

    if login_name is None or len(login_name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登陆用户名!"
        return jsonify(resp)

    if login_pwd is None or len(login_pwd) < 6:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登陆密码!"
        return jsonify(resp)

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名!"
        return jsonify(resp)

    has_in = User.query.filter(User.login_name == login_name,
                               User.uid != id).first()
    if has_in:
        resp['code'] = -1
        resp['msg'] = "该登录名已经存在,请换一个试试!"
        return jsonify(resp)

    user_info = User.query.filter_by(uid=id).first()
    # 编辑
    if user_info:
        model_user = user_info
    # 新增
    else:
        model_user = User()
        model_user.created_time = getCurrentDate()
        model_user.login_salt = UserService.gene_salt()  # 新增登录密匙

    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name
    # 密码修改,当编辑不改密码时,密码不改变,否则将重新设置
    if login_pwd != default_pwd:
        model_user.login_pwd = UserService.gene_pwd(login_pwd,
                                                    model_user.login_salt)
    model_user.updated_time = getCurrentDate()

    db.session.add(model_user)
    db.session.commit()
    return jsonify(resp)
Exemplo n.º 23
0
def ctl_admins_add(user_id):
    from common.models.user import User
    User.update(admin=True).where((User.user_id == user_id)).execute()
Exemplo n.º 24
0
def set():
    default_pwd = "******"

    if request.method == "GET":
        resp_data = {}
        req = request.args
        uid = int(req.get("id", 0))
        user_info = None
        if uid:
            user_info = User.query.filter_by(uid=uid).first()
        resp_data["user_info"] = user_info
        return ops_render("account/set.html", resp_data)

    resp = {"code": 200, "msg": "操作成功~", "data": {}}
    req = request.values

    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    mobile = req['mobile'] if 'mobile' in req else ''
    email = req['email'] if 'email' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名~"
        return jsonify(resp)

    if mobile is None or len(mobile) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的手机号码~"
        return jsonify(resp)

    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的邮箱~"
        return jsonify(resp)

    if login_name is None or len(login_name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登录用户名~"
        return jsonify(resp)

    if login_pwd is None or len(email) < 6:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登录密码~"
        return jsonify(resp)

    has_in = User.query.filter(User.login_name == login_name,
                               User.uid != id).first()
    if has_in:
        resp['code'] = -1
        resp['msg'] = "该登录名已存在,请换一个试试~"
        return jsonify(resp)

    user_info = User.query.filter_by(uid=id).first()
    if user_info:
        model_user = user_info
    else:
        model_user = User()
        model_user.created_time = get_current_date()
        model_user.login_salt = UserService.gen_salt()

    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name

    if login_pwd != default_pwd:
        if user_info and user_info.uid == 1:
            resp['code'] = -1
            resp['msg'] = "该用户是演示账号,不准修改密码和登录用户名~~"
            return jsonify(resp)

        model_user.login_pwd = UserService.gen_pwd(login_pwd,
                                                   model_user.login_salt)

    model_user.updated_time = get_current_date()
    db.session.add(model_user)
    db.session.commit()
    return jsonify(resp)
Exemplo n.º 25
0
def ctl_admins_remove(user_id):
    from common.models.user import User
    User.update(admin=False).where((User.user_id == user_id)).execute()
Exemplo n.º 26
0
def set():
    default_pwd = "******"
    if request.method == "GET":
        # pass user info into template to fill in values of html form
        uid = request.args["uid"] if "uid" in request.args else None
        user_info = User.query.filter_by(uid=uid).first() if uid else None
        ctx = {"user": user_info, "default_pwd": default_pwd}
        return render_template_with_global_vars("account/set.html",
                                                context=ctx)

    elif request.method == "POST":
        # obtain info from form
        uid = int(request.form["uid"]) if "uid" in request.form else 0
        username = request.form[
            "login_name"] if "login_name" in request.form else ""
        pwd = request.form["login_pwd"] if "login_pwd" in request.form else ""
        nickname = request.form[
            "nickname"] if "nickname" in request.form else ""
        mobile = request.form["mobile"] if "mobile" in request.form else ""
        email = request.form["email"] if "email" in request.form else ""
        app.logger.debug("setting info for uid %d, new username %s, pwd %s" %
                         (uid, username, pwd))

        # validate form elements
        if len(nickname) < 1 or len(email) < 1 or len(mobile) < 1:
            empty_items = []
            if len(nickname) < 1:
                empty_items.append("姓名")
            if len(mobile) < 1:
                empty_items.append("手机")
            if len(email) < 1:
                empty_items.append("邮箱")
            if len(username) < 1:
                empty_items.append("登录名")
            if len(pwd) < 1:
                empty_items.append("登录密码")
            msg = "以下内容不能为空:" + "、".join(empty_items)
            return json_error_response(msg)
        if len(pwd) < 6 and uid == 0:
            return json_error_response("您的密码不能短于6个字符!")

        user_info = User.query.filter(User.login_name == username,
                                      User.uid != uid).first()
        if user_info:
            return json_error_response("该用户名已被使用,请使用别的用户名!")

        user_info = User.query.filter_by(uid=uid).first()
        app.logger.debug("uid %d user_info %s" % (uid, user_info))
        new_user = False
        if user_info is None:
            new_user = True
            user_info = User()
            user_info.login_salt = generate_salt()
            user_info.created_time = get_current_time()

        user_info.login_name = username
        user_info.nickname = nickname
        user_info.mobile = mobile
        user_info.email = email
        user_info.updated_time = get_current_time()

        # edit password when it is not default value "*****" (see set.html)
        if pwd != default_pwd:
            user_info.login_pwd = generate_salted_pwd(pwd,
                                                      user_info.login_salt)

        db.session.add(user_info)
        db.session.commit()

        return json_response("账号个人信息编辑成功!", data={})
Exemplo n.º 27
0
def set():
    if request.method == "GET":
        resp_data = {}
        req = request.args
        uid = int(req.get("id", 0))
        info = None
        if uid:
            info = User.query.filter_by(uid=uid).first()
        resp_data['info'] = info
        return ops_render('account/set.html', resp_data)
    # POST  更新数据库
    resp = {'code': 200, 'msg': "操作成功", 'data': {}}
    # ajax 发送的数据
    req = request.values
    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    mobile = req['mobile'] if 'mobile' in req else ''
    email = req['email'] if 'email' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的昵称"
        return jsonify(resp)
    if mobile is None or len(mobile) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的手机号"
        return jsonify(resp)
    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的邮箱"
        return jsonify(resp)
    if login_name is None or len(login_name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登录用户名"
        return jsonify(resp)
    if login_pwd is None or len(login_pwd) < 6:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的密码"
        return jsonify(resp)

    is_exsits = User.query.filter(User.login_name == login_name,
                                  User.uid != id).first()
    if is_exsits:
        resp['code'] = -1
        resp['msg'] = "该登录名已经存在,请更换"
        return jsonify(resp)

    user_info = User.query.filter_by(uid=id).first()
    if user_info:
        model_user = user_info
    else:
        model_user = User()
        model_user.created_time = getCurrentDate()
        model_user.login_salt = UserService.generateSalt()

    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name
    if user_info and user_info.uid == 1:
        resp['code'] = -1
        resp['msg'] = "该用户为Bruce,不允许修改"
        return jsonify(resp)
    model_user.login_pwd = UserService.generatePwd(login_pwd,
                                                   model_user.login_salt)
    model_user.updated_time = getCurrentDate()

    db.session.add(model_user)
    db.session.commit()
    return jsonify(resp)
Exemplo n.º 28
0
def ctl_admins_list():
    from common.models.user import User
    users = list(User.select().where((User.admin >> True)))

    print _tabulate_model(users, 'User ID', 'Username', 'Discriminator')
def upload_site(local_site_id, site_name, xmls):
    try:
        # Connect to MySQL DB
        connection = pymysql.connect(host='localhost',
                                     user=USERNAME,
                                     password=PASSWORD,
                                     db="main2",
                                     charset='utf8mb4',
                                     cursorclass=pymysql.cursors.DictCursor)

        with connection.cursor() as cursor:
            # Insert our site into the db
            site_insert_sql = "INSERT IGNORE INTO `site` (`name`) VALUES (%s)"
            cursor.execute(site_insert_sql, site_name)
            remote_site_id = cursor.lastrowid

            # if the statement did not insert anything warn the user and stop

            if remote_site_id == 0:
                print(
                    f"Site '{site_name}' has already been added or partially added!"
                )
                return
            connection.commit()

            # create buffer for storing user data to use multiple insert

            buffer = []

            print(f"Adding users from Site '{site_name}'")
            # Users
            users_xml_file = list(
                filter(lambda x: "Users.xml" in x[1] and x[0] == local_site_id,
                       xmls))[0][1]
            user_insert_sql = "INSERT IGNORE INTO `user` (`id`, `siteId`, `username`, `reputation`, `created`) VALUES (%s, %s, %s, %s, %s)"
            user_data_lambda: Callable[[User], Tuple] = lambda user: (
                user.id, remote_site_id, user.name, user.rep, user.ts)
            for row in XMLParserUtilies.getRows(users_xml_file):
                buffer.append(User.parseUserXMLNode(row))

                # Insert the buffer and clear the buffer
                if (len(buffer)) >= BUFFER_SIZE:
                    cursor.executemany(user_insert_sql,
                                       map(user_data_lambda, buffer))
                    buffer = []

            # insert the remaining buffer
            if len(buffer) > 0:
                cursor.executemany(user_insert_sql,
                                   map(user_data_lambda, buffer))
                buffer = []
            connection.commit()

            # Tags
            print(f"Adding tags from Site '{site_name}'")
            u_tag_id_map: Dict[str, int] = {}
            tag_insert_sql = "INSERT IGNORE INTO `tag` (`u_tagId`,`tagId`, `name`, `count`) VALUES (%s, %s, %s, %s)"
            tag_data_lambda: Callable[
                [Tag],
                Tuple] = lambda tag: (tag.uuid, tag.id, tag.name, tag.count)
            tags_xml_file = list(
                filter(lambda x: "Tags.xml" in x[1] and x[0] == local_site_id,
                       xmls))[0][1]
            for row in XMLParserUtilies.getRows(tags_xml_file):
                tag = Tag.parseTagXMLNode(row)
                buffer.append(tag)

                # insert tags
                if (len(buffer)) >= BUFFER_SIZE:
                    cursor.executemany(tag_insert_sql,
                                       map(tag_data_lambda, buffer))
                    for i in range(len(buffer)):
                        # store id of tag in tag map
                        u_tag_id_map[buffer[i].name] = buffer[i].uuid
                    connection.commit()
                    buffer = []
                    # insert remaining tags
            if len(buffer) > 0:
                cursor.executemany(tag_insert_sql, map(tag_data_lambda,
                                                       buffer))
                for i in range(len(buffer)):
                    # store id of tag in tag map
                    u_tag_id_map[buffer[i].name] = buffer[i].uuid

                buffer = []
            connection.commit()

            # Posts
            print(f"Adding posts from Site '{site_name}'")
            post_counter = 0
            post_id_map = []
            posts_xml_file = list(
                filter(lambda x: "Posts.xml" in x[1] and x[0] == local_site_id,
                       xmls))[0][1]
            post_insert_sql = "INSERT IGNORE INTO `post` (`u_postId`, `postId`, `created`, `score`, `title`, `userId`, `siteId`, `body`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
            describes_insert_sql = "INSERT IGNORE INTO `describes` (`u_postId`, `u_tagId`) VALUES (%s, %s)"
            post_buffer = []
            describes_buffer = []
            tag_buffer = []

            for row in XMLParserUtilies.getRows(posts_xml_file):
                post: Union[Question, Answer] = Post.parsePostXMLNode(
                    row, remote_site_id)
                post_buffer.append(
                    (get_random_id(), post.id, post.date_created, post.score,
                     post.title, post.owner_id, post.site_id, post.body))

                # store tag id for insertion into describes later
                if type(post) is Question:
                    tag_buffer.append(post.tags)
                else:
                    tag_buffer.append([])

                if len(post_buffer) >= BUFFER_SIZE:
                    # insert posts
                    print(cursor.executemany(post_insert_sql, post_buffer),
                          len(post_buffer))

                    for i in range(len(post_buffer)):
                        # store post id in post id map
                        list_insert_helper(post_id_map, post_buffer[i][1],
                                           post_buffer[i][0])
                        # add tags to the describe buffer
                        for tag in tag_buffer[i]:
                            describes_buffer.append(
                                (post_buffer[i][0], u_tag_id_map[tag]))

                    # insert describes
                    cursor.executemany(describes_insert_sql, describes_buffer)
                    connection.commit()
                    post_buffer = []
                    describes_buffer = []
                    tag_buffer = []
            if len(post_buffer) > 0 or len(describes_buffer) > 0:
                print(cursor.executemany(post_insert_sql, post_buffer),
                      len(post_buffer))
                for i in range(len(post_buffer)):
                    list_insert_helper(post_id_map, post_buffer[i][1],
                                       post_buffer[i][0])
                    for tag in tag_buffer[i]:
                        describes_buffer.append(
                            (post_buffer[i][0], u_tag_id_map[tag]))
                cursor.executemany(describes_insert_sql, describes_buffer)
                connection.commit()
                post_buffer = []
                describes_buffer = []
                tag_buffer = []

            # Posts round 2 to fill in question and aswer tables
            answer_buffer = []
            question_buffer = []
            print(f"Adding qs & as '{site_name}'")
            answer_insert_sql = "INSERT IGNORE INTO `answer` (`u_postId`, `questionId`) VALUES (%s, %s)"
            question_insert_sql = "INSERT IGNORE INTO `question` (`u_postId`, `acceptedId`) VALUES (%s, %s)"
            for row in XMLParserUtilies.getRows(posts_xml_file):
                post: Union[Question, Answer] = Post.parsePostXMLNode(
                    row, remote_site_id)

                # insert the correct entry
                if type(post) is Question:
                    question_buffer.append(
                        (post_id_map[post.id], None if post.acceptedId == None
                         or post.acceptedId >= len(post_id_map)
                         or post_id_map[post.acceptedId] == None else
                         post_id_map[post.acceptedId]))
                else:
                    answer_buffer.append(
                        (post_id_map[post.id], None if post.questionId == None
                         or post.questionId >= len(post_id_map)
                         or post_id_map[post.questionId] == None else
                         post_id_map[post.questionId]))

                if len(question_buffer) >= BUFFER_SIZE or len(
                        answer_buffer) >= BUFFER_SIZE:
                    # insert qs and as
                    cursor.executemany(question_insert_sql, question_buffer)
                    cursor.executemany(answer_insert_sql, answer_buffer)
                    connection.commit()

                    answer_buffer = []
                    question_buffer = []

            if len(question_buffer) > 0 or len(answer_buffer) > 0:
                # insert qs and as
                cursor.executemany(question_insert_sql, question_buffer)
                cursor.executemany(answer_insert_sql, answer_buffer)
                connection.commit()

                answer_buffer = []
                question_buffer = []

            # Comments
            print(f"Adding comments from Site '{site_name}'")
            comments_xml_file = list(
                filter(
                    lambda x: "Comments.xml" in x[1] and x[0] == local_site_id,
                    xmls))[0][1]
            comment_insert_sql = "INSERT IGNORE INTO `comment` (`id`, `score`, `body`, `created`, `userId`, `siteId`, `u_postId`) VALUES (%s, %s, %s, %s, %s, %s, %s)"
            # use post_id_map to convert site post id to u_postId
            comment_data_lambda: Callable[[Comment], Tuple] = \
                lambda comment: (
                comment.id, comment.score, comment.body, comment.date_created, comment.user_id, remote_site_id,
                post_id_map[comment.post_id])

            for row in XMLParserUtilies.getRows(comments_xml_file):
                buffer.append(Comment.parseCommentXMLNode(row))

                if (len(buffer)) >= BUFFER_SIZE:
                    cursor.executemany(comment_insert_sql,
                                       map(comment_data_lambda, buffer))
                    buffer = []
            if len(buffer) > 0:
                cursor.executemany(comment_insert_sql,
                                   map(comment_data_lambda, buffer))
                buffer = []
            connection.commit()
    except Exception as ex:
        print(site_name, "failed!")
        print(str(ex))
        raise ex
    print(site_name, "succeeded!")
Exemplo n.º 30
0
def set():
    """
        修改个人信息页面、添加账号信息页面
    """
    default_pwd = "******"
    if request.method == "GET":
        resp_data = {}
        req = request.args
        uid = int(req.get("id", 0))
        info = None  # 因为如果是添加信息,那么上个页面,就不会传回id,所以为None,进入添加账号页面。否则点击编辑就传回id,进入修改信息页面
        if uid:
            info = User.query.filter_by(
                uid=uid).first()  # filter_by不用写类,他会自动区分的
        resp_data['info'] = info  # 统一渲染的 resp_data(json)里面,将user_info放进去
        return ops_render("account/set.html", resp_data)

    resp = {'code': 200, 'msg': u"操作成功", 'data': {}}
    # 获取登录变量
    req = request.values  # 所有的请求变量,放到这个数组里

    id = req['id'] if 'id' in req else 0  # id 是用来判断是增加用户信息,还是修改用户信息
    nickname = req['nickname'] if 'nickname' in req else ''  # 三元表达式
    mobile = req['mobile'] if 'mobile' in req else ''
    email = req['email'] if 'email' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if nickname is None or len(nickname) < 2 or len(nickname) > 15:  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名"
        return jsonify(resp)  # json 格式的转换

    if mobile is None or not re.match(REGEX_MOBILE, mobile):  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的手机号码"
        return jsonify(resp)  # json 格式的转换

    if email is None or not re.match(REGEX_Email, email):  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的邮箱"
        return jsonify(resp)  # json 格式的转换

    if login_name is None or not re.match(REGEX_LOGIN_NAME,
                                          login_name):  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登录名"
        return jsonify(resp)  # json 格式的转换

    if login_pwd is None or len(login_pwd) < 6 or len(
            login_pwd) > 15:  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登录密码"
        return jsonify(resp)  # json 格式的转换

    has_in = User.query.filter(User.login_name == login_name,
                               User.uid != id).first()
    # login_name判断用户是否存在。User.uid != id:这个表明是该用户id不存在,即为增加用户信息。filter支持的方式更多一点。filter_by只能传一个json

    if has_in:  # 如果用户名已经存在了
        resp['code'] = -1
        resp['msg'] = "该登录名已存在,请重新输入"
        return jsonify(resp)  # json 格式的转换

    user_info = User.query.filter_by(
        uid=id).first()  # 判断用户 id是否存在。如果存在,那么 modle_use,就是这个用户的信息。set页面为修改用户信息
    if user_info:
        modle_use = user_info
    else:  # 否则,就是这个uid不存在。那么久为增加用户信息界面
        modle_use = User()
        modle_use.created_time = getCurrentData()  # 增加用户信息时,created_time才改变
        modle_use.login_salt = UserService.geneSalt(
        )  # geneSalt即数据库salt字段, 自定义的加密规则。增加用户信息,才会生成salt

    modle_use.nickname = nickname
    modle_use.mobile = mobile
    modle_use.email = email
    modle_use.login_name = login_name
    if login_pwd != default_pwd:  # 如果传回来的密码value,不是default密码,那么就改密码,反之不改密码。
        modle_use.login_pwd = UserService.genePwd(
            login_pwd, modle_use.login_salt)  # 加密后的密码,就是前面定义的,通过密码和 salt进行加密
        resp['msg'] = "操作成功,登录用户 %s 的密码为:%s" % (login_name, login_pwd)
    modle_use.updated_time = getCurrentData()

    db.session.add(modle_use)  # 数据库添加数据,统一提交
    db.session.commit()
    return jsonify(resp)  # 返回信息,更改成功
Exemplo n.º 31
0
def score_users():
    # get fixture with status "updated_result"
    logger.info("Getting fixture with status `updated_result`")
    fixture_list = list(Fixture.status_index.query("updated_result", limit=1))
    if len(fixture_list) > 0:
        f = fixture_list[0]
        logger.info(
            "Calculating users score for the fixture result `{}`".format(
                f.fixture_id))
        logger.info(
            "Getting predictions for users with fixture_id `{}` in curr_prediction"
            .format(f.fixture_id))

        # get user records where current prediction fixture id is the same as the fixture that ended
        users_list = list(
            User.scan(User.curr_prediction.fixture == f.fixture_id))
        if len(users_list) > 0:

            user_list_to_save = []
            scoreline_dict = {}
            scorerpoints_dict = {}
            highest_user = None
            for u in users_list:
                u.curr_prediction.points = 0  # just to be sure
                logger.info("Calculating score for user : `{}`".format(
                    u.user_id))
                points = 0
                ur = u.curr_prediction.result
                if is_correct_result(ur, f.result):
                    points += 2
                    logger.info("Correct result - points = {}".format(points))
                if is_correct_scoreline(ur, f.result):
                    points += 3
                    logger.info(
                        "Correct scoreline - points = {}".format(points))
                    correct_scorers = list()
                    actual_scorers = list(f.result.scorers)
                    logger.info("Correct scorer = {}, pred_scorer = {}".format(
                        actual_scorers, ur.scorers))

                    for s in ur.scorers:
                        if s in actual_scorers:
                            correct_scorers.append(s)
                            actual_scorers.remove(s)

                    scoreline_dict[u.user_id] = 1
                    scorerpoints_dict[u.user_id] = len(correct_scorers)

                    points = points + len(correct_scorers)
                    logger.info(
                        "Adding scorer points, total = {}".format(points))

                # update points
                u = add_points(u, points, f.league)
                user_list_to_save.append(u)

            user_list_to_save = sorted(user_list_to_save,
                                       key=lambda u: u.curr_prediction.points,
                                       reverse=True)
            for u in user_list_to_save:
                print(u.user_id, u.curr_prediction.points)
            second_list_to_save = []
            highest_user = None
            while user_list_to_save:
                u = user_list_to_save.pop(0)
                if not highest_user:
                    highest_user = u
                else:
                    if u.curr_prediction.points > highest_user.curr_prediction.points:
                        highest_user = u
                    elif u.curr_prediction.points == highest_user.curr_prediction.points:
                        logger.info("{} vs {}".format(u.user_id,
                                                      highest_user.user_id))
                        if win_tie(u, highest_user, scoreline_dict,
                                   scorerpoints_dict, f):
                            logger.info("{} won".format(u.user_id))
                            highest_user = add_points(highest_user, 3,
                                                      f.league)
                            second_list_to_save.append(highest_user)
                            highest_user = u
                        else:
                            logger.info(
                                "Lost to highest user with same points, adding +3"
                            )
                            u = add_points(u, 3, f.league)
                            second_list_to_save.append(u)
                    else:
                        # current user less than highest_user, so break
                        second_list_to_save.append(u)
                        break

            highest_user = add_points(highest_user, 5, f.league)
            second_list_to_save.append(highest_user)

            for u in user_list_to_save:
                u.save()
            for u in second_list_to_save:
                u.save()
            return f