def check_user_agent
if api_access?
regex = Regexp.new("^([^/[:space:]]*)(/([^[:space:]]*))?([[:space:]]*\[[a-zA-Z][a-zA-Z]\])?[[:space:]]*(\\((([^()]|(\\([^()]*\\)))*)\\))?[[:space:]]*")
regex_match = regex.match(request.user_agent)
raise ForbiddenRequestError unless regex_match && USER_AGENTS.include?(regex_match[1])
end
end
Refactorings
No refactoring yet !
bob
February 16, 2009, February 16, 2009 07:54, permalink
I think your problem is you didn't escape the [ and ] characters enough (you need to escape it twice, for the string, and the regex). It's easier to use the / / syntax, or the %r syntax if you need to use delimiters other than /:
P.S. why are there so many parentheses?
# you can use any character as the delimiter; I am just using { } below as it is not used
%r{^([^/[:space:]]*)(/([^[:space:]]*))?([[:space:]]*\[[a-zA-Z][a-zA-Z]\])?[[:space:]]*(\\((([^()]|(\\([^()]*\\)))*)\\))?[[:space:]]*}
# also I suggest you use \s instead of [:space:]; it's less verbose
%r{^([^/\s]*)(/(\S*))?(\s*\[[a-zA-Z][a-zA-Z]\])?\s*(\\((([^()]|(\\([^()]*\\)))*)\\))?\s*}
Hola guys.. I am somewhat lost here what to escape and whatnot. Basically this lil method takes regular UserAgent Strings you can find in http headers and checks whether it's an allowed one. It only takes the actual application name (e.g. 'someUserAgent/v1.0 (compatible: yadda)' would only check someUserAgent.... the idea behind it simply is to make sure only allowed client apps access the webservice. api_access? only checks whether the request is coming via json/xml...
However the problem is, I see the warnings in the title all around.. the regex works, but fills up (in my case the apache2 error_log since it's being used with mod_rails)....
Any ideas/suggestions.. maybe major improvements?
Thanks,
-J :)