Skip to content

Commit

Permalink
Added Authentication Data (#2)
Browse files Browse the repository at this point in the history
Co-authored-by: arpankumarde <[email protected]>
  • Loading branch information
kevalkanp1011 and arpankumarde authored Jul 25, 2024
1 parent a620f2b commit 10b56e0
Show file tree
Hide file tree
Showing 30 changed files with 4,392 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dist/
node_modules/
.env
18 changes: 18 additions & 0 deletions data/dao/user/UserDAO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { User } from '../../db_models/User';
import { Otp } from "../../db_models/Otp";
import { RegisterUserData } from '../../../domain/models/RegisterUserData';

export interface UserDAO {

insertUser(userData: RegisterUserData): Promise<User>;

fetchUser(userId: number): Promise<User>;

fetchUserByEmail(email: string): Promise<User>;

getOtp(email: string, timestamp: number): Promise<Otp>;

insertOtp(email: string, otp: string): Promise<Otp>;

updatePassword(email: string, password: string): Promise<Boolean>;
}
139 changes: 139 additions & 0 deletions data/dao/user/UserDAOImpl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { Otp } from "../../db_models/Otp";
import { RegisterUserData } from "../../../domain/models/RegisterUserData";
import { User } from "../../db_models/User";
import { FetchUserByEmail, FetchUserUserDAO, InsertOTPUserDAO, InsertUserUSerDAO, IsEmailExistUserDAO, OTPNotFoundInDB, UnknownDatabaseError, UserNotFoundInDB } from "../../../routes/auth/errorhandling/ErrorCodes";
import { AuthError, DatabaseError } from "../../../routes/auth/errorhandling/ErrorUtils";
import { UserDAO } from "./UserDAO";




export class UserDAOImpl implements UserDAO {

async updatePassword(email: string, password: string): Promise<Boolean> {
try {
const [updatedCount] = await User.update({ password_hash: password }, { where: { email: email } });
return updatedCount == 1
} catch (error) {
throw new DatabaseError("e is not a instance of Error: UserDAOImpl --- updatePassword", UnknownDatabaseError);
}
}

async insertOtp(email: string, otp: string): Promise<Otp> {
try {
const now = new Date()
const otpData = await Otp.create({ email: email, otp_hash: otp, generated_at: now.getTime() })
return otpData
} catch (error) {
if (error instanceof AuthError) {
throw error
} else if (error instanceof Error) {
throw new DatabaseError(error.message, InsertOTPUserDAO);
} else {
throw new DatabaseError("e is not a instance of Error: UserDAOImpl --- insertOtp", UnknownDatabaseError);
}
}
}

async getOtp(email: string, timestamp: number): Promise<Otp> {
try {


const otpRow = await Otp.findOne({
where: {
email: email,
generated_at: timestamp
}
});

if (otpRow == null) {
throw new AuthError("otp with email: " + email + "doesn't exist in the database", OTPNotFoundInDB)
}

return otpRow
} catch (error) {
if (error instanceof AuthError) {
throw error
} else if (error instanceof Error) {
throw new DatabaseError("error.message", IsEmailExistUserDAO);
} else {
throw new DatabaseError("e is not a instance of Error: UserDAOImpl --- getOtp", UnknownDatabaseError);
}
}
}




async insertUser(userData: RegisterUserData): Promise<User> {

try {
const user = await User.create({ name: userData.name, email: userData.email, password_hash: userData.password_hash })
return user
} catch (error) {
if (error instanceof AuthError) {
throw error
} else if (error instanceof Error) {
throw new DatabaseError(error.message, InsertUserUSerDAO);
} else {
throw new DatabaseError("e is not a instance of Error: UserDAOImpl --- insertUser", UnknownDatabaseError);
}
}


}

async fetchUser(userId: number): Promise<User> {

try {
const user = await User.findByPk(userId);

if (user == null) {
throw new AuthError("user with id: " + userId + "is not found in the database", UserNotFoundInDB)
}
return user;
} catch (error) {
if (error instanceof AuthError) {
throw error
} else if (error instanceof Error) {
throw new DatabaseError(error.message, FetchUserUserDAO);
} else {
throw new DatabaseError("e is not a instance of Error: UserDAOImpl --- fetchUser", UnknownDatabaseError);
}
}


}

async fetchUserByEmail(email: string): Promise<User> {

try {
const emailToFind = email;
const user = await User.findOne({
where: {
email: emailToFind
}
});
if (user == null) {
throw new AuthError("user with email: " + email + " is not found in the database", UserNotFoundInDB)
}
return user;
} catch (error) {

if (error instanceof AuthError) {
throw error
} else if (error instanceof Error) {
throw new DatabaseError(error.message, FetchUserByEmail);
} else {
throw new DatabaseError("e is not a instance of Error: UserDAOImpl --- fetchUserByEmail", UnknownDatabaseError);
}
}


}


}



54 changes: 54 additions & 0 deletions data/db_models/Otp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Model, Optional, DataTypes, Sequelize } from 'sequelize';

interface OtpAttributes {
id: number;
email: string;
otp_hash: string;
generated_at: number;
};


interface OtpCreationAttributes extends Optional<OtpAttributes, 'id'> {}

export class Otp extends Model<OtpAttributes, OtpCreationAttributes> {
declare id: number;
declare email: string;
declare otp_hash: string;
declare generated_at: number;

}

export function initOtp(sequelize: Sequelize) {

Otp.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
//unique: true,
},
otp_hash: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
generated_at: {
type: DataTypes.BIGINT,
allowNull: false, // Optional timestamp
},

},
{
sequelize,
tableName: 'otps'
}
).sync({ alter: true });

}


61 changes: 61 additions & 0 deletions data/db_models/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Model, Optional, DataTypes, Sequelize } from 'sequelize';

interface UserAttributes {
id: number;
name: string;
email: string;
password_hash: string;
// other attributes...
};

interface UserCreationAttributes extends Optional<UserAttributes, 'id'> {}

export class User extends Model<UserAttributes, UserCreationAttributes> {
declare id: number;
declare name: string;
declare email: string;
declare password_hash: string;

public readonly createdAt!: Date;
public readonly updatedAt!: Date;
// other attributes...

}

export function initUser(sequelize: Sequelize) {

User.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password_hash: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},

},
{
sequelize: sequelize,
tableName: 'users2',
timestamps: true

}
).sync({
alter: true
});

}

5 changes: 5 additions & 0 deletions data/requests/GenerateOTPReq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@


export interface GenerateOTPReq {
email: string
}
5 changes: 5 additions & 0 deletions data/requests/LoginUserReq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

export interface LoginUserReq {
email: string;
password: string;
}
6 changes: 6 additions & 0 deletions data/requests/RegisterUserReq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

export interface RegisterUserReq {
name: string,
email: string;
password: string;
}
5 changes: 5 additions & 0 deletions data/requests/ResetPasswordReq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

export interface ResetPasswordReq {
email: string,
new_password: string
}
6 changes: 6 additions & 0 deletions data/requests/VerifyOTPReq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

export interface VerifyOTPReq {
email: string,
otp: string,
created_on: number
}
9 changes: 9 additions & 0 deletions data/responses/LoginUserResData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@


export interface LoginUserResData {

access_token: string,
user_id: number,
name: string,
email: string
}
6 changes: 6 additions & 0 deletions data/responses/VerifyOtpResData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@


export interface VerifyOtpResData {
email: string,
access_token: string
}
7 changes: 7 additions & 0 deletions db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Sequelize } from 'sequelize';

const connectionString = process.env.DATABASE_URL as string

const sequelize = new Sequelize(connectionString);

export default sequelize;
20 changes: 20 additions & 0 deletions di/container.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { UserDAOImpl } from '../data/dao/user/UserDAOImpl';
import { Container } from 'brandi';
import { TOKENS } from './tokens';
import { AuthService } from '../services/AuthService';



export const container = new Container();

container
.bind(TOKENS.userDao)
.toInstance(UserDAOImpl)
.inTransientScope();

container
.bind(TOKENS.authService)
.toInstance(AuthService)
.inTransientScope();


9 changes: 9 additions & 0 deletions di/tokens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { token } from 'brandi';
import { UserDAO } from '../data/dao/user/UserDAO';
import { AuthService } from '../services/AuthService';

export const TOKENS = {
userDao: token<UserDAO>('user_dao'),
authService: token<AuthService>('auth_service'),

};
5 changes: 5 additions & 0 deletions domain/models/RegisterUserData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface RegisterUserData {
name: string,
email: string;
password_hash: string;
}
Loading

0 comments on commit 10b56e0

Please sign in to comment.