repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
pjk25/cf-uaa-lib
spec/token_issuer_spec.rb
#-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'set' require 'spec_helper' require 'uaa/token_issuer' module CF::UAA describe TokenIssuer do let(:options) { {} } before do #Util.default_logger(:trace) @issuer = TokenIssuer.new('http://test.uaa.target', 'test_client', 'test_secret', options) end subject { @issuer } describe 'initialize' do let(:options) { {:http_proxy => 'http-proxy.com', :https_proxy => 'https-proxy.com', :skip_ssl_validation => true} } it 'sets skip_ssl_validation' do subject.skip_ssl_validation == true end end context 'with client credentials grant' do it 'gets a token with client credentials' do subject.set_request_handler do |url, method, body, headers| headers['content-type'].should =~ /application\/x-www-form-urlencoded/ headers['accept'].should =~ /application\/json/ # TODO check basic auth header url.should == 'http://test.uaa.target/oauth/token' method.should == :post reply = {:access_token => 'test_<PASSWORD>', :token_type => 'BEARER', :scope => 'logs.read', :expires_in => 98765} [200, Util.json(reply), {'content-type' => 'application/json'}] end token = subject.client_credentials_grant('logs.read') token.should be_an_instance_of TokenInfo token.info['access_token'].should == 'test_access_token' token.info['token_type'].should =~ /^bearer$/i token.info['scope'].should == 'logs.read' token.info['expires_in'].should == 98765 end it 'gets all granted scopes if none specified' do subject.set_request_handler do |url, method, body, headers| reply = {:access_token => 'test_<PASSWORD>', :token_type => 'BEARER', :scope => 'openid logs.read', :expires_in => 98765} [200, Util.json(reply), {'content-type' => 'application/json'}] end token = subject.client_credentials_grant Util.arglist(token.info['scope']).to_set.should == Util.arglist('openid logs.read').to_set end it 'raises a bad response error if response content type is not json' do subject.set_request_handler { [200, 'not json', {'content-type' => 'text/html'}] } expect {subject.client_credentials_grant}.to raise_exception BadResponse end it 'raises a bad response error if the response is not proper json' do subject.set_request_handler { [200, 'bad json', {'content-type' => 'application/json'}] } expect {subject.client_credentials_grant}.to raise_exception BadResponse end it 'raises a target error if the response is 400 with valid oauth json error' do subject.set_request_handler { [400, '{"error":"invalid scope"}', {'content-type' => 'application/json'}] } expect {subject.client_credentials_grant('bad.scope')}.to raise_exception TargetError end end context 'with owner password grant' do it 'gets a token with owner password' do subject.set_request_handler do |url, method, body, headers| headers['content-type'].should =~ /application\/x-www-form-urlencoded/ headers['accept'].should =~ /application\/json/ # TODO check basic auth header url.should == 'http://test.uaa.target/oauth/token' method.should == :post reply = {:access_token => 'test_access_token', :token_type => 'BEARER', :scope => 'openid', :expires_in => 98765} [200, Util.json(reply), {'content-type' => 'application/json'}] end token = subject.owner_password_grant('jo<PASSWORD>', "?<PASSWORD>$@ ", 'openid') token.should be_an_instance_of TokenInfo token.info['access_token'].should == 'test_access_token' token.info['token_type'].should =~ /^bearer$/i token.info['scope'].should == 'openid' token.info['expires_in'].should == 98765 end it 'gets a token with passcode' do subject.set_request_handler do |url, method, body, headers| headers['content-type'].should =~ /application\/x-www-form-urlencoded/ headers['accept'].should =~ /application\/json/ # TODO check basic auth header url.should == 'http://test.uaa.target/oauth/token' body.should =~ /(^|&)passcode=12345($|&)/ body.should =~ /(^|&)grant_type=password($|&)/ method.should == :post reply = {:access_token => 'test_access_token', :token_type => 'BEARER', :scope => 'openid', :expires_in => 98765} [200, Util.json(reply), {'content-type' => 'application/json'}] end token = subject.passcode_grant('12345') token.should be_an_instance_of TokenInfo token.info['access_token'].should == 'test_access_token' token.info['token_type'].should =~ /^bearer$/i token.info['scope'].should == 'openid' token.info['expires_in'].should == 98765 end end describe '#owner_password_credentials_grant' do it 'gets a token grant type password' do subject.set_request_handler do |url, method, body, headers| headers['content-type'].should =~ /application\/x-www-form-urlencoded/ headers['accept'].should =~ /application\/json/ url.should == 'http://test.uaa.target/oauth/token' method.should == :post body.split('&').should =~ ['passcode=<PASSWORD>', 'grant_type=password'] reply = {:access_token => 'test_access_token', :token_type => 'BEARER', :scope => 'openid', :expires_in => 98765} [200, Util.json(reply), {'content-type' => 'application/json'}] end token = subject.owner_password_credentials_grant({passcode: '<PASSWORD>'}) token.should be_an_instance_of TokenInfo token.info['access_token'].should == 'test_access_token' token.info['token_type'].should =~ /^bearer$/i token.info['scope'].should == 'openid' token.info['expires_in'].should == 98765 end end context 'with implicit grant' do it 'gets the prompts for credentials used to authenticate implicit grant' do subject.set_request_handler do |url, method, body, headers| info = { :prompts => {:username => ['text', 'Username'], :password => ['password', 'Password']} } [200, Util.json(info), {'content-type' => 'application/json'}] end result = subject.prompts result.should_not be_empty end it 'raises a bad target error if no prompts are received' do subject.set_request_handler do |url, method, body, headers| [200, Util.json({}), {'content-type' => 'application/json'}] end expect { subject.prompts }.to raise_exception BadResponse end context '#implicit_grant_with_creds' do it 'gets only an access token, no openid in scope' do subject.set_request_handler do |url, method, body, headers| headers['content-type'].should =~ /application\/x-www-form-urlencoded/ headers['accept'].should =~ /application\/json/ url.should match 'http://test.uaa.target/oauth/authorize' (state = /state=([^&]+)/.match(url)[1]).should_not be_nil method.should == :post location = 'https://uaa.cloudfoundry.com/redirect/test_client#' + 'access_token=test_access_token&token_type=bearer&' + "expires_in=98765&scope=logs.read&state=#{state}" [302, nil, {'content-type' => 'application/json', 'location' => location}] end expect(subject).to receive(:authorize_path_args).with('token', 'https://uaa.cloudfoundry.com/redirect/test_client', 'logs.read', anything) subject.stub(:random_state).and_return('1234') subject.stub(:authorize_path_args).and_return('/oauth/authorize?state=1234&scope=logs.read') token = subject.implicit_grant_with_creds({:username => 'joe+admin', :password => <PASSWORD>$@ "}, 'logs.read') token.should be_an_instance_of TokenInfo token.info['access_token'].should == 'test_access_token' token.info['token_type'].should =~ /^bearer$/i Util.arglist(token.info['scope']).to_set.should == Util.arglist('logs.read').to_set token.info['expires_in'].should == 98765 end it 'also asks for an id_token if scope contains openid' do subject.set_request_handler do |url, method, body, headers| location = 'https://uaa.cloudfoundry.com/redirect/test_client#' + 'access_token=test_access_token&id_token=test-id_token&token_type=bearer&' + 'expires_in=98765&scope=openid+logs.read&state=1234' [302, nil, {'content-type' => 'application/json', 'location' => location}] end expect(subject).to receive(:authorize_path_args).with('token id_token', 'https://uaa.cloudfoundry.com/redirect/test_client', 'openid logs.read', anything) subject.stub(:random_state).and_return('1234') subject.implicit_grant_with_creds({:username => 'joe+admin', :password => <PASSWORD>$@ "}, 'openid logs.read') end end it 'rejects an access token with wrong state' do subject.set_request_handler do |url, method, body, headers| location = 'https://uaa.cloudfoundry.com/redirect/test_client#' + 'access_token=test_access_token&token_type=bearer&' + 'expires_in=98765&scope=openid+logs.read&state=bad_state' [302, nil, {'content-type' => 'application/json', 'location' => location}] end expect {token = subject.implicit_grant_with_creds(:username => 'joe+admin', :password => <PASSWORD>$@ ")}.to raise_exception BadResponse end it 'asks for an id_token with openid scope' do uri_parts = subject.implicit_uri('http://call.back/uri_path', 'openid logs.read').split('?') params = Util.decode_form(uri_parts[1]) params['response_type'].should == 'token id_token' end it "only asks for token if scope isn't openid" do uri_parts = subject.implicit_uri('http://call.back/uri_path').split('?') params = Util.decode_form(uri_parts[1]) params['response_type'].should == 'token' end end context 'with auth code grant' do it 'gets the authcode uri to be sent to the user agent for an authcode' do redir_uri = 'http://call.back/uri_path' uri_parts = subject.authcode_uri(redir_uri, 'openid').split('?') uri_parts[0].should == 'http://test.uaa.target/oauth/authorize' params = Util.decode_form(uri_parts[1]) params['response_type'].should == 'code' params['client_id'].should == 'test_client' params['scope'].should == 'openid' params['redirect_uri'].should == redir_uri params['state'].should_not be_nil end it 'gets an access token with an authorization code' do subject.set_request_handler do |url, method, body, headers| headers['content-type'].should =~ /application\/x-www-form-urlencoded/ headers['accept'].should =~ /application\/json/ # TODO check basic auth header url.should match 'http://test.uaa.target/oauth/token' method.should == :post reply = {:access_token => 'test_access_token', :token_type => 'BEARER', :scope => 'openid', :expires_in => 98765} [200, Util.json(reply), {'content-type' => 'application/json'}] end cburi = 'http://call.back/uri_path' redir_uri = subject.authcode_uri(cburi) state = /state=([^&]+)/.match(redir_uri)[1] reply_query = "state=#{state}&code=kz8%2F5gQZ2pc%3D" token = subject.authcode_grant(redir_uri, reply_query) token.should be_an_instance_of TokenInfo token.info['access_token'].should == 'test_access_token' token.info['token_type'].should =~ /^bearer$/i token.info['scope'].should == 'openid' token.info['expires_in'].should == 98765 end end end end
pjk25/cf-uaa-lib
lib/uaa/token_coder.rb
<gh_stars>0 #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require "openssl" require "uaa/util" module CF::UAA # this code does not support the given token signature algorithim class SignatureNotSupported < DecodeError; end # this instance policy does not accept the given token signature algorithim class SignatureNotAccepted < DecodeError; end class InvalidSignature < DecodeError; end class InvalidTokenFormat < DecodeError; end class TokenExpired < AuthError; end class InvalidAudience < AuthError; end # This class is for OAuth Resource Servers. # Resource Servers get tokens and need to validate and decode them, # but they do not obtain them from the Authorization Server. This # class is for resource servers which accept bearer JWT tokens. # # For more on JWT, see the JSON Web Token RFC here: # {http://tools.ietf.org/id/draft-ietf-oauth-json-web-token-05.html} # # An instance of this class can be used to decode and verify the contents # of a bearer token. Methods of this class can validate token signatures # with a secret or public key, and they can also enforce that the token # is for a particular audience. class TokenCoder def self.init_digest(algo) # @private OpenSSL::Digest.new(algo.sub('HS', 'sha').sub('RS', 'sha')) end def self.normalize_options(opts) # @private opts = opts.dup pk = opts[:pkey] opts[:pkey] = OpenSSL::PKey::RSA.new(pk) if pk && !pk.is_a?(OpenSSL::PKey::PKey) opts[:audience_ids] = Util.arglist(opts[:audience_ids]) opts[:algorithm] = 'HS256' unless opts[:algorithm] opts[:verify] = true unless opts.key?(:verify) opts[:accept_algorithms] = Util.arglist(opts[:accept_algorithms], ["HS256", "HS384", "HS512", "RS256", "RS384", "RS512"]) opts end # Constructs a signed JWT. # @param token_body Contents of the token in any object that can be converted to JSON. # @param options (see #initialize) # @return [String] a signed JWT token string in the form "xxxx.xxxxx.xxxx". def self.encode(token_body, options = {}, obsolete1 = nil, obsolete2 = nil) unless options.is_a?(Hash) && obsolete1.nil? && obsolete2.nil? # deprecated: def self.encode(token_body, skey, pkey = nil, algo = 'HS256') warn "#{self.class}##{__method__} is deprecated with these parameters. Please use options hash." options = {:skey => options } options[:pkey], options[:algorithm] = obsolete1, obsolete2 end options = normalize_options(options) algo = options[:algorithm] segments = [Util.json_encode64("typ" => "JWT", "alg" => algo)] segments << Util.json_encode64(token_body) if ["HS256", "HS384", "HS512"].include?(algo) sig = OpenSSL::HMAC.digest(init_digest(algo), options[:skey], segments.join('.')) elsif ["RS256", "RS384", "RS512"].include?(algo) sig = options[:pkey].sign(init_digest(algo), segments.join('.')) elsif algo == "none" sig = "" else raise SignatureNotSupported, "unsupported signing method" end segments << Util.encode64(sig) segments.join('.') end # Decodes a JWT token and optionally verifies the signature. Both a # symmetrical key and a public key can be provided for signature verification. # The JWT header indicates what signature algorithm was used and the # corresponding key is used to verify the signature (if +verify+ is true). # @param [String] token A JWT token as returned by {TokenCoder.encode} # @param options (see #initialize) # @return [Hash] the token contents def self.decode(token, options = {}, obsolete1 = nil, obsolete2 = nil) unless options.is_a?(Hash) && obsolete1.nil? && obsolete2.nil? # deprecated: def self.decode(token, skey = nil, pkey = nil, verify = true) warn "#{self.class}##{__method__} is deprecated with these parameters. Please use options hash." options = {:skey => options } options[:pkey], options[:verify] = obsolete1, obsolete2 end options = normalize_options(options) segments = token.split('.') raise InvalidTokenFormat, "Not enough or too many segments" unless [2,3].include? segments.length header_segment, payload_segment, crypto_segment = segments signing_input = [header_segment, payload_segment].join('.') header = Util.json_decode64(header_segment) payload = Util.json_decode64(payload_segment, (:sym if options[:symbolize_keys])) return payload unless options[:verify] raise SignatureNotAccepted, "Signature algorithm not accepted" unless options[:accept_algorithms].include?(algo = header["alg"]) return payload if algo == 'none' signature = Util.decode64(crypto_segment) if ["HS256", "HS384", "HS512"].include?(algo) raise InvalidSignature, "Signature verification failed" unless options[:skey] && constant_time_compare(signature, OpenSSL::HMAC.digest(init_digest(algo), options[:skey], signing_input)) elsif ["RS256", "RS384", "RS512"].include?(algo) raise InvalidSignature, "Signature verification failed" unless options[:pkey] && options[:pkey].verify(init_digest(algo), signature, signing_input) else raise SignatureNotSupported, "Algorithm not supported" end payload end # Takes constant time to compare 2 strings (HMAC digests in this case) # to avoid timing attacks while comparing the HMAC digests # @param [String] a: the first digest to compare # @param [String] b: the second digest to compare # @return [boolean] true if they are equal, false otherwise def self.constant_time_compare(a, b) if a.length != b.length return false end result = 0 a.chars.zip(b.chars).each do |x, y| result |= x.ord ^ y.ord end result == 0 end # Creates a new token en/decoder for a service that is associated with # the the audience_ids, the symmetrical token validation key, and the # public and/or private keys. # @param [Hash] options Supported options: # * :audience_ids [Array<String>, String] -- An array or space separated # string of values which indicate the token is intended for this service # instance. It will be compared with tokens as they are decoded to ensure # that the token was intended for this audience. # * :skey [String] -- used to sign and validate tokens using symmetrical # key algoruthms # * :pkey [String, File, OpenSSL::PKey::PKey] -- may be a String or File in # PEM or DER formats. May include public and/or private key data. The # private key is used to sign tokens and the public key is used to # validate tokens. # * :algorithm [String] -- Sets default used for encoding. May be HS256, # HS384, HS512, RS256, RS384, RS512, or none. # * :verify [String] -- Verifies signatures when decoding tokens. Defaults # to +true+. # * :accept_algorithms [String, Array<String>] -- An Array or space separated # string of values which list what algorthms are accepted for token # signatures. Defaults to all possible values of :algorithm except 'none'. # @note the TokenCoder instance must be configured with the appropriate # key material to support particular algorithm families and operations # -- i.e. :pkey must include a private key in order to sign tokens with # the RS algorithms. def initialize(options = {}, obsolete1 = nil, obsolete2 = nil) unless options.is_a?(Hash) && obsolete1.nil? && obsolete2.nil? # deprecated: def initialize(audience_ids, skey, pkey = nil) warn "#{self.class}##{__method__} is deprecated with these parameters. Please use options hash." options = {:audience_ids => options } options[:skey], options[:pkey] = obsolete1, obsolete2 end @options = self.class.normalize_options(options) end # Encode a JWT token. Takes a hash of values to use as the token body. # Returns a signed token in JWT format (header, body, signature). # @param token_body (see TokenCoder.encode) # @param [String] algorithm -- overrides default. See {#initialize} for possible values. # @return (see TokenCoder.encode) def encode(token_body = {}, algorithm = nil) token_body[:aud] = @options[:audience_ids] if @options[:audience_ids] && !token_body[:aud] && !token_body['aud'] token_body[:exp] = Time.now.to_i + 7 * 24 * 60 * 60 unless token_body[:exp] || token_body['exp'] self.class.encode(token_body, algorithm ? @options.merge(:algorithm => algorithm) : @options) end # Returns hash of values decoded from the token contents. If the # audience_ids were specified in the options to this instance (see #initialize) # and the token does not contain one or more of those audience_ids, an # AuthError will be raised. AuthError is raised if the token has expired. # @param [String] auth_header (see Scim.initialize#auth_header) # @return (see TokenCoder.decode) def decode(auth_header) decode_at_reference_time(auth_header, Time.now.to_i) end # Returns hash of values decoded from the token contents, # taking reference_time as the comparison time for expiration. If the # audience_ids were specified in the options to this instance (see #initialize) # and the token does not contain one or more of those audience_ids, an # AuthError will be raised. AuthError is raised if the token has expired. # @param [String] auth_header (see Scim.initialize#auth_header) # @param [Integer] reference_time # @return (see TokenCoder.decode) def decode_at_reference_time(auth_header, reference_time) unless auth_header && (tkn = auth_header.split(' ')).length == 2 && tkn[0] =~ /^bearer$/i raise InvalidTokenFormat, "invalid authentication header: #{auth_header}" end reply = self.class.decode(tkn[1], @options) auds = Util.arglist(reply[:aud] || reply['aud']) if @options[:audience_ids] && (!auds || (auds & @options[:audience_ids]).empty?) raise InvalidAudience, "invalid audience: #{auds}" end exp = reply[:exp] || reply['exp'] unless exp.is_a?(Integer) && exp > reference_time raise TokenExpired, "token expired" end reply end end end
pjk25/cf-uaa-lib
lib/uaa/info.rb
<filename>lib/uaa/info.rb #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'uaa/http' module CF::UAA # Provides interfaces to various UAA endpoints that are not in the context # of an overall class of operations like SCIM resources or OAuth2 tokens. class Info include Http attr_accessor :target attr_reader :key_style # @param [String] target The base URL of the server. For example the target could # be {https://login.cloudfoundry.com}, {https://uaa.cloudfoundry.com}, or # {http://localhost:8080/uaa}. # @param [Hash] options can be # * +:symbolize_keys+, If set to true, response hashes will have symbols for their keys, otherwise # string keys are returned. def initialize(target, options = {}) self.target = target self.symbolize_keys = options[:symbolize_keys] initialize_http_options(options) end # sets whether the keys in returned hashes should be symbols. # @return [Boolean] the new state def symbolize_keys=(bool) @key_style = bool ? :sym : nil end # Gets information about the user authenticated by the token in the # +auth_header+. It GETs from the +target+'s +/userinfo+ endpoint and # returns user information as specified by OpenID Connect. # @see http://openid.net/connect/ # @see http://openid.net/specs/openid-connect-standard-1_0.html#userinfo_ep # @see http://openid.net/specs/openid-connect-messages-1_0.html#anchor9 # @param (see Misc.server) # @param [String] auth_header see {TokenInfo#auth_header} # @return [Hash] def whoami(auth_header) json_get(target, "/userinfo?schema=openid", key_style, "authorization" => auth_header) end # Gets various monitoring and status variables from the server. # Authenticates using +name+ and +pwd+ for basic authentication. # @param (see Misc.server) # @return [Hash] def varz(name, pwd) json_get(target, "/varz", key_style, "authorization" => Http.basic_auth(name, pwd)) end # Gets basic information about the target server, including version number, # commit ID, and links to API endpoints. # @return [Hash] def server reply = json_get(target, '/login', key_style) return reply if reply && (reply[:prompts] || reply['prompts']) raise BadResponse, "Invalid response from target #{target}" end # Gets a base url for the associated UAA from the target server by inspecting the # links returned from its info endpoint. # @return [String] url of UAA (or the target itself if it didn't provide a response) def discover_uaa info = server links = info['links'] || info[:links] uaa = links && (links['uaa'] || links[:uaa]) uaa || target end # Gets the key from the server that is used to validate token signatures. If # the server is configured to use a symetric key, the caller must authenticate # by providing a a +client_id+ and +client_secret+. If the server # is configured to sign with a private key, this call will retrieve the # public key and +client_id+ must be nil. # @param (see Misc.server) # @return [Hash] def validation_key(client_id = nil, client_secret = nil) hdrs = client_id && client_secret ? { "authorization" => Http.basic_auth(client_id, client_secret)} : {} json_get(target, "/token_key", key_style, hdrs) end # Gets all currently valid token verification keys. If the server has had # its signing key changed, then +/token_key+ will return a verification key # that does not match a JWT token issued before the change. To validate the # signature of these tokens, refer to the +kid+ header of the JWT token. The # +validation_keys_hash+ method returns a hash of all currently valid # verification keys, indexed by +kid+. To retrieve symmetric keys as part of # the result, client credentials are required. # @param (see Misc.server) # @return [Hash] def validation_keys_hash(client_id = nil, client_secret = nil) hdrs = client_id && client_secret ? { "authorization" => Http.basic_auth(client_id, client_secret)} : {} response = json_get(target, "/token_keys", key_style, hdrs) keys_map = {} response['keys'].each do |key| keys_map[key['kid']] = key end keys_map end # Sends +token+ to the server to validate and decode. Authenticates with # +client_id+ and +client_secret+. If +audience_ids+ are specified and the # token's "aud" attribute does not contain one or more of the audience_ids, # raises AuthError -- meaning the token is not for this audience. # @param (see Misc.server) # @param [String] token an access token as retrieved by {TokenIssuer}. See # also {TokenInfo}. # @param [String] token_type as retrieved by {TokenIssuer}. See {TokenInfo}. # @return [Hash] contents of the token def decode_token(client_id, client_secret, token, token_type = "bearer", audience_ids = nil) reply = json_parse_reply(key_style, *request(target, :post, '/check_token', Util.encode_form(:token => token), "authorization" => Http.basic_auth(client_id, client_secret), "content-type" => Http::FORM_UTF8,"accept" => Http::JSON_UTF8)) auds = Util.arglist(reply[:aud] || reply['aud']) if audience_ids && (!auds || (auds & audience_ids).empty?) raise AuthError, "invalid audience: #{auds.join(' ')}" end reply end # Gets information about the given password, including a strength score and # an indication of what strength is required. # @param (see Misc.server) # @return [Hash] def password_strength(password) json_parse_reply(key_style, *request(target, :post, '/password/score', Util.encode_form(:password => password), "content-type" => Http::FORM_UTF8, "accept" => Http::JSON_UTF8)) end end end
pjk25/cf-uaa-lib
spec/http_spec.rb
#-- # Cloud Foundry 2012.02.03 Beta # Copyright (c) [2009-2012] VMware, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'spec_helper' require 'uaa/http' require 'uaa/version' describe CF::UAA::Http do class HttpTest include CF::UAA::Http public :http_get end let(:http_instance) { HttpTest.new } let(:http_double) do http_double = double('http').as_null_object expect(HTTPClient).to receive(:new).and_return(http_double) http_double end let(:cert_store) { double('OpenSSL::X509::Store') } describe 'set_request_handler' do it 'sets a request handler' do http_instance.set_request_handler do |url, method, body, headers| [200, 'body', {'content-type' => 'text/plain'}] end status, body, resp_headers = http_instance.http_get('http://example.com') status.should == 200 body.should == 'body' resp_headers['content-type'].should == 'text/plain' end end describe 'http_get' do context 'when response has no status' do let(:response) { double('http::message') } it 'raises an HTTPException error' do expect(response).to receive(:status) expect(response).to receive(:content).and_return('TEST') expect(http_double).to receive(:get).and_return(response) expect { http_instance.http_get('https://example.com') }.to raise_error(CF::UAA::HTTPException, "Can't parse response from the server TEST") end end context 'when certificate is not valid' do it 'raises an SSLException' do expect(http_double).to receive(:get).and_raise(OpenSSL::SSL::SSLError) expect { http_instance.http_get('https://example.com') }.to raise_error(CF::UAA::SSLException) end end context 'when skipping ssl validation' do let(:ssl_config) { double('ssl_config') } it 'sets verify mode to VERIFY_NONE' do http_instance.initialize_http_options({skip_ssl_validation: true}) expect(http_double).to receive(:ssl_config).and_return(ssl_config) expect(ssl_config).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE) http_instance.http_get('https://uncached.example.com') end end context 'when validating ssl' do let(:ssl_config) { double('ssl_config') } it 'sets default values' do expect(http_double).to receive(:ssl_config).and_return(ssl_config) expect(ssl_config).to receive(:set_default_paths) http_instance.http_get('https://example.com') end end context 'when ssl certificate is provided' do let(:ssl_config) { double('ssl_config') } it 'passes it' do http_instance.initialize_http_options({ssl_ca_file: '/fake-ca-file'}) expect(http_double).to receive(:ssl_config).and_return(ssl_config).twice expect(ssl_config).to receive(:set_trust_ca).with('/fake-ca-file') expect(ssl_config).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER) http_instance.http_get('https://uncached.example.com') end end context 'when ssl cert store is provided' do let(:ssl_config) { double('ssl_config') } it 'passes it' do http_instance.initialize_http_options({ssl_cert_store: cert_store}) expect(http_double).to receive(:ssl_config).and_return(ssl_config).twice expect(ssl_config).to receive(:cert_store=).with(cert_store) expect(ssl_config).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER) http_instance.http_get('https://uncached.example.com') end end context 'when an http request timeout is provided' do it 'sets all timeouts on the http clien to the http_timeout' do http_instance.initialize_http_options({http_timeout: 10}) expect(http_double).to receive(:connect_timeout=).with(10) expect(http_double).to receive(:send_timeout=).with(10) expect(http_double).to receive(:receive_timeout=).with(10) http_instance.http_get('https://uncached.example.com') end end context 'when an http request timeout is not provided' do it 'does not override the default' do http_instance.initialize_http_options({}) expect(http_double).not_to receive(:connect_timeout=) expect(http_double).not_to receive(:send_timeout=) expect(http_double).not_to receive(:receive_timeout=) http_instance.http_get('https://uncached.example.com') end end end end
pjk25/cf-uaa-lib
lib/uaa/scim.rb
<gh_stars>0 #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'uaa/http' require 'uri' module CF::UAA # This class is for apps that need to manage User Accounts, Groups, or OAuth # Client Registrations. It provides access to the SCIM endpoints on the UAA. # For more information about SCIM -- the IETF's System for Cross-domain # Identity Management (formerly known as Simple Cloud Identity Management) -- # see {http://www.simplecloud.info}. # # The types of objects and links to their schema are as follows: # * +:user+ -- {http://www.simplecloud.info/specs/draft-scim-core-schema-01.html#user-resource} # or {http://www.simplecloud.info/specs/draft-scim-core-schema-01.html#anchor8} # * +:group+ -- {http://www.simplecloud.info/specs/draft-scim-core-schema-01.html#group-resource} # or {http://www.simplecloud.info/specs/draft-scim-core-schema-01.html#anchor10} # * +:client+ # * +:user_id+ -- {https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-APIs.rst#converting-userids-to-names} # # Naming attributes by type of object: # * +:user+ is "username" # * +:group+ is "displayname" # * +:client+ is "client_id" class Scim include Http private def force_attr(k) kd = k.to_s.downcase kc = { 'username' => 'userName', 'familyname' => 'familyName', 'givenname' => 'givenName', 'middlename' => 'middleName', 'honorificprefix' => 'honorificPrefix', 'honorificsuffix' => 'honorificSuffix', 'displayname' => 'displayName', 'nickname' => 'nickName', 'profileurl' => 'profileUrl', 'streetaddress' => 'streetAddress', 'postalcode' => 'postalCode', 'usertype' => 'userType', 'preferredlanguage' => 'preferredLanguage', 'x509certificates' => 'x509Certificates', 'lastmodified' => 'lastModified', 'externalid' => 'externalId', 'phonenumbers' => 'phoneNumbers', 'startindex' => 'startIndex', 'zoneid' => 'zoneId', 'includeinactive' => 'includeInactive' }[kd] kc || kd end def headers() hdrs = { 'authorization' => @auth_header } hdrs['X-Identity-Zone-Subdomain'] = @zone if @zone hdrs end # This is very inefficient and should be unnecessary. SCIM (1.1 and early # 2.0 drafts) specify that attribute names are case insensitive. However # in the UAA attribute names are currently case sensitive. This hack takes # a hash with keys as symbols or strings and with any case, and forces # the attribute name to the case that the uaa expects. def force_case(obj) return obj.collect {|o| force_case(o)} if obj.is_a? Array return obj unless obj.is_a? Hash new_obj = {} obj.each {|(k, v)| new_obj[force_attr(k)] = force_case(v) } new_obj end # an attempt to hide some scim and uaa oddities def type_info(type, elem) scimfo = { user: { path: '/Users', name_attr: 'userName', origin_attr: 'origin' }, group: { path: '/Groups', name_attr: 'displayName', origin_attr: 'zoneid' }, client: { path: '/oauth/clients', name_attr: 'client_id' }, user_id: { path: '/ids/Users', name_attr: 'userName', origin_attr: 'origin', }, group_mapping: { path: '/Groups/External', name_attr: 'externalGroup', origin_attr: 'origin' } } type_info = scimfo[type] unless type_info raise ArgumentError, "scim resource type must be one of #{scimfo.keys.inspect}" end value = type_info[elem] unless value raise ArgumentError, "scim schema element must be one of #{type_info.keys.inspect}" end value end def jkey(k) @key_style == :down ? k.to_s : k end def fake_client_id(info) idk, ck = jkey(:id), jkey(:client_id) info[idk] = info[ck] if info[ck] && !info[idk] end public # @param (see Misc.server) # @param [String] auth_header a string that can be used in an # authorization header. For OAuth2 with JWT tokens this would be something # like "bearer xxxx.xxxx.xxxx". The {TokenInfo} class provides # {TokenInfo#auth_header} for this purpose. # @param [Hash] options can be # * +:symbolize_keys+, if true, returned hash keys are symbols. def initialize(target, auth_header, options = {}) @target, @auth_header = target, auth_header @key_style = options[:symbolize_keys] ? :downsym : :down @zone = options[:zone] initialize_http_options(options) end # Convenience method to get the naming attribute, e.g. userName for user, # displayName for group, client_id for client. # @param type (see #add) # @return [String] naming attribute def name_attr(type) type_info(type, :name_attr) end # Creates a SCIM resource. # @param [Symbol] type can be :user, :group, :client, :user_id. # @param [Hash] info converted to json and sent to the scim endpoint. For schema of # each type of object see {Scim}. # @return [Hash] contents of the object, including its +id+ and meta-data. def add(type, info) path, info = type_info(type, :path), force_case(info) reply = json_parse_reply(@key_style, *json_post(@target, path, info, headers)) fake_client_id(reply) if type == :client # hide client reply, not quite scim reply end # Deletes a SCIM resource # @param type (see #add) # @param [String] id the id attribute of the SCIM object # @return [nil] def delete(type, id) http_delete @target, "#{type_info(type, :path)}/#{URI.encode(id)}", @auth_header, @zone end # Replaces the contents of a SCIM object. # @param (see #add) # @return (see #add) def put(type, info) path, info = type_info(type, :path), force_case(info) ida = type == :client ? 'client_id' : 'id' raise ArgumentError, "info must include #{ida}" unless id = info[ida] hdrs = headers if info && info['meta'] && (etag = info['meta']['version']) hdrs.merge!('if-match' => etag) end reply = json_parse_reply(@key_style, *json_put(@target, "#{path}/#{URI.encode(id)}", info, hdrs)) # hide client endpoints that are not quite scim compatible type == :client && !reply ? get(type, info['client_id']): reply end # Modifies the contents of a SCIM object. # @param (see #add) # @return (see #add) def patch(type, info) path, info = type_info(type, :path), force_case(info) ida = type == :client ? 'client_id' : 'id' raise ArgumentError, "info must include #{ida}" unless id = info[ida] hdrs = headers if info && info['meta'] && (etag = info['meta']['version']) hdrs.merge!('if-match' => etag) end reply = json_parse_reply(@key_style, *json_patch(@target, "#{path}/#{URI.encode(id)}", info, hdrs)) # hide client endpoints that are not quite scim compatible type == :client && !reply ? get(type, info['client_id']): reply end # Gets a set of attributes for each object that matches a given filter. # @param (see #add) # @param [Hash] query may contain the following keys: # * +attributes+: a comma or space separated list of attribute names to be # returned for each object that matches the filter. If no attribute # list is given, all attributes are returned. # * +filter+: a filter to select which objects are returned. See # {http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources} # * +startIndex+: for paged output, start index of requested result set. # * +count+: maximum number of results per reply # @return [Hash] including a +resources+ array of results and # pagination data. def query(type, query = {}) query = force_case(query).reject {|k, v| v.nil? } if attrs = query['attributes'] attrs = Util.arglist(attrs).map {|a| force_attr(a)} query['attributes'] = Util.strlist(attrs, ",") end qstr = query.empty?? '': "?#{Util.encode_form(query)}" info = json_get(@target, "#{type_info(type, :path)}#{qstr}", @key_style, headers) unless info.is_a?(Hash) && info[rk = jkey(:resources)].is_a?(Array) # hide client endpoints that are not yet scim compatible if type == :client && info.is_a?(Hash) info = info.each{ |k, v| fake_client_id(v) }.values if m = /^client_id\s+eq\s+"([^"]+)"$/i.match(query['filter']) idk = jkey(:client_id) info = info.select { |c| c[idk].casecmp(m[1]) == 0 } end return {rk => info} end raise BadResponse, "invalid reply to #{type} query of #{@target}" end info end # Get information about a specific object. # @param (see #delete) # @return (see #add) def get(type, id) info = json_get(@target, "#{type_info(type, :path)}/#{URI.encode(id)}", @key_style, headers) fake_client_id(info) if type == :client # hide client reply, not quite scim info end # Get meta information about client # @param client_id # @return (client meta) def get_client_meta(client_id) path = type_info(:client, :path) json_get(@target, "#{path}/#{URI.encode(client_id)}/meta", @key_style, headers) end # Collects all pages of entries from a query # @param type (see #query) # @param [Hash] query may contain the following keys: # * +attributes+: a comma or space separated list of attribute names to be # returned for each object that matches the filter. If no attribute # list is given, all attributes are returned. # * +filter+: a filter to select which objects are returned. See # {http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources} # @return [Array] results def all_pages(type, query = {}) query = force_case(query).reject {|k, v| v.nil? } query["startindex"], info, rk = 1, [], jkey(:resources) while true qinfo = query(type, query) raise BadResponse unless qinfo[rk] return info if qinfo[rk].empty? info.concat(qinfo[rk]) total = qinfo[jkey :totalresults] return info unless total && total > info.length unless qinfo[jkey :startindex] && qinfo[jkey :itemsperpage] raise BadResponse, "incomplete #{type} pagination data from #{@target}" end query["startindex"] = info.length + 1 end end # Gets id/name pairs for given names. For naming attribute of each object type see {Scim} # @param type (see #add) # @return [Array] array of name/id hashes for each object found def ids(type, *names) name_attr = type_info(type, :name_attr) origin_attr = type_info(type, :origin_attr) filter = names.map do |n| "#{name_attr} eq \"#{n}\"" end attributes = ['id', name_attr, origin_attr] all_pages(type, attributes: attributes.join(','), filter: filter.join(' or ')) end # Convenience method to query for single object by name. # @param type (see #add) # @param [String] name Value of the Scim object's name attribue. For naming # attribute of each type of object see {Scim}. # @return [String] the +id+ attribute of the object def id(type, name) res = ids(type, name) # hide client endpoints that are not scim compatible ik, ck = jkey(:id), jkey(:client_id) if type == :client && res && res.length > 0 && (res.length > 1 || res[0][ik].nil?) cr = res.find { |o| o[ck] && name.casecmp(o[ck]) == 0 } return cr[ik] || cr[ck] if cr end unless res && res.is_a?(Array) && res.length == 1 && res[0].is_a?(Hash) && (id = res[0][jkey :id]) raise NotFound, "#{name} not found in #{@target}#{type_info(type, :path)}" end id end # Change password. # * For a user to change their own password, the token in @auth_header must # contain "password.write" scope and the correct +old_password+ must be given. # * For an admin to set a user's password, the token in @auth_header must # contain "uaa.admin" scope. # @see https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-APIs.rst#change-password-put-useridpassword # @see https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-Security.md#password-change # @param [String] user_id the {Scim} +id+ attribute of the user # @return [Hash] success message from server def change_password(user_id, new_password, old_password = <PASSWORD>) req = {"password" => <PASSWORD>} req["oldPassword"] = <PASSWORD> if old_password json_parse_reply(@key_style, *json_put(@target, "#{type_info(:user, :path)}/#{URI.encode(user_id)}/password", req, headers)) end # Change client secret. # * For a client to change its own secret, the token in @auth_header must contain # "client.secret" scope and the correct +old_secret+ must be given. # * For an admin to set a client secret, the token in @auth_header must contain # "uaa.admin" scope. # @see https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-APIs.rst#change-client-secret-put-oauthclientsclient_idsecret # @see https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-Security.md#client-secret-mangagement # @param [String] client_id the {Scim} +id+ attribute of the client # @return [Hash] success message from server def change_secret(client_id, new_secret, old_secret = nil) req = {"secret" => new_secret } req["oldSecret"] = old_secret if old_secret json_parse_reply(@key_style, *json_put(@target, "#{type_info(:client, :path)}/#{URI.encode(client_id)}/secret", req, headers)) end def unlock_user(user_id) req = {"locked" => false} json_parse_reply(@key_style, *json_patch(@target, "#{type_info(:user, :path)}/#{URI.encode(user_id)}/status", req, headers)) end def map_group(group, is_id, external_group, origin = "ldap") key_name = is_id ? :groupId : :displayName request = {key_name => group, :externalGroup => external_group, :schemas => ["urn:scim:schemas:core:1.0"], :origin => origin } result = json_parse_reply(@key_style, *json_post(@target, "#{type_info(:group_mapping, :path)}", request, headers)) result end def unmap_group(group_id, external_group, origin = "ldap") http_delete(@target, "#{type_info(:group_mapping, :path)}/groupId/#{group_id}/externalGroup/#{URI.encode(external_group)}/origin/#{origin}", @auth_header, @zone) end def list_group_mappings(start = nil, count = nil) json_get(@target, "#{type_info(:group_mapping, :path)}/list?startIndex=#{start}&count=#{count}", @key_style, headers) end end end
pjk25/cf-uaa-lib
lib/uaa/token_issuer.rb
<reponame>pjk25/cf-uaa-lib<gh_stars>0 #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'securerandom' require 'uaa/http' module CF::UAA # The TokenInfo class is returned by various TokenIssuer methods. It holds access # and refresh tokens as well as token meta-data such as token type and # expiration time. See {TokenInfo#info} for contents. class TokenInfo # Information about the current token. The info hash MUST include # access_token, token_type and scope (if granted scope differs from requested # scope). It should include expires_in. It may include refresh_token, scope, # and other values from the auth server. # @return [Hash] attr_reader :info # Normally instantiated by {TokenIssuer}. def initialize(info) @info = info end # Constructs a string for use in an authorization header from the contents of # the TokenInfo. # @return [String] Typically a string such as "bearer xxxx.xxxx.xxxx". def auth_header "#{@info[:token_type] || @info['token_type']} #{@info[:access_token] || @info['access_token']}" end end # Client Apps that want to get access to resource servers on behalf of their # users need to get tokens via authcode and implicit flows, # request scopes, etc., but they don't need to process tokens. This # class is for these use cases. # # In general most of this class is an implementation of the client pieces of # the OAuth2 protocol. See {http://tools.ietf.org/html/rfc6749} class TokenIssuer include Http private def random_state; SecureRandom.hex end def parse_implicit_params(encoded_params, state) params = Util.decode_form(encoded_params) raise BadResponse, "mismatched state" unless state && params.delete('state') == state raise TargetError.new(params), "error response from #{@target}" if params['error'] raise BadResponse, "no type and token" unless params['token_type'] && params['access_token'] exp = params['expires_in'].to_i params['expires_in'] = exp if exp.to_s == params['expires_in'] TokenInfo.new(Util.hash_keys!(params, @key_style)) rescue URI::InvalidURIError, ArgumentError raise BadResponse, "received invalid response from target #{@target}" end # returns a CF::UAA::TokenInfo object which includes the access token and metadata. def request_token(params) if scope = Util.arglist(params.delete(:scope)) params[:scope] = Util.strlist(scope) end headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8, 'authorization' => Http.basic_auth(@client_id, @client_secret) } reply = json_parse_reply(@key_style, *request(@token_target, :post, '/oauth/token', Util.encode_form(params), headers)) raise BadResponse unless reply[jkey :token_type] && reply[jkey :access_token] TokenInfo.new(reply) end def authorize_path_args(response_type, redirect_uri, scope, state = random_state, args = {}) params = args.merge(:client_id => @client_id, :response_type => response_type, :redirect_uri => redirect_uri, :state => state) params[:scope] = scope = Util.strlist(scope) if scope = Util.arglist(scope) params[:nonce] = state "/oauth/authorize?#{Util.encode_form(params)}" end def jkey(k) @key_style ? k : k.to_s end public # @param [String] target The base URL of a UAA's oauth authorize endpoint. # For example the target would be {https://login.cloudfoundry.com} if the # endpoint is {https://login.cloudfoundry.com/oauth/authorize}. # The target would be {http://localhost:8080/uaa} if the endpoint # is {http://localhost:8080/uaa/oauth/authorize}. # @param [String] client_id The oauth2 client id, see # {http://tools.ietf.org/html/rfc6749#section-2.2} # @param [String] client_secret Needed to authenticate the client for all # grant types except implicit. # @param [Hash] options can be # * +:token_target+, the base URL of the oauth token endpoint -- if # not specified, +target+ is used. # * +:symbolize_keys+, if true, returned hash keys are symbols. def initialize(target, client_id, client_secret = nil, options = {}) @target, @client_id, @client_secret = target, client_id, client_secret @token_target = options[:token_target] || target @key_style = options[:symbolize_keys] ? :sym : nil initialize_http_options(options) end # Allows an app to discover what credentials are required for # {#implicit_grant_with_creds}. # @return [Hash] of credential names with type and suggested prompt value, # e.g. !{"username":["text","Email"],"password":["password","Password"]} def prompts reply = json_get(@target, '/login') return reply[jkey :prompts] if reply && reply[jkey :prompts] raise BadResponse, "No prompts in response from target #{@target}" end # Gets an access token in a single call to the UAA with the user # credentials used for authentication. # @param credentials should be an object such as a hash that can be converted # to a json representation of the credential name/value pairs corresponding to # the keys retrieved by {#prompts}. # @return [TokenInfo] def implicit_grant_with_creds(credentials, scope = nil) # this manufactured redirect_uri is a convention here, not part of OAuth2 redir_uri = "https://uaa.cloudfoundry.com/redirect/#{@client_id}" response_type = "token" response_type = "#{response_type} id_token" if scope && (scope.include? "openid") uri = authorize_path_args(response_type, redir_uri, scope, state = random_state) # the accept header is only here so the uaa will issue error replies in json to aid debugging headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8 } body = Util.encode_form(credentials.merge(:source => 'credentials')) status, body, headers = request(@target, :post, uri, body, headers) raise BadResponse, "status #{status}" unless status == 302 req_uri, reply_uri = URI.parse(redir_uri), URI.parse(headers['location']) fragment, reply_uri.fragment = reply_uri.fragment, nil raise BadResponse, "bad location header" unless req_uri == reply_uri parse_implicit_params(fragment, state) rescue URI::Error => e raise BadResponse, "bad location header in reply: #{e.message}" end # Constructs a uri that the client is to return to the browser to direct # the user to the authorization server to get an authcode. # @param [String] redirect_uri (see #authcode_uri) # @return [String] def implicit_uri(redirect_uri, scope = nil) response_type = "token" response_type = "#{response_type} id_token" if scope && (scope.include? "openid") @target + authorize_path_args(response_type, redirect_uri, scope) end # Gets a token via an implicit grant. # @param [String] implicit_uri must be from a previous call to # {#implicit_uri}, contains state used to validate the contents of the # reply from the server. # @param [String] callback_fragment must be the fragment portion of the URL # received by the user's browser after the server redirects back to the # +redirect_uri+ that was given to {#implicit_uri}. How the application # gets the contents of the fragment is application specific -- usually # some javascript in the page at the +redirect_uri+. # @see http://tools.ietf.org/html/rfc6749#section-4.2 # @return [TokenInfo] def implicit_grant(implicit_uri, callback_fragment) in_params = Util.decode_form(URI.parse(implicit_uri).query) unless in_params['state'] && in_params['redirect_uri'] raise ArgumentError, "redirect must happen before implicit grant" end parse_implicit_params(callback_fragment, in_params['state']) end # A UAA extension to OAuth2 that allows a client to pre-authenticate a # user at the start of an authorization code flow. By passing in the # user's credentials the server can establish a session with the user's # browser without reprompting for authentication. This is useful for # user account management apps so that they can create a user account, # or reset a password for the user, without requiring the user to type # in their credentials again. # @param [String] credentials (see #implicit_grant_with_creds) # @param [String] redirect_uri (see #authcode_uri) # @return (see #authcode_uri) def autologin_uri(redirect_uri, credentials, scope = nil) headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8, 'authorization' => Http.basic_auth(@client_id, @client_secret) } body = Util.encode_form(credentials) reply = json_parse_reply(nil, *request(@target, :post, "/autologin", body, headers)) raise BadResponse, "no autologin code in reply" unless reply['code'] @target + authorize_path_args('code', redirect_uri, scope, random_state, :code => reply['code']) end # Constructs a uri that the client is to return to the browser to direct # the user to the authorization server to get an authcode. # @param [String] redirect_uri is embedded in the returned uri so the server # can redirect the user back to the caller's endpoint. # @return [String] uri which def authcode_uri(redirect_uri, scope = nil) @target + authorize_path_args('code', redirect_uri, scope) end # Uses the instance client credentials in addition to +callback_query+ # to get a token via the authorization code grant. # @param [String] authcode_uri must be from a previous call to {#authcode_uri} # and contains state used to validate the contents of the reply from the # server. # @param [String] callback_query must be the query portion of the URL # received by the client after the user's browser is redirected back from # the server. It contains the authorization code. # @see http://tools.ietf.org/html/rfc6749#section-4.1 # @return [TokenInfo] def authcode_grant(authcode_uri, callback_query) ac_params = Util.decode_form(URI.parse(authcode_uri).query) unless ac_params['state'] && ac_params['redirect_uri'] raise ArgumentError, "authcode redirect must happen before authcode grant" end begin params = Util.decode_form(callback_query) authcode = params['code'] raise BadResponse unless params['state'] == ac_params['state'] && authcode rescue URI::InvalidURIError, ArgumentError, BadResponse raise BadResponse, "received invalid response from target #{@target}" end request_token(:grant_type => 'authorization_code', :code => authcode, :redirect_uri => ac_params['redirect_uri']) end # Uses the instance client credentials in addition to the +username+ # and +password+ to get a token via the owner password grant. # See {http://tools.ietf.org/html/rfc6749#section-4.3}. # @return [TokenInfo] def owner_password_grant(username, password, scope = nil) request_token(:grant_type => 'password', :username => username, :password => password, :scope => scope) end # Uses a one-time passcode obtained from the UAA to get a # token. # @return [TokenInfo] def passcode_grant(passcode, scope = nil) request_token(:grant_type => 'password', :passcode => <PASSWORD>, :scope => scope) end # Gets an access token with the user credentials used for authentication # via the owner password grant. # See {http://tools.ietf.org/html/rfc6749#section-4.3}. # @param credentials should be an object such as a hash that can be converted # to a json representation of the credential name/value pairs corresponding to # the keys retrieved by {#prompts}. # @return [TokenInfo] def owner_password_credentials_grant(credentials) credentials[:grant_type] = 'password' request_token(credentials) end # Uses the instance client credentials to get a token with a client # credentials grant. See http://tools.ietf.org/html/rfc6749#section-4.4 # @return [TokenInfo] def client_credentials_grant(scope = nil) request_token(:grant_type => 'client_credentials', :scope => scope) end # Uses the instance client credentials and the given +refresh_token+ to get # a new access token. See http://tools.ietf.org/html/rfc6749#section-6 # @return [TokenInfo] which may include a new refresh token as well as an access token. def refresh_token_grant(refresh_token, scope = nil) request_token(:grant_type => 'refresh_token', :refresh_token => refresh_token, :scope => scope) end end end
pjk25/cf-uaa-lib
lib/uaa/http.rb
#-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'base64' require 'uaa/util' require 'httpclient' module CF::UAA # Indicates URL for the target is bad or not accessible. class BadTarget < UAAError; end # Indicates invalid SSL Certification for the target. class SSLException < UAAError; end # Indicates the resource within the target server was not found. class NotFound < UAAError; end # Indicates a syntax error in a response from the UAA, e.g. missing required response field. class BadResponse < UAAError; end # Indicates an error from the http client stack. class HTTPException < UAAError; end # An application level error from the UAA which includes error info in the reply. class TargetError < UAAError attr_reader :info def initialize(error_info = {}) @info = error_info end end # Indicates a token is malformed or expired. class InvalidToken < TargetError; end # Utility accessors and methods for objects that want to access JSON web APIs. module Http def self.included(base) base.class_eval do attr_reader :skip_ssl_validation, :ssl_ca_file, :ssl_cert_store, :http_timeout end end def initialize_http_options(options) @skip_ssl_validation = options[:skip_ssl_validation] @ssl_ca_file = options[:ssl_ca_file] @ssl_cert_store = options[:ssl_cert_store] @http_timeout = options[:http_timeout] end # Sets the current logger instance to recieve error messages. # @param [Logger] logr # @return [Logger] def logger=(logr); @logger = logr end # The current logger or {Util.default_logger} if none has been set. # @return [Logger] def logger ; @logger || Util.default_logger end # Indicates if the current logger is set to +:trace+ level. # @return [Boolean] def trace? ; (lgr = logger).respond_to?(:trace?) && lgr.trace? end # Sets a handler for outgoing http requests. If no handler is set, an # internal cache of net/http connections is used. Arguments to the handler # are url, method, body, headers. # @param [Proc] blk handler block # @return [nil] def set_request_handler(&blk) @req_handler = blk; nil end # Constructs an http basic authentication header. # @return [String] def self.basic_auth(name, password) str = "#{name}:#{password}" 'Basic ' + (Base64.respond_to?(:strict_encode64)? Base64.strict_encode64(str): [str].pack('m').gsub(/\n/, '')) end JSON_UTF8 = 'application/json;charset=utf-8' FORM_UTF8 = 'application/x-www-form-urlencoded;charset=utf-8' private def json_get(target, path = nil, style = nil, headers = {}) raise ArgumentError unless style.nil? || style.is_a?(Symbol) json_parse_reply(style, *http_get(target, path, headers.merge('accept' => JSON_UTF8))) end def json_post(target, path, body, headers = {}) http_post(target, path, Util.json(body), headers.merge('content-type' => JSON_UTF8)) end def json_put(target, path, body, headers = {}) http_put(target, path, Util.json(body), headers.merge('content-type' => JSON_UTF8)) end def json_patch(target, path, body, headers = {}) http_patch(target, path, Util.json(body), headers.merge('content-type' => JSON_UTF8)) end def json_parse_reply(style, status, body, headers) raise ArgumentError unless style.nil? || style.is_a?(Symbol) unless [200, 201, 204, 400, 401, 403, 409, 422].include? status raise (status == 404 ? NotFound : BadResponse), "invalid status response: #{status}" end if body && !body.empty? && (status == 204 || headers.nil? || headers['content-type'] !~ /application\/json/i) raise BadResponse, 'received invalid response content or type' end parsed_reply = Util.json_parse(body, style) if status >= 400 raise parsed_reply && parsed_reply['error'] == 'invalid_token' ? InvalidToken.new(parsed_reply) : TargetError.new(parsed_reply), 'error response' end parsed_reply rescue DecodeError raise BadResponse, 'invalid JSON response' end def http_get(target, path = nil, headers = {}) request(target, :get, path, nil, headers) end def http_post(target, path, body, headers = {}) request(target, :post, path, body, headers) end def http_put(target, path, body, headers = {}) request(target, :put, path, body, headers) end def http_patch(target, path, body, headers = {}) request(target, :patch, path, body, headers) end def http_delete(target, path, authorization, zone = nil) hdrs = { 'authorization' => authorization } hdrs['X-Identity-Zone-Subdomain'] = zone if zone status = request(target, :delete, path, nil, hdrs)[0] unless [200, 204].include?(status) raise (status == 404 ? NotFound : BadResponse), "invalid response from #{path}: #{status}" end end def request(target, method, path, body = nil, headers = {}) headers['accept'] = headers['content-type'] if headers['content-type'] && !headers['accept'] url = "#{target}#{path}" logger.debug { "--->\nrequest: #{method} #{url}\n" + "headers: #{headers}\n#{'body: ' + Util.truncate(body.to_s, trace? ? 50000 : 50) if body}" } status, body, headers = @req_handler ? @req_handler.call(url, method, body, headers) : net_http_request(url, method, body, headers) logger.debug { "<---\nresponse: #{status}\nheaders: #{headers}\n" + "#{'body: ' + Util.truncate(body.to_s, trace? ? 50000: 50) if body}" } [status, body, headers] rescue Exception => e logger.debug { "<---- no response due to exception: #{e.inspect}" } raise e end def net_http_request(url, method, body, headers) uri = URI.parse(url) http = http_request(uri) headers['content-length'] = body.length.to_s if body case method when :get, :delete response = http.send(method, uri, nil, headers) when :post, :put, :patch response = http.send(method, uri, body, headers) else raise ArgumentError end unless response.status raise HTTPException.new "Can't parse response from the server #{response.content}" end response_headers = {} response.header.all.each { |k, v| response_headers[k.downcase] = v } return [response.status.to_i, response.content, response_headers] rescue OpenSSL::SSL::SSLError => e raise SSLException, "Invalid SSL Cert for #{url}. Use '--skip-ssl-validation' to continue with an insecure target" rescue URI::Error, SocketError, SystemCallError => e raise BadTarget, "error: #{e.message}" rescue HTTPClient::ConnectTimeoutError => e raise HTTPException.new "http timeout" end def http_request(uri) cache_key = URI.join(uri.to_s, '/') @http_cache ||= {} return @http_cache[cache_key] if @http_cache[cache_key] if uri.is_a?(URI::HTTPS) http = HTTPClient.new.tap do |c| if skip_ssl_validation c.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE elsif ssl_ca_file c.ssl_config.set_trust_ca File.expand_path(ssl_ca_file) c.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER elsif ssl_cert_store c.ssl_config.cert_store = ssl_cert_store c.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER else c.ssl_config.set_default_paths end end else http = HTTPClient.new end if http_timeout http.connect_timeout = http_timeout http.send_timeout = http_timeout http.receive_timeout = http_timeout end @http_cache[cache_key] = http end end end
pjk25/cf-uaa-lib
spec/integration_spec.rb
<reponame>pjk25/cf-uaa-lib<gh_stars>0 #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'spec_helper' require 'uaa' require 'pp' # ENV['UAA_CLIENT_ID'] = 'admin' # ENV['UAA_CLIENT_SECRET'] = 'admin_secret' # ENV['UAA_CLIENT_TARGET'] = 'https://login.identity.cf-app.com' # ENV['UAA_CLIENT_TARGET'] = 'http://localhost:8080/uaa' #Set this variable if you want to test skip_ssl_validation option. #Make sure that UAA_CLIENT_TARGET points to https endpoint with self-signed certificate. #It will run all the tests with ssl validation set to false # ENV['SKIP_SSL_VALIDATION'] = 'yes' #Set this variable to test ssl_ca_file option. #Make sure that UAA_CLIENT_TARGET points to https endpoint with self-signed certificate. # ENV['SSL_CA_FILE'] = '~/workspace/identity-cf.cert' #Set this variable to test cert_store option. #Make sure that UAA_CLIENT_TARGET points to https endpoint with self-signed certificate. # ENV['CERT_STORE'] = '~/workspace/identity-cf.cert' module CF::UAA def self.admin_scim(options) admin_client = ENV['UAA_CLIENT_ID'] || 'admin' admin_secret = ENV['UAA_CLIENT_SECRET'] || 'adminsecret' target = ENV['UAA_CLIENT_TARGET'] admin_token_issuer = TokenIssuer.new(target, admin_client, admin_secret, options) Scim.new(target, admin_token_issuer.client_credentials_grant.auth_header, options.merge(:symbolize_keys => true)) end describe 'when UAA does not respond' do let(:http_timeout) { 0.01 } let(:default_http_client_timeout) { 60 } let(:scim) { Scim.new(@target, "", {:http_timeout => http_timeout}) } let(:token_issuer) { TokenIssuer.new(@target, "", "", {:http_timeout => http_timeout}) } let(:blackhole_ip) { '10.255.255.1'} before do @target = "http://#{blackhole_ip}" end it 'times out the connection at the configured time for the scim' do expect { Timeout.timeout(default_http_client_timeout - 1) do scim.get(:user, "admin") end }.to raise_error HTTPException end it 'times out the connection at the configured time for the token issuer' do expect { Timeout.timeout(default_http_client_timeout - 1) do token_issuer.client_credentials_grant end }.to raise_error HTTPException end end if ENV['UAA_CLIENT_TARGET'] describe 'UAA Integration:' do let(:options) { @options } let(:token_issuer) { TokenIssuer.new(@target, @test_client, @test_secret, options) } let(:scim) { Scim.new(@target, token_issuer.client_credentials_grant.auth_header, options.merge(:symbolize_keys => true)) } before :all do @options = {} if ENV['SKIP_SSL_VALIDATION'] @options = {:skip_ssl_validation => true} end @target = ENV['UAA_CLIENT_TARGET'] @test_client = "test_client_#{Time.now.to_i}" @test_secret = '+=tEsTsEcRet~!@' gids = ['clients.read', 'scim.read', 'scim.write', 'uaa.resource', 'password.write'] test_client = CF::UAA::admin_scim(@options).add(:client, :client_id => @test_client, :client_secret => @test_secret, :authorities => gids, :authorized_grant_types => ['client_credentials', 'password'], :scope => ['openid', 'password.write']) expect(test_client[:client_id]).to eq(@test_client) end after :all do admin_scim = CF::UAA::admin_scim(@options) admin_scim.delete(:client, @test_client) expect { admin_scim.id(:client, @test_client) }.to raise_exception(NotFound) end if ENV['SKIP_SSL_VALIDATION'] context 'when ssl certificate is self-signed' do let(:options) { {:skip_ssl_validation => false} } it 'fails if skip_ssl_validation is false' do expect{ scim }.to raise_exception(CF::UAA::SSLException) end end end if ENV['SSL_CA_FILE'] context 'when you do not skip SSL validation' do context 'when you provide cert' do let(:options) { {:ssl_ca_file => ENV['SSL_CA_FILE']} } it 'works' do expect(token_issuer.prompts).to_not be_nil end end context 'if you do not provide cert file' do let(:options) { {} } it 'fails' do expect{ scim }.to raise_exception(CF::UAA::SSLException) end end end end if ENV['CERT_STORE'] context 'when you do not skip SSL validation' do context 'when you provide cert store' do let(:cert_store) do cert_store = OpenSSL::X509::Store.new cert_store.add_file File.expand_path(ENV['CERT_STORE']) cert_store end let(:options) { {:ssl_cert_store => cert_store} } it 'works' do expect(token_issuer.prompts).to_not be_nil end end context 'when you do not provide cert store' do let(:options) { {} } it 'fails' do expect{ scim }.to raise_exception(CF::UAA::SSLException) end end end end it 'should report the uaa client version' do expect(VERSION).to match(/\d+.\d+.\d+/) end it 'makes sure the server is there by getting the prompts for an implicit grant' do expect(token_issuer.prompts).to_not be_nil end it 'gets a token with client credentials' do tkn = token_issuer.client_credentials_grant expect(tkn.auth_header).to match(/^bearer\s/i) info = TokenCoder.decode(tkn.info['access_token'], :verify => false, :symbolize_keys => true) expect(info[:exp]).to be expect(info[:jti]).to be end it 'complains about an attempt to delete a non-existent user' do expect { scim.delete(:user, 'non-existent-user') }.to raise_exception(NotFound) end context 'as a client' do before :each do @username = "sam_#{Time.now.to_i}" @user_pwd = "<PASSWORD>~!`@\#\$%^&*()_/{}[]\\|:\";',.<>?/" usr = scim.add(:user, :username => @username, :password => <PASSWORD>, :emails => [{:value => '<EMAIL>'}], :name => {:givenname => 'none', :familyname => 'none'}) @user_id = usr[:id] end it 'deletes the user' do scim.delete(:user, @user_id) expect { scim.id(:user, @username) }.to raise_exception(NotFound) expect { scim.get(:user, @user_id) }.to raise_exception(NotFound) end context 'when user exists' do after :each do scim.delete(:user, @user_id) expect { scim.id(:user, @username) }.to raise_exception(NotFound) expect { scim.get(:user, @user_id) }.to raise_exception(NotFound) end it 'creates a user' do expect(@user_id).to be end it 'finds the user by name' do expect(scim.id(:user, @username)).to eq(@user_id) end it 'gets the user by id' do user_info = scim.get(:user, @user_id) expect(user_info[:id]).to eq(@user_id) expect(user_info[:username]).to eq(@username) end it 'lists all users' do expect(scim.query(:user)).to be end it "changes the user's password by name" do expect(scim.change_password(scim.id(:user, @username), '<PASSWORD>')[:status]).to eq('ok') end it 'should get a uri to be sent to the user agent to initiate autologin' do redir_uri = 'http://call.back/uri_path' uri_parts = token_issuer.autologin_uri(redir_uri, :username => @username, :password =><PASSWORD> ).split('?') expect(uri_parts[0]).to eq("#{ENV['UAA_CLIENT_TARGET']}/oauth/authorize") params = Util.decode_form(uri_parts[1], :sym) expect(params[:response_type]).to eq('code') expect(params[:client_id]).to eq(@test_client) expect(params[:scope]).to be_nil expect(params[:redirect_uri]).to eq(redir_uri) expect(params[:state]).to be expect(params[:code]).to be end end end end end end
pjk25/cf-uaa-lib
spec/spec_helper.rb
<filename>spec/spec_helper.rb #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ if ENV['COVERAGE'] require "simplecov" if ENV['COVERAGE'] =~ /rcov/ require "simplecov-rcov" SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter end SimpleCov.add_filter "^#{File.dirname(__FILE__)}" if ENV['COVERAGE'] =~ /exclude-spec/ SimpleCov.add_filter "^#{File.expand_path(File.join(File.dirname(__FILE__), "..", "vendor"))}" if ENV['COVERAGE'] =~ /exclude-vendor/ SimpleCov.start end require 'rspec'
alelievr/stalker_sama
sources/project_logger.rb
<reponame>alelievr/stalker_sama require 'json' require 'awesome_print' require_relative 'api42' class ProjectLogger < Api42 def get_infos(user_list, endpoint = '/v2/cursus_users') return [] unless user_list.count.positive? levels = [] [1..10].map do |page| response = send_uri("#{endpoint}?filter[user_id]=#{user_list.join(',')}&cursus_id=1&page=#{page}") response.map { |data| levels.push(login: data['user']['login'], level: data['level']) } end levels end def update_user(project_infos, user, slack, db) user_info = project_infos.detect { |i| i[:login] == user[:login42] } opts = { level: user_info[:level], xp: (user_info[:level] - user[:level]).round(2) } return unless opts[:xp].positive? slack.send_project_message(user[:login42], user[:slack_id], opts) db.update_user(user[:login42], :level, user_info[:level]) end end
alelievr/stalker_sama
sources/slack_pinger.rb
require 'slack-ruby-client' require 'json' def log_slack_pinger(infos, login42, slack_id, hash, message) puts 'infos -------------------------------------------------' ap infos puts 'slack_id ----------------------------------------------' ap slack_id puts 'login42 -----------------------------------------------' ap login42 puts 'hash --------------------------------------------------' ap hash puts 'message -----------------------------------------------' ap message puts "-------------------------------------------------------\n\n" end class SlackPinger CHAN = '#stalker'.freeze # CHAN = '#général'.freeze # CHAN = '#clusters-test'.freeze def initialize Slack.configure do |config| config.token = ENV['SLACK_API_TOKEN'] config.logger = Logger.new(STDOUT) config.logger.level = Logger::WARN raise 'Missing ENV[SLACK_API_TOKEN]!' unless config.token end @connect_quotes = JSON.parse(File.read('./connect_quotes.json')) @disconnect_quotes = JSON.parse(File.read('./disconnect_quotes.json')) @projects_quotes = JSON.parse(File.read('./projects_quotes.json')) @client = Slack::Web::Client.new end def pick_random_from_hours(user_secs, quotes) user_hours = user_secs / 60 / 60 quotes.each do |quote| next unless quote['hour'] >= user_hours return quote['messages'].sample end throw 'You\'re not supposed to be here' end def pick_random(quotes) quotes['messages'][rand(quotes['messages'].size)] end def send_message(message) return if message.nil? || message == '' puts "Sending message: #{message}" STDOUT.flush @client.chat_postMessage(channel: CHAN, text: message, as_user: true, link_names: 1) end def humanize(secs) [[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map do |count, name| next unless secs > 0 secs, n = secs.divmod(count) "#{n.to_i} #{name}" end.compact.reverse.join(' ') end def format_message(message, login42, slack_id, opts = {}) infos = @client.users_info(user: slack_id) hash = { ping: "<@#{infos.user.name}>", '42_login': login42, slack_login: infos.user.name, time: humanize(opts[:secs].to_f).to_s, seat: opts[:seat], level: opts[:level], xp: opts[:xp] } message = message.dup hash.map do |key, value| message.gsub!("{#{key}}", value.to_s) end log_slack_pinger(infos, login42, slack_id, hash, message) message end def send_project_message(login42, slack_id, opts = {}) quote = pick_random(@projects_quotes) send_message(format_message(quote, login42, slack_id, opts)) end def send_connected_message(login42, slack_id, opts = {}) quote = pick_random_from_hours(opts[:secs], @connect_quotes) send_message(format_message(quote, login42, slack_id, opts)) end def send_disconnected_message(login42, slack_id, opts = {}) quote = pick_random_from_hours(opts[:secs], @disconnect_quotes) send_message(format_message(quote, login42, slack_id, opts)) end def get_user_id(user_login) login = user_login @client.users_list(presence: true, limit: 10) do |response| res = response.members.detect { |r| [r.profile.real_name, r.profile.display_name, r.name].include? user_login } break unless res.nil? login = res.name end puts "Using slack name #{login}" @client.users_info(user: "@#{login}").user.id end end
alelievr/stalker_sama
sources/user_database.rb
require 'sqlite3' require 'sequel' class UserDatabase USER_TABLE = 'Users'.freeze DATABASE_FILE = 'stalker.db'.freeze def initialize @sqlite_db = SQLite3::Database.new DATABASE_FILE @db = Sequel.connect("sqlite://#{DATABASE_FILE}") stm1 = @sqlite_db.prepare "SELECT * FROM sqlite_master WHERE name ='#{USER_TABLE}' and type='table'; " rs = stm1.execute if rs.count.to_i.zero? puts 'creating a new table' stm2 = @sqlite_db.prepare "CREATE TABLE #{USER_TABLE}(`login42` varchar(10), `api42_id` int, `slack_id` varchar(10), `level` float, `connected` bool, `last_connected` varchar(50), `last_seat` varchar(20))" stm2.execute stm2.close end stm1.close end def add_user(login42, api42_id, slack_id, opts = {}) opts[:logged] ||= false opts[:last_connected] ||= Time.now opts[:level] ||= 0 opts[:last_seat] ||= 'e0r0p0' @users = @db.from(USER_TABLE) a = @users.where(login42: login42).first puts a if a.nil? puts "User #{login42} added to the database" if @users.insert(login42, api42_id, slack_id, opts[:level], opts[:logged], opts[:last_connected], opts[:last_seat]) else throw "Can't add #{login42} to the database, this user already exists" end end def get_users @users = @db.from(USER_TABLE).all @users.all end def update_connected(connected_logins) @users.where(login42: connected_logins).update(connected: 'true') @users.exclude(login42: connected_logins).update(connected: 'false') end def update_user(login42, field, value) @users.where(login42: login42).update(field => value) end def close @db.disconnect end end
alelievr/stalker_sama
sources/add_user.rb
<reponame>alelievr/stalker_sama<filename>sources/add_user.rb #!env ruby require 'oauth2' require_relative 'slack_pinger.rb' require_relative 'user_database.rb' return p 'Give me the 42 login and slack user name' unless ARGV[0] && ARGV[1] db = UserDatabase.new sb = SlackPinger.new client = OAuth2::Client.new(ENV['API42_UID'], ENV['API42_SECRET'], site: 'https://api.intra.42.fr') token = client.client_credentials.get_token res = token.get("/v2/users?filter[login]=#{ARGV[0]}") opts = {} exit(-1) unless res.status == 200 p "found user id:#{res.parsed[0]['id']} -> #{res.parsed[0]['login']}" api42_id = res.parsed[0]['id'] res = token.get("/v2/locations?filter[user_id]=#{api42_id}") exit(-1) unless res.status == 200 opts[:logged] = res.parsed[0]['end_at'].nil? opts[:last_connected] = opts[:logged] ? res.parsed[0]['begin_at'] : res.parsed[0]['end_at'] opts[:last_seat] = res.parsed[0]['host'] puts "last_connected: #{opts[:last_connected]}" res = token.get("/v2/cursus_users?filter[user_id]=#{api42_id}&cursus_id=1") exit(-1) unless res.status == 200 opts[:level] = res.parsed[0]['level'] slack_id = sb.get_user_id(ARGV[1]) print "slack id found: #{slack_id}" db.add_user(ARGV[0], api42_id, slack_id, opts)
alelievr/stalker_sama
sources/api42.rb
<gh_stars>0 require 'oauth2' class Api42 UID = ENV['API42_UID'] SECRET = ENV['API42_SECRET'] def initialize @client = OAuth2::Client.new(UID, SECRET, site: 'https://api.intra.42.fr') @token = @client.client_credentials.get_token end protected def send_uri(uri) sleep(3) initialize if (Time.now.to_i - @token.expires_at).abs < 200 response = @token.get(uri) throw "Bad api status: #{response.status}" unless response.status == 200 response.parsed end end
alelievr/stalker_sama
sources/cluster_logger.rb
<gh_stars>0 require 'json' require 'time' require 'awesome_print' require_relative 'api42' def log(c1, c2, opts) puts "\nTime: #{Time.now}" ap c1 puts "\n" ap c2 if c2 puts 'opts --------------------------------------------------' ap opts puts "-------------------------------------------------------\n\n" STDOUT.flush end class ClusterLogger < Api42 def update_logger(user_list, endpoint = '/v2/locations') return [] unless user_list.count != 0 connected = [] [1..10].map do |page| begin response = send_uri("#{endpoint}?filter[user_id]=#{user_list.join(',')}&sort=-end_at&filter[-end_at]&page=#{page}") response.each do |data| connected.push(login: data['user']['login'], seat: data['host'], connected: data['end_at'].nil?, begin_at: data['begin_at'], end_at: data['end_at']) end rescue Exception => e puts "An error occured in 42 API: #{e}" return [] end end connected.uniq { |c| c[:login] } end def update_user(connected_infos, user, slack, db) user_info = connected_infos.detect { |i| i[:login] == user[:login42] } return unless user_info secs = user_info[:connected] ? Time.now - Time.parse(user_info[:begin_at]) : Time.parse(user_info[:end_at]) - Time.parse(user_info[:begin_at]) opts = { secs: secs, seat: user_info[:seat] } # just log in if user_info[:connected] && !user[:connected] log(user, user_info, opts) slack.send_connected_message(user[:login42], user[:slack_id], opts) db.update_user(user[:login42], :last_seat, user_info[:seat]) db.update_user(user[:login42], :connected, true) return end return unless !user_info[:connected] && user[:connected] # just log out log(user, user_info, opts) slack.send_disconnected_message(user[:login42], user[:slack_id], opts) db.update_user(user[:login42], :last_connected, Time.parse(user_info[:end_at]).to_s) db.update_user(user[:login42], :connected, false) end def update_users(connected_infos, db) db.update_connected(connected_infos.map { |i| i[:login] }) rescue e puts "42 API update error: #{e}" end end
alelievr/stalker_sama
sources/main.rb
require_relative 'cluster_logger.rb' require_relative 'project_logger.rb' require_relative 'user_database.rb' require_relative 'slack_pinger.rb' require_relative 'slack_bot.rb' require 'awesome_print' cluster = ClusterLogger.new project = ProjectLogger.new slack = SlackPinger.new db = UserDatabase.new SlackBot.new loop do users = db.get_users users_api42_ids = users.map { |u| u[:api42_id] } begin connected_infos = cluster.update_logger(users_api42_ids) projects_infos = project.get_infos(users_api42_ids) rescue Exception => e puts "En error occured: #{e.message}" sleep 10 next end users.each do |user| cluster.update_user(connected_infos, user, slack, db) project.update_user(projects_infos, user, slack, db) end sleep 10 end
alelievr/stalker_sama
sources/slack_bot.rb
<reponame>alelievr/stalker_sama<gh_stars>0 require 'slack-ruby-client' require 'awesome_print' require 'json' require 'http' require 'final_redirect_url' require 'nokogiri' require 'open-uri' require 'rubycards' require_relative 'user_database.rb' include RubyCards class SlackBot def initialize Slack.configure do |config| config.token = ENV['SLACK_API_TOKEN'] config.logger = Logger.new(STDOUT) config.logger.level = Logger::WARN raise 'Missing ENV[SLACK_API_TOKEN]!' unless config.token end @ud = UserDatabase.new @client = Slack::RealTime::Client.new @client.on :message do |data| on_react(data) on_every_message(data) on_direct_message(data) if data.channel[0] == 'D' on_channel_message(data) if data.channel[0] == 'C' end @client.on :hello do puts "Successfully connected, welcome '#{@client.self.name}' to the '#{@client.team.name}' team at https://#{@client.team.domain}.slack.com." end @client.on :close do |_data| puts 'Connection closing, exiting.' end @client.on :closed do |_data| puts 'Connection has been disconnected.' end Thread.new { @client.start! } end def send_message(chan, text) @client.typing channel: chan @client.message channel: chan, text: text end def on_channel_message(data) #data: #"type" => "message", #"channel" => "D9JE10EBG", #"user" => "U9GUFLZ9N", #"text" => "yo", #"ts" => "1520183877.000114", #"source_team" => "T9B6RUSKT", #"team" => "T9B6RUSKT" return unless data.text =~ /.*cluster/i || data.text =~ /.*stalker.*/i puts data.text on_direct_message(data) end def on_react(data) case data.text when /is.*weak.*\?/ send_message(data.channel, 'Yes !') when /just pex/ react(data, :tada) when /mang(er|é)/i react(data, :pizza) react(data, :amerelo) when /cadam/ react(data, :madac) when /m’attendez pas/i react(data, :runner) when /malade/i react(data, :mask) when /chaud/i react(data, :burn) if rand(4) == 2 when /faille.*temporelle/i react(data, :octopus) when /lovecraft/i react(data, :squid) when /fuck/i react(data, :face_with_symbols_on_mouth) when /trop de monde/i react(data, :monkey) react(data, :sheep) react(data, :rabbit2) react(data, :rat) react(data, :chipmunk) when /zetes ou/i react(data, :eyes) when /pas moi/i react(data, :eyes) when /is faster than Usain Bolt/ react(data, :ultra_fast_parrot) when /has left, his weakness has no limits/ react(data, :shame) when /diseppears after/ react(data, :nuclear_explosion) if rand(2) == 1 when /caf[eé]/i react(data, :coffee) when /rage quit/i react(data, :rage) when /(shell|terminal|iterm|bash|zsh)/i react(data, :terminal) when /ah/i react(data, :ah) end #User specific reactions: case data.user when /UA3BFSJ3X/ # frmarinh react(data, :money_with_wings) if rand(6) == 1 when /U9CQUF9BR/ # nboulaye react(data, :terminal) if rand(8) == 1 when /U9G62CJDQ/ # bbrunell react(daat, :weak) if rand(8) == 1 when /U9B593R1N/ # bal-khan react(data, :banana) if rand(6) == 1 when /U9GUFLZ9N/ # alelievr react(data, :unity) if rand(3) == 1 when /U9B3RJWSU/ # ocarta-l react(data, :dark_sunglasses) if rand(10) == 1 react(data, :iex) if rand(10) == 1 when /U9BPLMTAP/ # hmoussa react(data, :ghost) if rand(6) == 1 when /U9B4EL3NC/ # flevesqu react(data, :octopus) if rand(6) == 1 react(data, :cthulhu) if rand(6) == 1 react(data, :tantacles) if rand(6) == 1 when /U9BTEQF7U/ # amerelo react(data, :amerelo) if rand(10) == 1 react(data, :rust) if rand(10) == 1 when /U9JVBA32S/ # cadam when /U9CBJLGDT/ # vbauguen react(data, :patapon_animated) if rand(10) == 1 when /UA6CRCFCZ/ # bciss react(data, :afro) if rand(4) == 1 when /U9JMHP8HJ/ # dmoureu- when /U9JLL19KK/ # amoreilh when /U9N1Q4D9V/ # vdaviot when /U9X6WU879/ # jblondea when /U9VC4R1TK/ # mconnat when /UA1SCLD7U/ # jguyet end end def on_every_message(data) case data.text when /\=\=/ send_message(data.channel, (rand(2) == 1) ? "true" : "false") end end def on_direct_message(data) return unless data.subtype.nil? ap data case data.text when /(\W+hi|^hi|\W+hey|^hey|^hello|\W+hello)\W+/i send_message(data.channel, "Hi <@#{data.user}> !") when /random gif/i random_gif(data) when /random commitstrip/i random_commitstrip(data) when /random commit/i random_commit(data) when /random quote/i random_quote(data) when /random card/i random_card(data) when /where.*you/i send_message(data.channel, 'In your back !') when /is.*weak.*\?/ send_message(data.channel, 'Yes !') when /who.*connected/i react(data, :eyes) send_message(data.channel, @ud.get_users.map { |u| "#{u[:login42]} @ #{u[:last_seat]}" if u[:connected] }.compact.join("\n")) else q = data.text.sub(/.*(stalker[s]?|cluster[s]?)\s*[\?\.,!:]*/i, '') react(data, :thinking_face) send_message(data.channel, ask_google(q)) end end def ask_google(query) return 'Nope sorry' if query.strip.empty? puts "query: #{query}" results = JSON.parse HTTP.get('https://www.googleapis.com/customsearch/v1', params: { q: query, key: ENV['GOOGLE_API_KEY'], cx: ENV['GOOGLE_CSE_ID'] }) result = results['items'].first if results['items'] return 'Daily search limit exedeed !' if results['error'] && results['error']['code'] == 403 result ? "#{result['title']}\n#{result['link']}" : 'Wait what ?' end def react(data, name) @client.web_client.reactions_add(name: name, channel: data.channel, timestamp: data.ts, as_user: true) end def random_card(data) hand = Hand.new deck = Deck.new deck.shuffle! hash = { 11 => 'jack', 12 => 'queen', 13 => 'king', 14 => 'ace' } hand.draw(deck, 2) card = hand.cards.first url = "https://raw.githubusercontent.com/hayeah/playing-cards-assets/master/png/#{card.to_i < 11 ? card.to_i.to_s : hash[card.to_i]}_of_#{card.suit.downcase}.png" card = hand.cards.last url2 = "https://raw.githubusercontent.com/hayeah/playing-cards-assets/master/png/#{card.to_i < 11 ? card.to_i.to_s : hash[card.to_i]}_of_#{card.suit.downcase}.png" send_message(data.channel, "#{url}\n#{url2}") end def random_gif(data) nokogiri_object = nokogiri('http://lesjoiesducode.tumblr.com/random') gif_url = nokogiri_object.xpath('//*/div[1]/p/img').first.values.detect { |i| i =~ /http/ } text = strip(nokogiri_object.xpath('//*/h1').first.children) send_message(data.channel, "*#{text}*\n#{gif_url}") end def random_commit(data) nokogiri_object = nokogiri('http://whatthecommit.com/') text = strip(nokogiri_object.xpath('//*/p').first) send_message(data.channel, "*#{text}*") end def random_quote(data) nokogiri_object = nokogiri('http://www.litquotes.com/Random-Quote.php') text = strip(nokogiri_object.xpath('//b').first) book = strip(nokogiri_object.xpath('//i').first) author = strip(nokogiri_object.xpath('//p/a').first) send_message(data.channel, "*#{text}*\n_#{book}_ by #{author}") end def random_commitstrip(data) nokogiri_object = nokogiri('http://www.commitstrip.com/fr/random') img_url = nokogiri_object.xpath('//div/p/img').first.values.detect { |i| i =~ /http/ } text = strip(nokogiri_object.xpath('//header[contains(@class, \'entry-header\')]/h1').first.children) send_message(data.channel, "*#{text}*\n#{img_url}") end def nokogiri(website) url = '' while url == '' url = (FinalRedirectUrl.final_redirect_url(website).to_s rescue '') end Nokogiri::HTML(open(url).read) end def strip(data) data.text.strip end end
selfcov/test_ruby
show_env.rb
#!/usr/bin/env ruby require 'base64' require 'json' ENV.sort.map do |key, value| puts key + '=' + value end puts Base64.encode64(ENV.to_hash.to_json)
codehearts/portfolio
_plugins/jekyll-gotenberg.rb
require 'net/http' # Convert an HTML file to PDF # The original HTML file is then removed # # This function makes a request to a Gotenberg server to render the site by URL def convert_html_to_pdf(item) # Read the global Jekyll config pdf_config = item.site.config.fetch 'pdf', {} gotenberg_config = pdf_config.fetch 'gotenberg', {} web_config = pdf_config.fetch 'web', {} # Establish hosts and ports for generation gotenberg_host = gotenberg_config.fetch 'host', 'localhost' gotenberg_port = gotenberg_config.fetch 'port', 3000 web_host = web_config.fetch 'host', 'localhost' web_port = web_config.fetch 'port', 4000 # Establish the Gotenberg endpoint endpoint = URI("http://#{gotenberg_host}:#{gotenberg_port}/forms/chromium/convert/url") # Create a request to the Gotenberg endpoint request = Net::HTTP::Post.new(endpoint) request.set_form({ 'url' => "http://#{web_host}:#{web_port}#{item.url}", 'marginTop' => '0', 'marginBottom' => '0', 'marginLeft' => '0', 'marginRight' => '0', 'waitDelay' => '1s' }, 'multipart/form-data') # Connect to the Gotenberg endpoint http = Net::HTTP.start( endpoint.host, endpoint.port, max_retries: 10) rescue retry # Communicate with the Gotenberg endpoint response = http.request(request) http.finish # Ensure the response was 200 response.value rescue raise 'Failed to connect with Gotenberg endpoint' # Write the PDF to the destination pdf_filename = File.join item.site.dest, item.relative_path[0..-6] + '.pdf' File.open(pdf_filename, 'wb') { |file| file.write(response.body) } # Remove the HTML file and its parent directory if empty File.delete item.destination('') Dir.delete File.dirname(item.destination('')) rescue nil end # Convert HTML to PDF after site is written if the front matter sets `pdf` true Jekyll::Hooks.register :site, :post_write, priority: Jekyll::Hooks::PRIORITY_MAP[:low] do |site| # Search through pages and documents (site.pages + site.documents).each do |item| convert_html_to_pdf(item) if item.data['pdf'] end end
codehearts/portfolio
_plugins/jekyll-cache-busting.rb
require 'fileutils' require 'digest' module Jekyll module CacheBusting # Mapping of file paths to their cache busting versions @@cached_files = Hash.new do |cache, path| # If an entry doesn't exist, hash and create it hash = Digest::MD5.hexdigest(File.read(path))[0..7] cache[path] = path.sub(/(\.)([^.]*)$/, ".#{hash}.\\2") end # Create a liquid filter which marks the uri for post processing def cache_busting(uri) "cache_bust(#{uri})" end def self.cache_busting(uri) @@cached_files[uri] end end end # Renames static and css files with thier md5 sum for cache busting Jekyll::Hooks.register :site, :post_write, priority: Jekyll::Hooks::PRIORITY_MAP[:high] do |site| # Creates an array of relative paths to all static files static_file_paths = site.static_files.map { |file| if file.destination_rel_dir.empty? relative_file_path = file.name else relative_path = file.destination_rel_dir relative_file_path = File.join relative_path, file.name end File.join site.dest, relative_file_path } # Creates an array of all pages to add cache busting to cached_page_paths = site.pages .map { |page| File.join site.dest, page.url } .filter { |page| page.end_with? '.css' } # Creates an array of all existent pages existent_page_paths = site.pages .map { |page| File.join site.dest, page.url.sub(/\/$/, '/index.html') } .filter { |page| File.exists? page } # Append a hash to each cache-controlled file (static_file_paths + cached_page_paths).each do |file_path| FileUtils.mv file_path, Jekyll::CacheBusting.cache_busting(file_path) end (static_file_paths + existent_page_paths).each do |file_path| # Read the cached filename if possible, or read the non-cached file if File.exists? Jekyll::CacheBusting.cache_busting file_path output_file_path = Jekyll::CacheBusting.cache_busting file_path else output_file_path = file_path end file_contents = File.read output_file_path # Replace all cache_bust() instances if found if file_contents.valid_encoding? and file_contents.index 'cache_bust' updated_file_contents = file_contents.gsub(/cache_bust\(([^)]+)\)/) { |_| Jekyll::CacheBusting.cache_busting(File.join site.dest, $1) .sub("#{site.dest}/", '') } # Write the updated file contents File.write output_file_path, updated_file_contents end end end Liquid::Template.register_filter(Jekyll::CacheBusting)
Monkee45/PMO
spec/Runner/project_spec.rb
<reponame>Monkee45/PMO require_relative 'spec_helper' require 'Runner/project' module Runner describe Project do before do # $stdout = StringIO.new @name = "terry" @name1 = 'john' @rating = 25 @member = TeamMember.new(@name, @rating) @member1 = TeamMember.new(@name1) @project = Project.new('r12 upgrade') @project.add_member(@member) @project.add_member(@member1) end it "has a capitalized name" do @project.name.should == 'R12 upgrade' end it "can have members added" do @project.members[0].to_s.should == "Terry has a rating of 25 after having 0 reviews" end it "can have multiple members added" do @project.members[1].to_s.should == "John has a rating of 10 after having 0 reviews" end context "when a high number is rolled" do it "adds 15 to the members rating" do Die.any_instance.stub(:roll).and_return(5) @project.review(2) @member.rating.should == @rating + (15*2) end end context "when a low number is rolled" do it "subtracts 15 from the members rating" do Die.any_instance.stub(:roll).and_return(2) @project.review(1) @member.rating.should == @rating - 15 end end context "when the ratings are finished" do it "it saves the final results to a file" do Die.any_instance.stub(:roll).and_return(5) @project.review(1) @project.save_final_ratings puts Dir.home File.exist?("#{Dir.home}/repos/PMO/bin/final_ratings.csv").should be true end end end end
Monkee45/PMO
lib/Runner/team_member.rb
<reponame>Monkee45/PMO require_relative 'ratings' module Runner class TeamMember attr_reader :name attr_accessor :rating attr_accessor :reviews include Ratings def initialize (name, rating=10, reviews=0) @name = name.capitalize @rating = rating @reviews = reviews end def to_s "#{@name} has a rating of #{@rating} after having #{@reviews} reviews" end end if __FILE__ == $PROGRAM_NAME suresh = TeamMember.new('suresh') puts suresh.to_s 1.upto(20) do suresh.rated_up end 1.upto(15) do suresh.rated_down end puts suresh.to_s end end
Monkee45/PMO
lib/Runner/ratings.rb
<filename>lib/Runner/ratings.rb module Runner module Ratings def rated_up(factor=1) @rating += (15*factor) @reviews += 1 puts "Awesome! #{@name} got rated up and is now #{@rating}" end def rated_down(factor=1) if (@rating -= (15*factor)) < 0 @rating = 0 end @reviews += 1 puts "Unluckly! #{@name} got rated down and is now #{@rating}" end def strong? rating > 79 end end end
Monkee45/PMO
test.rb
puts(Dir.pwd())
Monkee45/PMO
PMO.gemspec
<filename>PMO.gemspec Gem::Specification.new do |s| s.name = "PMO_mw" s.version = "1.0.0" s.author = "<NAME>" s.email = "<EMAIL>" s.homepage = "https://au.linkedin.com/in/Monkee45" s.summary = "basic project and team members with random rating system" s.description = File.read(File.join(File.dirname(__FILE__), 'README')) s.licenses = ['MIT'] s.files = Dir["{bin,lib,spec}/**/*"] + %w(LICENSE README) s.test_files = Dir["spec/**/*"] s.executables = [ 'PMO' ] s.required_ruby_version = '>=1.9' s.add_development_dependency 'rspec', '~> 0' end
Monkee45/PMO
spec/Runner/manager_spec.rb
<gh_stars>0 require_relative 'spec_helper' require 'Runner/manager' module Runner describe Manager do before do $stdout = StringIO.new @rating = 50 @manager = Manager.new('mandy', @rating, 'manager') end it "can be identified as a manager" do @manager.manager?.should == true end it "increases by 30 when rated up" do @manager.rated_up(2) @manager.rating.should == @rating+(15*2) end it "decreases by 15 when rated down" do @manager.rated_down(2) @manager.rating.should == @rating-(15*2) end it "is set to zero (0) if rated down below zero" do 1.upto(3) do @manager.rated_down(2) end @manager.rating.should == 0 end end end
Monkee45/PMO
lib/Runner/project.rb
<reponame>Monkee45/PMO require_relative 'team_member' require_relative 'die' require 'CSV' module Runner class Project attr_accessor :name attr_reader :members def initialize(name) @name = name.capitalize @members = [] end def add_member(member) @members << member end def show_members puts "#{self.name} has the following members:" sorted_members = @members.sort {|a,b| b.rating <=> a.rating} sorted_members.each do |member| puts "\t - #{member.name} rated #{member.rating}" end strong_members, weak_members = @members.partition{|member| member.strong?} puts "\n\nThe STRONG team members are:" strong_members.each do |member| puts "#{member.name}*" end puts "\n\nThe WEAK team members are:" weak_members.each do |member| puts "#{member.name}~" end end def review(cycles) dice = Die.new 1.upto(cycles) do |cycle| puts "CYCLE #{cycle}:" @members.each do |reviewer| puts "Review being done by #{reviewer.name}:" @members.each do |reviewee| if reviewee != reviewer puts "#{reviewer.name} is rating #{reviewee.name}" case dice.roll when 1,2 reviewee.rated_down when 4,5,6 reviewee.rated_up else puts "#{reviewer.name} doesn't know enough about #{reviewee.name}'s work" end end end # reviewee end # reviewer show_members end # cycle end # review def save_final_ratings CSV.open("#{Dir.home}/repos/PMO/bin/final_ratings.csv", 'w') do |csv| @members.each do |member| csv_string = [member.name,member.rating.to_s] csv << csv_string end end end end if __FILE__ == $PROGRAM_NAME suresh = TeamMember.new('suresh') vijay = TeamMember.new('vijay') ganesh = TeamMember.new('ganesh') r12upgrade = Project.new("R12-Upgrade") r12upgrade.add_member(suresh) r12upgrade.add_member(vijay) r12upgrade.add_member(cd ganesh) r12upgrade.show_members r12upgrade.review(2) r12upgrade.save_final_ratings end end
Monkee45/PMO
lib/Runner/manager.rb
require_relative 'team_member' module Runner class Manager < TeamMember def initialize(name, rating, type='manager') super(name, rating) @type = type.capitalize @factor = 2 end def manager? @type == 'Manager' end def rated_up(factor=1) puts "OMG! This is a Manager!!!" super(@factor) end def rated_down(factor=1) puts "OMG! Bad news for the Manager!!!" super(@factor) end end end
Monkee45/PMO
spec/Runner/team_member_spec.rb
<reponame>Monkee45/PMO require_relative 'spec_helper' require 'Runner/team_member' module Runner describe TeamMember do before do $stdout = StringIO.new @name = "terry" @name1 = 'john' @rating = 25 @member = TeamMember.new(@name, @rating) @member1 = TeamMember.new(@name1) end it "has a capitalized name" do @member.name.should == 'Terry' end it "has an initial rating" do @member.rating.should == 25 end it "has a string representation" do @member.to_s.should == "Terry has a rating of 25 after having 0 reviews" end it "has a default rating when required" do @member1.rating.should == 10 end it "increases by 15 when rated up" do @member.rated_up @member.rating.should == @rating+15 end it "decreases by 15 when rated down" do @member.rated_down @member.rating.should == @rating-15 end it "is set to zero (0) if rated down below zero" do 1.upto(3) do @member.rated_down end @member.rating.should == 0 end it "keeps count of the number of reviews a Team Member has had" do @member1.rated_up @member1.rated_down @member1.rated_up @member1.reviews.should == 3 end context "with a rating > 79" do before do @member1 = TeamMember.new('danny', 80) end it "is a strong performer" do @member1.should be_strong end end context "with a rating < 50" do before do @member1 = TeamMember.new('danny', 49) end it "is a weak performer" do @member1.should_not be_strong end end end end
bjork24/gliss
gliss.gemspec
<reponame>bjork24/gliss require './lib/gliss' Gem::Specification.new do |s| s.name = 'gliss-layout' s.version = Gliss::VERSION s.date = Gliss::DATE s.authors = ['<NAME>'] s.email = ['<EMAIL>'] s.homepage = 'http://product.voxmedia.com' s.license = 'MIT' s.summary = 'A constraint based responsive grid system.' s.description = 'Gliss is a system that uses max-width and width to allow elements to fall on different grids at different sizes instead of more traditional media queries. This allows elements to fluidly change their size instead of snapping to a new grid system at various breakpoints.' s.files = Dir['lib/**/*'] + Dir['stylesheets/**/*'] s.extra_rdoc_files = ['changelog.md', 'license.md', 'readme.md'] s.required_rubygems_version = '>= 1.3.6' s.add_runtime_dependency 'compass', '>= 0.12.0' end
ozataman/acts_as_bucket_on
init.rb
<gh_stars>1-10 require 'acts_as_bucket_on' ActiveRecord::Base.send :include, ActiveRecord::Acts::BucketOn RAILS_DEFAULT_LOGGER.info "** acts_as_bucket_on: initialized properly."
ozataman/acts_as_bucket_on
test/test_helper.rb
require 'rubygems' # require File.dirname(__FILE__) + "/../../../../config/environment.rb" require 'active_record' require 'active_support' require 'active_support/test_case' require File.dirname(__FILE__) + '/../init' class BucketableModel < ActiveRecord::Base acts_as_bucket_on :horizon, :conditions => "self.due_at.strftime('%y%m%d')" end
ozataman/acts_as_bucket_on
test/acts_as_bucket_on_test.rb
<filename>test/acts_as_bucket_on_test.rb require 'test_helper' class ActsAsBucketOnTest < ActiveSupport::TestCase test "that conditions are handled as expected" do assert_raise InvalidConditions { BucketableModel.send(:build_bucketing_condition, :trial, {:conditions => 1234}) } assert_nothing_raised { BucketableModel.send(:build_bucketing_condition, :trial, {:conditions => :name}) } end end
ozataman/acts_as_bucket_on
lib/acts_as_bucket_on.rb
<reponame>ozataman/acts_as_bucket_on<filename>lib/acts_as_bucket_on.rb require 'acts_as_bucket_on/acts_as_bucket_on'
ozataman/acts_as_bucket_on
lib/acts_as_bucket_on/acts_as_bucket_on.rb
module ActiveRecord module Acts module BucketOn def self.included(base) base.send :extend, ClassMethods end module ClassMethods class InvalidBucketName < StandardError; end class InvalidConditions < StandardError; end class InvalidObjectArray < StandardError; end class InvalidObject < StandardError; end # Dynamic bucketing function def bucket(collection, params = {}) params.assert_valid_keys([:conditions, :bucket_order, :max_buckets, :bucket_limit, :include_other]) raise InvalidObjectArray, "Input must respond to each (Enumerable)" unless collection.respond_to?(:each) condition_code = build_bucketing_condition(params[:conditions]) bucket_ordering_code = build_bucket_ordering(params[:bucket_order]) buckets = {} human_key_mappings = {} collection.each do |obj| unless obj.class.respond_to?(:base_class) && obj.class.base_class.descends_from_active_record? raise InvalidObject, "only ActiveRecord::Base descendants are allowed" end begin key, human_key = obj.instance_eval(condition_code) || ['nil', 'nil'] # if the given eval code raises an error for any reason # put the record in the unprocessed 'nil' bucket rescue key, human_key = ['nil', 'nil'] end human_key_mappings[key] = human_key buckets[key] ||= [] buckets[key] << obj end # order the keys and make sure each ordered key is actually present in the resulting dataset ordered_keys = buckets.instance_eval(bucket_ordering_code).map {|ok| human_key_mappings.keys.include?(ok) ? ok : nil}.compact # return ordered bucket keys and the buckets Hash [ordered_keys, human_key_mappings, buckets] end def acts_as_bucket_on(name, params = {}) bucket_name = name.to_s if bucket_name.blank? raise InvalidBucketName, "bucket name #{bucket_name} is not valid." end # save the given parameters to a class bucket parameters store write_inheritable_hash(:bucket_parameters, {bucket_name => params}) # define a method that will call the dynamic bucketer with # the previously saved bucketing parameters self.class_eval <<-HERE def self.bucket_on_#{bucket_name}(collection) bucket(collection, read_inheritable_attribute(:bucket_parameters)['#{bucket_name}']) end HERE end private # Build the qualities that bucketing will be based on # Accepts String, Symbol and Array objects def build_bucketing_condition(condition) if condition.nil? return nil elsif condition.is_a?(String) condition elsif condition.is_a?(Symbol) "send(:#{condition.to_s})" elsif condition.is_a?(Array) str = condition.map {|c| build_bucketing_condition(c) }.join(" && ") else raise InvalidConditions, "invalid condition given to acts_as_bucket_on" end end # Once the buckets are generated, the string defined here will be evaluated against # the buckets hash. # Once evaluated, the ordering function should # return the sorted bucket keys as an Array. # Once ported to Ruby 1.9, we can simply return an ordered Hash. def build_bucket_ordering(ordering) if ordering.nil? "keys" elsif ordering.is_a?(String) ordering elsif ordering.is_a?(Array) # methods to be applied as a chain to the resulting buckets.keys array. str = ordering.inject("keys") {|str, m| str + ".#{m}"} else raise InvalidConditions, "invalid bucket ordering given to acts_as_bucket_on" end end end end end end
vyorkin-forks/24pullrequests
app/models/archived_pull_requests.rb
class ArchivedPullRequest < ActiveRecord::Base belongs_to :user scope :year, -> (year) { where('EXTRACT(year FROM "created_at") = ?', year) } end
vyorkin-forks/24pullrequests
app/models/archived_pull_request.rb
<gh_stars>0 class ArchivedPullRequest < ActiveRecord::Base PAST_YEARS = [2013, 2012] belongs_to :user scope :year, -> (year) { where('EXTRACT(year FROM "created_at") = ?', year) } end
vyorkin-forks/24pullrequests
spec/models/concerns/pull_review_spec.rb
require 'rails_helper' describe Concerns::PullReview, type: :model do let(:user) { create(:user) } describe 'award_pullreview_coupon' do before do 3.times { create(:pull_request, user: user) } ENV['PULLREVIEW_COUPON'] = 'PULLREVIEW_COUPON' end it 'does not award PullReview coupon when less than 24 PRs' do expect(user.award_pullreview_coupon).to be_nil end it 'does not award PullReview coupon when not configured' do ENV['PULLREVIEW_COUPON'] = nil expect(user.award_pullreview_coupon).to be_nil end it 'awards PullReview coupon when 24 PRs' do 21.times { create(:pull_request, user: user) } expect(user.award_pullreview_coupon).to eq(ENV['PULLREVIEW_COUPON']) end end end
vyorkin-forks/24pullrequests
app/models/concerns/pull_review.rb
<reponame>vyorkin-forks/24pullrequests module Concerns module PullReview def award_pullreview_coupon return unless coupon.present? return coupon if pull_requests.year(CURRENT_YEAR).length > 23 end private def coupon @coupon ||= ENV['PULLREVIEW_COUPON'] end end end
alu0100831382/prct10
lib/biblio/fichero.rb
class Bibliography include Comparable attr_accessor :title,:author, :date def initialize(title,author,date) @title = title @author = author @date = date end def <=>(other) if(@author != other.author) @author <=> other.author elsif(@author == other.author) @date <=> other.date elsif(@date == other.date && @author == other.author) @title <=> other.title end end def to_s() @imprimir = "Autor/es: " + "#{@author}" + " Titulo: " + "#{@title}" + " Fecha: " + "#{@date}" end end class Libro < Bibliography #Clase para analizar los libros attr_accessor :edition,:volume,:place def initialize(title,author,date,edition,volume,place) @title = title @author = author @date = date @edition = edition @volume = volume @place = place end def to_s() #Formato dado para el APA en los libros @imprimir = "Autor/es: " + "#{@author}" + " Titulo: " + "#{@title}" + " Fecha: " + "#{@date}" + " Edicion: " + "#{@edition}" + " Volumen: " + "#{@volume}" + " Lugar de publicacion: " + "#{@place}" end end class Articulo < Bibliography #Clase para analizar los articulos attr_accessor :editor,:pages,:type def initialize(title,author,date,editor,pages,type) @title = title @author = author @date = date @editor = editor @pages = pages @type = type end def to_s() #Formato dado para el APA en los articulos @imprimir = "Autor/es: " + "#{@author}" + " Titulo: " + "#{@title}" + " Fecha: " + "#{@date}" + " Editor: " + "#{@editor}" + " Paginas: " + "#{@pages}" + " Obra: " + "#{@type}" end end
alu0100831382/prct10
spec/biblio_spec.rb
require 'spec_helper' describe Biblio do it 'has a version number' do expect(Biblio::VERSION).not_to be nil end describe Biblio do context "Las pruebas de los libros" do before :each do @l1 = Libro.new("Programming Ruby 1.9 & 2.0","<NAME>.","(2013)","(1 Edicion)","(2)","Inglaterra") @l2 = Libro.new("Pro Git 2009th Edition","<NAME>.","(2009)","(5 Edicion)","(3)","Inglaterra") @l3 = Libro.new("Ruby Programming Language","<NAME>.","(2008)","(2 Edicion)","(1)","Inglaterra") @l4 = Libro.new("The RSpecBook: Behaviour Driven Development with RSpec","<NAME>.","(2008)","(1 Edicion)","(2)","Inglaterra") @list_a = List.new() @list_b = List.new() @list_c = List.new() @list_a.insert_list(@l2) @list_a.insert_list(@l1) @list_b.insert_list(@l4) @list_b.insert_list(@l3) @list_c.insert_list(@l3) @list_c.insert_list(@l2) end it "Autores distintos, ordenados por autores" do expect(@list_a.sort).to eq([@l2,@l1]) end it "Autores iguales, ordenados por fechas" do expect(@list_c.sort).to eq([@l3,@l2]) end it "Autores iguales y fechas iguales, ordenados por titulos" do expect(@list_b.sort).to eq([@l3,@l4]) end it "Usando el formato de la Asociacion de Psicologica Americana (APA) en libros" do expect(@l1.to_s).to eq("Autor/es: <NAME>. Titulo: Programming Ruby 1.9 & 2.0 Fecha: (2013) Edicion: (1 Edicion) Volumen: (2) Lugar de publicacion: Inglaterra") expect(@l2.to_s).to eq("Autor/es: <NAME>. Titulo: Pro Git 2009th Edition Fecha: (2009) Edicion: (5 Edicion) Volumen: (3) Lugar de publicacion: Inglaterra") expect(@l3.to_s).to eq("Autor/es: <NAME>. Titulo: Ruby Programming Language Fecha: (2008) Edicion: (2 Edicion) Volumen: (1) Lugar de publicacion: Inglaterra") expect(@l4.to_s).to eq("Autor/es: <NAME>. Titulo: The RSpecBook: Behaviour Driven Development with RSpec Fecha: (2008) Edicion: (1 Edicion) Volumen: (2) Lugar de publicacion: Inglaterra") end context "Las pruebas de los articulos" do before :each do @a1 = Articulo.new("La Espanya que queremos","<NAME>.","(El Pais)","(2015)","(1)","Opinion") @a2 = Articulo.new("Asi es como malgastas energia (y dinero) en la cocina","<NAME>.","(El Pais)","(2013)","(2)","Columna") @a3 = Articulo.new("El Prado alcanza su cumbre digital","<NAME>.","(El Pais)","(2010)","(1)","Opinion") @a4 = Articulo.new("La justicia deportiva mantiene la suspension a Platini","<NAME>.","(El Pais)","(2010)","(2)","Articulo") @list_a = List.new() @list_b = List.new() @list_c = List.new() @list_a.insert_list(@a1) @list_a.insert_list(@a2) @list_b.insert_list(@a1) @list_b.insert_list(@a4) @list_c.insert_list(@a1) @list_c.insert_list(@a3) end it "Autores distintos, ordenados por autores" do expect(@list_a.sort).to eq([@a1,@a2]) end it "Autores iguales, ordenados por fechas" do expect(@list_c.sort).to eq([@a3,@a1]) end it "Autores iguales y fechas iguales, ordenados por titulos" do expect(@list_b.sort).to eq([@a3,@a4]) end it "Usando el formato de la Asociacion de Psicologica Americana (APA) en articulos" do expect(@a1.to_s).to eq("Autor/es: <NAME>. Titulo: La Espanya que queremos Fecha: (El Pais) Editor: (2015) Paginas: (1) Obra: Opinion") expect(@a2.to_s).to eq("Autor/es: <NAME>. Titulo: Asi es como malgastas energia (y dinero) en la cocina Fecha: (El Pais) Editor: (2013) Paginas: (2) Obra: Columna") expect(@a3.to_s).to eq("Autor/es: <NAME>. Titulo: El Prado alcanza su cumbre digital Fecha: (El Pais) Editor: (2010) Paginas: (1) Obra: Opinion") expect(@a4.to_s).to eq("Autor/es: <NAME>. Titulo: La justicia deportiva mantiene la suspension a Platini Fecha: (El Pais) Editor: (2010) Paginas: (2) Obra: Articulo") end end end end end
thomas-yancey/action-cable-chat-template
config/routes.rb
<reponame>thomas-yancey/action-cable-chat-template Rails.application.routes.draw do root to: 'welcome#index' resources :users, only: [:new, :index, :create] resources :sessions, only: [:new, :destroy, :create] resources :rooms, except: [:update, :edit, :destroy] do resources :memberships, only: [:index, :create] end resources :messages, only: [:create] # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
thomas-yancey/action-cable-chat-template
app/controllers/messages_controller.rb
class MessagesController < ApplicationController def create @message = Message.new(message_params) @message.save redirect_to :back end private def message_params params.require(:message).permit(:room_id, :content).merge(user_id: current_user.id) end end
thomas-yancey/action-cable-chat-template
app/controllers/memberships_controller.rb
<filename>app/controllers/memberships_controller.rb<gh_stars>0 class MembershipsController < ApplicationController before_action :verify_logged_in def index @room = Room.find(params[:room_id]) redirect_with_flash unless member_of_group @memberships = Membership.where(room_id: params[:room_id]) @users = User.where.not(id: @memberships.pluck(:user_id)) end def create @room = Room.find(params[:room_id]) redirect_with_flash unless member_of_group user = User.find(params[:user_id]) membership = Membership.new(user_id: user.id, room_id: @room.id) if membership.save json_hash = {username: user.username, id: user.id} render text: JSON.generate(json_hash) else #error handling end end end
thomas-yancey/action-cable-chat-template
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController def new @user = User.new end def create @user = User.find_by(username: params[:session][:username]) #utilize bcrypts authenticate method to see if the password is correct if @user && @user.authenticate(params[:session][:password]) session[:user_id] = @user.id redirect_to rooms_path else @errors = @user.nil? ? ["username not found"] : ["username and password do not match"] render "/sessions/new" end end def destroy session.clear redirect_to root_path end end
thomas-yancey/action-cable-chat-template
app/models/user.rb
<reponame>thomas-yancey/action-cable-chat-template class User < ApplicationRecord has_secure_password has_many :memberships has_many :rooms, through: :memberships validates_uniqueness_of :username validates_presence_of :username validates :username, length: {maximum: 16} end
thomas-yancey/action-cable-chat-template
app/controllers/users_controller.rb
<filename>app/controllers/users_controller.rb class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id # Here we are pushing the first room which is # going to be our open chat room @user.rooms << Room.find(1) redirect_to rooms_path else @errors = @user.errors.full_messages render "/users/new" end end private def user_params params.require(:user).permit(:username, :password) end end
thomas-yancey/action-cable-chat-template
app/models/room.rb
<reponame>thomas-yancey/action-cable-chat-template<gh_stars>0 class Room < ApplicationRecord has_many :memberships has_many :messages has_many :users, through: :memberships validates :name, presence: true, length: { maximum: 10}, uniqueness: true end
thomas-yancey/action-cable-chat-template
app/models/membership.rb
class Membership < ApplicationRecord belongs_to :user belongs_to :room validates_presence_of :room_id validates_presence_of :user_id validates_uniqueness_of :user_id, :scope => :room_id def name User.find(self.user_id).username end end
thomas-yancey/action-cable-chat-template
app/controllers/rooms_controller.rb
class RoomsController < ApplicationController before_action :verify_logged_in def show @room = Room.find(params[:id]) redirect_with_flash unless member_of_group @messages = @room.messages.order(id: :desc).limit(500).reverse @message = Message.new @users = @room.users end def index @rooms = current_user.rooms @room = Room.new end def create @room = Room.new(room_params) if @room.save @room.users << current_user redirect_to room_memberships_path(@room) else flash[:error] = @room.errors.full_messages.to_sentence redirect_to rooms_path end end private def room_params params.require(:room).permit(:name) end end
thomas-yancey/action-cable-chat-template
app/models/message.rb
<filename>app/models/message.rb class Message < ApplicationRecord belongs_to :user belongs_to :room validates_presence_of :content validates_presence_of :user_id validates_presence_of :room_id end
thomas-yancey/action-cable-chat-template
app/controllers/application_controller.rb
<filename>app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery with: :exception helper_method :current_user, :logged_in?, :member_of_group, :verified_log_in, :redirect_with_flash def current_user return unless session[:user_id] @current_user ||= User.find(session[:user_id]) end def logged_in? !!session[:user_id] end def member_of_group !!@room.memberships.find_by(user_id: current_user.id) end def redirect_with_flash flash[:notice] = "You are not a member of that room" redirect_to root_path end def verify_logged_in unless logged_in? flash[:notice] = "You must be logged in to view that page" redirect_to root_path end end end
GrahamMThomas/advent_of_code_2018
2/main.rb
<filename>2/main.rb # Prompt https://adventofcode.com/2018/day/2 num_of_threes = 0 num_of_twos = 0 File.readlines("input.txt").each do |box_id| box_id = box_id.strip tracker = Hash.new(0) box_id.each_char do |x| tracker[x] += 1 end occurance_tracker = tracker.each_with_object({}){|(k,v),o|(o[v]||=[])<<k} occurance_tracker.default = [] num_of_threes += 1 unless occurance_tracker[3].empty? num_of_twos += 1 unless occurance_tracker[2].empty? end puts "Number of threes #{num_of_threes}" puts "Number of twos #{num_of_twos}" puts "Answer #{num_of_threes * num_of_twos}"
GrahamMThomas/advent_of_code_2018
8/main.rb
<filename>8/main.rb # Prompt https://adventofcode.com/2018/day/4 require 'awesome_print' class Node attr_accessor :children, :metadata_entries, :num_of_children, :num_of_metadata def initialize() @num_of_children = 0 @num_of_metadata = 0 @children = [] @metadata_entries = [] end def get_children(tree) total_metadata = 0 @num_of_children = tree.get_next_input @num_of_metadata = tree.get_next_input num_of_children.times do |x| bob = Node.new total_metadata += bob.get_children(tree) total_metadata += bob.get_metadata(tree) @children << bob end total_metadata end def get_metadata(tree) @num_of_metadata.times do |x| @metadata_entries << tree.get_next_input end @metadata_entries.sum end end class Tree attr_accessor :input_pointer, :input, :root def initialize(input) @input = input.split(' ').map(&:to_i) @input_pointer = 0 end def get_next_input tmp = @input[@input_pointer] @input_pointer += 1 return tmp end ## Part 1 method def get_metadata_sum @root = Node.new() total_metadata = @root.get_children(self) total_metadata += @root.get_metadata(self) total_metadata end end # Build my quick shoddy version of a "graph" input = File.open('input.txt').read bob = Tree.new(input) puts "Answer is: #{bob.get_metadata_sum}"
GrahamMThomas/advent_of_code_2018
3/main.rb
<reponame>GrahamMThomas/advent_of_code_2018<filename>3/main.rb<gh_stars>0 # Prompt https://adventofcode.com/2018/day/3 require "awesome_print" class SquareInch attr_accessor :claims def initialize @claims = [] end end fabric = Array.new(1000) { Array.new(1000) {SquareInch.new}} File.readlines("input.txt").each do |claim| # Parsing =================================================================== parsed_claim = /#(\d+) @ (\d+),(\d+): (\d+)x(\d+)/.match(claim.strip()) claim_id = parsed_claim.captures[0].to_i from_left_edge = parsed_claim.captures[1].to_i from_top_edge = parsed_claim.captures[2].to_i width = parsed_claim.captures[3].to_i height = parsed_claim.captures[4].to_i # Iteration ================================================================= (0...width).each do |x_coord| (0...height).each do |y_coord| fabric[x_coord + from_left_edge][y_coord+from_top_edge].claims << claim_id end end end File.readlines("input.txt").each do |claim| # Parsing =================================================================== parsed_claim = /#(\d+) @ (\d+),(\d+): (\d+)x(\d+)/.match(claim.strip()) claim_id = parsed_claim.captures[0].to_i from_left_edge = parsed_claim.captures[1].to_i from_top_edge = parsed_claim.captures[2].to_i width = parsed_claim.captures[3].to_i height = parsed_claim.captures[4].to_i # Iteration ================================================================= catch :overlaps do (0...width).each do |x_coord| (0...height).each do |y_coord| throw :overlaps if fabric[x_coord + from_left_edge][y_coord+from_top_edge].claims.length > 1 end end puts "Answer #{claim_id}" end end
GrahamMThomas/advent_of_code_2018
4/main.rb
# Prompt https://adventofcode.com/2018/day/4 require "awesome_print" guard_sleep_times = Hash.new(0) guard_sleep_minute_tracker = Hash.new { |h,k| h[k] = Hash.new(0) } current_guard_id = 0 current_sleep_start_time = 0 break_check = 0 File.readlines("input.txt").each do |event| parsed_event = /\[\d{4}\-\d{2}\-\d{2} \d{2}:(\d{2})\] (Guard #(\d+) begins shift|falls asleep|wakes up)/.match(event.strip()) minute = parsed_event.captures[0].to_i event_type = parsed_event.captures[1] if event.include? "falls asleep" current_sleep_start_time = minute elsif event.include? "wakes up" guard_sleep_times[current_guard_id] += (minute - current_sleep_start_time) ((current_sleep_start_time)..(minute-1)).each do |time| guard_sleep_minute_tracker[current_guard_id][time] += 1 end elsif event.include? "begins shift" puts "Beginning shift for #{current_guard_id}" current_guard_id = parsed_event.captures[2] else raise "Failed to match event. #{event}" end # if break_check == 6 # puts "STATS" # ap guard_sleep_times # ap guard_sleep_minute_tracker['2953'] # puts "DONE -----" # break # end # break_check += 1 end answer = Hash[guard_sleep_times.sort_by{|k,v| v.to_i}] guard = [answer.max_by{|k,v| v}][0][0] puts "Laziest Guard is ##{guard}" ap guard_sleep_minute_tracker[guard] puts "Most often asleep at #{guard_sleep_minute_tracker[guard].max_by{|k,v| v}.first}"
GrahamMThomas/advent_of_code_2018
5b/main.rb
<gh_stars>0 # Prompt https://adventofcode.com/2018/day/5 require "awesome_print" polymer_alphabet = Hash.new(0) ('a'..'z').to_a.each do |letter| polymer = File.open('input.txt').read done = false while not done skip_index = 0 tmp_polymer = polymer tmp_polymer.gsub!(letter, '') tmp_polymer.gsub!(letter.upcase, '') done = true (0...polymer.length-1).each do |x| x -= skip_index if polymer[x] != polymer[x+1] and polymer[x].downcase == polymer[x+1].downcase tmp_polymer.slice!(x+1) tmp_polymer.slice!(x) skip_index += 2 done = false end end polymer = tmp_polymer end polymer_alphabet[letter] = tmp_polymer.length end ap polymer_alphabet.min_by {|k,v| v}
GrahamMThomas/advent_of_code_2018
7/main.rb
<gh_stars>0 # Prompt https://adventofcode.com/2018/day/4 require "awesome_print" class Step attr_accessor :prereqs, :unlocks, :letter def initialize letter = '' @prereqs = [] @unlocks = [] end end graph = Hash.new { |h,k| h[k] = Step.new } File.readlines("input.txt").each do |step| parsed_step = /Step (\w) must be finished before step (\w) can begin./.match(step.strip()) prereq = parsed_step.captures[0] target = parsed_step.captures[1] graph[prereq].letter = prereq graph[target].letter = target graph[target].prereqs << graph[prereq] graph[prereq].unlocks << graph[target] end starting_point = graph.select {|k,v| v.prereqs == []}.sort.map(&:first) answer = [] queue = [starting_point].flatten while queue.length > 0 queue.sort! letter = queue.delete_at(0) answer << letter graph[letter].unlocks.map(&:letter).each do |unlock| queue << unlock if (graph[unlock].prereqs.map(&:letter) - answer).length.zero? end # sleep 1 # puts "Answer: " # ap answer # sleep 1 # puts "Queue: " # ap queue end graph.each do |h,k| puts "Letter: #{h} Prereqs: #{k.prereqs.map(&:letter)}" end puts answer.join('')
GrahamMThomas/advent_of_code_2018
5/main.rb
# Prompt https://adventofcode.com/2018/day/5 require "awesome_print" polymer = File.open('input.txt').read done = false while not done skip_index = 0 tmp_polymer = polymer done = true (0...polymer.length-1).each do |x| x -= skip_index if polymer[x] != polymer[x+1] and polymer[x].downcase == polymer[x+1].downcase tmp_polymer.slice!(x+1) tmp_polymer.slice!(x) skip_index += 2 done = false end end polymer = tmp_polymer end puts polymer.length
GrahamMThomas/advent_of_code_2018
1b/main.rb
<reponame>GrahamMThomas/advent_of_code_2018 # Prompt https://adventofcode.com/2018/day/1 frequency = 0 frequnecies = Hash.new(0) frequnecies[0] = 1 while true File.readlines("input.txt").each do |num| frequency += num.to_i if frequnecies[frequency] == 1 puts frequency.to_i exit else frequnecies[frequency] = 1 end end puts frequency end
GrahamMThomas/advent_of_code_2018
8b/main.rb
<gh_stars>0 # Prompt https://adventofcode.com/2018/day/4 require 'awesome_print' class Node attr_accessor :children, :metadata_entries, :num_of_children, :num_of_metadata def initialize() @num_of_children = 0 @num_of_metadata = 0 @children = [] @metadata_entries = [] end def get_children(tree) total_metadata = 0 @num_of_children = tree.get_next_input @num_of_metadata = tree.get_next_input num_of_children.times do |x| bob = Node.new total_metadata += bob.get_children(tree) total_metadata += bob.get_metadata(tree) @children << bob end total_metadata end def get_metadata(tree) @num_of_metadata.times do |x| @metadata_entries << tree.get_next_input end @metadata_entries.sum end def get_value if @num_of_children.zero? puts "Returning #{@metadata_entries.sum}" return @metadata_entries.sum end total_value = 0 ap @children @metadata_entries.each do |value| unless @children[value - 1].nil? puts "Getting value for #{value}" total_value += @children[value - 1].get_value puts total_value end end total_value end end class Tree attr_accessor :input_pointer, :input, :root def initialize(input) @input = input.split(' ').map(&:to_i) @input_pointer = 0 end def get_next_input tmp = @input[@input_pointer] @input_pointer += 1 tmp end ## Part 1 method def get_metadata_sum @root = Node.new total_metadata = @root.get_children(self) total_metadata += @root.get_metadata(self) total_metadata end end # Build my quick shoddy version of a "graph" input = File.open('input.txt').read bob = Tree.new(input) bob.get_metadata_sum puts "Answer is: #{bob.root.get_value}"
GrahamMThomas/advent_of_code_2018
7b/main.rb
<gh_stars>0 # Prompt https://adventofcode.com/2018/day/4 require "awesome_print" class Step attr_accessor :prereqs, :unlocks, :letter, :health def initialize letter = '' health = 0 @prereqs = [] @unlocks = [] end end graph = Hash.new { |h,k| h[k] = Step.new } # Build my quick shoddy version of a "graph" File.readlines("input.txt").each do |step| parsed_step = /Step (\w) must be finished before step (\w) can begin./.match(step.strip()) prereq = parsed_step.captures[0] target = parsed_step.captures[1] graph[prereq].letter = prereq graph[target].letter = target graph[prereq].health = prereq.ord - 64 + 60 graph[target].health = target.ord - 64 + 60 graph[target].prereqs << graph[prereq] graph[prereq].unlocks << graph[target] end # Select all starting points with no prereqs starting_point = graph.select {|k,v| v.prereqs == []}.sort.map(&:first) answer = [] queue = [starting_point].flatten # Every iteration is a second. Reduce one health for every second until it's empty # Probably not the most efficient way to do it but... seconds = 0 while queue.length > 0 queue.sort! five_workers = queue[0..4] five_workers.each do |working_letter| graph[working_letter].health -= 1 if graph[working_letter].health <= 0 letter = queue.delete(working_letter) answer << letter graph[letter].unlocks.map(&:letter).each do |unlock| queue << unlock if (graph[unlock].prereqs.map(&:letter) - answer).length.zero? end end end seconds += 1 end graph.each do |h,k| puts "Letter: #{h} Prereqs: #{k.prereqs.map(&:letter)}" end puts seconds
GrahamMThomas/advent_of_code_2018
2b/main.rb
<filename>2b/main.rb # Prompt https://adventofcode.com/2018/day/2 boxes = File.open("input.txt").read boxes = boxes.split("\n").map(&:strip) answer = "Shit." File.readlines("input.txt").each do |box_id| box_id = box_id.strip tracker = Hash.new(0) box_id.each_char do |x| tracker[x] += 1 end boxes.each do |box| diff_chars_count = 0 box.length.times.each do |x| if box[x] != box_id[x] diff_chars_count += 1 end end if diff_chars_count == 1 puts "First box: #{box_id}" puts "Second box: #{box}" answer = (box_id.scan(/./) & box.scan(/./)) end end end puts "Answer #{answer.join('')}"
GrahamMThomas/advent_of_code_2018
4b/main.rb
<reponame>GrahamMThomas/advent_of_code_2018<gh_stars>0 # Prompt https://adventofcode.com/2018/day/4 require "awesome_print" guard_sleep_times = Hash.new(0) guard_sleep_minute_tracker = Hash.new { |h,k| h[k] = Hash.new(0) } current_guard_id = 0 current_sleep_start_time = 0 File.readlines("input.txt").each do |event| parsed_event = /\[\d{4}\-\d{2}\-\d{2} \d{2}:(\d{2})\] (Guard #(\d+) begins shift|falls asleep|wakes up)/.match(event.strip()) minute = parsed_event.captures[0].to_i event_type = parsed_event.captures[1] if event.include? "falls asleep" current_sleep_start_time = minute elsif event.include? "wakes up" guard_sleep_times[current_guard_id] += (minute - current_sleep_start_time) ((current_sleep_start_time)..(minute-1)).each do |time| guard_sleep_minute_tracker[current_guard_id][time] += 1 end elsif event.include? "begins shift" puts "Beginning shift for #{current_guard_id}" current_guard_id = parsed_event.captures[2] else raise "Failed to match event. #{event}" end end answer = Hash[guard_sleep_times.sort_by{|k,v| v.to_i}] guard = [answer.max_by{|k,v| v}][0][0] puts "Laziest Guard is ##{guard}" ap guard_sleep_minute_tracker[guard] puts "Most often asleep at #{guard_sleep_minute_tracker[guard].max_by{|k,v| v}.first}" guard_sleep_minute_tracker.each do |k, v| puts "##{k} sleep most times: #{v.max_by{|k,v| v}}" end
dehlen/atlas-framework
AtlasFramework.podspec
Pod::Spec.new do |s| s.name = "AtlasFramework" s.version = "1.2.0" s.summary = "Atlas is a framework that helps you structure your iOS app using the MVVM-C architecture pattern." s.description = <<-DESC Atlas is a framework that helps you structure your iOS app using the MVVM-C architecture pattern. The Atlas framework is based on the concepts introduced in the MVVM-C talk by <NAME>. DESC s.homepage = "https://github.com/dm-drogeriemarkt/atlas-framework" s.license = { :type => "MIT", :file => "LICENSE.txt" } s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/dm-drogeriemarkt/atlas-framework.git", :tag => "#{s.version}" } s.source_files = "Atlas/Atlas/**/*.{h,m,swift}" s.public_header_files = "Atlas/Atlas/**/*.h" s.swift_version = '4.2' s.platform = :ios, '9.0' end
JesterPrince/docker-web-framework-examples
rails/app/controllers/hello_controller.rb
<filename>rails/app/controllers/hello_controller.rb class HelloController < ApplicationController def home render html: "Hello world with RAILS_ENV=#{ENV['RAILS_ENV']}" end end
JesterPrince/docker-web-framework-examples
rails/config/application.rb
<reponame>JesterPrince/docker-web-framework-examples require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" # require "action_cable/engine" require "sprockets/railtie" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Hello class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. # Set up logging to be the same in all environments but control the level # through an environment variable. config.log_level = ENV['LOG_LEVEL'] # Log to STDOUT because Docker expects all processes to log here. You could # then redirect logs to a third party service on your own such as systemd, # or a third party host such as Loggly, etc.. logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.log_tags = %i[subdomain uuid] config.logger = ActiveSupport::TaggedLogging.new(logger) end end
JesterPrince/docker-web-framework-examples
rails/config/routes.rb
Rails.application.routes.draw do # For details on the DSL available within this file: # see http://guides.rubyonrails.org/routing.html root to: 'hello#home' # Set up a custom health check endpoint (no controller needed). get '/healthy', to: ->(_) { [200, {}, ['']] } end
OnkelDisMaster/retort
spec/models/retort_spec.rb
<reponame>OnkelDisMaster/retort require "spec_helper" path = "./plugins/retort/plugin.rb" source = File.read(path) plugin = Plugin::Instance.new(Plugin::Metadata.parse(source), path) plugin.activate! plugin.initializers.first.call describe ::Retort::Retort do before do SiteSetting.load_settings(File.join(Rails.root, 'plugins', 'retort', 'config', 'settings.yml')) end let(:user) { Fabricate :user } let(:topic) { Fabricate :topic } let(:post) { Fabricate :post, topic: topic } let(:another_post) { Fabricate :post, topic: topic } let(:another_topic_post) { Fabricate :post } let(:emoji) { 'kickbutt' } let(:altermoji) { 'puntrear' } let(:retort) { Retort::Retort.new(post, user, emoji) } describe 'initialize' do it 'stores the post' do expect(retort.post).to eq post end it 'stores the user' do expect(retort.user).to eq user end it 'stores the retort' do expect(retort.retort).to eq emoji end end describe 'where' do let(:another_user) { Fabricate :user } let(:a_third_user) { Fabricate :user } let!(:existing) { Fabricate :post_detail, post: post, key: "retort_#{user.id}", value: 'retort', extra: emoji } let!(:another_existing) { Fabricate :post_detail, post: post, key: "retort_#{another_user.id}", value: :retort, extra: emoji } let!(:another_post_retort) { Fabricate :post_detail, post: another_post, key: "retort_#{user.id}", value: :retort, extra: emoji } let!(:another_topic_retort) { Fabricate :post_detail, post: another_topic_post, key: "retort_#{user.id}", value: :retort, extra: emoji } it 'finds an existing retort by post / user' do found = Retort::Retort.where(post: post, user: user) expect(found).to include existing expect(found).to_not include another_existing end it 'finds existing retorts by topic / user' do found = Retort::Retort.where(topic: topic) end it 'finds all retorts for a post if no user is specified' do found = Retort::Retort.where(post: post) expect(found).to include existing expect(found).to include another_existing expect(found).to_not include another_post_retort expect(found).to_not include another_topic_retort end it 'finds all retorts for a topic if no user is specified' do found = Retort::Retort.where(topic: topic) expect(found).to include existing expect(found).to include another_existing expect(found).to include another_post_retort expect(found).to_not include another_topic_retort end it 'returns empty when no post or topic is specified' do found = Retort::Retort.where(user: user) expect(found).to be_empty end it 'returns empty when no retort exists' do expect(Retort::Retort.where(post: post, user: a_third_user)).to be_empty end end describe 'save' do it 'saves the retort to the posts details' do expect { retort.save }.to change { PostDetail.count }.by(1) expect(PostDetail.find_by(post: post, key: "retort_#{user.id}", value: :retort, extra: emoji)).to be_present end it 'overwrites an existing retort' do retort.save retort.retort = altermoji expect { retort.save }.not_to change { PostDetail.count } expect(PostDetail.find_by(post: post, key: "retort_#{user.id}", value: :retort, extra: altermoji)).to be_present expect(PostDetail.find_by(post: post, key: "retort_#{user.id}", value: :retort, extra: emoji)).not_to be_present end it 'deletes an empty retort' do retort.save retort.retort = '' expect { retort.save }.to change { PostDetail.count }.by(-1) expect(PostDetail.find_by(post: post, key: "retort_#{user.id}", value: :retort, extra: emoji)).not_to be_present end end end
OnkelDisMaster/retort
spec/controllers/retorts_controller_spec.rb
<filename>spec/controllers/retorts_controller_spec.rb require "spec_helper" path = "./plugins/retort/plugin.rb" source = File.read(path) plugin = Plugin::Instance.new(Plugin::Metadata.parse(source), path) plugin.activate! plugin.initializers.first.call describe ::Retort::RetortsController do routes { ::Retort::Engine.routes } before do SiteSetting.load_settings(File.join(Rails.root, 'plugins', 'retort', 'config', 'settings.yml')) end describe "index" do it "returns a list retorts for a post" do xhr :get, :index end it "returns a list of retorts for a topic" do end end describe "update" do it "updates a retort" do end end describe "destroy" do it "destroys a retort" end def response_json JSON.parse(response.body) end end
borisrorsvort/traduction_litteraire
helpers/page_title_helper.rb
# frozen_string_literal: true module PageTitleHelper def site_title data.config.site.title end def title_separator data.config.site.title_separator end def render_page_title current_page.data.title + title_separator + site_title end end
borisrorsvort/traduction_litteraire
helpers/meta_tag_helper.rb
# frozen_string_literal: true module MetaTagHelper # Sets the page meta description and keywords, which can be composed by either # a) data in config.yml (which is sitewide), or # b) data set in the FrontMatter of each page def meta_keywords keywords = current_page.data.meta_keywords || data.config.site.meta_keywords keywords.join(', ') end def meta_description current_page.data.meta_description || data.config.site.meta_description end end
borisrorsvort/traduction_litteraire
config.rb
<filename>config.rb<gh_stars>0 # -------------------------------------------------------------------------------------------------- # Helpers # -------------------------------------------------------------------------------------------------- helpers do # Helpers are defined in and can be added to `helpers/custom_helpers.rb`. # In case you require helpers within `config.rb`, they can be added here. end activate :autoprefixer do |prefix| prefix.browsers = "last 2 versions" end page '/*.xml', layout: false page '/*.json', layout: false page '/*.txt', layout: false # Use LiveReload # activate :livereload # Use Search Engine Sitemap set :url_root, "http://www.traduction-litteraire.com" activate :search_engine_sitemap # -------------------------------------------------------------------------------------------------- # Paths # -------------------------------------------------------------------------------------------------- # set :css_dir, 'stylesheets' # set :fonts_dir, 'fonts' # set :images_dir, 'images' # set :js_dir, 'javascripts' activate :blog do |blog| blog.prefix = 'articles' blog.permalink = '{title}.html' blog.layout = 'articles' blog.sources = '{id}-{title}.html' blog.tag_template = "/tag.html" blog.paginate = true blog.per_page = 10 blog.page_link = "page/{num}" end activate :directory_indexes # Pretty URLs - See https://middlemanapp.com/advanced/pretty_urls/ activate :relative_assets set :relative_links, true page "/feed.xml", layout: false # -------------------------------------------------------------------------------------------------- # Build configuration # -------------------------------------------------------------------------------------------------- set :markdown_engine, :redcarpet set :haml, { :format => :html5 } configure :build do activate :minify_css activate :minify_javascript activate :gzip activate :asset_hash, ignore: [/images\/(.*\.png|.*\.svg)/] end activate :gh_pages do |gh_pages| gh_pages.remote = '<EMAIL>:borisrorsvort/traduction_litteraire.git' end Haml::TempleEngine.disable_option_validator!
tobytripp/text_to_noise
spec/text_to_noise/player_spec.rb
require "spec_helper" module Rubygame class Sound class << self attr_accessor :autoload_dirs def []( sound_name ) end def autoload_dirs() @autoload_dirs ||= [] end end end end describe TextToNoise::Player do describe "construction" do it "adds the default folder to the autoload paths" do described_class.new Rubygame::Sound.autoload_dirs.should include( TextToNoise::Player::SOUND_DIR ) end end describe "#sound_dirs" do it "delegates to the underlying rubygame attribute" do subject.sound_dirs << "bar" Rubygame::Sound.autoload_dirs.should include( "bar" ) end end end
tobytripp/text_to_noise
lib/text_to_noise/conditions/throttled_match_condition.rb
module TextToNoise::Conditions class ThrottledMatchCondition attr_accessor :last_played, :throttle_period def initialize( period=0.25) @throttle_period = period # seconds @last_played = 0 end def play?( match_data=nil ) if elapsed > throttle_period self.last_played = Time.now true else false end end alias_method :call, :play? def elapsed() Time.now.to_f - last_played.to_f end end end
tobytripp/text_to_noise
spec/text_to_noise/log_reader_spec.rb
<reponame>tobytripp/text_to_noise require 'spec_helper' require 'stringio' module TextToNoise describe LogReader do let( :io ) { StringIO.new "phantasm" } let( :mapper ) { double( "LineToSoundMapper", :dispatch => nil ) } subject { LogReader.new io, mapper } describe "#call" do it "reads lines from the provided IO object using #gets" do io.should_receive( :gets ) subject.call end it "calls #dispatch on an instance of LineToSoundMapper with each line" do mapper.should_receive( :dispatch ).with "phantasm" subject.call end it "calls TextToNoise.throttle! after each line is processed" do TextToNoise.should_receive( :throttle! ) subject.call end end end end
tobytripp/text_to_noise
ssh.sounds.rb
match /sshd.*Accepted/ => %w[rooster hawk chicken crow]
tobytripp/text_to_noise
lib/text_to_noise/player.rb
<reponame>tobytripp/text_to_noise module TextToNoise class Player include Logging SOUND_DIR = File.expand_path File.join( APP_ROOT, 'sounds' ) class SoundNotFound < StandardError def initialize( sound_name ) super "Could not locate '#{sound_name}' in #{Rubygame::Sound.autoload_dirs}" end end def initialize() self.class.load_rubygame Rubygame::Sound.autoload_dirs << SOUND_DIR themes = Dir.new(SOUND_DIR).entries.reject { |e| e =~ /^[.]/ } Rubygame::Sound.autoload_dirs.concat themes.map { |t| File.join SOUND_DIR, t } @sounds = [] end def play( sound_name ) sound = Rubygame::Sound[sound_name] raise SoundNotFound, sound_name if sound.nil? debug "Playing #{sound_name}" sound.play :fade_out => 2 @sounds << sound debug "#{@sounds.size} sounds in queue" if playing? end def playing? @sounds = @sounds.select &:playing? not @sounds.empty? end def sound_dirs() Rubygame::Sound.autoload_dirs end def available_sounds() Rubygame::Sound.autoload_dirs.map do |dir| Dir[ "#{dir}/*.wav" ].map { |f| File.basename f } end.flatten end def self.load_rubygame() old_verbose, $VERBOSE = $VERBOSE, nil old_stream, stream = $stdout.dup, $stdout return if defined? Rubygame::Sound stream.reopen '/dev/null' stream.sync = true begin require 'rubygame' rescue LoadError require 'rubygems' require 'rubygame' end raise "No Mixer found! Make sure sdl_mixer is installed." unless defined? Rubygame::Sound ensure $VERBOSE = old_verbose stream.reopen(old_stream) end end end
tobytripp/text_to_noise
features/support/env.rb
<reponame>tobytripp/text_to_noise require 'aruba/cucumber' lib = File.expand_path( '../../../lib/', __FILE__ ) $:.unshift lib unless $:.include?( lib ) require 'text_to_noise' TextToNoise.logger = Logger.new "log/cucumber.log" TextToNoise.logger.level = Logger::DEBUG
tobytripp/text_to_noise
lib/text_to_noise/command_line.rb
<gh_stars>1-10 require 'text_to_noise/logging' module TextToNoise class CommandLine include Logging attr_reader :options, :mapping DEFAULT_FILE_DELAY = 100 def initialize( mapping_configurations, options={} ) @options = { :input => $stdin }.merge options configs = Array === mapping_configurations ? mapping_configurations : [mapping_configurations] raise ArgumentError, "No configuration file provided." if configs.empty? @mapping = Router.parse File.read( configs.first ) TextToNoise.player = self.player TextToNoise.throttle_delay = @options[:throttle] if @options[:throttle] TextToNoise.throttle_delay = @options[:throttle] || DEFAULT_FILE_DELAY if @options[:input] != $stdin TextToNoise.logger.level = Logger::DEBUG if @options[:debug] rescue Errno::ENOENT => e raise ArgumentError, "Could not locate configuration file: '#{configs.first}' (#{e})" end def run LogReader.new( options[:input], mapping ).call info "Input processing complete. Waiting for playback to finish..." while TextToNoise.player.playing? sleep 1 end end def player @options[:mute] ? MutePlayer.new : Player.new end end end
tobytripp/text_to_noise
text_to_noise.gemspec
# -*- encoding: utf-8 -*- lib = File.expand_path( '../lib/', __FILE__ ) $:.unshift lib unless $:.include?( lib ) require 'text_to_noise/version' Gem::Specification.new do |spec| spec.name = "text-to-noise" spec.version = TextToNoise::VERSION spec.platform = Gem::Platform::RUBY spec.summary = "Play sounds based on string matches." spec.description = "Pipe a file, like a log file, into text_to_noise and it will play sound effects triggered by regex matches in the input." spec.authors = ["<NAME>", "<NAME>"] spec.email = "<EMAIL>" spec.homepage = "https://github.com/tobytripp/text_to_noise" spec.required_rubygems_version = ">= 1.3.6" spec.add_dependency "rubygame", "~> 2.6.4" spec.requirements << "SDL_mixer [http://www.libsdl.org/projects/SDL_mixer/]" spec.add_development_dependency "cucumber" spec.add_development_dependency "aruba" spec.add_development_dependency "rspec" spec.files = `git ls-files`.split("\n") spec.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") spec.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } spec.require_path = 'lib' end
tobytripp/text_to_noise
spec/text_to_noise/noise_mapping_spec.rb
<filename>spec/text_to_noise/noise_mapping_spec.rb require 'spec_helper' describe TextToNoise::NoiseMapping do before do TextToNoise.player = double( TextToNoise::Player ) now = Time.now times = (0..60).map { |i| now + i } Time.stub(:now) { times.shift } end describe "#initialize" do it "can accept a Hash" do mapping = described_class.new /exp/ => "target" mapping.target.should be_a( Proc ) end it "allows the 'every' option to be specified in the Hash" do mapping = described_class.new /exp/ => "target", :every => 3 mapping.matcher_conditions.should_not be_empty end end describe "#===" do context "when matching against a regex" do subject { described_class.new /green/ } it "returns true when the input matches its regex" do subject.should === "green" end it "returns false when the input does not match its regex" do subject.should_not === "blue" end end context "when matching against a Proc" do subject do described_class.new( /green (\d+)/ ) { |match_data| match_data[1].to_i > 5 } end it "matches if the block returns true" do should === "green 6" end it "does not match if the block returns false" do should_not === "green 1" end end context "throttling" do subject { described_class.new( /green/ ) } it "prevents immediately consecutive matches" do now = Time.now Time.stub( :now ).and_return now should === "green" should_not === "green" end end end describe "#to" do subject { described_class.new /green/ } it "sets the target of the mapping to a Proc" do subject.to( "bar" ) subject.target.should be_a( Proc ) end it "sets the target to call Player#play on #call" do subject.to( "bar.wav" ) TextToNoise.player.should_receive( :play ).with "bar.wav" subject.target.call end it "automatically appends .wav, if it's not present" do subject.to( "bar" ) TextToNoise.player.should_receive( :play ).with "bar.wav" subject.target.call end it "can accept a list of target files" do subject.to ["foo", "bar", "baz"] TextToNoise.player.should_receive( :play ).with "foo.wav" TextToNoise.player.should_receive( :play ).with "bar.wav" TextToNoise.player.should_receive( :play ).with "baz.wav" subject.target.call subject.target.call subject.target.call end it "returns self" do subject.to( "foo" ).should == subject end end describe "#every" do context "when passed the value '3'" do subject { described_class.new( /green/ ).to( "red" ).every( 3 ) } it "does not match immediately" do subject.should_not === 'green' end it "only matches on the given iteration" do subject.should_not === 'green' subject.should_not === 'green' subject.should === 'green' subject.should_not === 'green' subject.should_not === 'green' end end context "when passed the value 1" do subject { described_class.new( /green/ ).to( "red" ).every( 1 ) } it "matches on every iteration" do subject.should === 'green' subject.should === 'green' subject.should === 'green' end end context "when passed the value 0" do subject { described_class.new( /green/ ).to( "red" ).every( 0 ) } it "matches on every iteration" do subject.should === 'green' subject.should === 'green' subject.should === 'green' end end context "when passed the value -1" do subject do described_class.new( /green/ ).to( "red" ).every( 0 ) end it "matches on every iteration" do subject.should === 'green' subject.should === 'green' subject.should === 'green' end end context "when called multiple times" do subject do described_class.new( /green/ ).to( "red" ). every( 3 ). every( 5 ) end it "fires when any rule matches" do TextToNoise.player.should_receive( :play ).exactly( 3 ).times 8.times { subject.call if subject === "green" } end end end describe "#when" do let( :player ) { TextToNoise.player } context "given a Proc that returns true" do subject { described_class.new( /blue/ ).to( "green" ).when { true } } it "will match the given input" do subject.should === "blue" end end context "given a Proc that returns false" do subject { described_class.new( /blue/ ).to( "green" ).when { false } } it "does not match the input" do subject.should_not === "blue" end end end describe "#call" do subject do described_class.new( /green/ ).tap do |mapping| mapping.targets = [ Proc.new { "called" } ] end end it "calls #call on its target" do subject.call.should == "called" end end end
tobytripp/text_to_noise
lib/text_to_noise/logging.rb
<reponame>tobytripp/text_to_noise require 'forwardable' module TextToNoise module Logging extend Forwardable def_delegators :logger, :warn, :debug, :error, :info def logger() TextToNoise.logger; end end end
tobytripp/text_to_noise
spec/text_to_noise/sound_map.rb
match /macaw/ => "blue_amazon_macaw.wav" match /canary/ => "canary.wav"
tobytripp/text_to_noise
lib/text_to_noise/conditions/iteration_mapping_condition.rb
module TextToNoise::Conditions class IterationMappingCondition attr_accessor :count def initialize( count ) self.count = count @iteration = 0 end def play?( match_data=nil ) @iteration += 1 count == 1 || (@iteration % count == 0) end alias_method :call, :play? def count=( new_count ) if new_count > 0 @count = new_count else @count = 1 end end end end
tobytripp/text_to_noise
spec/text_to_noise/router_spec.rb
<reponame>tobytripp/text_to_noise require 'spec_helper' module TextToNoise describe Router do it "reloads its configuration if it has changed" describe ".parse" do let( :mapping ) { double( NoiseMapping, :to => nil ) } context "given a nil configuration" do it "raises an ArgumentError" do lambda { Router.parse nil }.should raise_error( ArgumentError ) end end context "given a blank configuration" do it "raises an ArgumentError" do lambda { Router.parse " \t \n" }.should raise_error( ArgumentError ) end end context "given a single line configuration" do let( :config ) { "match( /brown/ ).to \"blue\"" } it "creates a Mapping object for the given configuration line" do NoiseMapping.should_receive( :new ).with( /brown/ ).and_return mapping Router.parse config end it "configures the mapping" do NoiseMapping.stub!( :new ).with( /brown/ ).and_return mapping mapping.should_receive( :to ).with( "blue" ) Router.parse config end end context "given a multiple line configuration" do let( :config ) { 'match( /brown/ ).to "blue"; map( /green/ ).to "orange"' } before { NoiseMapping.stub!( :new ).and_return mapping } it "configures the second mapping in addition to the first" do mapping.should_receive( :to ).with "blue" mapping.should_receive( :to ).with "orange" Router.parse config end it "stores the mappings" do Router.parse( config ).should have( 2 ).mappings end end context "given a hash-style configuration" do let( :config ) { "match /brown/ => \"blue\"\n" } it "configures the mapping" do NoiseMapping.should_receive( :new ).with( /brown/ => "blue" ).and_return mapping Router.parse config end end end describe "#sound_path" do subject { described_class.new } before { TextToNoise.player = double( TextToNoise::Player ) } it "adds the argument to the player's sound paths" do paths = [] TextToNoise.player.should_receive( :sound_dirs ).and_return paths subject.sound_path "foo" end end describe "#dispatch" do let( :blue ) { /blue/ } let( :green ) { /green/ } let( :blue2 ) { /blu/ } subject { Router.new.tap { |m| m.mappings = [blue, green, blue2] } } it "iterates over its mappings comparing them to the input with #===" do blue.should_receive( :=== ).with( anything ) green.should_receive( :=== ).with( anything ) subject.dispatch "orange" end it "calls #call on all mappings that matched" do blue.should_receive :call blue2.should_receive :call green.should_not_receive :call subject.dispatch( "blue" ) end end end end
tobytripp/text_to_noise
lib/text_to_noise/router.rb
module TextToNoise class Router include Logging attr_accessor :mappings def initialize() @mappings = [] end def self.parse( config ) raise ArgumentError, "No configuration given" if config.nil? or config.strip.empty? new.tap { |m| m.instance_eval config m.info "Configured #{m.mappings.size} mappings." } end def dispatch( line ) debug "Dispatching: #{line.rstrip}" matches = mappings.select { |m| m === line } debug "#{matches.size} matched mappings" matches.map { |m| m.call } end def sound_path( path ) TextToNoise.player.sound_dirs << path end def match( expression, &block ) debug "Creating map for #{expression.inspect}" mappings << mapping = NoiseMapping.new( expression, &block ) mapping end alias_method :map, :match end end
tobytripp/text_to_noise
lib/text_to_noise.rb
<filename>lib/text_to_noise.rb LIB_DIR = File.dirname File.expand_path( __FILE__ ) APP_ROOT = File.join LIB_DIR, '..' $LOAD_PATH << LIB_DIR require 'logger' Dir["#{LIB_DIR}/text_to_noise/**/*.rb"].each { |lib| lib =~ %r<lib/(.*)\.rb$> require $1 } module TextToNoise include Logging def player @player ||= Player.new end def player=( player ) @player = player end def logger @logger ||= Logger.new( STDOUT ).tap { |l| l.level = Logger::INFO } end def logger=( logger ) @logger = logger @logger end def throttle_delay=( ms_delay ) @delay = ms_delay end def throttle! return unless @delay debug "waiting #{@delay}ms (#{@delay / 1_000.0}s)" sleep @delay / 1_000.0 end extend self end
tobytripp/text_to_noise
spec/spec_helper.rb
<gh_stars>1-10 require 'rspec' lib = File.expand_path( '../lib/', __FILE__ ) $:.unshift lib unless $:.include?( lib ) require 'text_to_noise' TextToNoise.logger = Logger.new "log/test.log" TextToNoise.logger.level = Logger::DEBUG Rspec.configure do |c| c.mock_with :rspec end
tobytripp/text_to_noise
sample.sounds.rb
<gh_stars>1-10 sound_path "tmp/sounds" scale = 2 map /Rendered/ => %w(cardinal canary whipperwhill), :every => scale map /Processing/ => "crickets", :every => scale * 2 map /User Load/ => %w"nightingale pigeons red_lories" map /SessionsController#new/ => "owl-short" map /404 Not Found/ => "hawk" map /RoutingError/ => "hawk", :every => scale map( /Completed in (\d+)ms/ ) { |match_data| match_data[1].to_i > 500 }.to "vulture"
tobytripp/text_to_noise
spec/text_to_noise/iteration_mapping_condition_spec.rb
require 'spec_helper' describe TextToNoise::Conditions::IterationMappingCondition do describe "construction" do it "accepts a count" do described_class.new 4 end end context "for value 1" do subject { described_class.new 1 } it "#play? returns true for all calls" do 3.times do subject.play?.should be_true end end end context "for value 2" do subject { described_class.new 2 } it "#play? returns true on every other call" do subject.play?.should be_false subject.play?.should be_true subject.play?.should be_false subject.play?.should be_true end end end
tobytripp/text_to_noise
spec/text_to_noise/command_line_spec.rb
<reponame>tobytripp/text_to_noise<filename>spec/text_to_noise/command_line_spec.rb require 'spec_helper' module TextToNoise describe TextToNoise::CommandLine do let( :mapping ) { double( NoiseMapping ) } let( :reader ) { double( LogReader, :call => nil ) } before :each do Router.stub!( :parse ).and_return mapping LogReader.stub!( :new ).and_return reader File.stub!( :read ).with( "sound_map.rb" ).and_return "config" end describe "#initialize" do it "accepts an options object" do CommandLine.new "sound_map.rb", {} end it "throws an error if no config file is given" do lambda { CommandLine.new }.should raise_error( ArgumentError ) end it "raises an error if the config file cannot be found" do File.stub!( :read ).and_raise Errno::ENOENT lambda { CommandLine.new "not_found" }.should raise_error( ArgumentError ) end context "when given a 'config' option" do it "instantiates a NoiseMapping object with the specified configuration" do File.should_receive( :read ).with( "sound_map.rb" ).and_return "config" Router.should_receive( :parse ).with( "config" ) CommandLine.new "sound_map.rb" end end context "when given the 'mute' option" do it "sets the global Player to an instance of MutePlayer" do TextToNoise.should_receive( :player= ).with instance_of( MutePlayer ) CommandLine.new "sound_map.rb", :mute => true end end context "when given the 'throttle' option" do it "sets the throttle_delay attribute on TextToNoise" do TextToNoise.should_receive( :throttle_delay= ).with 100 CommandLine.new "sound_map.rb", :throttle => 100 end end context "when given a 'file' option" do it "sets a default throttle_delay" do TextToNoise.should_receive( :throttle_delay= ).with 100 CommandLine.new "sound_map.rb", :input => "sample.log" end end end describe "#run" do let( :options ) { Hash[:input, :io] } subject { CommandLine.new( "sound_map.rb", options ) } it "creates a new LogReader object" do LogReader.should_receive( :new ) subject.run end it "passes the contents of the file in :input option to the reader" do LogReader.should_receive( :new ).with( :io, anything ) subject.run end it "passes an instance of a NoiseMapping to the LogReader" do LogReader.should_receive( :new ).with( anything, mapping ) subject.run end it "calls #call on the LogReader" do reader.should_receive :call subject.run end end end end
tobytripp/text_to_noise
lib/text_to_noise/mute_player.rb
<gh_stars>1-10 module TextToNoise class MutePlayer include Logging def play( sound_name ) info "Playing #{sound_name}" end def playing?() false; end end end
tobytripp/text_to_noise
lib/text_to_noise/noise_mapping.rb
# -*- coding: utf-8 -*- module TextToNoise class NoiseMapping include Logging attr_accessor :targets, :matcher_conditions, :filter_conditions def initialize( expression_or_map, &block ) debug "Parsing expression: #{expression_or_map.inspect}" @matcher_conditions = [] @filter_conditions = [] @regex = nil case expression_or_map when Regexp @regex = expression_or_map when Hash expression_or_map.each do |k,v| case k when Regexp @regex = k self.to v else self.send k.to_sym, v end end else raise ArgumentError, "Unrecognized Mapping configuration: #{expression_or_map.inspect}" end raise ArgumentError, "Bad configuration line. Missing match expression in \"#{expression_or_map.inspect}\"" if @regex.nil? matcher_conditions << block if block_given? filter_conditions << Conditions::ThrottledMatchCondition.new end def ===( other ) match_data = @regex.match( other ) !match_data.nil? && play?( match_data ) end def to( sound_or_sounds ) if sound_or_sounds.is_a? Array sounds = sound_or_sounds else sounds = [sound_or_sounds] end sounds.each do |sound| s = sound s += ".wav" unless sound =~ /.wav$/ self.targets << Proc.new { info "#{self.class.name} : #{@regex.inspect} -> #{sound}" TextToNoise.player.play s } end self end def every( iteration_count ) @matcher_conditions << Conditions::IterationMappingCondition.new( iteration_count ) self end def when( &clause ) @matcher_conditions << clause self end def call() debug "Calling '#{@regex.inspect}' target…" target.call end def targets() @targets ||= []; end def target() raise "No Sound mapped for rule: '#{@regex.inspect}'" if targets.empty? @i = -1 unless @i @i = (@i + 1) % targets.size self.targets[@i] end private def play?( match_data ) return false unless @filter_conditions.all? { |c| c.call match_data } return true if @matcher_conditions.empty? @matcher_conditions.any? { |c| c.call match_data } end end end
tobytripp/text_to_noise
lib/text_to_noise/log_reader.rb
<reponame>tobytripp/text_to_noise<filename>lib/text_to_noise/log_reader.rb module TextToNoise class LogReader attr_reader :io def initialize( io, mapper ) @io, @mapper = io, mapper end def call() while line = io.gets @mapper.dispatch line TextToNoise.throttle! end end end end
tobytripp/text_to_noise
features/step_definitions/debugger_steps.rb
<reponame>tobytripp/text_to_noise<filename>features/step_definitions/debugger_steps.rb When /^I am debugging$/ do require 'ruby-debug' debugger end
tobytripp/text_to_noise
spec/text_to_noise/conditions/throttled_match_condition_spec.rb
require 'spec_helper' describe TextToNoise::Conditions::ThrottledMatchCondition do describe "#play?" do before :each do @now = Time.now Time.stub!( :now ).and_return @now end it "returns true on the first call" do subject.play?.should be_true end it "returns false if called again immediately" do subject.play?.should be_true subject.play?.should be_false end it "returns true again after a delay" do subject.play? Time.stub!( :now ).and_return @now + 500 subject.play?.should be_true end end end
tobytripp/text_to_noise
watchr.rb
# Run me with: # watchr watchr.rb # # I will automatically run the relevant specs when you change things. # Aren't I convenient? # begin require "g" puts "Growl loaded" rescue LoadError puts "No growl library found" end def announce( message ) puts message g message if Kernel.respond_to? :g end def spec( *files ) announce "Running specs: #{files}" execute "rspec #{files.join " "} --options spec/spec.opts" end def specs_matching( type, name ) puts "looking for specs of #{name}" spec *Dir["spec/**/*#{name}*_spec.rb"] end def run_all_tests announce "Running full test suite" execute "rake" end def execute( cmd ) puts "> #{cmd}" system cmd system 'date' end watch( '^spec/[^/]*/(.*)_spec\.rb' ) { |m| spec m[0] } watch( '^spec/spec_helper\.rb' ) { |m| execute "rake spec" } watch( '^spec/support/.*' ) { |m| execute "rake spec" } watch( '^app/([^/]+)/(.*)\.rb' ) { |m| specs_matching m[1], m[2] } watch( '^features/(.*)' ) { |m| execute "cucumber #{m[0]}" } watch( '^features/step_definitions/.*' ) { |m| execute "cucumber features" } Signal.trap 'INT' do if @sent_an_int then puts " A second INT? Ok, I get the message. Shutting down now." exit else puts " Did you just send me an INT? Ugh. I'll quit for real if you do it again." @sent_an_int = true Kernel.sleep 1.5 run_all_tests end end
megorei/motionkit-example
app/views/example_view.rb
class ExampleView < UIView def initWithFrame(frame) super.tap do |v| v.backgroundColor = UIColor.blackColor v.addSubview(we) v.addSubview(love) v.addSubview(rubymotion) end end def we UILabel.alloc.init.tap do |l| l.text = "We" l.font = UIFont.systemFontOfSize(24) l.textColor = UIColor.whiteColor l.frame = [[0, screen_height/2 - 90], [screen_width, 30]] # You can define frames like this (first sub-array is the origin, second is the size) l.textAlignment = NSTextAlignmentCenter end end def love image = UIImage.imageWithContentsOfFile("#{App.resources_path}/love.png") UIImageView.alloc.initWithImage(image).tap do |i| i.frame = CGRectMake( screen_width/2 - 50, # x-origin screen_height/2 - 45, # y-origin 100, # width 90 # height ) end end def rubymotion UILabel.alloc.init.tap do |l| l.text = "RubyMotion" l.font = UIFont.systemFontOfSize(24) l.textColor = UIColor.whiteColor l.frame = CGRectMake(0, screen_height/2 + 60, screen_width, 30) l.textAlignment = NSTextAlignmentCenter end end # --- Helper Methods --- def screen_width UIScreen.mainScreen.bounds.size.width end def screen_height UIScreen.mainScreen.bounds.size.height end end
megorei/motionkit-example
app/controllers/example_controller.rb
<filename>app/controllers/example_controller.rb class ExampleController < UIViewController # NOTICE: only use ONE of the methods. If both are active, the MotionKit layout will be rendered inside the already completed ExampleView instance def loadView self.view = ExampleView.alloc.initWithFrame(UIScreen.mainScreen.bounds) self.view end # def viewDidLoad # @layout = ExampleMotionKitLayout.new(root: self.view).build # end end