NotFoundHttp Exception (Controller Method Not Found )- Laravel 5.1 Facebook Login - facebook-login

I am integrating Facebook Login in my New Laravel 5.1.The user will have the option to manually login by using Facebook Login or the traditional form login.So far I have no problem implementing traditional login
For the Laravel Socialite, I think I already set correctly
composer.json
"laravel/socialite": "^2.0",
config/app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
.........
.........
Illuminate\Html\HtmlServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Laracasts\Flash\FlashServiceProvider::class,
Laracasts\Generators\GeneratorsServiceProvider::class,
AlgoliaSearch\Laravel\AlgoliaServiceProvider::class,
Laravel\Socialite\SocialiteServiceProvider::class,
],
AuthController
<?php
namespace App\Http\Controllers\Auth;
use Socialite;
//use Illuminate\Routing\Controller;
use App\User;
use Validator;
use Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
//temporarily redirected to duterte-run.mendanielle.com
public function getRegister()
{
return view('auth.login');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider()
{
return Socialite::driver('facebook')->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback()
{
// try {
$user = Socialite::driver('facebook')->user();
// } catch (Exception $e) {
// return redirect('auth/facebook');
// }
// $authUser = $this->findOrCreateUser($user);
// Auth::login($authUser, true);
// return redirect()->route('home');
}
routes.php
Route::get('/auth/facebook', 'Auth\AuthController#redirectToProvider');
Route::get('/auth/facebook/callback', 'Auth\AuthController#handleProviderCallback');
// Logging in and out
get('/auth/login', 'Auth\AuthController#getLogin');
post('/auth/login', 'Auth\AuthController#postLogin');
get('/auth/logout', 'Auth\AuthController#getLogout');
login form
<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember Me</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">Login</button>
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<a class="btn btn-link" href="{{ url('/auth/facebook') }}">Login With Facebook</a>
</div>
</div>
</form>
I followed the latest documentation at Laravel.com website,and inside services.php
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('CALL_BACK_URL'),
],
And the .env file
FACEBOOK_CLIENT_ID=1834566497828637244
FACEBOOK_CLIENT_SECRET=9505676d1f50bty7b613baa7b68786op5ba48
CALL_BACK_URL=http://localhost:9090/auth/login
The login button will redirect me to
localhost:9090/auth/facebook
NotFoundHttpException in Controller.php line 269:
Controller method not found.
at Controller->missingMethod('facebook')
at call_user_func_array(array(object(AuthController), 'missingMethod'), array('_missing' => 'facebook')) in Controller.php line 256
at Controller->callAction('missingMethod', array('_missing' => 'facebook')) in ControllerDispatcher.php line 164
at ControllerDispatcher->call(object(AuthController), object(Route), 'missingMethod') in ControllerDispatcher.php line 112
at ControllerDispatcher->Illuminate\Routing{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in RedirectIfAuthenticated.php line 41
So what's the proper way? How do you integrate Socialite in Laravel 5.1?
update
I see this 'weird' result in php artisan route:list
GET|HEAD|POST|PUT|PATCH|DELETE | auth/{_missing} | App\Http\Controllers\Auth\AuthController#missingMethod | guest |
Just under the
| auth/facebook|App\Http\Controllers\Auth\AuthController#redirect

Got it
In controller, instead of
use App\Http\Controllers\Controller;
This is the correct controller
use Illuminate\Routing\Controller;
And I fixed the routes,
Route::get('/auth/facebook/callback','Auth\AuthController#handleProviderCallback');
Should match the call back_url listed in .env file which is
http://localhost:9090/admin
So to correct this
Route::get('/admin','Auth\AuthController#handleProviderCallback');
Needs some tweaks when saving if the user is not listed in database but it works when a registered user logs

Related

In listing of data form is rendered when any input edited?

with livewire 1.3 / alpinejs 2.x.x I make listing of data with filter text
and selection inputs and clicking on “Search” button I need to run search when
“Search” button is clicked.
But search is run when text/selection input lose focus without clicking on “Search” button.
I see it by form's wire:loading block and 1 line in log file, which I trigger in render method
That is not what I need : I need to run render method only clicking on “Search” button.
I tried to use alpinejs, but failed...
In component app/Http/Livewire/Admin/AppNews.php I have:
<?php
namespace App\Http\Livewire\Admin;
use Carbon\Carbon;
use Livewire\Component;
use App\News;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
class AppNews extends Component
{
use WithPagination;
use WithFileUploads;
public $filters = [
'title' => '',
'published' => '',
];
];
public $uploaded_file_name;
public $uploadedImageFilenameData;
public $uploadedNewsImage;
protected $listeners = ['fileUpload' => 'handleFileUpload'];
public $current_news_id;
public $updateMode = 'browse';
public function render()
{
\Log::info('-1 NewsRENDER $this->filters ::' . print_r($this->filters, true));
$news_rows_count = News
::getByTitle($this->filters['title'], true)
->getByPublished($this->filters['published'], true)
->count();
$backend_per_page = Settings::getValue('backend_per_page', CheckValueType::cvtInteger, 20);
$this->emit('app_news_opened', ['mode' => 'browse', 'id' => null]);
$newsPublishedValueArray = SetArrayHeader([['key' => '', 'label' => ' -Select published- ']], News::getNewsPublishedValueArray(true));
$newsDataRows = News
::getByTitle($this->filters['title'], true)
->getByPublished($this->filters['published'], true)
->with('creator')
->orderBy('news.created_at', 'desc')
->paginate($backend_per_page);
$newsDataIds = [];
foreach ($newsDataRows as $nextNews) {
$newsDataIds[] = $nextNews->id;
}
return view('livewire.admin.app-news.container', [
'newsDataRows' => $newsDataRows,
'newsDataIds' => $newsDataIds,
'form' => $this->form,
'news_rows_count' => $news_rows_count,
'newsPublishedValueArray' => $newsPublishedValueArray,
]);
}
and in the template resources/views/livewire/admin/app-news/container.blade.php :
<article class="admin_page_container">
<div class="card form-admin-news">
<div class="card-body card-block">
<div class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</div>
...
<fieldset class="bordered text-muted p-2 m-2" x-data="{ title: '{{$filters['title']}}', published: '{{$filters['published']}}' ,
publishedItems: <?php print str_replace('"',"'",json_encode( $newsPublishedValueArray) ) ?> } ">
<div> $filters::{{ var_dump($filters) }}</div>
title::<div x-html="title"></div>
published::<div x-html="published"></div>
<legend class="bordered">Filters</legend>
<dl class="block_2columns_md m-0 p-2">
<dt class="key_values_rows_label_13">
<label class="col-form-label" for="temp_filter_title">
By title
</label>
</dt>
<dd class="key_values_rows_value_13" >
<div class="content_with_right_button">
<div
class="content_with_right_button_left_content"
wire:model.lazy="filters.title"
>
<input
class="form-control admin_control_input"
type="text"
x-model="title"
x-on:blur="$dispatch('input', title)"
id="title"
>
</div>
<div class="content_with_right_button_right_button pl-2">
<button class="btn btn-outline-secondary nowrap_block" wire:click="makeSearch( )">
{!! $viewFuncs->showAppIcon('filter') !!}Search
</button>
</div>
</div>
</dd>
</dl>
<dl class="block_2columns_md m-0 p-2">
<dt class="key_values_rows_label_13">
<label class="col-form-label" for="temp_filter_published">
By published
</label>
</dt>
<dd
class="key_values_rows_value_13"
wire:model.lazy="filters.published"
>
<select
x-model="published"
x-on:blur="$dispatch('select', published)"
id="published"
class="form-control editable_field admin_control_input"
>
<template x-for="nextPublishedItem in publishedItems">
<option :value="nextPublishedItem.key" x-text="nextPublishedItem.label"></option>
</template>
</select>
#error('form.published')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl>
</fieldset> <!-- Filters -->
...
#endif {{-- #if($updateMode=='browse')--}}
#endif {{-- #if($updateMode=='browse')--}}
#if(count($newsDataRows) > 0)
<div class="table-responsive table-wrapper-for-data-listing" x-data="selectedNewsIdsBoxXData()">
<table>
...
</table>
</div> <!-- <div class="table-responsive table-wrapper-for-data-listing"> -->
#endif {{-- #if(count($newsDataRows) > 0) --}}
#endif {{-- #if($updateMode=='browse') --}}
</div> <!-- <div class="card-body card-block"> -->
</div> <!-- <div class="card"> -->
</article> <!-- page_content_container -->
Which is the valid way?
Modified BLOCK 2:
I try another way with using of alpinejs2 : I try to use it in this case, as when public var of component is changed:
with dispatch methid when button “Search” is clicked
<div class="card form-admin-facilities" x-data="adminFacilitiesComponent()">
...
filter_name: {{$filter_name}}<br>
...
temp_filter_name: <span x-html="temp_filter_name"></span><br>
...
<fieldset class="bordered text-muted p-2 m-2">
<legend class="bordered">Filters</legend>
<div class="content_with_right_button" wire:model.lazy="filter_name">
<div class="content_with_right_button_left_content" >
<input
class="form-control admin_filter_input"
x-model="temp_filter_name"
type="text"
>
</div>
<div class="content_with_right_button_right_button pl-2" >
<button class="btn btn-outline-secondary" #click="$dispatch('input', temp_filter_name)" type="button">Search
</button>
<!-- In more complicated form can be several filter fields : text and select inputs -->
</div>
</div>
</fieldset> <!-- Filters -->
...
<script>
function adminFacilitiesComponent() {
return {
temp_filter_name:'',
and in the component I defined public $filter_name var, which is used in render method :
class Facilities extends Component
{
public $form= [
'name'=>'',
'descr'=> '',
'created_at'=> '',
'is_reopen' => false,
];
public $current_facility_id;
public $filter_name= '';
public $updateMode = 'browse';
public function render()
{
\Log::info( '-1 render Facilities $this->filter_name ::' . print_r( $this->filter_name, true ) );
$this->facility_rows_count = Facility
::getByName($this->filter_name, true)
->count();
$backend_per_page = Settings::getValue('backend_per_page', CheckValueType::cvtInteger, 20);
return view('livewire.admin.facilities.container', [
'facilityDataRows' => Facility
::orderBy('created_at', 'desc')
->getByName($this->filter_name, true)
->paginate($backend_per_page),
'facility_rows_count'=> $this->facility_rows_count
]);
}
But it does not work as I expect : entering value in text input when this input lose focus
form is rendered again. I expected form to be rendered only when I click on “Search” button
and form will be rendered with new entered value. I do not use blur event for text input and
do not understand why the form is rendered when this input lose focus?
Modified BLOCK 3:
Using x-ref= I do :
<div class="content_with_right_button" wire:model.lazy="filter_name">
<div class="content_with_right_button_left_content" >
<input
class="form-control admin_filter_input"
x-model="temp_filter_name"
x-ref="searched"
type="text"
> 1111111
</div>
<div class="content_with_right_button_right_button pl-2" >
<button class="btn btn-outline-secondary nowrap_block" wire:click="makeSearch(this.$refs.searched)" type="button">
Search
</button>
</div>
</div>
But I got error clicking on search button:
VM1983:6 Uncaught TypeError: Cannot read property 'searched' of undefined
at eval (eval at parseOutMethodAndParams (directive.js:55), <anonymous>:6:27)
at _default.parseOutMethodAndParams (directive.js:55)
Looks like it is impossible to use this.$refs. value in
wire:click="makeSearch .
I need to trigger component method
public function makeSearch($search_value='')
{
and send entered value into it.
Looks like the way I tried was invalid.
If there is a valid way?
Thanks!
In your modified block 2, you should use wire:ignore in base div of your AlpineJS component. This will make livewire ignore the component.
<div class="card form-admin-facilities" wire:ignore x-data="adminFacilitiesComponent()">
Your $dispatch() should handle setting the value when you click the button.
In order to make livewire ignore the component just add wire:ignore to your component's div in modified block 2 and then in your dispatch method you can write the logic that happens after clicking the button.

CSRF verification failed. Request aborted when calling Password Reset API with Angular

I am trying to create password reset api using Django Rest Framework and Angular 6. But when I try to do POST call to the password reset url I am receiving error saying "CSRF verification failed. Request aborted"
my url.py file includes:
url(r'password-reset/', auth_views.PasswordResetView.as_view()),
url(r'password-reset/done/', auth_views.PasswordResetDoneView.as_view()),
url(r'password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view()),
url(r'password_reset_complete/',auth_views.PasswordResetCompleteView.as_view())
For the front end I am using Angular as follows:
my forgot-password.html includes:
<navbar></navbar>
<div class="container-fluid px-xl-5">
<section class="py-5">
<div class="row">
<div class="col-lg-12 mb-5">
<div class="card">
<div class="card-header" style="text-align: center;">
<h3 class="h6 text-uppercase mb-0">RESET PASSWORD FORM</h3>
</div>
<div class="card-body">
<form class="form-horizontal" #forgotPassword="ngForm">
<div class="form-group row">
<label class="col-md-3 form-control-label">Email Address</label>
<div class="col-md-6">
<input class="validate" #email="ngModel" [(ngModel)]="input.email" name= "email" type="email" placeholder="Email Address" class="form-control" [pattern]="emailpattern" required>
<div class="alert alert-danger" *ngIf="email.touched && !email.valid">Email is required!</div>
</div>
</div>
<div class="line"></div>
<div class="alert alert-success" *ngIf="successMessage">{{ successMessage }}</div>
<div class="alert alert-danger" *ngIf="errorMessage">{{ errorMessage }}</div>
<div class="form-group row">
<label class="col-md-3 form-control-label"><a routerLink="/login">Back to Login</a></label>
<div class="col-md-12" style="text-align: center;">
<button (click)="submitEmail()" type="submit" class="btn btn-primary shadow" [disabled]="!forgotPassword.valid">Send Reset Link</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</div>
and forgot-password.ts file is as follow:
import { Component, OnInit } from '#angular/core';
import { UsersService } from 'src/app/services/users.service';
#Component({
selector: 'app-forgot-password',
templateUrl: './forgot-password.component.html',
styleUrls: ['./forgot-password.component.scss'],
providers: [UsersService]
})
export class ForgotPasswordComponent implements OnInit {
input;
emailpattern = "[a-z0 - 9!#$%& '*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&' * +/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
errorMessage: string = '';
successMessage: string = '';
constructor(private userService: UsersService) { }
ngOnInit() {
this.input = {
email: ''
};
}
submitEmail() {
this.successMessage = '';
this.errorMessage = '';
this.userService.resetPassword(this.input).subscribe(
response => {
this.successMessage = 'Please Check you mail for password reset link!';
},
error => this.errorMessage = 'Please enter correct email or try again later!'
);
}
}
and finally .service is as follows:
resetPassword(data): Observable<any> {
return this.http.post('http://127.0.0.1:8000/api/password-reset/', data);
}
I am not able to understand what to do and how to solve this issue.
CSRF are usually used if session authentication. SPAs don't use this kind of auth (usually it's used another pattern such as JSON web tokens). You can disable CSRF in the Django as explained here: Django Rest Framework remove csrf

Template Parse Erros Angular "<" (" with Django REST framework

I've been trying to create a DRF API with an Angular front end for an existing project that I have. I've created a serializer for User and Device. I tried removing multiple pieces of the HTML component, managing to result in a different error, StaticInjectorError(AppModule -> DevicePostService).
I'm still pretty new to Angular so what it seems like the error is coming from is the fact that my devicepostservice is not getting served to the web page for some reason.
Console error:
[Error] Error: Template parse errors:
Unexpected character "<" ("
<div class="col-sm-4">
<button (click)="login()" class="btn btn-primary">Log In</button
[ERROR ->]</div>
<div class="col-sm-12">
<span *ngFor="let error of _userService.errors.non_field_errors""): ng:///AppModule/AppComponent.html#15:2
Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("
<div class="col-sm-4">
<button (click)="login()" class="btn btn-primary">Log In</button
[ERROR ->]</div>
<div class="col-sm-12">
<span *ngFor="let error of _userService.errors.non_field_errors""): ng:///AppModule/AppComponent.html#15:2
Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (" <span *ngFor="let error of _userService.errors.non_field_errors">{{ error }}<br /></span>
</div>
[ERROR ->]</div>
<div class="row" *ngIf="_userService.token">
<div class="col-sm-12">You are logged in as {{ "): ng:///AppModule/AppComponent.html#19:0
_preparseLoadedTemplate (vendor.js:24658)
normalizeTemplate (vendor.js:24635)
loadDirectiveMetadata (vendor.js:26827)
(anonymous function) (vendor.js:34471)
forEach
(anonymous function) (vendor.js:34470)
forEach
_loadModules (vendor.js:34467:83)
_compileModuleAndComponents (vendor.js:34445)
compileModuleAsync (vendor.js:34405)
bootstrapModule (vendor.js:53721)
./src/main.ts (main.js:326:116)
__webpack_require__ (runtime.js:79)
(anonymous function) (main.js:339)
__webpack_require__ (runtime.js:79)
checkDeferredModules (runtime.js:46)
webpackJsonpCallback (runtime.js:33)
Global Code (main.js:1)
App.component.html
<h2>Log In</h2>
<div class="row" *ngIf="!_userService.token">
<div class="col-sm-4">
<label>Username:</label><br />
<input type="text" name="login-username" [(ngModel)]="user.username">
<span *ngFor="let error of _userService.errors.username"><br />
{{ error }}</span></div>
<div class="col-sm-4">
<label>Password:</label><br />
<input type="password" name="login-password" [(ngModel)]="user.password">
<span *ngFor="let error of _userService.errors.password"><br />
{{ error }}</span>
</div>
<div class="col-sm-12">
<span *ngFor="let error of _userService.errors.non_field_errors">{{ error }}<br /></span>
</div>
</div>
<div class="row" *ngIf="_userService.token">
<div class="col-sm-12">You are logged in as {{ _userService.username }}.<br />
Token Expires: {{ _userService.token_expires }}<br />
<button (click)="refreshToken()" class="btn btn-primary">Refresh Token</button>
<button (click)="logout()" class="btn btn-primary">Log Out</button>
</div>
</div>
<!--
<h2 class="mt-3">Devices</h2>
<div *ngFor="let device of devices">
<div class="row mb-3">
<label class="col-md-2">Owner:</label>
<div class="col-md-2 mb-1">{{ device.owner }}</div>
<label class="col-md-2">Brand:</label>
<div class="col-md-6">{{ device.brand }}</div>
<div class="col-md-12">{{ device.name }}</div>
</div>
</div>-->
App.component.ts
import {Component, OnInit} from '#angular/core';
import {DevicePostService} from './device_post.service';
import {UserService} from './user.service';
import {throwError} from 'rxjs';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
/**
* An object representing the user for the login form
*/
public user: any;
public devices;
public new_device: any;
constructor(private _devicePostService: DevicePostService, private _userService: UserService) { }
ngOnInit() {
this.getDevices();
this.new_device = {};
this.user = {
username: '',
password: ''
};
}
getDevices() {
this._devicePostService.list().subscribe(
data => {
this.devices = data;
},
err => console.error(err),
() => console.log('done loading devices')
)
}
updateDevice () {
this._devicePostService.create(this.new_device, this.user.token).subscribe(
data => {
this.getDevices();
return true;
},
error => {
console.error('Error saving!');
return throwError(error);
}
);
}
login() {
this._userService.login({'username': this.user.username, 'password': this.user.password});
}
refreshToken() {
this._userService.refreshToken();
}
logout() {
this._userService.logout();
}
}
Seems like you have a basic syntax error in your template
<button (click)="login()" class="btn btn-primary">Log In</button
should be
<button (click)="login()" class="btn btn-primary">Log In</button>
(note the final '>' character)

How to ensure Ember is saving variable state on reload

I'm creating and saving a form using Ember but when I reload the page the toggle keeping track of whether the form has been submitted or not resets to false.
I have a page where the default text is 'You have no account linked'. I then have a button that when pressed displays a form for the user to fill out information . When they click submit and save their information, the form disappears and renders some text about their account. When I reload the page however the text renders to the default 'You have no account linked', and when I click the submit form button, their information is populated in the form fields. How can I ensure that when the page is reloaded the text about the user account is displayed?
This is the controller for the page
export default Controller.extend({
isToggled: false,
emailConnected: false,
actions: {
submitImap(mailbox, toggle, email) {
this.get('ajax').request(`/api/accounts/${this.session.account.id}/mailboxes/imap`, {
method: 'POST',
data: mailbox
})
.then(() => Utils.notify("IMAP settings saved.", 'success'))
.catch(() => Utils.notify("Error saving IMAP account. Try again", 'error'));
this.send('contract', toggle);
this.send('expand', email);
},
disconnectIMAP(mailbox, property, email) {
this.get('ajax').request(`/api/accounts/${this.session.account.id}/mailboxes/imap`, {
method: 'DELETE',
data: {
user_id: mailbox.user_id
}
}).then(() => {
this.set(property, { smtp: {}});
})
.then(() => Utils.notify("IMAP removed. ", 'success'))
.catch(() => Utils.notify("Error removing IMAP account", 'error'));
this.send('contract',email );
},
expand: function(toggle) {
this.set(toggle, true)
},
contract: function(toggle) {
this.set(toggle, false)
}
}
});
This is the template handling the form submission
<h3>IMAP/SMTP</h3>
{{#if emailConnected}}
{{#if isToggled}}
<p> Edit your IMAP settings below </p>
{{else}}
<p>
You currently have IMAP account <strong>{{imapMailbox.username}}</strong>
connected for messaging.
</p>
<button {{action "disconnectIMAP" imapMailbox 'imapMailbox' 'emailConnected' }} class = 'btn btn-danger'>Disconnect</button>
{{/if}}
{{else}}
<p>
You currently do not have an account linked for messaging.
</p>
{{/if}}
{{#if isToggled}}
<form name='imap' class='modern-form full-width' {{action 'submitImap' imapMailbox 'isToggled' 'emailConnected' on="submit" }}>
<div class='row'>
<div class='col-sm-6'>
<h4>IMAP</h4>
<div class='form-group'>
<label>
Host
</label>
{{input type='text' required=true name='address' value=imapMailbox.address class='form-control'}}
</div>
<div class='form-group'>
<label>
Port
</label>
{{input type='text' required=true name='port' value=imapMailbox.port class='form-control'}}
</div>
<div class='form-check'>
{{input type='checkbox' name='ssl' checked=imapMailbox.ssl class='form-check-input'}}
<label for='ssl'>
SSL
</label>
</div>
<div class='form-check'>
{{input type='checkbox' name='starttls' checked=imapMailbox.starttls class='form-check-input'}}
<label>
TLS
</label>
</div>
<div class='form-group'>
<label>
Username
</label>
{{input type='text' required=true name='username' value=imapMailbox.username class='form-control'}}
</div>
<div class='form-group'>
<label>
Password
</label>
{{input type='password' required=true name='password' value=imapMailbox.password class='form-control'}}
</div>
</div>
<div class='col-sm-6'>
<h4>SMTP</h4>
<div class='form-group'>
<label>
Host
</label>
{{input type='text' required=true name='smtp_address' value=imapMailbox.smtp.address class='form-control'}}
</div>
<div class='form-group'>
<label>
Port
</label>
{{input type='text' required=true name='smtp_port' value=imapMailbox.smtp.port class='form-control'}}
</div>
<div class='form-check'>
{{input type='checkbox' name='smtp_ssl' checked=imapMailbox.smtp.ssl class='form-check-input'}}
<label for='ssl'>
SSL
</label>
</div>
<div class='form-check'>
{{input type='checkbox' name='smtp_starttls' checked=imapMailbox.smtp.enable_starttls_auto class='form-check-input'}}
<label>
TLS
</label>
</div>
<div class='form-group'>
<label>
Username
</label>
{{input type='text' required='true' name='smtp_username' value=imapMailbox.smtp.user_name class='form-control'}}
</div>
<div class='form-group'>
<label>
Password
</label>
{{input type='password' required='true' name='smtp_password' value=imapMailbox.smtp.password class='form-control'}}
</div>
</div>
</div>
<button type="submit" class='btn btn-success'>
Save
</button>
<button {{action 'contract' 'isToggled'}} class = 'btn btn-danger'>
Cancel
</button>
</form>
{{else}}
<button {{action 'expand' 'isToggled'}} class= 'btn btn-success'>
Connect email
</button>
{{/if}}
Right now, if I submit the form the behavior is as expected, displaying the current username of the account, but on reload the emailConnected variable resets to false and the default of 'you have no account connected' is present and when I click the form the values are populated.
If you reload the page (or) switch to a different route, the controller's property isToggled will reset to its initial state (i.e) to false in your case.
If you want to maintain the state and make use of the property isToggled at various parts of your application, you can use ember service
But in your case, you want to maintain the property state even after the page reloads. ember service doesn't maintain the state after the page reloads.
Here comes the use of browsers localStorage
So, in your case -
1) store the value of the property isToggled in browsers localStorage
import { computed } from '#ember/object';
export default Controller.extend({
isToggled: computed(function () {
// when the user visits the page for the very first time,
// isToggled value is set to false,
// from next time it gets the value from browsers localStorage.
if (localStorage.isToggled) {
return JSON.parse(localStorage.isToggled);
} else {
return false;
}
}),
...
actions: {
...
expand: function() {
localStorage.setItem('isToggled', JSON.stringify(true));
this.set('isToggled', true);
},
contract: function() {
localStorage.setItem('isToggled', JSON.stringify(false));
this.set('isToggled', false);
}
...
}
});
Now when the page is reloaded the isToggled property state doesn't change to the initial state.
You can find the isToggle browsers localStorage variable in your browsers developer tool: Application -> Local Storage tab
You could also use Ember Local Storage library to achieve this: https://github.com/funkensturm/ember-local-storage

Laravel 5.5 The email and password field is required

I am new and installed Laravel 5.5 and trying to work on login functionality. I am using custom fields to login; user_name and user_password. When I submit I am getting
The email field is required.
The password field is required.
but my fields are user_name and user_password in the user table
Login controller
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectAfterLogout = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Logout, Clear Session, and Return.
*
* #return void
*/
public function logout()
{
$user = Auth::user();
Log::info('User Logged Out. ', [$user]);
Auth::logout();
Session::flush();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
protected function getCredentials(Request $request){
return $request->only('user_name', 'user_password');
}
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<div>
<a class="hiddenanchor" id="signup"></a>
<a class="hiddenanchor" id="signin"></a>
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<form class="form-horizontal" role="form" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<h1>Login Form</h1>
<div>
<input id="email" type="email" class="form-control" name="user_name" value="{{ old('user_name') }}" required autofocus>
</div>
<div>
<input id="password" type="password" class="form-control" name="user_password" required>
</div>
<div>
<button type="submit" name="login" class="btn btn-default submit">Log in</button>
<a class="reset_pass" href="#">Lost your password?</a>
</div>
<div class="clearfix"></div>
<div class="separator"></div>
</form>
</section>
</div>
</div>
</div>
You are using the trait AuthenticatesUsers and it is responsible for validating the data after the user submitted the form. If you take a look at this file, you will see this method:
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
More specifically, as you can see, this method is in charge for calling the validator on the fields name "password" and by the method username(). If you only wanted to custom the username field, you could overwrite the username() method in LoginController class:
public function username()
{
return 'user_name';
}
But since you want to custom both the username field name and the password field name, I suggest that you overwrite the validateLogin() method in the LoginController class:
protected function validateLogin(Request $request)
{
$this->validate($request, [
'user_name' => 'required|string',
'user_password' => 'required|string',
]);
}
Hope that helps.
You must go to app/User.php and change
protected $fillable = [
'name', 'email', 'password',
];
to
protected $fillable = [
'name', 'user_email', 'user_password',
];
It will solve your problem. But i must suggest to you change your view form field to email, password instead of user_name, user_password