kakao OCR로 추출한 주민등록번호를 DB에 추가하려고 한다.
그냥 추가하면 재미없으니까 본인확인, 유효성검사를 한 후에 DB에 추가해보자.
css는 중요하지 않으니까 코드에서 빼겠다.
이번 글에서는 비밀번호 인증 부분을 작성하겠다.
<div class="idpw_area">
<!-- 아이디 area -->
<h3><label for="username" class="margin25">아이디</label></h3>
<input type="text" id="username" name="username"
disabled value="{{ g_user }}">
<!-- 비밀번호 area -->
<h3><label for="password" class="margin25">비밀번호</label></h3>
<input type="password" id="password" name="password">
<span class="error_box" id="pw_error">비밀번호가 맞지 않습니다.</span>
<!-- 비밀번호 인증 area -->
<div class="pwval_area">
<h3><label for="pw_btn" id="pw_label">비밀번호 확인</label></h3>
<input type="submit" id="pw_btn" name="pw_btn">
</div>
</div>
👉 아이디 area
아이디 area는 입력하지 못하게 disabled
속성을 추가했고,
value
는 flask에서 받은 값이다.
👉 비밀번호 area
비밀번호의 값은 id="password"
로 추출할 수 있다.
만약 비밀번호가 틀릴 경우 css로 숨겨놓았던 span태그가 출력된다.
👉비밀번호 인증 area
비밀번호 확인 버튼 클릭 시, Javascript로 비밀번호의 값을 넘긴다.
// 비밀번호 비동기 통신 유효성 검사를 위한 변수선언
const pw_input = document.querySelector("#password");
const pw_btn = document.querySelector("#pw_btn");
const pw_area = document.querySelector(".pwval_area");
const pw_label = document.querySelector("#pw_label");
const pw_error = document.querySelector("#pw_error");
let pw_status = true; // 인증완료시 false 로 변경
// 비밀번호 확인 버튼 클릭 시
pw_btn.addEventListener('click', ()=> {
// flask 에 전달할 input 값/종류를 JSON 형태로 선언
const postdata = {
'password':pw_input.value, 'kind': 'password'
}
$.ajax({
type: 'POST',
data: JSON.stringify(postdata),
dataType : 'JSON',
contentType: "application/json",
success: function(result){
// success -> 인증성공 Alert 출력
successAlert();
// 인증성공시 비활성화하기
disabled(pw_input, false, pw_btn, pw_area, pw_label, pw_error);
pw_status = false;
},
error: function(result){
// error -> 인증실패 Alert 출력
failedAlert();
// 인증실패시 에러메시지 출력
error_msg(pw_input, false, pw_error);
}
})
});
한줄씩 해석해보자.
// 비밀번호 확인 버튼 클릭 시 pw_btn.addEventListener('click', ()=> { const postdata = { // flask 에 전달할 input 값/종류를 JSON 형태로 선언 'password':pw_input.value, 'kind': 'password' }
비밀번호 확인버튼을 눌렀을 때 실행한다. -> addEventListner('click')
postdata
는 비밀번호 값을 Python(flask)에 전달할 JSON 변수이다.
$.ajax({ type: 'POST', data: JSON.stringify(postdata), dataType : 'JSON', contentType: "application/json",
$.ajax
: Python과 비동기 통신을 하기 위한 제이쿼리 함수이다.
type
: POST/GET 둘 중 하나를 선택한다.
data
: 보낼 data이다.
dataType
: 서버에서 반환받는 데이터 타입이다.
contentType
: 보내는 데이터의 타입이다.
success: function(result){ // success -> 인증성공 Alert 출력 successAlert(); // 인증성공시 비활성화하기 disabled(pw_input, false, pw_btn, pw_area, pw_label, pw_error); pw_status = false; }, error: function(result){ // error -> 인증실패 Alert 출력 failedAlert(); // 인증실패시 에러메시지 출력 error_msg(pw_input, false, pw_error); }
📌 success
성공했을 때 실행하는 함수이다.
successAlert()
: 인증알림창 함수이다. sweetAlert2 사용했다.
disabled()
: 인증성공시, css를 변경하는 함수이다.
pw_status
: 인증상태를 저장하는 변수이다. 나중에 사용된다.
📌 error
실패했을 때 실행하는 함수이다.
failedAlert()
: 인증실패알림 함수이다. sweetAlert2 사용햇다.
error_msg()
: 인증실패시, 에러메시지를 input 밑에 출력한다.
@bp.route('/print/', methods=['POST', 'GET'])
def print():
# POST 형식으로 호출되었을 때
if request.method == 'POST':
user = User.query.filter_by(username=g.user.username).first()
if request.get_json(): # 비동기 통신의 경우
result = request.get_json() # 비동기 통신 데이터 저장
if result['kind'] == 'password': # 데이터의 종류가 password 일 경우
password = result['password']
if check_password_hash(user.password, password): # 입력받은 pw와 기존 user.pw 비교
return jsonify(result="success", data=result)
else:
return jsonify(result="error", data=result), 500 # false일 경우 500 오류
한줄씩 해석해보자.
if request.method == 'POST': user = User.query.filter_by(username=g.user.username).first()
POST형식으로 데이터가 왔을 때 응답한다.
user
변수에는 현재 로그인되어있는 계정의 정보들을 담는다.
if request.get_json(): # 비동기 통신의 경우 result = request.get_json() # 비동기 통신 데이터 저장
JSON 형태로 비동기 통신으로 왔을 경우에 result
변수에 전해준 데이터를 저장한다.
if result['kind'] == 'password': # 데이터의 종류가 password 일 경우 password = result['password']
kind
키의 값이 password
일 경우에
password
변수에 서버로 전송된 비밀번호를 저장한다.
if check_password_hash(user.password, password): # 입력받은 pw와 기존 user.pw 비교 return jsonify(result="success", data=result) else: return jsonify(result="error", data=result), 500
check_password_hash()
함수를 통해
hash값으로 DB에 저장된 비밀번호user.password
와 입력받은 비밀번호password
를 비교한다.
📌맞다면 jsonify()
로 return한다. 📌틀리다면 500
키워드를 통해 ajax 오류를 낸다.
출처