Skip to content
Snippets Groups Projects
Commit 2bc4493b authored by michael.minelli's avatar michael.minelli
Browse files

User model class

parent 2694b105
No related branches found
No related tags found
No related merge requests found
import Session from '../controllers/Session';
import Config from '../config/Config';
import Toolbox from '../shared/Toolbox';
import * as bcrypt from 'bcryptjs';
import Model from './Model';
import db from '../helpers/DatabaseHelper';
class User extends Model {
userID: number = null;
userFirstName: string = '';
userLastName: string = '';
userMail: string = null;
userRole: string = null;
userDeleted: boolean = null;
userPassword: string = null;
unencryptedPassword: string = null; // This value is not set from the db. It's a value that is not null only if we have called createPassword function
currentSession: Session = null;
public async toJsonObject(lightVersion: boolean): Promise<Object> {
const result = {
'id' : this.userID,
'firstName': this.userFirstName,
'lastName' : this.userLastName,
'mail' : this.userMail,
'role' : this.userRole,
'deleted' : this.userDeleted
};
return result;
};
get fullName(): string {
return this.userLastName.toUpperCase() + ' ' + this.userFirstName;
}
public importFromJsonObject(jsonObject: any) {
this.userID = jsonObject.id;
this.userFirstName = jsonObject.firstName;
this.userLastName = jsonObject.lastName;
this.userMail = jsonObject.mail;
this.userRole = jsonObject.role;
this.userDeleted = jsonObject.deleted;
}
public generateHashedPassword() {
this.userPassword = bcrypt.hashSync(this.unencryptedPassword, Config.userPasswordSaltRounds);
}
public replacePassword(password: string) {
this.unencryptedPassword = password;
this.generateHashedPassword();
}
public createPassword() {
this.unencryptedPassword = Toolbox.randomString(Config.userPasswordLength);
this.generateHashedPassword();
}
public toDb(): any {
return {
userFirstName: Toolbox.capitalizeName(this.userFirstName),
userLastName : Toolbox.capitalizeName(this.userLastName),
userRole : this.userRole,
userMail : this.userMail,
userPassword : this.userPassword
};
}
create(): Promise<void> {
return db(User.tableName).insert(this.toDb());
}
update(): Promise<void> {
return db(User.tableName).where('userID', this.userID).update(this.toDb());
}
updatePassword(): Promise<void> {
return db(User.tableName).where('userID', this.userID).update({ 'userPassword': this.userPassword });
}
del(): Promise<void> {
return db(User.tableName).where('userID', this.userID).update({ 'userDeleted': true });
}
}
export default User;
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment