Laravel Authentication - Username and Password in different tables - laravel-5.5

getting problem with authentication in laravel as I have username and password in different tables.As Auth uses same table for username and password but my database is already setup where the the username is in table users and the password is in table webpages_membership, and I cant change the database structure because that database is used by other mobile application and website too. So how do I use Auth for login system.
#btl:
I tried the solution but now there is another error of
"Undefined index: password" in vendor\laravel\framework\src\Illuminate\Auth\GenericUser.php
following is my user model code.
Code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\WebPages_Membership;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'Users';
protected $dbPrefixOveride = '';
protected $primaryKey = 'UserId';
protected $fillable = [
'Username', 'FirstName', 'LastName','Email','MobileNumber','CreatedBy','CreatedDate','ModifiedBy','ModifiedDate','DistributorId','Telephone','IsAuthorized','AlternateMobileNumber','AlternateEmail','IsDeleted','UnauthorizationRemark'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
/*protected $hidden = [
'password', 'remember_token',
];*/
public function webpagesMembership() {
return $this->hasOne(WebPages_Membership::class);
}
public function getPasswordAttribute() {
return $this->webpagesMembership->getAttribute('Password');
}
}
?>

I'd do something like this. Assuming a one-to-one relationship between your tables.
Define a relationship between User and WebpagesMembership models. Your User model would have the following:
public function webpagesMembership() {
return $this->hasOne(WebpagesMembership::class);
}
Add an accessor function
public function getPasswordAttribute() {
return $this->webpagesMembership->getAttribute('password');
}
That way Auth will work when it attempts to access the password attribute on your User model.
Edit:
Add password to the User model's $appends property:
protected $appends = [
'password'
];
This will act as if it were an attribute on the model now. The error you encountered was because the GenericUser's attributes were being set in the constructor and password did not exist. It then attempted to access password in:
public function getAuthPassword()
{
return $this->attributes['password'];
}
Hence, the undefined index.

Related

how to structure a mutation in vuex orm graphql to connect with django graphql backend

I'm having problems making queries and creating / updating / deleting things in django graphql through the graphql plugin of vuex orm.
From the interface provided by django to execute queries, I can perfectly use my mutations and consult any particular data or any collection of them.
I'm going to write an example of how I create an object called "TipoProducto" from the django interface:
mutation myMutation {
createTipoProducto(input: {nombre:"Pizza", descripcion:"foobar"}) {
tipoProducto {nombre, descripcion}
status
}
}
This code will return the object with its attributes and a status 200 if it was successful.
The Django classes in the schema:
class TipoProductoNode(DjangoObjectType):
class Meta:
model = TipoProducto
filter_fields = ['nombre', 'productos']
interfaces = (relay.Node, )
class TipoProducto(graphene.ObjectType):
nombre = graphene.String()
descripcion = graphene.String()
class CreateTipoProducto(graphene.ClientIDMutation):
class Input:
nombre = graphene.String(required=True)
descripcion = graphene.String(required=True)
tipo_producto = graphene.Field(TipoProducto)
status = graphene.Int()
ok = graphene.Boolean()
def mutate_and_get_payload(self, info, nombre, descripcion, client_id_mutation=None):
tipo_producto = TipoProductoNode._meta.model(nombre=nombre, descripcion=descripcion)
tipo_producto.save()
return CreateTipoProducto(tipo_producto=tipo_producto, ok=bool(tipo_producto.id), status=200)
My model in vuex orm:
import { Model } from '#vuex-orm/core';
import Product from './Product'
export default class TipProd extends Model {
static entity = "tipProds"
static fields () {
return {
id: this.increment(),
nombre: this.attr(''),
descripcion: this.attr(''),
producto: this.hasMany(Product, 'tipProd_id')
}
}
}
This is the method I try to use to create a new object "TipoProducto":
methods: {
async register (tipProduct) {
await TipProd.insert({
data:
tipProduct
});
const tipProd = TipProd.query().last()
await tipProd.$mutate({ name: 'createTipoProducto' });
}
where data: tipProducto are the attributes taken from a form
I can not find the way that vuex orm correctly structured the query to create an object. What am I doing wrong?
I did not get apollo devtools to work in order to debug the exit of the vuex-orm. I have no idea how the query is being created.
Sorry for the english and thanks.
The structure was fine, I could not see the query because there was none, I failed the connection between Django Graphene and Vuex-ORM Graphql plugin, since the API side had badly defined mutations.

Loopback ACL hide 'apikey' column

I have a user model with one of the columns is 'apikey'. I just want that 'apikey' can be accessed only by its user.
Should I use a different model such as 'Account' which columns are 'apikey' and its id, and make ACL to that model?
Or, should I tweak the remote method?
Any suggestions on how to do that?
I would delete the property apikey before giving the response to the client, based on user permissions.
This is a code example, you should adapt it to your needs.
User.afterRemote('findById', (context, user, next) => {
let userId = context.req.accessToken.userId
if (!userId || user.id !== userId) {
context.result.apykey = undefined
}
next()
})

Doctrine Native Query does not load related entities even if I add addMetaResult mapping

I have 2 tables:
users - id, firstName, lastName
posts - id, title, content, user_id
I'm trying to load entities with native query:
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Entity\Post', 'p');
$rsm->addFieldResult('p', 'id', 'id');
$rsm->addFieldResult('p', 'title', 'title');
$rsm->addMetaResult('p', 'user_id', 'user_id');
$sql = 'select p.id, p.title, p.user_id from posts p';
$query = $em->createNativeQuery($sql, $rsm);
$posts = $query->getResult();
Doctrine loads "Post" entity, and fills "User" relation, but all attributes of "User" entity is NULL. Why it doesn't load "User" entity with proxy object? For what does "addMetaResult" exists?
Actually if you call get_class on "User", than you'll see that it is a doctrine proxy. All attributes are nulls because proxy is not loaded. Call on of "getter" methods (for example getFirstName()) on one of attribute and doctrine will load class and fill all other attributes.

Testing Model Save

I'm trying to do a very basic test:
public function testUsernameIsRequired(){
$user = new User;
$user->email = "phil#ipbrown.com";
// User should not save
$this->assertFalse($user->save());
}
on the following model:
class User extends Eloquent implements UserInterface, RemindableInterface {
use SoftDeletingTrait;
protected $fillable = array('email', 'username', 'password');
public static $rules = array(
'email' => 'required|min:3',
'username' => 'required|min:3',
'password' => 'required|min:3'
);
}
According to my thinking (...yeah) this test should succeed, as a User model which gets saved without required fields doesn't actually save.
But this Model somehow does save, doesn't throw any errors and creates a completely empty User.
Any ideas as to what I'm doing wrong?
$rules is just something you made up - it wont work out of the box like that. You need to actually validate the models against the rules to enforce it on save.
Laravel 4 - Trouble overriding model's save method will do what you want without Ardent.

Doctrine2 - Inheritance and relation

Is it possible to solve this problem in doctrine? I have one entity, called Comment and this entity have relation with another entity caller Author. The relation is made througt two columns: author_id and author_type
/**
* #ORM\Entity
* #ORM\Table(name="comments")
*/
class Comment
{
/**
* #ORM\ManyToOne(targetEntity="Entities\Authors\Guest", cascade={"persist"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="author_id", referencedColumnName="author_id", nullable=FALSE),
* #ORM\JoinColumn(name="author_type", referencedColumnName="author_type", nullable=FALSE)
* })
**/
protected $author;
}
This relation is because author could be system user, guest, facebook user, etc. and each user have their own author id and author type (guest, system, facebook, etc.) so the author entity look like this:
/**
* #ORM\Entity
* #ORM\Table(name="authors")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="author_type", type="string")
* #ORM\DiscriminatorMap({
* "guest" = "Guest",
* "system" = "System",
* "facebook" = "Facebook",
* "twitter" = "Twitter",
* "google" = "Google",
* "github" = "Github"
* })
*/
class Guest
{
}
To separate each author type i use single table inheritance. with column author_type. Primary key for author table is author_id and author_type
When i load comment entity, it is successfully loaded with author, but problem is when i try to create new comment entity and store it to the database. The author_id stored in comment table is ok, but author_type is always "guest" even if correct author entity is added to the comment entity.
So is there possibility to solve this? Or should i use diffrent type of relation, add extra column etc.?