Skip to content

Commit 765fdc8

Browse files
committed
finished register user
1 parent 03dce7e commit 765fdc8

File tree

3 files changed

+68
-1
lines changed

3 files changed

+68
-1
lines changed

server/cmd/api/auth.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package main
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/gin-gonic/gin"
7+
"github.com/kunalkumar-1/Evently/internals/database"
8+
"golang.org/x/crypto/bcrypt"
9+
)
10+
11+
type registerRequest struct {
12+
Email string `json:"email" binding:"required,email"`
13+
Password string `json:"password" binding:"required,min=8"`
14+
Name string `json:"name" binding:"required,min=3,max=50"`
15+
}
16+
17+
func (app *application) registerUser(c *gin.Context) {
18+
var register registerRequest
19+
20+
if err := c.ShouldBindJSON(&register); err != nil {
21+
c.JSON(http.StatusBadRequest, gin.H{
22+
"error": err.Error(),
23+
})
24+
return
25+
}
26+
27+
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(register.Password), bcrypt.DefaultCost)
28+
if err != nil {
29+
c.JSON(http.StatusInternalServerError, gin.H{
30+
"error": "Something went wrong while Hashing password",
31+
})
32+
return
33+
}
34+
35+
register.Password = string(hashedPassword)
36+
user := &database.User{
37+
Email: register.Email,
38+
Password: register.Password,
39+
Name: register.Name,
40+
}
41+
42+
err = app.models.Users.Insert(user)
43+
if err != nil {
44+
c.JSON(http.StatusInternalServerError, gin.H{
45+
"error": "Failed to register user",
46+
})
47+
return
48+
}
49+
50+
c.JSON(http.StatusCreated, user)
51+
}

server/cmd/api/routes.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ func (app *application) routes() http.Handler {
1616
v1.GET("/events/:id", app.getEvent) // get event by id
1717
v1.PUT("/events/:id", app.updateEvent) // update event by id
1818
v1.DELETE("/events/:id", app.deleteEvent) //delete the event by id
19+
20+
v1.POST("/register", app.registerUser) // register user
1921
}
2022

2123
return r

server/internals/database/users.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package database
22

3-
import "database/sql"
3+
import (
4+
"context"
5+
"database/sql"
6+
"time"
7+
)
48

59
type UserModel struct {
610
Db *sql.DB
@@ -12,3 +16,13 @@ type User struct {
1216
Email string `json:"email"`
1317
Password string `json:"-"`
1418
}
19+
20+
func (u *UserModel) Insert(user *User) error {
21+
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
22+
defer cancel()
23+
24+
query := `INSERT INTO users(name, email, password) VALUES($1, $2, $3) RETURNING id`
25+
26+
return u.Db.QueryRowContext(ctx, query, user.Name, user.Email, user.Password).Scan(&user.Id)
27+
28+
}

0 commit comments

Comments
 (0)