@@ -11,6 +11,7 @@ import {
11
11
findUserByUsernameOrEmail as _findUserByUsernameOrEmail ,
12
12
updateUserById as _updateUserById ,
13
13
updateUserPrivilegeById as _updateUserPrivilegeById ,
14
+ updateUserVerification as _updateUserVerification ,
14
15
} from "../model/repository" ;
15
16
import {
16
17
validateEmail ,
@@ -22,6 +23,10 @@ import {
22
23
import { IUser } from "../model/user-model" ;
23
24
import { upload } from "../config/multer" ;
24
25
import { uploadFileToFirebase } from "../utils/utils" ;
26
+ import redisClient from "../config/redis" ;
27
+ import crypto from "crypto" ;
28
+ import { sendMail } from "../utils/mailer" ;
29
+ import { ACCOUNT_VERIFICATION_SUBJ } from "../utils/constants" ;
25
30
26
31
export async function createUser (
27
32
req : Request ,
@@ -77,6 +82,14 @@ export async function createUser(
77
82
email ,
78
83
hashedPassword
79
84
) ;
85
+
86
+ const emailToken = crypto . randomBytes ( 16 ) . toString ( "hex" ) ;
87
+ await redisClient . set ( email , emailToken , { EX : 60 * 5 } ) ; // expire in 5 minutes
88
+ const emailText = `Hello ${ username } ,\n\n
89
+ Please click on the following link to verify your account:\n\nhttp://localhost:3001/api/users/verify-email/${ email } /${ emailToken } \n\n
90
+ If you did not request this, please ignore this email.` ;
91
+ await sendMail ( email , ACCOUNT_VERIFICATION_SUBJ , emailText ) ;
92
+
80
93
return res . status ( 201 ) . json ( {
81
94
message : `Created new user ${ username } successfully` ,
82
95
data : formatUserResponse ( createdUser ) ,
@@ -94,6 +107,41 @@ export async function createUser(
94
107
}
95
108
}
96
109
110
+ export const verifyUser = async (
111
+ req : Request ,
112
+ res : Response
113
+ ) : Promise < Response > => {
114
+ try {
115
+ const { email, token } = req . params ;
116
+
117
+ const user = await _findUserByEmail ( email ) ;
118
+ if ( ! user ) {
119
+ return res . status ( 404 ) . json ( { message : `User ${ email } not found` } ) ;
120
+ }
121
+
122
+ const expectedToken = await redisClient . get ( email ) ;
123
+
124
+ if ( expectedToken !== token ) {
125
+ return res
126
+ . status ( 400 )
127
+ . json ( { message : "Invalid token. Please request for a new one." } ) ;
128
+ }
129
+
130
+ const updatedUser = await _updateUserVerification ( email ) ;
131
+ if ( ! updatedUser ) {
132
+ return res . status ( 404 ) . json ( { message : `User ${ email } not verified.` } ) ;
133
+ }
134
+
135
+ return res
136
+ . status ( 200 )
137
+ . json ( { message : `User ${ email } verified successfully.` } ) ;
138
+ } catch {
139
+ return res
140
+ . status ( 500 )
141
+ . json ( { message : "Unknown error when verifying user!" } ) ;
142
+ }
143
+ } ;
144
+
97
145
export const createImageLink = async (
98
146
req : Request ,
99
147
res : Response
0 commit comments