import mongooseUniqueValidator from "mongoose-unique-validator"; import {AppMaster} from "@onebro/appmaster"; import { DeepPartial, IModelCreator, IStatus, IQuery, mapSelectedData, getSchemaRefs, ObjectId, hash, compare} from "@onebro/oba-common"; import { OBAuthCredsConfig, OBAuthCredsModel, OBAuthCreds, OBAuthCredsJson,} from "../types"; import {obAuthCredsSchema as creds} from "../schemas"; const refs = getSchemaRefs(creds); export const obAuthCredsModels:IModelCreator = async m => { creds.plugin(mongooseUniqueValidator); creds.statics._populate = async function(o?:OBAuthCreds){ await o.populate(refs).execPopulate(); return o;}; creds.statics._find = async function(o:Partial|string){ if(!o) return m.e.badinfo(); const p = typeof o == "string"? await OBAuthCreds.findById(o): await OBAuthCreds.findOne(OBAuthCreds.translateAliases(o)); if(!p) throw m.e.doesNotExist("credentials"); return p;}; creds.statics._create = async function(o:OBAuthCredsConfig){return new OBAuthCreds({...o});}; creds.statics._update = async function(o:OBAuthCreds,p:DeepPartial){ if(p.pin){await o.setPin(p.pin);delete p.pin;} await o.set(p).save(); return await OBAuthCreds._populate(o);}; creds.statics._remove = async function(o:OBAuthCreds){return await o.remove().then(() => ({removed:o._id}));}; creds.statics._query = async function(o:IQuery){ const {query,populate,limit,skip,sort,select} = o; const results:OBAuthCreds[] = await this.find(this.translateAliases(query)) .populate(populate) //.where(where) .limit(limit) .skip(skip) .sort(sort) .exec(); const credss = mapSelectedData(select,results); return {credss};}; creds.methods.setPin = async function(s:string){ this.pin = await hash(s); this.atttempts = 0; this.reset = null; this.lastReset = new Date(); return await this.save();}; creds.methods.valid = async function(o:Pick){ if(o.pin){ if(!await compare(o.pin,this.pin)) this.attempts++; else{ this.lastLogin = new Date(); this.attempts = 0;}} else this.attempts = this.reset !== o.reset?this.attempts + 1:0; return await this.save();}; creds.methods.json = function(){ const {id,created,updated,lastLogin,lastReset} = this as OBAuthCreds; const json = {id,created,updated,lastLogin,lastReset} as OBAuthCredsJson; return json;}; const OBAuthCreds = m.db.model("onebrother","OBAuthCreds",creds); await OBAuthCreds.init(); return {OBAuthCreds}; };