Ejemplo n.º 1
0
def dispatchApiCall(reqJson):
    print("Json request:", reqJson)
    if not "mode" in reqJson:
        print("API JSON Request without mode!")
        return getResponse("No mode in API Request!", error=True)

    mode = reqJson["mode"]
    if not mode in DISPATCH_TABLE:
        print("Invalid mode in request: '{mode}'".format(mode=mode))
        return getResponse(
            "Invalid mode in API Request ({mode})!".format(mode=mode),
            error=True)

    dispatch_method, auth_required, csrf_required = DISPATCH_TABLE[mode]
    try:
        if csrf_required:
            csrf.protect()

        if auth_required and not current_user.is_authenticated():
            return getResponse(LOGIN_REQ, error=True)

        else:
            ret = dispatch_method(reqJson)

    except AssertionError as e:
        traceback.print_exc()
        print(reqJson)
        return getResponse("Error processing API request: '%s'!" % e,
                           error=True)

    return ret
Ejemplo n.º 2
0
def dispatchApiCall(reqJson):
	print("Json request:", reqJson)
	if not "mode" in reqJson:
		print("API JSON Request without mode!")
		return getResponse("No mode in API Request!", error=True)

	mode = reqJson["mode"]
	if not mode in DISPATCH_TABLE:
		print("Invalid mode in request: '{mode}'".format(mode=mode))
		return getResponse("Invalid mode in API Request ({mode})!".format(mode=mode), error=True)

	dispatch_method, auth_required, csrf_required = DISPATCH_TABLE[mode]
	try:
		if csrf_required:
			csrf.protect()

		if auth_required and not current_user.is_authenticated():
			return getResponse(LOGIN_REQ, error=True)

		else:
			ret = dispatch_method(reqJson)

	except AssertionError as e:
		traceback.print_exc()
		print(reqJson)
		return getResponse("Error processing API request: '%s'!" % e, error=True)



	return ret
Ejemplo n.º 3
0
def punch(id):
    '''study.punch(id)'''
    csrf.protect()
    video = Video.query.get_or_404(id)
    if not current_user.can_play(video=video):
        abort(403)
    if request.json is None:
        abort(500)
    if not current_user.punched(video=video):
        add_user_log(user=current_user._get_current_object(),
                     event='视频研修:{}'.format(video.name),
                     category='study')
    current_user.punch(video=video, play_time=request.json.get('play_time'))
    db.session.commit()
    if video.lesson.type.name in ['VB', 'Y-GRE', 'Y-GRE AW']:
        # synchronize study progress with Y-System
        punch = current_user.get_punch(video=video)
        if punch.sync_required:
            data = y_system_api_request(api='punch',
                                        token_data={
                                            'user_id': current_user.id,
                                            'section': video.section,
                                        })
            if verify_data_keys(data=data, keys=['success']):
                punch.set_synchronized()
                add_user_log(user=current_user._get_current_object(),
                             event='同步研修进度至Y-System:{}'.format(video.section),
                             category='study')
                db.session.commit()
    return jsonify({
        'progress': current_user.video_progress(video=video),
    })
Ejemplo n.º 4
0
    def signup(self,):
        csrf.protect()
        form = SignUpForm()

        if form.validate_on_submit():
            pass
            # TODO Create User object
            # Log User in

        return redirect(url_for("main.MainView:index"))
Ejemplo n.º 5
0
    def signup(self):
        """ Render the login form.

        Authentication and Authorisation handled by app.backend.auth
        """
        csrf.protect()
        context = {
            'form': SignUpForm()}

        return render_template(
            "main/login.html",
            **context)
Ejemplo n.º 6
0
    def login(self,):
        csrf.protect()
        if current_user.is_authenticated:
            return redirect(url_for("main.MainView:login"))

        form = LoginForm()
        if form.validate_on_submit():
            pass
            #TODO check user password
            #Log user in
        
        return redirect(url_for("main.MainView:index"))
Ejemplo n.º 7
0
def dispatchApiCall(reqJson):

	forwarded_for = request.headers.get('X-Forwarded-For', None)

	# if forwarded_for == '108.28.56.67':
	# 	print("Bouncing possible abuse from %s" % (forwarded_for, ))
	# 	return getResponse("Hi there! Please contact me on github.com/fake-name/wlnupdates before doing bulk scraping, please!", error=True)

	if not "mode" in reqJson:
		print("API JSON Request without mode!")
		return getResponse("No mode in API Request!", error=True)

	mode = reqJson["mode"]
	if not mode in DISPATCH_TABLE:
		print("Invalid mode in request: '{mode}'".format(mode=mode))
		return getResponse("Invalid mode in API Request ({mode})!".format(mode=mode), error=True)

	dispatch_method, auth_required, csrf_required, rate_limited = DISPATCH_TABLE[mode]
	try:
		if csrf_required:
			csrf.protect()

		if auth_required and not current_user.is_authenticated():
			return getResponse(LOGIN_REQ, error=True)

		if rate_limited and not current_user.is_authenticated():
			limiter_key = forwarded_for + " " + mode
			if limiter_key in RATE_LIMITER:
				print("Anon User hit rate limiting. Bouncing.")
				return getResponse("API calls when not logged in are rate limited. Please either log in, or slow down. "
					"Complain at github.com/fake-name/wlnupdates/issues if this is a problem", error=True)

			print("Inserting anon requester into rate-limit cache.")
			RATE_LIMITER[limiter_key] = True

			ret = dispatch_method(reqJson)

		else:
			ret = dispatch_method(reqJson)

	except AssertionError as e:
		traceback.print_exc()
		print(reqJson)
		return getResponse("Error processing API request: '%s'!" % e, error=True)



	return ret
Ejemplo n.º 8
0
def login():
    # Protect with csrf
    csrf.protect()

    # Here we use a class of some kind to represent and validate our
    # client-side form data. For example, WTForms is a library that will
    # handle this for us.
    form = LoginForm()
    if form.validate_on_submit():
        # Login and validate the user.
        login_user(form.user)

        flask.flash('Logged in successfully.')

        next = flask.request.args.get('next')
        if not is_safe_url(next):
            return flask.abort(400)

        return flask.redirect(next or flask.url_for('index'))

    return flask.render_template('login.html', form=form)
Ejemplo n.º 9
0
def check_csrf():
    csrf.protect()
Ejemplo n.º 10
0
 def decorated_function(*args, **kwargs):
     csrf.protect()
     return f(*args, **kwargs)