<commit_before>#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------- #
# Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

ONE_LOCATION = ENV["ONE_LOCATION"]

if !ONE_LOCATION
    LOG_LOCATION = "/var/log/one"
    VAR_LOCATION = "/var/lib/one"
    ETC_LOCATION = "/etc/one"
    RUBY_LIB_LOCATION = "/usr/lib/one/ruby"
else
    VAR_LOCATION = ONE_LOCATION + "/var"
    LOG_LOCATION = ONE_LOCATION + "/var"
    ETC_LOCATION = ONE_LOCATION + "/etc"
    RUBY_LIB_LOCATION = ONE_LOCATION+"/lib/ruby"
end

SUNSTONE_AUTH             = VAR_LOCATION + "/.one/sunstone_auth"
SUNSTONE_LOG              = LOG_LOCATION + "/sunstone.log"
CONFIGURATION_FILE        = ETC_LOCATION + "/sunstone-server.conf"

PLUGIN_CONFIGURATION_FILE = ETC_LOCATION + "/sunstone-plugins.yaml"

SUNSTONE_ROOT_DIR = File.dirname(__FILE__)

$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+'/cloud'
$: << SUNSTONE_ROOT_DIR
$: << SUNSTONE_ROOT_DIR+'/models'

##############################################################################
# Required libraries
##############################################################################
require 'rubygems'
require 'sinatra'
require 'erb'
require 'yaml'

require 'CloudAuth'
require 'SunstoneServer'
require 'SunstonePlugins'


##############################################################################
# Configuration
##############################################################################

begin
    conf = YAML.load_file(CONFIGURATION_FILE)
rescue Exception => e
    STDERR.puts "Error parsing config file #{CONFIGURATION_FILE}: #{e.message}"
    exit 1
end

conf[:debug_level] ||= 3

CloudServer.print_configuration(conf)

#Sinatra configuration

set :config, conf
set :bind, settings.config[:host]
set :port, settings.config[:port]

use Rack::Session::Pool, :key => 'sunstone'

# Enable logger

include CloudLogger
enable_logging SUNSTONE_LOG, settings.config[:debug_level].to_i

begin
    ENV["ONE_CIPHER_AUTH"] = SUNSTONE_AUTH
    cloud_auth = CloudAuth.new(settings.config)
rescue => e
    settings.logger.error {
        "Error initializing authentication system" }
    settings.logger.error { e.message }
    exit -1
end

set :cloud_auth, cloud_auth

##############################################################################
# Helpers
##############################################################################
helpers do
    def authorized?
        session[:ip] && session[:ip]==request.ip ? true : false
    end

    def build_session
        begin
            result = settings.cloud_auth.auth(request.env, params)
        rescue Exception => e
            error 500, ""
            logger.error { e.message }
        end

        if result.nil?
            logger.info { "Unauthorized login attempt" }
            return [401, ""]
        else
            client  = settings.cloud_auth.client(result)
            user_id = OpenNebula::User::SELF

            user    = OpenNebula::User.new_with_id(user_id, client)
            rc = user.info
            if OpenNebula.is_error?(rc)
                logger.error { rc.message }
                return [500, ""]
            end

            session[:user]       = user['NAME']
            session[:user_id]    = user['ID']
            session[:user_gid]   = user['GID']
            session[:user_gname] = user['GNAME']
            session[:ip]         = request.ip
            session[:remember]   = params[:remember]

            #User IU options initialization
            #Load options either from user settings or default config.
            # - LANG
            # - WSS CONECTION

            if user['TEMPLATE/LANG']
                session[:lang] = user['TEMPLATE/LANG']
            else
                session[:lang] = settings.config[:lang]
            end

            if user['TEMPLATE/VNC_WSS']
                session[:wss] = user['TEMPLATE/VNC_WSS']
            else
                wss = settings.config[:vnc_proxy_support_wss]
                #limit to yes,no options
                session[:wss] = (wss == true || wss == "yes" || wss == "only" ?
                                 "yes" : "no")
            end

            #end user options

            if params[:remember] == "true"
                env['rack.session.options'][:expire_after] = 30*60*60*24
            end

            return [204, ""]
        end
    end

    def destroy_session
        session.clear
        return [204, ""]
    end
end

before do
    cache_control :no_store
    unless request.path=='/login' || request.path=='/'
        halt 401 unless authorized?

        @SunstoneServer = SunstoneServer.new(
                              settings.cloud_auth.client(session[:user]),
                              settings.config,
                              settings.logger)
    end
end

after do
    unless request.path=='/login' || request.path=='/'
        unless session[:remember] == "true"
            if params[:timeout] == true
                env['rack.session.options'][:defer] = true
            else
                env['rack.session.options'][:expire_after] = 60*10
            end
        end
    end
end

##############################################################################
# HTML Requests
##############################################################################
get '/' do
    if !authorized?
        if settings.config[:auth] == "x509"
            templ = "login_x509.html"
        else
            templ = "login.html"
        end

        return File.read(File.dirname(__FILE__)+'/templates/'+templ)
    end
    time = Time.now + 60*10
    response.set_cookie("one-user",
                        :value=>"#{session[:user]}",
                        :expires=>time)
    response.set_cookie("one-user_id",
                        :value=>"#{session[:user_id]}",<commit_msg>Fix timeout check in Sunstone<commit_after>#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------- #
# Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

ONE_LOCATION = ENV["ONE_LOCATION"]

if !ONE_LOCATION
    LOG_LOCATION = "/var/log/one"
    VAR_LOCATION = "/var/lib/one"
    ETC_LOCATION = "/etc/one"
    RUBY_LIB_LOCATION = "/usr/lib/one/ruby"
else
    VAR_LOCATION = ONE_LOCATION + "/var"
    LOG_LOCATION = ONE_LOCATION + "/var"
    ETC_LOCATION = ONE_LOCATION + "/etc"
    RUBY_LIB_LOCATION = ONE_LOCATION+"/lib/ruby"
end

SUNSTONE_AUTH             = VAR_LOCATION + "/.one/sunstone_auth"
SUNSTONE_LOG              = LOG_LOCATION + "/sunstone.log"
CONFIGURATION_FILE        = ETC_LOCATION + "/sunstone-server.conf"

PLUGIN_CONFIGURATION_FILE = ETC_LOCATION + "/sunstone-plugins.yaml"

SUNSTONE_ROOT_DIR = File.dirname(__FILE__)

$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+'/cloud'
$: << SUNSTONE_ROOT_DIR
$: << SUNSTONE_ROOT_DIR+'/models'

##############################################################################
# Required libraries
##############################################################################
require 'rubygems'
require 'sinatra'
require 'erb'
require 'yaml'

require 'CloudAuth'
require 'SunstoneServer'
require 'SunstonePlugins'


##############################################################################
# Configuration
##############################################################################

begin
    conf = YAML.load_file(CONFIGURATION_FILE)
rescue Exception => e
    STDERR.puts "Error parsing config file #{CONFIGURATION_FILE}: #{e.message}"
    exit 1
end

conf[:debug_level] ||= 3

CloudServer.print_configuration(conf)

#Sinatra configuration

set :config, conf
set :bind, settings.config[:host]
set :port, settings.config[:port]

use Rack::Session::Pool, :key => 'sunstone'

# Enable logger

include CloudLogger
enable_logging SUNSTONE_LOG, settings.config[:debug_level].to_i

begin
    ENV["ONE_CIPHER_AUTH"] = SUNSTONE_AUTH
    cloud_auth = CloudAuth.new(settings.config)
rescue => e
    settings.logger.error {
        "Error initializing authentication system" }
    settings.logger.error { e.message }
    exit -1
end

set :cloud_auth, cloud_auth

##############################################################################
# Helpers
##############################################################################
helpers do
    def authorized?
        session[:ip] && session[:ip]==request.ip ? true : false
    end

    def build_session
        begin
            result = settings.cloud_auth.auth(request.env, params)
        rescue Exception => e
            error 500, ""
            logger.error { e.message }
        end

        if result.nil?
            logger.info { "Unauthorized login attempt" }
            return [401, ""]
        else
            client  = settings.cloud_auth.client(result)
            user_id = OpenNebula::User::SELF

            user    = OpenNebula::User.new_with_id(user_id, client)
            rc = user.info
            if OpenNebula.is_error?(rc)
                logger.error { rc.message }
                return [500, ""]
            end

            session[:user]       = user['NAME']
            session[:user_id]    = user['ID']
            session[:user_gid]   = user['GID']
            session[:user_gname] = user['GNAME']
            session[:ip]         = request.ip
            session[:remember]   = params[:remember]

            #User IU options initialization
            #Load options either from user settings or default config.
            # - LANG
            # - WSS CONECTION

            if user['TEMPLATE/LANG']
                session[:lang] = user['TEMPLATE/LANG']
            else
                session[:lang] = settings.config[:lang]
            end

            if user['TEMPLATE/VNC_WSS']
                session[:wss] = user['TEMPLATE/VNC_WSS']
            else
                wss = settings.config[:vnc_proxy_support_wss]
                #limit to yes,no options
                session[:wss] = (wss == true || wss == "yes" || wss == "only" ?
                                 "yes" : "no")
            end

            #end user options

            if params[:remember] == "true"
                env['rack.session.options'][:expire_after] = 30*60*60*24
            end

            return [204, ""]
        end
    end

    def destroy_session
        session.clear
        return [204, ""]
    end
end

before do
    cache_control :no_store
    unless request.path=='/login' || request.path=='/'
        halt 401 unless authorized?

        @SunstoneServer = SunstoneServer.new(
                              settings.cloud_auth.client(session[:user]),
                              settings.config,
                              settings.logger)
    end
end

after do
    unless request.path=='/login' || request.path=='/'
        unless session[:remember] == "true"
            if params[:timeout] == "true"
                env['rack.session.options'][:defer] = true
            else
                env['rack.session.options'][:expire_after] = 60*10
            end
        end
    end
end

##############################################################################
# HTML Requests
##############################################################################
get '/' do
    if !authorized?
        if settings.config[:auth] == "<PASSWORD>"
            templ = "login_x509.html"
        else
            templ = "login.html"
        end

        return File.read(File.dirname(__FILE__)+'/templates/'+templ)
    end
    time = Time.now + 60*10
    response.set_cookie("one-user",
                        :value=>"#{session[:user]}",
                        :expires=>time)
    response.set_cookie("one-user_id",
                        :value=>"#{session[:user_id]}",
{'fraction_non_alphanumeric': 0.20796651753499784, 'fraction_numerical': 0.007865492856111994, 'mean_word_length': 1.9060599706437409, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 28, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6251973', 'n_tokens_mistral': 3752, 'n_tokens_neox': 3523, 'n_words': 801}