From 1c3a1a6aaba3f07222f9f1959bfe9a2a4f1141f9 Mon Sep 17 00:00:00 2001 From: "leo.selig" Date: Fri, 12 Feb 2016 11:08:14 +0100 Subject: [PATCH] Authenticate action import_proforma_xml via OAuth2 - currently done manually, we should definitely consider a gem here (doorkeeper) - right now, the provided Bearer token from the Authorization header is just looked up in the configured code harbor links of the current user, if one is found -> authenticated -> exercise gets imported (leoselig/codeocean#1) --- app/controllers/exercises_controller.rb | 50 +++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/app/controllers/exercises_controller.rb b/app/controllers/exercises_controller.rb index 39324272..85a3650b 100644 --- a/app/controllers/exercises_controller.rb +++ b/app/controllers/exercises_controller.rb @@ -67,11 +67,55 @@ class ExercisesController < ApplicationController end def import_thin_common_cartridge - logger.info(request.headers['Authorization']) - logger.info(request.headers['Authorisation']) - render :nothing => true, :status => 200, :content_type => 'text/html' + begin + user = user_for_oauth2_request() + exercise = Exercise.new + exercise.from_proforma_xml(request.body.read) + exercise.update(:user => user) + saved = exercise.save + if saved + render :text => 'SUCCESS', :status => 200 + else + render :text => 'Invalid exercise', :status => 400 + end + rescue => error + if error.class == Hash + render :text => error.message, :status => error.status + else + raise error + render :text => '', :status => 500 + end + end end + def user_for_oauth2_request + authorizationHeader = request.headers['Authorization'] + if authorizationHeader == nil + raise ({status: 401, message: 'No Authorization header'}) + end + + oauth2Token = authorizationHeader.split(' ')[1] + if oauth2Token == nil || oauth2Token.size == 0 + raise ({status: 401, message: 'No token in Authorization header'}) + end + + user = user_by_code_harbor_token(oauth2Token) + if user == nil + raise ({status: 401, message: 'Unknown OAuth2 token'}) + end + + return user + end + private :user_for_oauth2_request + + def user_by_code_harbor_token(oauth2Token) + link = CodeHarborLink.where(:oauth2token => oauth2Token)[0] + if link != nil + return link.user + end + end + private :user_by_code_harbor_token + def exercise_params params[:exercise].permit(:description, :execution_environment_id, :file_id, :instructions, :public, :hide_file_tree, :team_id, :title, files_attributes: file_attributes).merge(user_id: current_user.id, user_type: current_user.class.name) end