javascript 如何使用Laravel和React发送电子邮件验证?

vwkv1x7d  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(135)

我想在用户创建个人资料后给他们发一封验证邮件。我正在使用axios和Sanctum来处理用户注册。
在我的AuthController.php文件中,我有

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function register(Request $request){
    $validator = Validator::make($request->all(),[
        'name' => 'required|max:40',
        'email' => 'required|email|max:200|unique:users,email',
        'password' => 'required|min:8',

    ]);
    if($validator->fails()){
        return response()->json(['validation_errors'=>messages()]);
    }
    else{
        $user = User::create([
            'name'=> $request->name,
            'email'=> $request->email,
            'password'=> Hash::make($request->password),
        ]);
        $token = $user->createToken($user->email.'_Token')->plainTextToken;
        return response()->json([
            'status'=>200,
            'username'=>$user->name,
            'token'=>$token,
            'message'=>'Registration Successful',
        ])->header('Access-Control-Allow-Origin', '*');
    }
}

在Register.jsx文件中,我有
'

export default function Register() {
const navigate = useNavigate();
const [registerInput, setRegister] = useState({
    name: '',
    email: '',
    password: '',
    error_list: [],
})
const handleInput = (e) => {
    e.persist();
    setRegister({...registerInput, [e.target.name]: e.target.value });
}

const registerSubmit = (e) => {
    e.preventDefault();
    
    const data = {
        name: registerInput.name,
        email: registerInput.email,
        password: registerInput.password,
    }

    axios.get('/sanctum/csrf-cookie').then(response => {
        axios.post(`http://localhost:8000/api/register`, data).then(res => { 
            if(res.data.status === 200)
            {
                localStorage.setItem('auth_token', res.data.token);
                localStorage.setItem('auth_name', res.data.username);
                swal("Success",res.data.message,"success");
                navigate('/login');
            }
            else
            {
                setRegister({...registerInput, error_list: res.data.validation_errors});
            }
        });
    });
  }

}

这个方法很有效,我可以在表中创建新用户。问题是我想对创建的用户进行身份验证,因为项目可能会充满机器人。

5jvtdoz2

5jvtdoz21#

如果您想集成项目电子邮件验证:

  • 首先你需要电子邮件或smtp信用卡,
  • 成功创建用户后,你应该在你的情况下响应需要验证消息前端React(而不是登录页面).之后有不同的方法来做验证过程.简单的方法是生成唯一的链接验证和发送给他们的用户电子邮件,当输入此网址,你可以设置用户激活后,发送用户登录到帐户的登录页面.示例实现:https://codeanddeploy.com/blog/laravel/how-to-implement-laravel-8-email-verification

相关问题