Rework authentication system
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
51
src/auth/repository/orm/ORMUserRepository.ts
Normal file
51
src/auth/repository/orm/ORMUserRepository.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
Authenticatable,
|
||||
AuthenticatableIdentifier,
|
||||
AuthenticatableRepository,
|
||||
} from '../../types'
|
||||
import {Awaitable, Maybe, uuid4} from '../../../util'
|
||||
import {ORMUser} from './ORMUser'
|
||||
import {Container, Inject, Injectable} from '../../../di'
|
||||
import {AuthenticatableAlreadyExistsError} from '../../AuthenticatableAlreadyExistsError'
|
||||
|
||||
/**
|
||||
* A user repository implementation that looks up users stored in the database.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ORMUserRepository extends AuthenticatableRepository {
|
||||
@Inject('injector')
|
||||
protected readonly injector!: Container
|
||||
|
||||
/** Look up the user by their username. */
|
||||
getByIdentifier(id: AuthenticatableIdentifier): Awaitable<Maybe<Authenticatable>> {
|
||||
return (this.injector.getStaticOverride(ORMUser) as typeof ORMUser).query<ORMUser>()
|
||||
.where('username', '=', id)
|
||||
.first()
|
||||
}
|
||||
|
||||
/** Returns true if this repository supports registering users. */
|
||||
supportsRegistration(): boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
/** Create a user in this repository from basic credentials. */
|
||||
async createFromCredentials(username: string, password: string): Promise<Authenticatable> {
|
||||
if ( await this.getByIdentifier(username) ) {
|
||||
throw new AuthenticatableAlreadyExistsError(`Authenticatable already exists with credentials.`, {
|
||||
username,
|
||||
})
|
||||
}
|
||||
|
||||
const user = <ORMUser> this.injector.makeByStaticOverride(ORMUser)
|
||||
user.username = username
|
||||
await user.setPassword(password)
|
||||
await user.save()
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
/** Create a user in this repository from an external Authenticatable instance. */
|
||||
async createFromExternal(user: Authenticatable): Promise<Authenticatable> {
|
||||
return this.createFromCredentials(String(user.getUniqueIdentifier()), uuid4())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user