File tree Expand file tree Collapse file tree 1 file changed +39
-1
lines changed
Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Original file line number Diff line number Diff line change 1+ import config from "../../config/config" ;
2+
13import { Request , Response } from "express" ;
24import User , { IUser } from "../../models/User" ;
5+ import bcrypt from "bcrypt" ;
6+ import jwt from "jsonwebtoken" ;
7+
8+ function createToken ( user : IUser ) {
9+ return jwt . sign (
10+ {
11+ id : user . id ,
12+ email : user . email ,
13+ } ,
14+ config . secretKey ,
15+ {
16+ expiresIn : 60 * 60 * 24 ,
17+ }
18+ ) ;
19+ }
320
421export const signUp = async (
522 req : Request ,
@@ -21,4 +38,25 @@ export const signUp = async (
2138 return res . status ( 201 ) . json ( newUser ) ;
2239} ;
2340
24- export const signIn = ( req : Request , res : Response ) => { } ;
41+ export const signIn = async (
42+ req : Request ,
43+ res : Response
44+ ) : Promise < Response > => {
45+ if ( ! req . body . email || ! req . body . password ) {
46+ return res
47+ . status ( 400 )
48+ . json ( { msg : "Please, send your email and password." } ) ;
49+ }
50+
51+ const user = await User . findOne ( { email : req . body . email } ) ;
52+ if ( ! user ) {
53+ return res . status ( 400 ) . json ( { msg : "User does not exixts!" } ) ;
54+ }
55+
56+ const isMatch = await bcrypt . compare ( req . body . password , user . password ) ;
57+ if ( isMatch ) {
58+ return res . status ( 201 ) . json ( { token : createToken ( user ) } ) ;
59+ }
60+
61+ return res . status ( 400 ) . json ( { msg : "The email or password are incorrect!" } ) ;
62+ } ;
You can’t perform that action at this time.
0 commit comments