#30일 애플리케이션 쓰기: e-메일 확인 및 암호 분실
간단한 소개
#30DaysOfAppwrite은 개발자에게 Appwrite의 모든 기능, 기초 기능부터 클라우드 기능 등 고급 기능까지 이해할 수 있도록 한 달 동안의 활동입니다!이 밖에도 이러한 기술이 어떻게 실현되었는지 보여주기 위해 기능이 완비된 미디어 복제를 구축할 것이다
실제 세계의 응용 프로그램을 구축할 때 이러한 개념을 응용할 수 있다.우리는 또한 우리 개발자를 따르기 위해 감동적인 보상을 제공했다.
계정 확인
12일째에 오신 걸 환영합니다.👋. e-메일 확인 및 암호 복구는 모든 애플리케이션의 두 가지 핵심 기능입니다!Appwrite를 사용하여 이러한 두 가지 기능을 구현하는 방법을 학습합니다.
Note: This requires that you have SMTP setup on Appwrite. Check out where we teach you how to enable SMTP on Appwrite.
이메일 인증부터 시작하겠습니다.OAuth2가 로그인할 때 전자 우편 인증을 할 필요가 없습니다. 왜냐하면 이 예에서 전자 우편 주소는 로그인 공급자가 검증했기 때문입니다.
초기화 확인
계정을 확인하려면 사용자를 위한 세션을 만든 후
createVerification(url)  메서드를 호출해야 합니다.이 방법은 사용자의 전자 우편 주소에 인증 메시지를 보내서 그들이 이 주소의 유효한 소유자임을 확인합니다.제공된 URL은 응답용 프로그램으로 사용자를 리디렉션하고 사용자가 이미 제공한 userId과 secret 매개 변수를 검증하여 검증 과정을 완성할 수 있도록 해야 합니다.let promise = sdk.account.createVerification('http://myappdomain/verifyEmail');
promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});
http://myappdomain/verify을 전달하는 경우 이메일을 통해 사용자에게 제공되는 URL은 다음과 같습니다.http://localhost/verifyEmail?userId=XXXX&secret=YYYY
  이메일 확인 완료
사용자가 계정 유효성 검사 프로세스를 초기화할 수 있으므로 이메일에 제공된 URL을 재정의하여 완료해야 합니다.
첫 번째 단계는 URL에서 제공하는
userId 및 secret 값을 검색하는 것입니다.JavaScript에서는 다음과 같은 결과를 얻을 수 있습니다.const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get('userId');
const secret = urlParams.get('secret');
updateVerification(userId, secret) 을 사용하여 이메일 인증을 완료할 수 있습니다.const sdk = new Appwrite();
sdk
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
;
let promise = sdk.account.updateVerification(userId, secret);
promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});
Be sure that this method is executed only on the URL provided in the email. In our example, this would be
http://myappdomain/verifyEmail.
전체 예
좋습니다. 이제 프레젠테이션 프로그램에서 상술한 기능을 실현합시다.
src/lib/Navigation.svelte에서 사용자의 검증 상태를 표시하는 단추를 만듭니다...
{#if !$state.user.emailVerification}
    <button on:click={startEmailVerification}>Not Verified ❌</button>
{:else}
    <p>Verified ✅</p>
{/if}
....
<script> 부분에 startEmailVerification 함수를 추가합니다.... 
import { api } from "../appwrite";
const startEmailVerification = async () => {
    try {
        const url = `${window.location.origin}/#/verifyEmail`
        await api.createVerification(url)
        alert("Verification Email sent")
    } catch (error) {
        alert(error.message)
    }
}
...
src/appwrite.js에서 다음 함수를 만듭니다...
createVerification: async (url) => {
    await sdk.account.createVerification(url);
},
completeEmailVerification: async(userId, secret) => {
    await sdk.account.updateVerification(userId, secret);
},
...
새 파일 생성
src/routes/VerifyEmail.svelte 및 다음 내용 추가<script>
    import { api } from "../appwrite";
    let urlSearchParams = new URLSearchParams(window.location.search);
    let secret = urlSearchParams.get("secret");
    let userId = urlSearchParams.get("userId");
    console.log(userId,secret);
    const completeEmailVerification = async () => {
        await api.completeEmailVerification(userId, secret)
        window.location.href = "/"
    }
    completeEmailVerification()
</script> 
src/App.svelte에 생성하는 것을 잊지 마십시오.😊import VerifyEmail from "./routes/VerifyEmail.svelte";
...
const routes = {
    "/": Index,
    "/login": Login,
    "/register": Register,
    "/verifyEmail": VerifyEmail,
    "*": NotFound,
};
...
Email Verification을 사용했습니다. 백엔드 코드를 한 줄 작성할 필요가 없습니다.이제 Password Recovery을 사용할 때가 되었다.암호 복구
현재 사용자는 그들의 계정을 검증할 수 있고, 우리는 그들이 비밀번호를 잃어버린 상황에서 계정을 회복할 수 있도록 해야 한다.이 절차는 계정을 검증할 때 사용하는 절차와 매우 비슷하다.
암호 복구 초기화
첫 번째 단계는 URL에서 암호를 재설정하기 위해 임시 키가 있는 이메일을
createRecovery(email, url)  방법으로 사용자에게 보내는 것입니다.let promise = sdk.account.createRecovery('[email protected]', 'http://myappdomain/resetPassword');
promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});
secret과 userid 값은 createRecovery(email, url)에 전달된 URL에 추가됩니다.전체 복구 암호
복구 페이지에서 새 암호를 두 번 입력하라는 메시지가 표시되고 커밋할 때
updateRecovery(userId, secret, password, passwordAgain) 으로 전화하십시오.앞에서 설명한 것처럼 URL에서 userId 및 secret 값을 가져옵니다.const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get('userId');
const secret = urlParams.get('secret');
updateRecovery(userId, secret, password, passwordAgain)을 사용하여 암호 복구를 완료할 수 있습니다.const sdk = new Appwrite();
sdk
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
;
let password; // Assign the new password choosen by the user
let passwordAgain;
let promise = sdk.account.updateRecovery(userId, secret, password, paswordAgain);
promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});
전체 예
다행이다, 인코딩해야겠다!
src/routes/Login.svelte에서 비밀번호를 복구할 수 있는 단추를 만듭니다...
<button class="button" on:click|preventDefault={forgotPassword}>Forgot Password?</button>
....
<script> 부분에 forgotPassword 함수를 추가합니다.... 
import { api } from "../appwrite";
const forgotPassword = async () => {
    const url = `${window.location.origin}/#/resetPassword`
    console.log(url);
    try {
        await api.forgotPassword(mail, url)
        alert("Recovery Email Sent")
    } catch (error) {
        alert(error.message);
    }
}
...
src/appwrite.js에서 다음 함수를 만듭니다....
forgotPassword: async (email, url) => { 
    await sdk.account.createRecovery(email, url) 
},
completePasswordRecovery: async (userId, secret, pass, confirmPass) => { 
    await sdk.account.updateRecovery(userId, secret, pass, confirmPass) 
},
...
src/routes/ResetPassword.svelte을 만들고 다음 코드를 추가합니다.어찌할 바를 모르다.URL 매개 변수에서
userId과 secret을 가져오면 새 비밀번호를 입력하고 updateRecovery에 요청을 보내고 성공할 때 로그인 페이지로 다시 지정할 수 있습니다.<script>
    import { api } from "../appwrite";
    let urlSearchParams = new URLSearchParams(window.location.search);
    let secret = urlSearchParams.get("secret");
    let userId = urlSearchParams.get("userId");
    let password = "",
        confirmPassword = "";
    const submit = async () => {
        try {
            await api.completePasswordRecovery(
                userId,
                secret,
                password,
                confirmPassword
            );
            window.location.href = "/#/login";
        } catch (error) {
            alert(error.message);
        }
    };
</script>
<div>
    <h1>Reset your password</h1>
    <form on:submit|preventDefault={submit}>
        <label for="password"><b>New Password</b></label>
        <input
            bind:value={password}
            type="password"
            placeholder="Enter New Password"
            name="password"
            required />
        <label for="confirmPassword"><b>Confirm Password</b></label>
        <input
            bind:value={confirmPassword}
            type="password"
            placeholder="Confirm Password"
            name="confirmPassword"
            required />
        <button class="button" type="submit">Reset Password</button>
    </form>
</div>
<style>
    div {
        margin-left: auto;
        margin-right: auto;
        width: 400px;
    }
    form {
        display: flex;
        flex-direction: column;
    }
</style>
src/App.svelte에 생성하는 것을 잊지 마십시오.😊import ResetPassword from "./routes/ResetPassword.svelte";
...
const routes = {
    "/": Index,
    "/login": Login,
    "/register": Register,
    "/resetPassword": ResetPassword,
    "/verifyEmail": VerifyEmail,
    "*": NotFound,
};
...
크레디트
우리는 네가 이 문장을 좋아하길 바란다.너는 소셜 미디어에서 우리의 모든 댓글을 주목할 수 있다.전체 활동 일정은 here에서 확인할 수 있습니다.
Appwrite Homepage
Reference
이 문제에 관하여(#30일 애플리케이션 쓰기: e-메일 확인 및 암호 분실), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/appwrite/30daysofappwrite-email-verification-and-forgot-password-420o텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)