Python flask.g 模块,user() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.g.user()

项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def create():
    form = UserCreateForm.from_json(request.get_json())

    if not form.validate():
        return jsonify(form.errors), 400

    user = User()
    user.email = form.data.get('email')
    user.first_name = form.data.get('first_name')
    user.last_name = form.data.get('last_name')
    user.avatar = form.data.get('avatar', None)
    user.password = User.make_password(form.data.get('password'))
    user.save()

    access_token = jwt.jwt_encode_callback(user)

    return jsonify({'user': user.serialize(), 'access_token': access_token.decode('utf-8')}), 200
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def login():
    data = request.get_json()
    username = data.get(current_app.config.get('JWT_AUTH_USERNAME_KEY'), None)
    password = data.get(current_app.config.get('JWT_AUTH_PASSWORD_KEY'), None)
    criterion = [username, password, len(data) == 2]

    if not all(criterion):
        return jsonify({'message': 'Invalid credentials'}), 401

    user = jwt.authentication_callback(username, password)
    if user:
        if not user.is_active:
            return jsonify({'message': 'InActive User'}), 401

        access_token = jwt.jwt_encode_callback(user)

        return jsonify({'user': user.serialize(), 'access_token': access_token.decode('utf-8')}), 200
    else:
        return jsonify({'message': 'Invalid credentials'}), 401
项目:Cloudroid    作者:cyberdb    | 项目源码 | 文件源码
def signup():
    from forms import SignupForm

    form = SignupForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data.lower()).first()
        if user is not None:
            form.email.errors.append("The Email address is already taken.")
            return render_template('signup.html', form=form)

        newuser = User(form.firstname.data,form.lastname.data,form.email.data,form.password.data)
        db.session.add(newuser)
        db.session.commit()

        session['email'] = newuser.email
        return redirect(url_for('login'))

    return render_template('signup.html', form=form)
项目:Cloudroid    作者:cyberdb    | 项目源码 | 文件源码
def login():
    if g.user is not None and g.user.is_authenticated:
        return redirect(url_for('index'))

    from app.forms import LoginForm

    form = LoginForm()
    if form.validate_on_submit():
        session['remember_me'] = form.remember_me.data
        user = User.query.filter_by(email=form.email.data.lower()).first()
        if user and user.check_password(form.password.data):
            session['email'] = form.email.data
            login_user(user,remember=session['remember_me'])
            return redirect(url_for('index'))
        else:
            return render_template('login.html',form=form,failed_auth=True)

    return render_template('login.html',form=form)
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def create_app():
    app.config.from_object(development)

    db.init_app(app)

    bcrypt.init_app(app)

    from views.auth import auth_view
    from views.users import user_view
    from views.chat import chat_view
    from models.user import authenticate, identity

    jwt.identity_handler(identity)
    jwt.authentication_handler(authenticate)
    jwt.init_app(app)

    # Register Routes
    app.register_blueprint(auth_view, url_prefix='/api')
    app.register_blueprint(user_view, url_prefix='/api')
    app.register_blueprint(chat_view, url_prefix='/api')

    return app
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def messages(room_id):
    room_member = RoomMember.where('room_id', room_id).where('user_id', g.user['id']).first()
    if not room_member:
        return jsonify({'message': "Unknown Room"}), 400

    room = Room.where('id', room_id).with_('members.user').first().serialize()

    for item in room['members']:
        item['user']['username'] = '%s %s' % (item['user']['first_name'],item['user']['last_name'])

    messages = Message.select('messages.*', 'u.first_name', 'u.last_name', 'u.avatar') \
        .where('room_id', room_id) \
        .join('users as u', 'u.id', '=', 'messages.sender_id') \
        .order_by('created_at', 'desc') \
        .limit(100) \
        .get()

    return jsonify({'room': room, 'messages': messages.serialize()}), 200
项目:polichombr    作者:ANSSI-FR    | 项目源码 | 文件源码
def index():
    """
    Index. Distinction between logged-in users and guests is performed
    in the template.
    """
    machex_import_form = ImportForm()
    upload_sample_form = UploadSampleForm()
    families_choices = [(0, "None")]
    families_choices += [(f.id, f.name) for f in Family.query.order_by('name')]
    upload_sample_form.family.choices = families_choices
    uncategorized = []
    if g.user.is_authenticated:
        uncategorized = api.samplecontrol.get_user_uncategorized_samples(
            g.user)
    return render_template('index.html',
                           families=api.familycontrol.get_all(),
                           impform=machex_import_form,
                           uncategorized=uncategorized,
                           form=upload_sample_form)
项目:polichombr    作者:ANSSI-FR    | 项目源码 | 文件源码
def login():
    """
    Flask-Login.
    """
    if g.user.is_authenticated:
        return redirect(url_for('index'))

    login_form = LoginForm()
    if login_form.validate_on_submit():
        username = login_form.username.data
        user = api.usercontrol.get_by_name(username)
        if user is None:
            return redirect(url_for('login'))
        if api.usercontrol.check_user_pass(user, login_form.password.data):
            login_user(user, remember=True)
            security.datastore.commit()
            flash("Logged in!", "success")
            return redirect(url_for("index"))
        else:
            flash("Cannot login...", "error")
    return render_template('login.html', title='Sign In', form=login_form)
项目:polichombr    作者:ANSSI-FR    | 项目源码 | 文件源码
def register_user():
    """
    User registration, if enabled in configuration file.
    """
    if g.user.is_authenticated or app.config['USERS_CAN_REGISTER'] is not True:
        return redirect(url_for('index'))
    registration_form = UserRegistrationForm()
    if registration_form.validate_on_submit():
        ret = api.usercontrol.create(registration_form.username.data,
                                     registration_form.password.data,
                                     registration_form.completename.data)
        if ret:
            return redirect(url_for('login'))
        else:
            app.logger.error("Error during user registration")
            flash("Error registering user")
    return render_template('register.html',
                           form=registration_form)
项目:MoegirlUpdater    作者:kafuuchino    | 项目源码 | 文件源码
def userlist():
    u=User()
    form=AddUserForm()
    flag=current_user.is_administrator(g.user)
    if flag is True:
        userlist=u.GetUserList()
        jsondata=request.get_json()
        if request.method == 'POST' and jsondata:
            if jsondata['action'] == u'edit':
                username=jsondata['username']
                location=url_for('.admin_edit_profile',username=username)
                return jsonify({"status":302,"location":location})
            else:
                username=jsondata['username']
                u.RemUser(username)
                return redirect('userlist')
        elif request.method == 'POST' and form.validate():
            pwd=u.GetPassword(g.user)
            if u.verify_password(form.oripassword.data):
                u.AddUser(form.username.data,form.password.data,form.role.data,form.email.data)
                return redirect('userlist')
        else:
            return render_template('userlist.html',userlist=userlist,form=form)
    else:
        abort(403)
项目:MoegirlUpdater    作者:kafuuchino    | 项目源码 | 文件源码
def admin_edit_profile(username):
    u=User()
    form=AdminEditProfileForm()
    flag=current_user.is_administrator(g.user)
    if request.method == 'POST' and form.validate():
        if flag is True:
            pwd=u.GetPassword(g.user)
            if u.verify_password(form.oripassword.data):
                email=form.email.data
                aboutme=form.about_me.data
                role=form.role.data
                if form.password.data is not u'':
                    u.ChangePassword(username,form.password.data)
                u.AdminChangeProfile(username,email,role,aboutme)
                flash('??????')
                return redirect(url_for('.user',username=username))
            else:
                flash('??????????')
        else:
            abort(403)
    u.GetUserInfo(username)
    form.email.data=u.email
    form.about_me.data=u.aboutme
    form.role.data=u.role
    return render_template('admin_edit_profile.html',form=form,u=u)
项目:MoegirlUpdater    作者:kafuuchino    | 项目源码 | 文件源码
def log():
    flag=current_user.is_administrator(g.user)
    if flag is True:
        p=Page()
        record=p.GetRecord()
        records={}
        records=OrderedDict()
        total=len(record)
        page = request.args.get('page',1,type=int)
        per_page=10
        keys=record.keys()
        offset=(page - 1) * per_page
        for i in range(len(keys)):
            if i < per_page and (offset+i) < len(keys):
                records[keys[offset+i]]=record[keys[offset+i]]
            else:
                break
        pagination=Pagination(css_framework='bootstrap3',link_size='sm',show_single_page=False,page=page,per_page=per_page,total=total,format_total=True,format_number=True)
        return render_template('log.html',records=records,page=page,per_page=per_page,pagination=pagination)  
    else:
        abort(403)
项目:MoegirlUpdater    作者:kafuuchino    | 项目源码 | 文件源码
def Add(self,title):
        flag=GetImage(title.encode('utf8'))
        if flag==True:
            timenow=time.time()
            r.zadd('expire',MU_MainConfig.EDITEDPREFIX+title,timenow)
            r.hset('queue',MU_MainConfig.EDITEDPREFIX+title,title)
            r.zadd('queuenumber',title,0)
            scorequeue=r.zrange('queuenumber',0,-1)
            pushtime=r.hget('pushtime',g.user)
            r.hset('pushtime',g.user,int(pushtime)-1)
            for i in range(len(scorequeue)):
                score=r.zscore('queuenumber',scorequeue[i])
                r.zadd('queuenumber',scorequeue[i],score+1)
            img=r.hget('img',MU_MainConfig.EDITEDPREFIX+title)
            r.hset('imgkey',title,img)
            return True
        else:
            return False
项目:flask-vue-example    作者:levi-lq    | 项目源码 | 文件源码
def post(self):
        args = login_parser.parse_args()
        _user = User.get_object(username=args.username)
        if not _user.verify_password(args.password):
            return http_responses.HTTP_400_BAD_REQUEST(msg={"error": u"????"})

        token = _user.generate_auth_token()
        g.user = _user
        # ?????????
        # if not hasattr(g, "identity"):
        _permissions = cache_user_privileges(token)
        permissions = set()
        for per in _permissions:
            permissions.add(".".join([per.name, per.needs.name]))

        return http_responses.HTTP_200_OK(msg={"message": "Login success",
                                               "username": _user.username,
                                               "nickname": _user.nickname,
                                               "id": _user.id,
                                               "is_superuser": _user.is_superuser,
                                               "permissions": list(permissions),
                                               "token": token})
项目:pymock    作者:halilkaya    | 项目源码 | 文件源码
def create_blog_post():
    """
    Creates a new blog post
    """
    if not request.json:
        abort(400)
    title = request.json.get('title')
    content = request.json.get('content')
    tags = request.json.get('tags')
    author = g.user
    if not title or not content:
        abort(400)
    post = BlogPost()
    post.title = title
    post.content = content
    if tags:
        post.tags = tags
    post.author = author.id
    db.session.add(post)
    db.session.commit()
    return jsonify({
        "status": "Created",
        "code": 201,
        "message": "Blog post created!"
    }), 201
项目:plexivity    作者:mutschler    | 项目源码 | 文件源码
def jsonhistory():
    history = db.session.query(models.Processed)
    table = DataTable(request.args, models.Processed, history, [
        ("date", "time", lambda i: "{}".format(i.time.strftime('%Y/%m/%d')) if i.stopped else '<span class="orange">{}</span>'.format(_("Currently watching..."))),
        ("ipaddress", lambda i: "{}".format(i.get_xml().find('Player').get("address"))),
        ("user", lambda i: '<a href="{0}" class="invert-link">{1}</a>'.format(url_for('user', name=i.user), i.user)),
        ("platform"),
        ("title", lambda i: u'<a class="invert-link" href="{0}">{1}</a>'.format(url_for('info', id=i.get_xml_value('ratingKey')), i.title)),
        ("type", lambda i: "{}".format(i.get_xml_value("type"))),
        ("streaminfo", lambda i: '<a href="#" data-link="{0}" class="orange" data-target="#streamModal" data-toggle="modal"><i class="glyphicon glyphicon glyphicon-info-sign"></i></a>'.format(url_for('streaminfo',id=i.id)) if i.platform != "Imported" else ''),
        ("time",lambda i: "{}".format(i.time.strftime('%H:%M'))),
        ("paused_counter", lambda i: "{} min".format(int(i.paused_counter)/60) if i.paused_counter else "0 min" ),
        ("stopped", lambda i: "{}".format(i.stopped.strftime('%H:%M')) if i.stopped else "n/a"),
        ("duration", lambda i: "{} min".format(int((((i.stopped - i.time).total_seconds() - (int(i.paused_counter or 0))) /60))) if i.stopped else "n/a"),
        ("completed", lambda i: '<span class="badge badge-warning">{}%</span>'.format(helper.getPercentage(i.get_xml_value("duration") if i.platform == "Imported" else i.get_xml_value("viewOffset"), i.get_xml_value("duration")))),
    ])
    table.searchable(lambda queryset, user_input: perform_some_search(queryset, user_input))

    return json.dumps(table.json())
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def templates():
    if request.method == "GET":
        templates = Template.domain_query(g.domain).fetch()
        return render_template("templates.html", templates=templates)

    form = TemplateForm(request.form, domain=g.domain)
    if form.validate_on_submit():
        template = Template(
            name=form.name.data,
            text=form.text.data,
            subject=form.subject.data,
            sender=g.user.email(),
            owner_domain=g.domain,
            created_by=g.user.email())
        template.put()
        return jsonify(template.to_dict())
    return json_error(400, list_errors(form), {})
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def edit_template(template_id):
    '''
    Edits an existing template.

    Args:
    template_id - int - The ID of the template to edit
    '''
    template = Template.get_by_id(template_id)
    if not template or template.owner_domain != g.domain:
        abort(404)

    form = TemplateForm(request.form, domain=g.domain, template_id=template_id)
    if form.validate_on_submit():
        template.name = form.name.data
        template.text = form.text.data
        template.subject = form.subject.data
        template.sender = g.user.email()
        template.put()
        return jsonify(template.to_dict())
    return json_error(400, list_errors(form), {})
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def send_test_template():
    '''
    Sends a test template to the provided address
    '''
    form = SendTestTemplateForm(request.form)
    if form.validate_on_submit():
        report = EmailReport.make_sample()
        try:
            subject = render_template_string(form.subject.data, report=report)
            text = render_template_string(form.text.data, report=report)
            email_provider.send(
                to=form.recipient.data,
                sender=g.user.email(),
                subject=subject,
                body=text)
            return jsonify({'success': True, 'message': 'Sent test email.'})
        except Exception as e:
            return json_error(400, str(e), {})
    return json_error(400, list_errors(form), {})
项目:hashtagtodo-open    作者:slackpad    | 项目源码 | 文件源码
def search_user():
    query = request.args.get('q', '')
    results = User.search(query)
    simplified = list()
    for result in results:
        entry = {
            'link': '/admin/user/manage/%s' % result.doc_id
        }
        for field in result.fields:
            if field.name == 'created':
                entry[field.name] = arrow.get(field.value).humanize()
            else:
                entry[field.name] = field.value
        simplified.append(entry)
    extra = {
        'total': results.number_found,
        'shown': len(results.results),
    }
    return render_template('admin-user-search.html', results=simplified, extra=extra)
项目:hashtagtodo-open    作者:slackpad    | 项目源码 | 文件源码
def delete():
    if request.method == 'POST':
        dos = arrow.get(g.user.created).humanize()
        calendars = len([c for c in Calendar.query(ancestor=g.user.key)])
        todos = len([e for e in Event.query(ancestor=g.user.key)])
        subject = '%s %s closed their account' % (g.user.first_name, g.user.last_name)
        body = '''
%s (joined %s, made %d todos and had %d calendars)

%s
''' % (g.user.email, dos, todos, calendars, request.form.get('feedback'))
        mail.send_mail(sender=EMAILS['alerts'], to=EMAILS['support'], subject=subject, body=body)

        calendars = Calendar.get_all(g.user.key)
        for calendar in calendars:
            for event in Event.get_all(calendar.key):
                event.key.delete()
            calendar.key.delete()

        User.unindex(g.user.key.urlsafe())
        g.user.key.delete()
        session.pop('user', None)
        return redirect('/index.html')

    return render_template('delete.html')
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update_or_delete_comment(defendant=None, comment=None):
    """ Update or delete defendant comments
    """
    if request.method == 'PUT':
        body = request.get_json()
        return CommentsController.update(
            body,
            comment_id=comment,
            user_id=g.user.id
        )
    else:
        return CommentsController.delete(
            comment_id=comment,
            defendant_id=defendant,
            user_id=g.user.id
        )
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update_or_delete_comment(ticket=None, comment=None):
    """ Update or delete ticket comments
    """
    if request.method == 'PUT':
        body = request.get_json()
        return CommentsController.update(
            body,
            comment_id=comment,
            ticket_id=ticket,
            user_id=g.user.id
        )
    else:
        return CommentsController.delete(
            comment_id=comment,
            ticket_id=ticket,
            user_id=g.user.id
        )
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def __call__(self, func):

        @wraps(func)
        def decorator(*args, **kwargs):
            response = func(*args, **kwargs)
            if not USE_CACHE:
                return response
            for path in self.routes:
                route = '%s,%s,%s' % (path, json.dumps(self.args), None)
                Cache.delete(unicode(route))
                user = kwargs.get('user', None) if self.clear_for_user else None
                Logger.debug(unicode('clear %s from cache' % (route)))
                if user:
                    route = '%s,%s,%s' % (path, json.dumps(self.args), user)
                    Cache.delete(unicode(route))
                    Logger.debug(unicode('clear %s from cache' % (route)))
            return response
        return decorator
项目:os-reststack-manager    作者:gemagomez    | 项目源码 | 文件源码
def authenticate():
    # logger.debug("endpoint request: %s" % request.endpoint)
    if re.search('tenant_provisioned', str(request.endpoint)):
        g.user = "phone_home"
        logger.info("Authentication bypassed: tenant_provisioned")
        return

    try:
        decoded = jwt.decode(request.headers['X-Auth-Token'], credentials['tenant_secret'], algorithms=['HS256'])
        g.user = decoded['user']
    except KeyError:
        logger.error("Error: key error.")
        abort(401)
    except jwt.DecodeError:
        logger.error("Error: decode error")
        abort(401)
项目:os-reststack-manager    作者:gemagomez    | 项目源码 | 文件源码
def create_tenant():
    logger.info("User %s requested creation", g.user)
    data = request.get_json(force=True)
    logger.debug("Request data: %s" % data)

    mconf = data['machine_conf'] if 'machine_conf' in data else CONF.MACHINE
    cconf = data['cloud_conf'] if 'cloud_conf' in data else CONF.CLOUD_CONFIG

    ip, machine_id = tenant_create(tenant_name=data['tenant'],
                                   tenant_keys=extract_keys(data['pub_key']),
                                   image_name_or_id=data['image_id'],
                                   credentials=credentials, cloud_conf=cconf,
                                   machine_conf=mconf)
    tenant = Tenant(tenant_name=data['tenant'], machine_id=machine_id, ip=ip)
    db.session.add(tenant)
    db.session.commit()

    return jsonify(tenant=data['tenant'], machine_id=machine_id, ip=ip), 202
项目:opsweb    作者:wylok    | 项目源码 | 文件源码
def update_query():
    K = '%s_%s' %(g.user,g.secret_key)
    Key = '%s_update_php' %K
    Key_incr = '%s_incr' % Key
    Redis.expire(Key,30)
    if Redis.lrange(Key,0,-1):
        data = Redis.rpop(Key)
        if '_End_' in data:
            Redis.expire(Key,3)
        return render_template_string(data)
    else:
        Redis.incr(Key_incr, 1)
        if int(Redis.get(Key_incr)) > 10000:
            Redis.delete(Key_incr)
            return render_template_string("_End_")
        return render_template_string("")
项目:opsweb    作者:wylok    | 项目源码 | 文件源码
def publish_java_query():
    K = '%s_%s' %(g.user,g.secret_key)
    messageKey = '%s_publish_java' % K
    Key_incr = '%s_incr' % messageKey
    myRedis.expire(messageKey,30)
    if myRedis.lrange(messageKey,0,-1):
        data = myRedis.rpop(messageKey)
        if '_End_' in data:
            myRedis.expire(messageKey,3)
        return render_template_string(data)
    else:
        myRedis.incr(Key_incr, 1)
        if int(myRedis.get(Key_incr)) > 10000:
            myRedis.delete(Key_incr)
            return render_template_string("_End_")
        return render_template_string("")
项目:opsweb    作者:wylok    | 项目源码 | 文件源码
def update_java_query():
    K = '%s_%s' %(g.user,g.secret_key)
    messageKey = '%s_update_java' % K
    Key_incr = '%s_incr' % messageKey
    myRedis.expire(messageKey,30)
    if myRedis.lrange(messageKey,0,-1):
        data = myRedis.rpop(messageKey)
        if '_End_' in data:
            myRedis.expire(messageKey,3)
        return render_template_string(data)
    else:
        myRedis.incr(Key_incr, 1)
        if int(myRedis.get(Key_incr)) > 10000:
            myRedis.delete(Key_incr)
            return render_template_string("_End_")
        return render_template_string("")
项目:grest    作者:mostafa    | 项目源码 | 文件源码
def authenticate(func):
    @wraps(func)
    def authenticate_requests(*args, **kwargs):
        """
        The authentication_function can be either empty, which
        results in all requests being taken as granted and authenticated.
        Otherwise the authentication_function must return one of these values:
        1- False -> To indicate the user is not authenticated
        2- g.user global user instance ->
            + not None: access is granted.
            + None: access is denied.
        3- jsonified error message:
            + It is directly returned to user, e.g.:
                return jsonify(error="Authentication failed!"), 403
        """
        authenticated = False
        if (global_config.DEBUG):
            app.ext_logger.info(
                request.endpoint.replace(":", "/").replace(".", "/").lower())
        # authenticate users here!
        if hasattr(app, "authentication_function"):
            authenticated = app.authentication_function(
                global_config.X_AUTH_TOKEN)
        else:
            return func(*args, **kwargs)

        if authenticated is False:
            return jsonify(errors=["Authentication failed!"]), 403
        elif g.user is not None:
            return func(*args, **kwargs)
        else:
            return authenticated
    return authenticate_requests
项目:grest    作者:mostafa    | 项目源码 | 文件源码
def authorize(func):
    @wraps(func)
    def authorize_requests(*args, **kwargs):
        """
        The authorization_function can be either empty, which
        results in all requests being taken as granted and authorized.
        Otherwise the authorization_function must return one of these values:
        1- False -> To indicate the user is not authorized
        2- g.is_authorized global boolean variable ->
            + True: access is granted.
            + False: access is denied.
        3- jsonified error message:
            + It is directly returned to user, e.g.:
                return jsonify(error="Access denied!"), 401
        """
        authorized = False
        if (global_config.DEBUG):
            app.ext_logger.info(
                request.endpoint.replace(":", "/").replace(".", "/").lower())

        # authorize users here!
        if hasattr(app, "authorization_function"):
            authorized = app.authorization_function(
                global_config.X_AUTH_TOKEN)
        else:
            return func(*args, **kwargs)

        if authorized is False:
            return jsonify(errors=["Access denied!"]), 401
        elif g.is_authorized is True:
            return func(*args, **kwargs)
        else:
            return authorized

    return authorize_requests
项目:Cloudroid    作者:cyberdb    | 项目源码 | 文件源码
def before_request():
    g.user = current_user
项目:Cuneiform    作者:nervouna    | 项目源码 | 文件源码
def before_request():
    g.user = Author.get_current()
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def _before_reques():
    g.user = get_jwt_user()
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def get_jwt_user():
    try:
        token = jwt.request_callback()
        payload = jwt.jwt_decode_callback(token)
        user = jwt.identity_callback(payload)
    except InvalidTokenError:
        user = None
    except JWTError:
        user = None

    return user
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def login_required():
    def decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if g.user is None or not g.user['is_active']:
                return jsonify({'message': "Forbidden"}), 403

            return func(*args, **kwargs)

        return decorated_view

    return decorator
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def user(id):
    user = User.find(id)
    if not user:
        return jsonify({}), 404

    return jsonify(user.serialize()), 200
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def rooms():
    rooms = Room.select('rooms.*') \
        .add_select(
        db.raw(
            '(select m.created_at from messages as m where rooms.id = m.room_id order by m.created_at desc limit 1) as last_message_date')
    ) \
        .add_select(
        db.raw(
            'IF(rooms.is_group,false,(select CONCAT(u.first_name," ",u.last_name) from room_members as mem join users as u on u.id = mem.user_id where mem.room_id = rooms.id and u.id != %s limit 1)) as username' %
            g.user['id'])
    ) \
        .add_select(
        db.raw(
            'IF(rooms.is_group,false,(select u.avatar from room_members as mem join users as u on u.id = mem.user_id where mem.room_id = rooms.id and u.id != %s limit 1)) as avatar' %
            g.user['id'])
    ) \
        .add_select(
        db.raw(
            'IF(rooms.is_group,false,(select u.id from room_members as mem join users as u on u.id = mem.user_id where mem.room_id = rooms.id and u.id != %s limit 1)) as friend_id' %
            g.user['id'])
    ) \
        .add_select(
        db.raw(
            '(select count(m.id) from room_members as mem join messages as m on m.room_id = mem.room_id where mem.user_id = %s and mem.room_id = rooms.id and m.id > IF(mem.last_read_message,mem.last_read_message,0)) as unread_messages' %
            g.user['id'])
    ) \
        .join('room_members as rm', 'rm.room_id', '=', 'rooms.id') \
        .where('rm.user_id', g.user['id']) \
        .group_by('rooms.id') \
        .order_by('last_message_date', 'desc') \
        .get()\
        .serialize()

    for room in rooms:
        if not room['is_group']:
            client = _.findWhere(connected_users, {'id': room['friend_id']})
            room['online'] = True if client else False

    return jsonify(rooms), 200
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def user_leave_room(room_id):
    member = RoomMember.select('room_members.id','room_members.user_id', 'r.user_id as owner_id') \
        .join('rooms as r', 'r.id', '=', 'room_members.room_id') \
        .where('room_members.room_id', room_id) \
        .where('room_members.user_id', g.user['id']) \
        .first()

    if not member:
        return jsonify({'message': "Unknown Room"}), 400

    if member.user_id == member.owner_id:
        Room.where('id', room_id).delete()
        socketio.emit('close_room', {'room_id': room_id}, room='room-%s' % room_id)
        close_room(room='room-%s' % room_id, namespace='/')

    else:
        member.delete()

        clients = _.where(connected_users, {'id': member.user_id})
        if clients and _.isList(clients):
            for item in clients:
                leave_room('room-%s' % room_id, sid=item['sid'], namespace='/')

        socketio.emit('update_members', {'room_id': room_id, 'detach': []}, room='room-%s' % room_id)

    return jsonify({'message': 'Success'}), 200
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def update_counter(room_id):
    data = request.get_json()
    if data and 'message_id' in data:
        try:
            RoomMember.where('user_id', g.user['id']).where('room_id', room_id).update(last_read_message=data['message_id'])
        except Exception:
            return jsonify({'message':'Bad Request'}), 400

    return jsonify({}), 200




# Socket events
项目:Andy-Chat    作者:andriy-sa    | 项目源码 | 文件源码
def me():
    if g.user is None:
        return jsonify({'message': 'User does not exist'}), 401

    return jsonify(g.user), 200
项目:Ranobe-Honyaku    作者:WeebWare    | 项目源码 | 文件源码
def login_required(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        if g.user is None:
            return redirect(url_for("login"))
        return func(*args, **kwargs)
    return wrapped
项目:Ranobe-Honyaku    作者:WeebWare    | 项目源码 | 文件源码
def anon_only(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        if g.user is not None:
            return redirect(url_for("index"))
        return func(*args, **kwargs)
    return wrapped
项目:linkero    作者:ingran    | 项目源码 | 文件源码
def verify_auth_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = User.query.get(data['id'])
        return user
项目:linkero    作者:ingran    | 项目源码 | 文件源码
def verify_password(username_or_token, password):
    # first try to authenticate by token
    user = User.verify_auth_token(username_or_token)
    if not user:
        # try to authenticate with username/password
        user = User.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True
项目:linkero    作者:ingran    | 项目源码 | 文件源码
def new_user():
    if pwd_context.verify(request.values.get('secret'), secret) == False:
        abort(401)    # unauthorized
    username = request.values.get('username')
    password = request.values.get('password')
    if username is None or password is None:
        abort(400)    # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(409)    # existing user
    user = User(username=username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return (jsonify({'username': user.username}), 201,
            {'Location': url_for('get_user', id=user.id, _external=True)})
项目:linkero    作者:ingran    | 项目源码 | 文件源码
def get_user(id):
    user = User.query.get(id)
    if not user:
        abort(400)
    return jsonify({'username': user.username})
项目:linkero    作者:ingran    | 项目源码 | 文件源码
def get_auth_token():
    token = g.user.generate_auth_token(tokenLife)
    return jsonify({'token': token.decode('ascii'), 'duration': tokenLife})
项目:linkero    作者:ingran    | 项目源码 | 文件源码
def verify_auth_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = User.query.get(data['id'])
        return user
项目:linkero    作者:ingran    | 项目源码 | 文件源码
def verify_password(username_or_token, password):
    # first try to authenticate by token
    user = User.verify_auth_token(username_or_token)
    if not user:
        # try to authenticate with username/password
        user = User.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True