program tip

RoR 4에서 유효성 검사가있는 정규식

radiobox 2020. 9. 21. 07:32
반응형

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

전략 읽기 :


문제 정규식은 고안이 아니라 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

반응형