2FAuth/app/Http/Controllers/UserController.php

100 lines
2.4 KiB
PHP
Raw Normal View History

2019-05-20 07:37:41 +02:00
<?php
namespace App\Http\Controllers;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
2019-05-29 11:04:12 +02:00
/**
* log a user in
* @return [type] [description]
*/
2020-01-09 11:14:39 +01:00
public function login(Request $request)
2019-05-20 07:37:41 +02:00
{
2020-01-09 11:14:39 +01:00
$messages = [
'email.exists' => 'No account found using this email',
];
$validator = Validator::make($request->all(), [
'email' => 'required|exists:users,email',
'password' => 'required',
], $messages);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 400);
}
2019-05-20 07:37:41 +02:00
$credentials = [
'email' => request('email'),
'password' => request('password')
];
if (Auth::attempt($credentials)) {
$success['token'] = Auth::user()->createToken('MyApp')->accessToken;
2019-05-28 17:29:15 +02:00
$success['name'] = Auth::user()->name;
2019-05-20 07:37:41 +02:00
2020-01-10 13:43:36 +01:00
return response()->json(['success' => $success], 200);
2019-05-20 07:37:41 +02:00
}
return response()->json(['error' => 'Unauthorised'], 401);
}
2019-05-29 11:04:12 +02:00
/**
* log out current user
* @param Request $request
* @return json
*/
public function logout()
{
$accessToken = Auth::user()->token();
$accessToken->revoke();
return response()->json(['success' => 'signed out']);
}
/**
* register new user
* @param Request $request [description]
* @return json
*/
2019-05-20 07:37:41 +02:00
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
2020-01-09 11:14:39 +01:00
'password' => 'required|confirmed',
2019-05-20 07:37:41 +02:00
]);
if ($validator->fails()) {
2020-01-10 13:43:36 +01:00
return response()->json(['error' => $validator->errors()], 400);
2019-05-20 07:37:41 +02:00
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return response()->json(['success' => $success]);
}
2019-05-29 11:04:12 +02:00
/**
* get detailed information about a user
* @return [type] [description]
*/
2019-05-20 07:37:41 +02:00
public function getDetails()
{
2019-05-29 11:04:12 +02:00
return response()->json(Auth::user(), 200);
2019-05-20 07:37:41 +02:00
}
}