@@ -2,8 +2,10 @@ package main
22
33import (
44 "net/http"
5+ "time"
56
67 "github.com/gin-gonic/gin"
8+ "github.com/golang-jwt/jwt/v4"
79 "github.com/kunalkumar-1/Evently/internals/database"
810 "golang.org/x/crypto/bcrypt"
911)
@@ -14,6 +16,15 @@ type registerRequest struct {
1416 Name string `json:"name" binding:"required,min=3,max=50"`
1517}
1618
19+ type loginRequest struct {
20+ Email string `json:"email" binding:"required,email"`
21+ Password string `json:"password" binding:"required,min=8"`
22+ }
23+
24+ type loginResponse struct {
25+ Token string `json:"token"`
26+ }
27+
1728func (app * application ) registerUser (c * gin.Context ) {
1829 var register registerRequest
1930
@@ -49,3 +60,51 @@ func (app *application) registerUser(c *gin.Context) {
4960
5061 c .JSON (http .StatusCreated , user )
5162}
63+
64+ func (app * application ) login (c * gin.Context ) {
65+ var auth loginRequest
66+ if err := c .ShouldBindJSON (& auth ); err != nil {
67+ c .JSON (http .StatusBadRequest , gin.H {
68+ "error" : err .Error (),
69+ })
70+ return
71+ }
72+
73+ existingUser , err := app .models .Users .GetByEmail (auth .Email )
74+ if existingUser == nil {
75+ c .JSON (http .StatusUnauthorized , gin.H {
76+ "error" : "Invlid Email or Password" ,
77+ })
78+ return
79+ }
80+ if err != nil {
81+ c .JSON (http .StatusUnauthorized , gin.H {
82+ "error" : err .Error (),
83+ })
84+ return
85+ }
86+ err = bcrypt .CompareHashAndPassword ([]byte (existingUser .Password ), []byte (auth .Password ))
87+ if err != nil {
88+ c .JSON (http .StatusUnauthorized , gin.H {
89+ "error" : "Invalid Email or Password" ,
90+ })
91+ return
92+ }
93+
94+ token := jwt .NewWithClaims (jwt .SigningMethodHS256 , jwt.MapClaims {
95+ "UserId" : existingUser .Id ,
96+ "expr" : time .Now ().Add (time .Hour * 72 ).Unix (),
97+ })
98+
99+ tokenString , err := token .SignedString ([]byte (app .jwtSecret ))
100+ if err != nil {
101+ c .JSON (http .StatusInternalServerError , gin.H {
102+ "error" : "Error Generating token" ,
103+ })
104+ return
105+ }
106+
107+ c .JSON (http .StatusOK , loginResponse {
108+ Token : tokenString ,
109+ })
110+ }
0 commit comments