summaryrefslogtreecommitdiff
path: root/lib/helper.rb
blob: bb0279e1b434c341a14a68621be68ccf14cef731 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
helpers do

  # Authentification
  def protected!(subjectid)
    if env["session"]
      unless authorized?(subjectid)
        flash[:notice] = "You don't have access to this section: "
        redirect back
      end
    elsif !env["session"] && subjectid
      unless authorized?(subjectid)
        throw(:halt, [401, "Not authorized.\n"])
        redirect back
      end
    else
      throw(:halt, [401, "Not authorized.\n"]) unless authorized?(subjectid)
    end
  end

  def authorized?(subjectid)
    if CONFIG[:authorization][:authorize_request].include?(request.env['REQUEST_METHOD'])
      ret = OpenTox::Authorization.authorize("#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}#{request.env['REQUEST_URI']}", request.env['REQUEST_METHOD'], subjectid)
      LOGGER.debug "OpenTox helpers OpenTox::Authorization authorized? method: #{request.env['REQUEST_METHOD']}, URI: #{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}#{request.env['REQUEST_URI']}, subjectid: #{subjectid} with return #{ret}."
      return ret
    end
    if CONFIG[:authorization][:authenticate_request].include?(env['REQUEST_METHOD'])
      if OpenTox::Authorization.is_token_valid(subjectid)
        return true
      end
    end
    LOGGER.debug "Not authorized for: #{request.env['rack.url_scheme']}://#{request['REQUEST_URI']} with Method: #{request.env['REQUEST_METHOD']} with Token #{subjectid}"
    return false
  end

  def unprotected_requests
    case  env['REQUEST_URI']
    when /\/login$|\/logout$|\/predict$|\/toxcreate\/models$/
      return true
    when /\/compound|\/feature|\/task|\/toxcreate/   #to fix: read from config | validation should be protected
      return true
    else
      return false
    end
   end

  def check_subjectid(subjectid)
    return false if !subjectid
    return true if subjectid.size > 62
    false
  end
end

before do
  unless !AA_SERVER or unprotected_requests or CONFIG[:authorization][:free_request].include?(env['REQUEST_METHOD']) 
    begin
      subjectid = session[:subjectid] if session[:subjectid]
      subjectid = params[:subjectid]  if params[:subjectid]  and !check_subjectid(subjectid)
      subjectid = request.env['HTTP_SUBJECTID'] if request.env['HTTP_SUBJECTID'] and !check_subjectid(subjectid)
      # see http://rack.rubyforge.org/doc/SPEC.html
      subjectid = CGI.unescape(subjectid) if subjectid.include?("%23")
    rescue
      LOGGER.debug "OpenTox ruby api wrapper: helper before filter: NO subjectid for URI: #{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}#{request.env['REQUEST_URI']}"
      subjectid = ""
    end
    @subjectid = subjectid
    protected!(subjectid)
  end
end