This commit is contained in:
64
src/auth/orm/ORMUser.ts
Normal file
64
src/auth/orm/ORMUser.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import {Field, FieldType, Model} from '../../orm'
|
||||
import {Authenticatable, AuthenticatableIdentifier} from '../types'
|
||||
import {Injectable} from '../../di'
|
||||
import * as bcrypt from 'bcrypt'
|
||||
import {Awaitable, JSONState} from '../../util'
|
||||
|
||||
/**
|
||||
* A basic ORM-driven user class.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ORMUser extends Model<ORMUser> implements Authenticatable {
|
||||
|
||||
protected static table = 'users'
|
||||
|
||||
protected static key = 'user_id'
|
||||
|
||||
/** The primary key of the user in the table. */
|
||||
@Field(FieldType.serial, 'user_id')
|
||||
public userId!: number
|
||||
|
||||
/** The unique string-identifier of the user. */
|
||||
@Field(FieldType.varchar)
|
||||
public username!: string
|
||||
|
||||
/** The user's first name. */
|
||||
@Field(FieldType.varchar, 'first_name')
|
||||
public firstName!: string
|
||||
|
||||
/** The user's last name. */
|
||||
@Field(FieldType.varchar, 'last_name')
|
||||
public lastName!: string
|
||||
|
||||
/** The hashed and salted password of the user. */
|
||||
@Field(FieldType.varchar, 'password_hash')
|
||||
public passwordHash!: string
|
||||
|
||||
/** Human-readable display name of the user. */
|
||||
getDisplayIdentifier(): string {
|
||||
return `${this.firstName} ${this.lastName}`
|
||||
}
|
||||
|
||||
/** Unique identifier of the user. */
|
||||
getIdentifier(): AuthenticatableIdentifier {
|
||||
return this.username
|
||||
}
|
||||
|
||||
/** Check if the provided password is valid for the user. */
|
||||
verifyPassword(password: string): Awaitable<boolean> {
|
||||
return bcrypt.compare(password, this.passwordHash)
|
||||
}
|
||||
|
||||
/** Change the user's password, hashing it. */
|
||||
async setPassword(password: string): Promise<void> {
|
||||
this.passwordHash = await bcrypt.hash(password, 10)
|
||||
}
|
||||
|
||||
async dehydrate(): Promise<JSONState> {
|
||||
return this.toQueryRow()
|
||||
}
|
||||
|
||||
async rehydrate(state: JSONState): Promise<void> {
|
||||
await this.assumeFromSource(state)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user