23
loading...
This website collects cookies to deliver better user experience
bcrypt
hashing implementation but now it became more standartized, the use of PHC string format allows to incorporate different hashers and verify the hashes against the current configuration and then decide if the hash needs to be rehashed or not.legacy
driverlegacy
driverargon2
node ace make:provider LegacyHasher
/providers
folder. After the file has been generated, we have to add it to .adonisrc.json
into providers
section.Hash
driver, as an example we can use the code provided in an official documentation here./providers
, named it LegacyHashDriver
and placed my legacy
driver there (inside an index.ts
file).import bcrypt from 'bcrypt';
import { HashDriverContract } from '@ioc:Adonis/Core/Hash';
/**
* Implementation of custom bcrypt driver
*/
export class LegacyHashDriver implements HashDriverContract {
/**
* Hash value
*/
public async make(value: string) {
return bcrypt.hash(value);
}
/**
* Verify value
*/
public async verify(hashedValue: string, plainValue: string) {
return bcrypt.compare(plainValue, hashedValue);
}
}
bcrypt
package, you'll have to install it before running.Hash
core library.import { ApplicationContract } from '@ioc:Adonis/Core/Application';
import { LegacyHashDriver } from './LegacyHashDriver';
export default class LegacyHasherProvider {
constructor(protected app: ApplicationContract) {}
public async boot() {
const Hash = this.app.container.use('Adonis/Core/Hash');
Hash.extend('legacy', () => {
return new LegacyHashDriver();
});
}
}
contracts/hash.ts
:declare module '@ioc:Adonis/Core/Hash' {
interface HashersList {
bcrypt: {
config: BcryptConfig;
implementation: BcryptContract;
};
argon: {
config: ArgonConfig;
implementation: ArgonContract;
};
legacy: {
config: {};
implementation: HashDriverContract;
};
}
}
config/hash.ts
:...
legacy: {
driver: 'legacy',
},
...
const usesLegacyHasher = /^\$2[aby]/.test(user.password);
let isMatchedPassword = false;
if (usesLegacyHasher) {
isMatchedPassword = await Hash.use('legacy').verify(user.password, password);
} else {
isMatchedPassword = await Hash.verify(user.password, password);
}
try {
const token = await auth.use('api').generate(user);
// rehash user password
if (usesLegacyHasher) {
user.password = await Hash.make(password);
await user.save();
}
return response.ok({
message: 'ok',
user,
token,
});
} catch (e) {
return response.internalServerError({ message: e.message });
}