Answer the question
In order to leave comments, you need to log in
Message: "The given data was invalid." Or where am I wrong?
Friends, I am mastering the backend in the laravel + vuejs bundle, there was a problem at the authorization stage, as I understand it, in the validation of the entered data.
export default {
components: {
VuexyLogo,
BRow,
BImg,
BCol,
BLink,
BButton,
BForm,
BCardText,
BCardTitle,
BFormCheckbox,
BFormGroup,
BFormInput,
BInputGroup,
BInputGroupAppend,
//validations,
ValidationProvider,
ValidationObserver,
},
mixins: [togglePasswordVisibility],
data() {
return {
status: '',
username: '',
useremail: '',
password: '',
sideImg: require('@/assets/images/pages/register-v2.svg'),
//validation,
required,
email,
}
},
computed: {
passwordToggleIcon() {
return this.passwordFieldType === 'password' ? 'EyeIcon' : 'EyeOffIcon'
},
imgUrl() {
if (store.state.appConfig.layout.skin === 'dark') {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
this.sideImg = require('@/assets/images/pages/register-v2-dark.svg')
return this.sideImg
}
return this.sideImg
},
},
methods: {
register() {
this.$refs.registerForm.validate().then(success => {
if (success) {
useJwt.register({
name: this.username,
email: this.useremail,
password: this.password,
})
.then(response => {
useJwt.setToken(response.data.accessToken)
useJwt.setRefreshToken(response.data.refreshToken)
localStorage.setItem('userData', JSON.stringify(response.data.userData))
this.$ability.update(response.data.userData.ability)
this.$router.push('/')
})
.catch(error => {
this.$refs.registerForm.setErrors(error.response.data.error)
})
}
})
},
},
}
import { ValidationProvider, ValidationObserver } from 'vee-validate'
import { required, email } from '@validations'
import { togglePasswordVisibility } from '@core/mixins/ui/forms'
import store from '@/store/index'
import useJwt from '@/auth/jwt/useJwt'
import useJwt from '@core/auth/jwt/useJwt'
import axios from '@axios'
// Token Refresh
let isAlreadyFetchingAccessToken = false
let subscribers = []
function onAccessTokenFetched (access_token) {
subscribers = subscribers.filter(callback => callback(access_token))
}
function addSubscriber (callback) {
subscribers.push(callback)
}
const { jwt } = useJwt(axios, {})
export default {
init () {
axios.interceptors.response.use(function (response) {
return response
}, function (error) {
// const { config, response: { status } } = error
const { config, response } = error
const originalRequest = config
// if (status === 401) {
if (response && response.status === 401) {
if (!isAlreadyFetchingAccessToken) {
isAlreadyFetchingAccessToken = true
store.dispatch('auth/fetchAccessToken')
.then((access_token) => {
isAlreadyFetchingAccessToken = false
onAccessTokenFetched(access_token)
})
}
const retryOriginalRequest = new Promise((resolve) => {
addSubscriber(access_token => {
originalRequest.headers.Authorization = `Bearer ${access_token}`
resolve(axios(originalRequest))
})
})
return retryOriginalRequest
}
return Promise.reject(error)
})
},
login (email, password) {
return axios.post('auth/login', {
email,
password
})
},
register (name, email, password) {
return axios.post('auth/register', {
name,
email,
password
})
},
setRefreshToken () {
return axios.post('auth/refresh-token', {accessToken: localStorage.getItem('accessToKen')})
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth as JWTAuth;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required|string|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:6|max:10',
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json(['user' => $user]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
/** public function login()
* {
* $credentials = request(['email', 'password']);
*
* if (! $token = auth('api')->attempt($credentials)) {
* return response()->json(['error' => 'Unauthorized'], 401);
* }
*
* return $this->respondWithToken($token);
* }
**/
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ( ! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth('api')->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth('api')->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth('api')->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'user' => $this->guard()->user(),
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
public function guard(){
return \Auth::Guard('api');
}
}
Route::group(['prefix' => 'auth'], function () {
Route::post('login', [AuthController::class, 'login']);
Route::post('register', [AuthController::class, 'register']);
Route::post('refresh-token', [AuthController::class, 'refresh']);
Route::group(['middleware' => 'auth:api'], function() {
Route::get('logout', [AuthController::class, 'logout']);
Route::get('user', [AuthController::class, 'user']);
});
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question