是否可以从Laravel中的现有电子邮件密码结构创建仅电子邮件身份验证

时间:2019-02-27 12:02:07

标签: mysql laravel

我正在尝试创建仅电子邮件身份验证。我希望不进行登录,而只需要注册,一旦输入电子邮件,便创建了一个承载令牌。 我有注册功能和登录功能,当我启动密码时可以使用,但是我删除了密码,但是尝试将“创建令牌”移至注册。它给出了令牌未定义的错误。

注册功能

public function signup(Request $request)
    {
        $request->validate([
           'email' => 'required|string|email|unique:users'
        ]);
        $user = new User([
            'email' => $request->email
        ]);
        $user->save();
        return response()->json([
            'message' => 'Successfully created user!'
        ], 201);
    }

登录功能

public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email'

        ]);
        $credentials = request(['email', '=']);
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

1 个答案:

答案 0 :(得分:1)

这很简单,您已经完成了这里需要完成的大部分工作。您不需要登录功能,而是需要复制该功能的令牌部分,如下所示

 public function signup(Request $request)
    {
        $request->validate([
           'email' => 'required|string|email|unique:users'
        ]);
        $user = new User([

            'email' => $request->email
        ]);
         $user->save();
        Auth::login($user);
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'message' => 'Successfully created user!',
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
            ], 201);


    }