Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ui #6

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .env

This file was deleted.

24 changes: 24 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
.env
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/ui/node_modules
/.pnp
.pnp.js

# testing
/ui/coverage

# production
/ui/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
40 changes: 38 additions & 2 deletions api/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func ConnectDB() *gorm.DB {

func CreateUser(db *gorm.DB, user User) error {
// Append to the User in User table
if result := db.Create(&user); result.Error != nil {
if result := db.FirstOrCreate(&user, User{Phone: user.Phone}); result.Error != nil {
return result.Error
}

Expand Down Expand Up @@ -146,11 +146,47 @@ func AddBetHistory(db *gorm.DB, bethistory []BetHistory) error {
return nil
}

func GetBets(db *gorm.DB, gameid int, bets *[]Bet) error {
func GetBetsbyGameID(db *gorm.DB, gameid int, bets *[]Bet) error {

if result := db.Where("game_id=?", gameid).Find(&bets); result.Error != nil {
return result.Error
}

return nil
}

func GetBetsByUserID(db *gorm.DB, userid int, bets *[]Bet) error {

if result := db.Where("user_id=?", userid).Find(&bets); result.Error != nil {
return result.Error
}
return nil
}

func GetPastBets(db *gorm.DB, userid int, pastbets *[]BetHistory) error {

if result := db.Where("user_id=?", userid).Find(&pastbets); result.Error != nil {
return result.Error
}
return nil
}

func GetUsers(db *gorm.DB, users *[]User) error {

if result := db.Find(&users); result.Error != nil {
return result.Error
}
return nil
}


func DeleteUserbyID(db *gorm.DB, userid int) error {
var user User
if result := db.First(&user, userid); result.Error != nil {
return result.Error
}
if result := db.Delete(&user); result.Error != nil {
return result.Error
}
return nil
}
70 changes: 69 additions & 1 deletion api/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ func DeclairWinnerController(app *Config) gin.HandlerFunc {

var bets []Bet

if err := GetBets(db, winner.GameID, &bets); err != nil {
if err := GetBetsbyGameID(db, winner.GameID, &bets); err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to parse Games data from DB", Data: err.Error()})

return
Expand All @@ -279,6 +279,8 @@ func DeclairWinnerController(app *Config) gin.HandlerFunc {
bethistory := BetHistory{
ResultTime: time.Now().UTC(),
PlacedBet: bet.ID,
UserId: bet.UserId,
BetAmount: bet.Amount,
}
if winner.Result == bet.Number {
bethistory.Winner = true
Expand Down Expand Up @@ -406,3 +408,69 @@ func WithdrawCashController(app *Config) gin.HandlerFunc {

}
}

func GetBetsByUserIDController(app *Config) gin.HandlerFunc {
return func(ctx *gin.Context) {
// Fetched UserID from request param
userid, err := strconv.Atoi(ctx.Param("userid"))
if err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to parse userid from request body while fetching Bets", Data: err.Error()})
return
}
var bets []Bet
err = GetBetsByUserID(db, userid, &bets)
if err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to get Bets from DB", Data: err.Error()})
return
}
ctx.JSON(http.StatusOK, JsonResponse{Status: http.StatusOK, Message: "Bets fetched successfully", Data: bets})
}
}

func GetPastBetsController(app *Config) gin.HandlerFunc {
return func(ctx *gin.Context) {
// Fetched UserID from request param
userid, err := strconv.Atoi(ctx.Param("userid"))
if err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to parse userid from request body while fetching past Bets", Data: err.Error()})
return
}
var pastbets []BetHistory
err = GetPastBets(db, userid, &pastbets)
if err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to get pas Bets from DB", Data: err.Error()})
return
}
ctx.JSON(http.StatusOK, JsonResponse{Status: http.StatusOK, Message: "Past Bets fetched successfully", Data: pastbets})
}
}

func GetUsersController(app *Config) gin.HandlerFunc {
return func(ctx *gin.Context) {
// Fetched UserID from request param
var users []User
err := GetUsers(db, &users)
if err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to get Users from DB", Data: err.Error()})
return
}
ctx.JSON(http.StatusOK, JsonResponse{Status: http.StatusOK, Message: "Users fetched successfully", Data: users})
}
}

func DeleteUserController(app *Config) gin.HandlerFunc {
return func(ctx *gin.Context) {
// Fetched UserID from request param
userid, err := strconv.Atoi(ctx.Param("userid"))
if err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to parse userid from request body while deleting User", Data: err.Error()})
return
}
err = DeleteUserbyID(db, userid)
if err != nil {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to delete User from DB", Data: err.Error()})
return
}
ctx.JSON(http.StatusOK, JsonResponse{Status: http.StatusOK, Message: "User deleted successfully", Data: nil})
}
}
2 changes: 1 addition & 1 deletion api/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func generateJWT(phone string) (string, error) {

claims["authorized"] = true
claims["phone"] = phone
claims["exp"] = time.Now().Add(time.Minute * 10).Unix()
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()

tokenString, err := token.SignedString(sampleSecretKey)

Expand Down
18 changes: 17 additions & 1 deletion api/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func ValidateJWT(app *Config) gin.HandlerFunc {
_, cancel := context.WithTimeout(context.Background(), appTimeout)
defer cancel()

token := ctx.GetHeader("auth-key")
token := ctx.GetHeader("Authorization")

if token == "" {
ctx.JSON(http.StatusForbidden, JsonResponse{Status: http.StatusForbidden, Message: "failed to extract jwt token from request"})
Expand All @@ -32,3 +32,19 @@ func ValidateJWT(app *Config) gin.HandlerFunc {

}
}

// Add middleware for cors handling
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
2 changes: 2 additions & 0 deletions api/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,10 @@ type BetHistory struct {
gorm.Model
ID int `json:"id,omitempty" validate:"required" bson:"_id" gorm:"primaryKey"`
PlacedBet int `json:"placed_bet,omitempty" validate:"required" bson:"placed_bet"`
UserId int `json:"userid,omitempty" validate:"required" bson:"user_id"`
ResultTime time.Time `json:"result_time,omitempty" validate:"required" bson:"result_time"`
Winner bool `json:"winner,omitempty" validate:"required" bson:"winner"`
BetAmount int `json:"bet_amount,omitempty" validate:"required" bson:"bet_amount"`
}

type Cash struct {
Expand Down
4 changes: 4 additions & 0 deletions api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ func (app *Config) Routes() {
app.Router.POST("/getgames", GetGamesController(app))
app.Router.POST("/reschedulegame/", RescheduleGameController(app))
app.Router.POST("/addbet/:userid", AddBetController(app))
app.Router.GET("/getbets/:userid", GetBetsByUserIDController(app))
app.Router.POST("/declairewinner/", DeclairWinnerController(app))
app.Router.POST("/addcash/:userid", AddCashController(app))
app.Router.POST("/withdrawcash/:userid", WithdrawCashController(app))
app.Router.GET("/getpastbets/:userid", GetPastBetsController(app))
app.Router.GET("/getusers", GetUsersController(app))
app.Router.DELETE("/deleteuser/:userid", DeleteUserController(app))

}
2 changes: 2 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ func main() {

router := gin.Default()

router.Use(api.CORSMiddleware())

app := api.Config{Router: router}

app.Routes()
Expand Down
23 changes: 23 additions & 0 deletions ui/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
70 changes: 70 additions & 0 deletions ui/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.

The page will reload when you make changes.\
You may also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can't go back!**

If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.

You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)

### Analyzing the Bundle Size

This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)

### Making a Progressive Web App

This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)

### Advanced Configuration

This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)

### Deployment

This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)

### `npm run build` fails to minify

This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Loading