I'm building a laravel API. I want when i register , email verify will be sent activation code to user email automatically.
the problem is when i create a new activation code , i create a new record in tokens table too, this record has user_id field , so for store it , i use JWTAuth::user()->id but i have this error:
Trying to get property 'id' of non-object
i know why this happens , because I did not enter any tokens and i don't know how handle it and where to create a new record in tokens table
for more details I have :
AuthController : Login and register
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name'=>'required|string|min:3|max:30',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)],
));
$token = JWTAuth::fromUser($user);
dd($this->sendNotification());
$user->$this->sendNotification();
return response()->json([
'message' => 'successfully created',
'user' => $user,
'token' => $token,
], 201);
}
EmailVerifyController : for verify user email and validate activation code
public function emailVerify(Request $request){
$data = $request->validate([
'code' => 'required|size:10|numeric',
]);
$interedCode = (int)$data['code'];//convert code from string to integer
$userCode = Token::where('user_id' , JWTAuth::user()->id)->first();//find user from tokens table
$activationCode = $userCode->code; //get activation code of user in tokens table
$expires_in = (int)$userCode->expires_in; //get expire time of code
$now = Carbon::now()->timestamp;
if($interedCode == $activationCode) {
if ($now < $expires_in) {
$user = JWTAuth::user()->id;
$findUser = User::find($user);
$findUser->email_verified_at = Carbon::now()->timestamp;
$findUser->save();
$token = Token::where('user_id', JWTAuth::user()->id)->first();
$token->status = 1;
$token->save();
return response()->json('email verified successfully', 200);
} else {
return response()->json('code expired', 400);
}
}else{
return response()->json('wrong activation code' , 400);
}
}
SendNotificationTrait : for send email and create a new record in token table
trait EmailVerifyTrait
{
public function sendNotification(){
$random = $this->generateVerificationCode(6);
$details = [
'title' => 'Mail from ItSolutionStuff.com',
'body' =>$random,
];
Mail::to('*****#gmail.com')->send(new VerifyMail($details));
return response()->json([
'message'=>'your email verification code sent to your email'
] , 201);
}
public function generateVerificationCode($length = 6) {
$characters = '0123456789';
$charactersLength = strlen($characters);
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $characters[rand(0, $charactersLength - 1)];
}
$token = new Token();
$token->user_id = JWTAuth::user()->id;
$token->code = $code;
$token->status = 0;
$token->save();
return $code;
}
tokens tables : has this fields : user_id , code , created_at , expires_in
so how can i handle creating new Token record in tokens table ?
or should i use event listener ?
thank you for your help and sorry for my language.
for handle this email verification , i used laravel Notification : https://laravel.com/docs/8.x/notifications
and i used $user->id for getting id and use it for user_id field in tokens table.
codes:
Register method
use ActivationCode;
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name'=>'required|string|min:3|max:30',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
//create user
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)],
));
//create token
$token = JWTAuth::fromUser($user);
//create a new activation code
$activationCode = $this->generateVerificationCode();
//create a new token
$newToken = new Token;
$newToken->code = $activationCode;
$newToken->status = 0;
$newToken->user_id = $user->id;
$newToken->save();
//email details
$details = [
'greeting' => 'Hi'.$request->name,
'body' => 'use this activation code for verify your email address',
'activation_code'=>$newToken->code,
'thanks' => 'thank you',
'order_id' => 101
];
//send email verify to user email
Notification::send($user, new EmailVerification($details));
return response()->json([
'message' => 'use created successfully and activation code sent to email',
'user' => $user,
'token' => $token,
], 201);
}
Activation code trait:
trait ActivationCode
{
public function generateVerificationCode($length = 6) {
$characters = '0123456789';
$charactersLength = strlen($characters);
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $characters[rand(0, $charactersLength - 1)];
}
return $code;
}
}
EmailVerify Notification :
class EmailVerification extends Notification
{
use Queueable;
private $details;
public function __construct($details){
$this->details = $details;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->greeting($this->details['greeting'])
->line($this->details['body'])
->line($this->details['thanks'])
->line($this->details['activation_code']);
}
public function toArray($notifiable)
{
return [
'order_id' => $this->details['order_id']
];
}
}
Related
I am using Laravel-8 and Maatwebsite-3.1 package to import Excel into the DB using Laravel API as the endpoint.
Trait:
trait ApiResponse {
public
function coreResponse($message, $data = null, $statusCode, $isSuccess = true) {
if (!$message) return response() - > json(['message' => 'Message is required'], 500);
// Send the response
if ($isSuccess) {
return response() - > json([
'message' => $message,
'error' => false,
'code' => $statusCode,
'results' => $data
], $statusCode);
} else {
return response() - > json([
'message' => $message,
'error' => true,
'code' => $statusCode,
], $statusCode);
}
}
public
function success($message, $data, $statusCode = 200) {
return $this - > coreResponse($message, $data, $statusCode);
}
public
function error($message, $statusCode = 500) {
return $this - > coreResponse($message, null, $statusCode, false);
}
}
Import:
class EmployeeImport extends DefaultValueBinder implements OnEachRow, WithStartRow, SkipsOnError, WithValidation, SkipsOnFailure
{
use Importable, SkipsErrors, SkipsFailures;
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
if($rowIndex >= 1000)
return; // Not more than 1000 rows at a time
$row = $row->toArray();
$employee = Employee::create([
'first_name' => $row[0],
'other_name' => $row[1] ?? '',
'last_name' => $row[2],
'email' => preg_replace('/\s+/', '', strtolower($row[3])),
'created_at' => date("Y-m-d H:i:s"),
'created_by' => Auth::user()->id,
]);
public function startRow(): int
{
return 2;
}
}
Controller:
public function importEmployee(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'document' => 'file|mimes:xls,xlsx|max:5000',
]);
if ($request->hasFile('document'))
{
if($validator->passes()) {
$import = new EmployeeImport;
$file = $request->file('document');
$file->move(public_path('storage/file_imports/employee_imports'), $file->getClientOriginalName());
Excel::import($import, public_path('storage/file_imports/employee_imports/' . $file->getClientOriginalName() ));
foreach ($import->failures() as $failure) {
$importerror = new ImportError();
$importerror->data_row = $failure->row(); // row that went wrong
$importerror->data_attribute = $failure->attribute(); // either heading key (if using heading row concern) or column index
$importerror->data_errors = $failure->errors()[0]; // Actual error messages from Laravel validator
$importerror->data_values = json_encode($failure->values());
$importerror->created_by = Auth::user()->id;
$importerror->created_at = date("Y-m-d H:i:s");
$importerror->save();
}
return $this->success('Employees Successfully Imported.', [
'file' => $file
]);
}else{
return $this->error($validator->errors(), 422);
}
}
} catch(\Throwable $e) {
Log::error($e);
return $this->error($e->getMessage(), $e->getCode());
}
}
I made it to SkipOnError and SkipOnFailure.
If there's error, it saves the error into the DB. This is working.
However, there is issue, if some rows fail it still display success (Employees Successfully Imported) based on this:
return $this->success('Employees Successfully Imported.
When there is partial upload, or all the rows or some of the rows have issues, I want to display this to the user. So that it will be interactive.
How do I achieve this?
Thanks
I am trying to delete the cookie i create when user logs in but somehow delete_cookie() function is not deleting the cookie i made. I checked the documentation and everything but i cannot get it to work
Here is my code
public function __construct()
{
helper('cookie');
}
public function login() {
$data = [];
$session = session();
$model = new AdminModel();
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
$remember = $this->request->getPost('agree');
$rules = [
'username' => 'required',
'password' => 'required',
];
if(!$this->validate($rules)) {
$data['validation'] = $this->validator;
} else {
$admin = $model->where('username', $username)->where('password', $password)->first();
if($admin) {
$session->set('uid', $admin['id']);
if($remember) {
set_cookie([
'name' => 'id',
'value' => $admin['id'],
'expire' => '3600',
'httponly' => false
]);
}
} else {
$session->setFlashdata('msg', 'Incorrect Username or Password');
return redirect()->to('admin/login');
}
}
return view('admin/login', $data);
}
public function logout() {
$session = session();
$session->destroy();
delete_cookie('id');
return redirect()->to('admin/login')->withCookies();
}
Edit:
I fixed it. I had to redirect with withCookies();
use this Library
use Config\Services;
Services::response()->deleteCookie('id');
refer this link
https://codeigniter.com/user_guide/libraries/cookies.html
This is friend request code, When i request to another user than token(login user or auth user)didn't entry in table. This is my frd table, you can show here..How can i set auth user as user_id_2 and entry in data table
public function request(Request $request) {
$input =$request->all();
$user = User::find($request->user_id_1);
$friend->user_id_2 = Auth::guard('api')->user()->id;
if(empty($user)){
return [
'status' => 'error',
'msg' => 'no user found'
];
}
if($request->approved == "yes"){
$friend = new Friend();
$friend->user_id_1 = $user->id;
$friend->approved = "yes";
// dd($user);
$friend->save();
$data = array("status" => $user);
return $data;
}
else{
$friend->approved = false;
$friend->save();
return [
'user_id' => $user->id,
'true' => true
];
}
}
Please update your code below.
public function request(Request $request) {
$input =$request->all();
$user = User::find($request->user_id_1);
if(empty($user)){
return [
'status' => 'error',
'msg' => 'no user found'
];
}
if($request->approved == "yes"){
$friend = new Friend();
$friend->user_id_1 = $user->id;
$friend->user_id_2 = Auth::guard('api')->user()->id;
$friend->approved = "yes";
$friend->save();
$data = array("status" => $user);
return $data;
}
else{
$friend->approved = false;
$friend->save();
return [
'user_id' => $user->id,
'true' => true
];
}
}
I'm working on an api in Laravel and want to edit the login procedure a bit.
Users log in with a username and a password but as a third parameter I want to add an app_id.
This is because usernames can be double in the database when the app_id is different. This is my current login code. It's using JWT as a driver.
$credentials = request(['username', 'password']);
if(!$token = auth()->attempt($credentials)) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
How can I accomplish this?
Kind regards,
Kevin Walter
Edit: My entire AuthController
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('jwt.verify', ['except' => ['login', 'refresh']]);
}
/**
* Login to get JWT credentials
*/
public function login() {
//TODO: LOCKOUT AFTER X AMOUNT OF TRIES
if(!$token = auth()->attempt($this->credentials())) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
return $this->me(true, $token);
}
public function checkPin() {
$username = request('username');
$pincode = request('pincode');
$user = auth()->user();
if($user && $user->username && $user->pincode && $username == $user->username && $pincode == $user->pincode) {
return $this->outputJson(0, 'auth', 'checkPin',[
"firebase_key" => $this->create_custom_token($user->uid, true),
"pin_ok" => 1,
]);
} else {
return $this->outputJson(0, 'auth', 'checkPin', ["pin_ok" => 0]);
}
}
public function me($withToken = false, $token = "") {
$user = auth()->user();
$output = $user;
$output->groups = $user->groups;
$output->categories = $user->categories;
$output->hasPin = $user->hasPin();
$headers = array();
if($withToken) {
$headers["X-TOKEN-RETURN"] = $token;
}
return $this->outputJson('0', 'auth', 'me', $output, $headers);
}
public function logout() {
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
}
It was just as simple as merging the app_id in the credentials. This is the working example!
//Add app ID into the mix of credentials
protected function credentials()
{
return array_merge(request(['username', 'password']), ['app_id' => \request()->header('X-APP-ID')]);
}
/**
* Login to get JWT credentials
*/
public function login() {
//TODO: LOCKOUT AFTER X AMOUNT OF TRIES
if(!$token = auth()->attempt($this->credentials())) {
return response()->json([
'error' => ['code' => 1],
'status' => 'error',
], 401);
}
return $this->me(true, $token);
}
I'm learning both Laravel and UnitTesting at the moment, so this may be a stupid question.
I'm getting stuck on how to best test the controller function below:
UserController:
public function store()
{
$input = Input::all();
$user = new User($input);
if( ! $user->save()){
return Redirect::back()->withInput()->withErrors($user->getErrors());
}
return Redirect::to('/user');
}
here's the test as I have it so far:
/**
* #dataProvider providerTestUserStoreAddsUsersCorrectly
*/
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$response = $this->call('POST', 'user', array('first_name'=>$first_name, 'last_name'=>$last_name, 'email'=>$email, 'password'=>$password));
}
public function providerTestUserStoreAddsUsersCorrectly(){
return array(
array("FirstName", "LastName", "Email#add.com", "pass1234")
);
}
This is actually working and adding the user to the db correctly, but I'm not sure how to test the output / what assertions to use as the response should be to add the user to the db and to redirect to the /user page.
How do I finish this test?
If you need to check success status then you can simply send status code from your controller
and check status in test
public function store()
{
$input = Input::all();
$user = new User($input);
if( !$user->save() ){
return array("status"=>'failed');
}
return array("status"=>'success');
}
public function testUserStoreAddsUsersCorrectly($first_name, $last_name, $email, $password)
{
$requested_arr = [
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $password
];
$response = $this->call('POST', 'user', $requested_arr);
$data = json_decode($response ->getContent(), true);
if ($data['status']) {
$this->assertTrue(true);
} else {
$this->assertTrue(false);
}
}