RoR 4에서 유효성 검사가있는 정규식
다음 코드가 있습니다.
class Product < ActiveRecord::Base
validates :title, :description, :image_url, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.(gif|jpg|png)$}i,
message: 'URL must point to GIT/JPG/PNG pictures'
}
end
작동하지만 "rake test"를 사용하여 테스트하려고하면 다음 메시지가 표시됩니다.
rake aborted!
The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?
무슨 뜻인가요? 어떻게 고칠 수 있습니까?
^
그리고 $
시작되어 선 및 최종 라인의 앵커. 동안 \A
과 \z
영구 시작이다 문자열의 및 종료 문자열의 앵커.
차이점보기 :
string = "abcde\nzzzz"
# => "abcde\nzzzz"
/^abcde$/ === string
# => true
/\Aabcde\z/ === string
# => false
레일 그래서 "당신은 당신이 사용 하시겠습니까, 당신을 말하고있다 ^
하고 $
그래서? 당신이 사용하지 \A
하고 \z
대신?"
여기 에이 경고를 생성하는 레일 보안 문제가 더 있습니다 .
이 경고는 유효성 검사 규칙이 자바 스크립트 삽입에 취약하기 때문에 발생합니다.
귀하의 경우 \.(gif|jpg|png)$
에는 줄 끝까지 일치합니다. 따라서 규칙은이 값 pic.png\nalert(1);
을 true로 확인 합니다.
"test.png\n<script>alert(1)</script>" === /\.(gif|jpg|png)$/i
# => true
"test.png\n<script>alert(1)</script>" === /\.(gif|jpg|png)\z/i
# => false
전략 읽기 :
- http://caiustheory.com/validating-data-with-regular-expressions-in-ruby
- http://guides.rubyonrails.org/security.html#regular-expressions
문제 정규식은 고안이 아니라 config / initializers / devise.rb에 있습니다. 변화:
# Regex to use to validate the email address
config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
에:
# Regex to use to validate the email address
config.email_regexp = /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\Z/i
경고는 다음과 같은 문자열이 유효성 검사를 통과하지만 원하는 것이 아닐 수도 있음을 알려줍니다.
test = "image.gif\nthis is not an image"
re = /\.(gif|jpg|png)$/i
re.match(test) #=> #<MatchData ".gif" 1:"gif">
^
및 둘 다 $
문자열의 시작 / 끝이 아닌 모든 행의 시작 / 끝 과 일치합니다. \A
그리고 \z
각각 전체 문자열의 시작과 끝을 일치시킵니다.
re = /\.(gif|jpg|png)\z/i
re.match(test) #=> nil
The second part of the warning (“or forgot to add the :multiline => true option”) is telling you that if you actually want the behaviour of ^
and $
you can simply silence the warning passing the :multiline
option.
If Ruby wants to see \z
instead of the $
symbol sign, for security, you need to give it to him, then the code would look like this :
validates :image_url, allow_blank: true, format: {with: %r{\.(gif|jpg|png)\z}i, message: 'URL must point to GIF, JPG, PNG.'}
참고URL : https://stackoverflow.com/questions/17759735/regular-expressions-with-validations-in-ror-4
'program tip' 카테고리의 다른 글
Assert.AreEqual (T obj1, Tobj2)이 동일한 바이트 배열로 실패하는 이유 (0) | 2020.09.21 |
---|---|
C ++에서 assert ()를 사용하고 있습니까? (0) | 2020.09.21 |
너비 / 높이에 영향을주지 않고 DIV 패딩을 변경하는 방법은 무엇입니까? (0) | 2020.09.20 |
GitHub에서 비공개 Git 리포지토리를 어떻게 설정하나요? (0) | 2020.09.20 |
Symfony2에서 번들과 관련된 파일 액세스 (0) | 2020.09.20 |