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 { OBAuthIdConfig, OBAuthIdModel, OBAuthId, OBAuthIdJson,} from "../types"; import {obAuthIdSchema as authId} from "../schemas"; const refs = getSchemaRefs(authId); export const obAuthIdModels:IModelCreator = async m => { authId.plugin(mongooseUniqueValidator); authId.statics._populate = async function(o?:OBAuthId){ await o.populate(refs).execPopulate(); return o;}; authId.statics._find = async function(o:Partial|string){ if(!o) return m.e.badinfo(); const p = typeof o == "string"? await OBAuthId.findById(o): await OBAuthId.findOne(OBAuthId.translateAliases(o)); if(!p) throw m.e.doesNotExist("authenticationId"); return p;}; authId.statics._create = async function(o:OBAuthIdConfig){return new OBAuthId({...o});}; authId.statics._update = async function(o:OBAuthId,p:DeepPartial){ await o.set(p).save(); return await OBAuthId._populate(o);}; authId.statics._remove = async function(o:OBAuthId){return await o.remove().then(() => ({removed:o._id}));}; authId.statics._query = async function(o:IQuery){ const {query,populate,limit,skip,sort,select} = o; const results:OBAuthId[] = await this.find(this.translateAliases(query)) .populate(populate) //.where(where) .limit(limit) .skip(skip) .sort(sort) .exec(); const authIds = mapSelectedData(select,results); return {authIds};}; authId.methods.setCode = async function(s:string){ this.verification = await hash(s); this.verified = null; return await this.save();}; authId.methods.valid = async function(s:string){ if(!await compare(s,this.verification)) throw m.e.mismatch("username or pin"); this.verified = new Date(); this.verification = null; return await this.save();}; authId.methods.json = function(){ const {id,created,updated,email,handle,next,verified} = this as OBAuthId; const json = {id,created,updated,username:handle||email,email,verified,token:next} as OBAuthIdJson; return json;}; const OBAuthId = m.db.model("onebrother","OBAuthId",authId); await OBAuthId.init(); return {OBAuthId}; };