You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

225 lines
7.8 KiB

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Api\BaseAuthApiController as BaseAuthApiController;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\Agent;
use App\Models\AgentUser;
use App\Http\Requests\Api\RegisterApiRequest;
use App\Http\Requests\Api\LoginApiRequest;
class AuthApiController extends BaseAuthApiController
{
public $_default_usertype = 'agents';
public $_default_grant_two = '2';
const AGENTS = 'agents';
const GENERAL = 'general';
//
public function login(LoginApiRequest $request)
{
if (filter_var($request->username, FILTER_VALIDATE_EMAIL)) {
$user = User::where('email', $request->username)->first();
} else {
$user = User::where('phone', $request->username)->first();
}
if(empty($user)){
return response()->json(['status' =>false, 'msg' => 'Email hoặc SĐT chưa được đăng ký.'], parent::HTTP_OK);
}
if (!Auth::attempt(['id' => $user->id, 'password' => $request->password])) {
return response()->json(['status' =>false, 'msg' =>'Tài khoản hoặc mật khẩu không chính xác. Vui lòng thử lại.'], parent::HTTP_OK);
}
$user = User::find($user->id);
if (empty($user)) {
$this->sendError('Error: ', ['error' => 'No data invalid']);
}
$data = [
'id' => $user->id,
'address' => $user->address,
'avatar' => $user->avatar,
'birthday' => $user->birthday,
'email' => $user->email,
'fullname' => $user->name,
'gender' => $this->getGenderText($user->gender),
'phone' => $user->phone,
'last_login' => $user->last_login,
];
//Find Agent USer
$agentUser = AgentUser::where('user_id', $user->id)->latest()->first();
if (!empty($agentUser->agent_root_id)) {
// Agent User Root
$agentRootInfo = Agent::find($agentUser->agent_root_id);
}
if (!empty($agentUser->agent_id)) {
// Agent User Current
$myAgent = Agent::find($agentUser->agent_id);
}
$phone = $user->phone ?? null;
$data['general_agents_code'] = $agentUser->code ?? '';
$data['general_agents_name'] = $agentRootInfo->name ?? '';
$data['downline_register'] = $this->getLinkParam('downline_register', $agentUser->code);
$data['promotional_link'] = $this->getLinkParam('promotional_link', $agentUser->code);
$data['role'] = $user->user_type;
// Creating a token without scopes...
$token = $user->createToken($user->id . ' token ' . time(), ['*'])->accessToken;
$data['access_token'] = $token;
$data['token_type'] = 'Bearer';
$data['expires_in'] = 1296000;
$user->update(['last_login' => new \DateTime()]);
$data['status'] = true;
$data['msg'] = "Đăng nhập thành công.";
return response()->json($data, 200);
}
public function register(RegisterApiRequest $request)
{
// $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
// 'email' => 'required|email',
// 'fullname' => 'required'
// ]);
// if ($validator->fails()) {
// return $this->sendError('Validation Error.', $validator->errors());
// }
$checkUserAgent = AgentUser::where('code', '=', $request->agents_code)->first();
if (empty($checkUserAgent)) {
return response()->json(['status' => false, 'msg' => 'Đăng ký thất bại, Không tìm thấy đại lý.']);
}
$lastIndex = AgentUser::latest()->first();
$lastCode = $lastIndex->code??null;
if(empty($lastCode)){
$lastCode = "A99";
}
$agentCodeNew = $this->generateNewCode($lastCode);
$dataInsert = $this->transformRegisterData($request->all());
if (!empty($dataInsert)) {
$userId = \App\Models\User::insertGetId($dataInsert);
if ($userId) {
$dataAgentInsert = [
'name' => $dataInsert['name'] ?? '',
'type' => self::AGENTS,
'grant' => $this->_default_grant_two,
'phone' => $dataInsert['phone'] ?? '',
'address' => $dataInsert['address'] ?? '',
];
$agentInsertId = Agent::insertGetId($dataAgentInsert);
if ($agentInsertId) {
AgentUser::insert([
'user_id' => $userId,
'agent_id' => $agentInsertId,
'status' => 1,
'code' => $agentCodeNew??'',
'agent_root_id' => $checkUserAgent->agent_root_id
]);
}
;
}
return response()->json(['status' => true, 'msg' => $this->getMessageReponse(1)]);
}
return response()->json(['status' => false, 'msg' => $this->getMessageReponse(2)]);
}
public function generateNewCode($code){
$newCode = '';
if(!empty($code)){
$latestCodeNumber = (int) substr($code, 1);
$newCodeNumber = $latestCodeNumber + 1;
$newCode = 'A' . str_pad($newCodeNumber, 3, '0', STR_PAD_LEFT);
}
return $newCode;
}
public function logout(Request $request)
{
$token = $request->user()->token();
// expried token
$token->revoke();
// Response
return response()->json([
'status' => true,
'msg' => 'Đăng xuất thành công.'
]);
}
function transformRegisterData($data)
{
$finalData = [];
if (!empty($data['email'])) {
$finalData['email'] = $data['email'];
}
if (!empty($data['address'])) {
$finalData['address'] = $data['address'];
}
if (!empty($data['birthday'])) {
$finalData['birthday'] = $data['birthday'];
}
if (!empty($data['fullname'])) {
$finalData['name'] = $data['fullname'];
}
if (!empty($data['phone'])) {
$finalData['phone'] = $data['phone'];
}
$finalData['password'] = !empty($data['password']) ? Hash::make($data['password']) : Hash::make('1qaz2wsxA@');
if (!empty($data['gender'])) {
$finalData['gender'] = !empty($data['gender']) && $data['gender'] == 'male' ? 1 : 0;
}
$finalData['user_type'] = !empty($data['role']) ? $data['role'] : $this->_default_usertype;
return $finalData;
}
function getMessageReponse($key)
{
$msg = [
1 => "Tạo tài khoản thành công.",
2 => "Tạo tài khoản thất bại.",
3 => "Email đã tồn tại.",
4 => "Email không hợp lệ.",
5 => "Mật khẩu phải có ít nhất 8 ký tự, bao gồm chữ cái và số.",
6 => "Tên đăng nhập phải có ít nhất 6 ký"
];
return $msg[$key] ?? '';
}
function getGenderText($gender)
{
if ($gender == 1) {
return 'male';
}
if ($gender == 0) {
return 'female';
}
return null;
}
function getLinkParam($type, $phone)
{
$arr = [
'downline_register' => 'daisu.sundayenglish.com/dk',
'promotional_link' => 'thongtin.sundayenglish.com'
];
$domain = $arr[$type] ?? '';
if (empty($phone)) {
return $domain;
} else {
$params = http_build_query(['mds' => $phone]);
return $domain . '?' . $params;
}
}
}