Files
ETAApi/v2/server/src/Apps/Account/Repository/Objection/index.js
2024-08-05 15:56:23 -06:00

89 lines
2.7 KiB
JavaScript

'use strict';
const { getModel } = require('../../../../Shared/Models/Objection');
const Users = getModel('users');
const Sessions = getModel('users_sessions');
const Companies = getModel('companies');
class SpecificModelRepository{
constructor(){}
async populate( user ){
if( user.company_id ){
const company = await Companies.query().findById( user.company_id );
user.company = company;
}else{
user.company = null;
}
return user;
}
async getByEmail( email ){
const user = await Users.query()
.select( "*" )
.where("email","=",email).first();
return user;
}
async createOne( email, safe_password ){
const user = await Users.query().insert({
email,
password : safe_password,
"name":"No name",
"last_name":"No lastname",
"createdAt" : new Date().toISOString()
});
return await this.populate( user );
}
async findByEmailPassword( email, safe_password ){
const user = await Users.query().select('*')
.where("email","=",email)
.where("password","=",safe_password)
.first();
return await this.populate( user );
}
async updateSessionToken( old_token, token, expiration ){
const entry = await Sessions.query().select('*').where('token','=',old_token).first();
const data = {
token,
expiration,
};
if( entry ){
return await Sessions.query().patch( data ).where('token','=',old_token).first();
}
return null;
}
async updatePassword( userId , safe_password ){
return await Users.query()
.findById( userId )
.patch( { password : safe_password } );
}
async addSessionToken( userId , token, expiration ){
const entry = await Sessions.query().select('*').where("user_id",'=',userId).first();
const data = {
token,
expiration : expiration.toISOString(),
};
if( entry ){
return await Sessions.query()
.findById( entry.id )
.patch(data);
}else{
data.user_id = userId;
return await Sessions.query().insert( data );
}
}
async findBySessionToken( token ){
const session = await Sessions.query().select("*").where("token","=",token).first();
const user = await Users.query().findById( session.user_id );
return await this.populate( user );
}
}
module.exports = new SpecificModelRepository();