워드프레스 회원가입할 때 암호 바로 등록하고 reCAPTCHA 적용

워드프레스 회원가입 기본 인증 방식은 인증링크(암호변경 링크)를 가입 시 이메일로 보내 이메일 인증과 동시에 가입 회원이 암호를 정할 수 있도록 하는 것입니다. 사실, 이 방법이 가장 쉽고 효율적인 방식입니다.

이 글의 암호 바로 등록 방식의 사이트 운용은 권장하지 않지만, 때로는 이메일 인증 방식에 여전히 익숙하지 않아 가입을 완료하지 못하는 사람이 있고, 웹사이트의 성격에 따라 이메일 인증이 꼭 필요하지 않거나 가입을 더 쉽게 해야 할 때도 있으므로 알아보는 것도 좋습니다.

간단한 플러그인 형식 구성

다음의 간단한 플러그인 형식의 코드를 추가한 파일을 먼저 만들고, 플러그인 설치 방법으로 설치하고 활성화한 다음 진행합니다.

<?php
/**
 * Plugin Name: 가입할 때 암호 등록하고 reCAPTCHA
 * Version: 0.0.1
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * 로그인 페이지 스타일, 스크립트
 */
add_action( 'login_enqueue_scripts', 'ccc_login_script', 22 );
function ccc_login_script() {
	//
}

/**
 * 기본 회원가입 페이지 필드 추가
 */
add_action( 'register_form', 'ccc_add_register_field' );
function ccc_add_register_field() {
	//
}

/**
 * 암호, reCAPTCHA 검증
 */
add_filter( 'registration_errors', 'ccc_register_field_verify', 10, 3 );
function ccc_register_field_verify( $errors, $sanitized_user_login, $user_email ) {
	//
}

/**
 * 암호 저장
 */
add_action( 'user_register', 'c2ca_save_user_custom_data' );
function c2ca_save_user_custom_data( $user_id ) {
	//
}

/**
 * 회원가입 후 회원에게 가입 정보 및 환영 메일 발송
 */
if ( !function_exists('wp_new_user_notification') ) {
	//
}

위 코드 전체를 복사하여 ccc_register_pass.php 이름의 파일을 만들어 워드프레스 플러그인 디렉터리에 업로드 또는 파일을 압축파일로 다시 만든 후 관리페이지에서 플러그인 업로드 방식의 설치로 설치한 후 활성화합니다. 파일 이름은 원하는 것으로 정하면 됩니다.

이어지는 내용에서 코드 추가할 때 코멘트 블록을 참고하여 코드를 대체하면 됩니다.

회원가입 페이지에 암호 입력 필드 추가

기본 회원가입 페이지 필드 추가 부분을 찾아 다음 코드를 입력하고 저장하면 암호 입력 필드가 나옵니다. 다음 코드 참고하세요.

/**
 * 기본 회원가입 페이지 필드 추가
 */
add_action( 'register_form', 'ccc_add_register_field' );
function ccc_add_register_field() {
	?>
	<p>
		<label for="user_pass">암호<br>
		<input type="password" name="user_pass" id="user_pass" class="input" value="" size="20" autocomplete="off"></label>
	</p>
	<p>
		<label for="user_pass">암호확인<br>
		<input type="password" name="user_pass2" id="user_pass2" class="input" value="" size="20" autocomplete="off"></label>
	</p>
	<?php
}

다음 그림을 확인하세요.

암호 입력 필드 추가

암호 입력 확인

다음은 암호 필드와 값을 확인하고, 입력한 암호가 같은지 확인합니다.

/**
 * 암호, reCAPTCHA 검증
 */
add_filter( 'registration_errors', 'ccc_register_field_verify', 10, 3 );
function ccc_register_field_verify( $errors, $sanitized_user_login, $user_email ) {
	// 암호
	if ( empty( $_POST['user_pass'] ) ) {
		$errors->add( 'pass_empty','<strong>오류</strong> : <strong>암호</strong>를 입력하세요.' );
	}
	if ( empty( $_POST['user_pass2'] ) ) {
		$errors->add( 'pass2_empty','<strong>오류</strong> : <strong>암호확인</strong>란이 비었습니다.' );
	}
	if ( $_POST[ 'user_pass' ] && $_POST[ 'user_pass2' ] ) {
		if ( $_POST[ 'user_pass' ] != $_POST[ 'user_pass2' ] ) {
			$errors->add( 'pass_wrong','<strong>오류</strong> : <strong>암호가</strong> 일치하지 않습니다.' );
		}
	}
	
	return $errors;
}

암호 저장

암호 입력 필드의 과정을 통과했다면 암호를 저장합니다.

/**
 * 암호 저장
 */
add_action( 'user_register', 'c2ca_save_user_custom_data' );
function c2ca_save_user_custom_data( $user_id ) {
	if ( ! empty( $_POST['user_pass'] ) ) {
		wp_set_password( $_POST['user_pass'], $user_id );
	}
}

user_activation_key, default_password_nag

워드프레스 기본 회원가입 흐름은, 가입 시 입력한 이메일로 암호변경 링크를 제공하며, 그 링크를 클릭하여 암호를 등록한 후 로그인합니다. 이때 로그인하면 wp_users 테이블의 user_activation_key 필드에 생성된 값이 삭제됩니다.

지금은 가입 시 암호를 바로 등록하였고, 암호를 알고 있으므로 이메일의 인증링크가 없어도 로그인할 수 있습니다. 따라서 user_activation_key 값이 그대로 존재합니다. 이 값을 지우는 게 좋습니다.

또, 워드프레스는 자동 생성된 암호를 사용할 경우 프로필 페이지에서 그 암호를 사용할 것인지 메시지로 물어봅니다. (자동 생성된 암호 사용할 때라기보다는 기본 가입 흐름이 아닐 때 나오는 것으로 생각하세요.) 이 잔소리 나오지 않도록 값을 변경합니다. 따라서 앞의 코드를 다음처럼 변경합니다.

/**
 * 암호 저장
 */
add_action( 'user_register', 'c2ca_save_user_custom_data' );
function c2ca_save_user_custom_data( $user_id ) {
	// 암호 업데이트, user_activation_key 삭제
	if ( ! empty( $_POST['user_pass'] ) ) {
		wp_set_password( $_POST['user_pass'], $user_id );
		update_user_option( $user_id, 'default_password_nag', false, true ); // wp_usermeta, 자동으로 생성된 암호 사용 시 프로필페이지에 나오는 잔소리

		global $wpdb;
		$wpdb->update( $wpdb->users, array( 'user_activation_key' => '' ), array( 'ID' => $user_id ) ); // wp_users
	}
}

가입 후 메일 내용 변경

가입 후 기본 메일은 다음처럼 암호변경 링크가 있는 메일입니다.

워드프레스 기본 가입 후 메일 내용

암호를 가입 시 등록하였기에 메일 내용을 환영의 내용으로 변경하는 게 좋습니다. 다음 코드를 추가하면 간단하게 변경할 수 있습니다.

/**
 * 회원가입 후 회원에게 가입 정보 및 환영 메일 발송
 */
if ( !function_exists('wp_new_user_notification') ) {
    function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {
		if ( $deprecated !== null ) {
			_deprecated_argument( __FUNCTION__, '4.3.1' );
		}

		$user = get_userdata( $user_id );
		$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

		if ( 'admin' === $notify || ( empty( $deprecated ) && empty( $notify ) ) ) {
			return;
		}

		$switched_locale = switch_to_locale( get_user_locale( $user ) );

		$msg .= __('회원가입을 환영합니다.') . "\r\n\r\n";
		$msg .= sprintf(__('아이디: %s'), $user->user_login) . "\r\n";
		$msg .= sprintf(__('이메일: %s'), $user->user_email) . "\r\n";
		$msg .= sprintf(__('가입시각: %s'), current_time( 'mysql' )) . "\r\n\r\n";
		$msg .= __('로그인 링크 : ') . wp_login_url() . "\r\n";

		$wp_new_user_notification_email = array(
			'to'      => $user->user_email,
			'subject' => __( '[%s] 가입을 환영합니다' ),
			'message' => $msg,
			'headers' => '',
		);

		$wp_new_user_notification_email = apply_filters( 'wp_new_user_notification_email', $wp_new_user_notification_email, $user, $blogname );

		wp_mail(
			$wp_new_user_notification_email['to'],
			wp_specialchars_decode( sprintf( $wp_new_user_notification_email['subject'], $blogname ) ),
			$wp_new_user_notification_email['message'],
			$wp_new_user_notification_email['headers']
		);
		if ( $switched_locale ) {
			restore_previous_locale();
		}
	}
}

나중에 한번에 확인하면 됩니다.

회원가입 페이지에 구글 reCAPTCHA 적용하기

암호를 바로 등록할 수 있도록 하였기에, 뭔가 좀 허전합니다. 간단하게 적용할 수 있는 구글의 reCAPTHCA를 사용해봅니다.

로그인페이지에 스크립트 추가

워드프레스에서 로그인, 회원가입, 암호찾기 등의 페이지에 스타일
(또는 파일)과 스크립트 (또는 파일) 추가는 login_enqueue_scripts 훅을 사용합니다.

우선 다음처럼 이미 존재하는 해당 코드 블록을 변경합니다.

/**
 * 로그인 페이지 스타일, 스크립트
 */
add_action( 'login_enqueue_scripts', 'ccc_login_script', 22 );
function ccc_login_script() {
	?>
	<script src="https://www.google.com/recaptcha/api.js" async defer></script>
	<?php
}

reCAPTHCA 키 얻기

구글 계정이 있어야 하며, reCAPTHCA Amdin Console 페이지를 검색으로 찾아 다음 그림 참고하여 제출한 후 2개의 키를 얻습니다.

구글 reCAPTCHA 생성
구글 reCAPTCHA 생성

제출 후 다음처럼 키를 얻을 수 있습니다. 2개의 키를 복사해두세요.

가입 페이지에 reCAPTHCA 필드 추가

앞의 암호 입력 필드 추가 코드를 다음처럼 변경합니다. 15번 줄 reCAPTCHA 부분만 추가해도 됩니다.

/**
 * 기본 회원가입 페이지 필드 추가
 */
add_action( 'register_form', 'ccc_add_register_field' );
function ccc_add_register_field() {
	?>
	<p>
		<label for="user_pass">암호<br>
		<input type="password" name="user_pass" id="user_pass" class="input" value="" size="20" autocomplete="off"></label>
	</p>
	<p>
		<label for="user_pass">암호확인<br>
		<input type="password" name="user_pass2" id="user_pass2" class="input" value="" size="20" autocomplete="off"></label>
	</p>
	<div class="g-recaptcha" data-sitekey="6LcRBMIUAABCWHnhk5--nPnjW1VyHS8qi1iIbg-k"></div>
	<?php
}

data-sitekey 값은 자신의 사이트키 값을 입력하세요.

reCAPTHCA 검증

앞의 암호 입력 확인 코드를 다음처럼 변경합니다.

/**
 * 암호, reCAPTCHA 검증
 */
add_filter( 'registration_errors', 'ccc_register_field_verify', 10, 3 );
function ccc_register_field_verify( $errors, $sanitized_user_login, $user_email ) {
	// 암호
	if ( empty( $_POST['user_pass'] ) ) {
		$errors->add( 'pass_empty','<strong>오류</strong> : <strong>암호</strong>를 입력하세요.' );
	}
	if ( empty( $_POST['user_pass2'] ) ) {
		$errors->add( 'pass2_empty','<strong>오류</strong> : <strong>암호확인</strong>란이 비었습니다.' );
	}
	if ( $_POST[ 'user_pass' ] && $_POST[ 'user_pass2' ] ) {
		if ( $_POST[ 'user_pass' ] != $_POST[ 'user_pass2' ] ) {
			$errors->add( 'pass_wrong','<strong>오류</strong> : <strong>암호가</strong> 일치하지 않습니다.' );
		}
	}
	
	// reCAPTCHA
	if ( isset( $_POST['g-recaptcha-response'] ) ) {
		$recaptcha_secret_key = '1LcRBMIUAAAAAMTv4x-ROX_DVcRUOwB3HTNaXVyn';
		$response = wp_remote_get( 'https://www.google.com/recaptcha/api/siteverify?secret=' . $recaptcha_secret_key .'&response='. $_POST['g-recaptcha-response'] );
		$response = json_decode( $response['body'], true );

		if ( false == $response['success'] ) {
			$errors->add( 'recaptcha_fail','<strong>오류</strong> : <strong>reCAPTCHA</strong> 인증 필요.' );
		}
		
	}
	
	return $errors;
}

21번 줄의 시크릿키는 자신의 시크릿키를 입력하세요.

$_POST['g-recaptcha-response'] 필드는 페이지 소스보기를 통해 알 수 있으며, wp_remote_get 함수를 이용하여 reCAPTCHA 인증 요청한 것으로, reCAPTCHA API 관련 정보는 Verifying the user’s response 페이지를 보면 확인할 수 있습니다.

여기까지 따라했다면 다음의 회원가입 페이지를 볼 수 있습니다.

reCAPTCHA 필드로 레이아웃이 조금 어긋납니다. 또, “가입 확인 이메일이 발송될 것입니다.”라는 글자를 보이지 않도록 합니다. 글에서는 가장 쉽고, 간단한 방법을 사용합니다. 로그인 페이지 스타일, 스크립트 코드 부분을 다음으로 대체합니다.

/**
 * 로그인 페이지 스타일, 스크립트
 */
add_action( 'login_enqueue_scripts', 'ccc_login_script', 22 );
function ccc_login_script() {
	?>
	<script src="https://www.google.com/recaptcha/api.js" async defer></script>
	<style>
	body.login div#login {
		min-width: 350px;
	}
	#reg_passmail {
		display: none;
	}
	</style>
	<?php
}

다음은 스타일 적용 후 이 글의 최종 결과 화면입니다.

모든 과정을 따라했다면 회원가입 페이지에서 가입을 시도해보세요.

완성 파일

다음에서 이 글의 완성 파일을 받을 수 있습니다. 이 파일을 사용하려면 작업한 파일을 지우세요. 압축파일을 플러그인 업로드 설치 방법으로 설치하고 활성화하면 됩니다. 당연하게도 사이트에 회원가입 허용이 되어 있어야 가입 페이지에서 관련 기능을 사용할 수 있습니다.

마무리

반복하는 것인데, 워드프레스 기본 가입 방식인, 이메일 인증을 권장하며 특정한 경우가 아니면 암호를 바로 등록하는 것은 좋은 선택 아닌 거 같습니다. 다만, 별도의 가입 또는 로그인 폼 플러그인보다는 기본 제공 가입 및 로그인 페이지를 기준으로 여러 기능 도입을 도모하는 것이 좋습니다.

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.