Skip to content
This repository has been archived by the owner on Dec 13, 2024. It is now read-only.

Commit

Permalink
feat/fix: adds player handlers,dockerfiles & minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
zakhaev26 committed Feb 27, 2024
1 parent 88ff29a commit 6e503fe
Show file tree
Hide file tree
Showing 23 changed files with 230 additions and 70 deletions.
2 changes: 2 additions & 0 deletions auth/cmd/main/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import (
"fmt"
"net/http"

"github.com/p-society/gc-server/auth/internal/db"
"github.com/p-society/gc-server/auth/internal/router"
)

func main() {
db.InitAuth()
fmt.Println("Running...")
http.ListenAndServe(":2609", router.AuthRouter())
}
30 changes: 23 additions & 7 deletions auth/internal/handlers/callback_signup.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import (
"encoding/json"
"net/http"
"strings"
"time"

"github.com/p-society/gc-server/auth/internal/db"
"github.com/p-society/gc-server/auth/internal/utils"
"github.com/p-society/gc-server/auth/pkg/security"
errors "github.com/p-society/gc-server/errors/pkg"
model "github.com/p-society/gc-server/schemas/pkg/models"
)

Expand Down Expand Up @@ -37,21 +39,35 @@ func CallbackVerification(w http.ResponseWriter, r *http.Request) {

if err := p.Valid(); err != nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
errors.SendErrorJson(w, err)
return
}

if err := utils.CheckOTP(p.OTP, reqBody.OTP); err != nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
errors.SendErrorJson(w, err)
return
}

res, _ := db.PlayerCollection.InsertOne(context.TODO(), p)
res, err := db.PlayerCollection.InsertOne(context.TODO(), model.Player{
FirstName: p.FirstName,
LastName: p.LastName,
Email: p.Email,
Password: p.Password,
Role: p.Role,
Branch: p.Branch,
Year: p.Year,
ContactNo: p.ContactNo,
Social: p.Social,
CreatedAt: time.Now(),
})
if err != nil {
// TODO: Handle Error Properly (Duplicacy Mongo..
// @zakhaev26
// )
errors.SendErrorJson(w, err)
return
}

json.NewEncoder(w).Encode(res.InsertedID)
}
34 changes: 15 additions & 19 deletions auth/internal/handlers/signup_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@ import (
"time"

"github.com/golang-jwt/jwt"
"github.com/p-society/gc-server/auth/internal"
"github.com/p-society/gc-server/auth/internal/utils"
"github.com/p-society/gc-server/auth/pkg/security"
enum "github.com/p-society/gc-server/enums/pkg"
errors "github.com/p-society/gc-server/errors/pkg"
model "github.com/p-society/gc-server/schemas/pkg/models"
"golang.org/x/crypto/bcrypt"
)

func SignUpHandler(w http.ResponseWriter, r *http.Request) {
Expand All @@ -23,27 +22,23 @@ func SignUpHandler(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&p)
defer r.Body.Close()
if err != nil {
json.NewEncoder(w).Encode(err)
errors.SendErrorJson(w, err)
return
}
// NOTE: To create PSA , Comment this as of now.
p.Role = enum.PLAYER

err = p.Valid()
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
errors.SendErrorJson(w, err)
return
}

err = utils.IsUniqueInDB(p.Email)
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
return
}
// err = utils.IsUniqueInDB(p.Email)
// if err != nil {
// errors.SendErrorJson(w, err)
// return
// }

p.StandardClaims = jwt.StandardClaims{
IssuedAt: time.Now().Unix(),
Expand All @@ -54,23 +49,24 @@ func SignUpHandler(w http.ResponseWriter, r *http.Request) {
p.OTP = utils.GenerateOTP(6)
fmt.Println(p.OTP)

if err := internal.SendEmail(&p); err != nil {
json.NewEncoder(w).Encode(err.Error())
if err := utils.SendEmail(&p); err != nil {
w.WriteHeader(http.StatusInternalServerError)
errors.SendErrorJson(w, fmt.Errorf("internal server error"))
return
}

hashedPass, err := bcrypt.GenerateFromPassword([]byte(p.Password), 10)
hashedPass, err := security.HashPassword(p.Password)

if err != nil {
errors.SendErrorJson(w, err)
panic(err)
}

p.Password = string(hashedPass)

token, err := security.NewAccessToken(p)
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
errors.SendErrorJson(w, err)
return
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package internal
package utils

func RenderEngine(OTP int) string {
return `
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package internal
package utils

import (
"bytes"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utils
package security

import (
"fmt"
Expand All @@ -9,7 +9,7 @@ import (
func ExtractTokenFromHeader(r *http.Request) (string, error) {

authHeader := r.Header.Get("Authorization")
if authHeader == "" && strings.Split(authHeader, " ")[0] == "Bearer" {
if authHeader == "" || len(authHeader) == 2 {
return "", fmt.Errorf("token not found")
}

Expand Down
7 changes: 7 additions & 0 deletions auth/pkg/security/hash_passwords.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package security

import "golang.org/x/crypto/bcrypt"

func HashPassword(password string) ([]byte, error) {
return bcrypt.GenerateFromPassword([]byte(password), 10)
}
13 changes: 9 additions & 4 deletions auth/pkg/security/rbac.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package security

import (
"encoding/json"
"net/http"

"github.com/p-society/gc-server/auth/internal/utils"
)

type RoleGuard struct {
Expand All @@ -17,10 +16,13 @@ func (rg *RoleGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err error
)

token, err = utils.ExtractTokenFromHeader(r)
if err != nil {
token, err = ExtractTokenFromHeader(r)
if err != nil || token == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
return
}

Expand All @@ -29,6 +31,9 @@ func (rg *RoleGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !contains(rg.AllowedRoles, p.Role) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": "you are not authorized to access this resource",
})
return
}

Expand Down
12 changes: 11 additions & 1 deletion core/cmd/main/main.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
package main

func main() {
import (
"fmt"
"net/http"

"github.com/p-society/gc-server/core/internal"
"github.com/p-society/gc-server/core/internal/db"
)

func main() {
db.Init()
fmt.Println("core live @ 127.0.0.1:8080")
http.ListenAndServe(":8080", internal.Router())
}
46 changes: 45 additions & 1 deletion core/internal/player/handlers/delete_handler.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,51 @@
package handlers

import "net/http"
import (
"context"
"encoding/json"
"net/http"
"time"

"github.com/p-society/gc-server/auth/pkg/security"
"github.com/p-society/gc-server/core/internal/db"
errors "github.com/p-society/gc-server/errors/pkg"
model "github.com/p-society/gc-server/schemas/pkg/models"
"go.mongodb.org/mongo-driver/bson"
)

func DeleteHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

token, err := security.ExtractTokenFromHeader(r)
if err != nil {
errors.SendErrorJson(w, err)
}

p := security.ParseAccessToken(token)

p.IsDeleted = true
p.DeletedBy = p.ID

update := bson.M{
"$set": bson.M{
"isDeleted": true,
"deletedBy": p.ID, //for now ...
"deletedAt": time.Now(),
},
}

filter := bson.M{"_id": p.ID}

var x model.Player
res := db.PlayerCollection.FindOneAndUpdate(context.Background(), filter, update)

if err := res.Decode(&x); err != nil {
errors.SendErrorJson(w, err)
return
}

json.NewEncoder(w).Encode(map[string]interface{}{
"updated": true,
})

}
9 changes: 9 additions & 0 deletions core/internal/player/handlers/get_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package handlers

import "net/http"

func GetHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")


}
52 changes: 51 additions & 1 deletion core/internal/player/handlers/update_handler.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,57 @@
package handlers

import "net/http"
import (
"context"
"encoding/json"
"fmt"
"net/http"

"github.com/p-society/gc-server/auth/pkg/security"
"github.com/p-society/gc-server/core/internal/db"
errors "github.com/p-society/gc-server/errors/pkg"
model "github.com/p-society/gc-server/schemas/pkg/models"
"go.mongodb.org/mongo-driver/bson"
)

func UpdateHandler(w http.ResponseWriter, r *http.Request) {
var (
p map[string]interface{}
)
token, _ := security.ExtractTokenFromHeader(r)
reqP := security.ParseAccessToken(token)
id := reqP.ID
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
errors.SendErrorJson(w, err)
return
}

filter := bson.M{"_id": id}

// Prepare update operation
update := bson.M{
"$set": p,
}

if p["email"] != nil {
w.WriteHeader(http.StatusBadRequest)
errors.SendErrorJson(w, fmt.Errorf("email can't be changed"))
return
}

var x model.Player
res := db.PlayerCollection.FindOneAndUpdate(context.Background(), filter, update)
if res.Err() != nil {
errors.SendErrorJson(w, res.Err())
return
}

// Decode the result into x
if err := res.Decode(&x); err != nil {
errors.SendErrorJson(w, err)
return
}

json.NewEncoder(w).Encode(map[string]interface{}{
"updated": true,
})
}
16 changes: 10 additions & 6 deletions core/internal/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,19 @@ import (
func Router() *mux.Router {
r := mux.NewRouter()

r.Handle("/v0/players/update", &security.RoleGuard{
AllowedRoles: []string{enum.ADMIN, enum.PLATFORM_SUPER_ADMIN, enum.ADMIN},
r.Handle("/v0/players", &security.RoleGuard{
AllowedRoles: []string{enum.ADMIN, enum.PLAYER, enum.PLATFORM_SUPER_ADMIN},
Handler: http.HandlerFunc((handlers.UpdateHandler)),
})
}).Methods("PATCH")

r.Handle("/v0/players/delete", &security.RoleGuard{
AllowedRoles: []string{enum.ADMIN, enum.PLATFORM_SUPER_ADMIN, enum.ADMIN},
r.Handle("/v0/players", &security.RoleGuard{
AllowedRoles: []string{enum.ADMIN, enum.PLATFORM_SUPER_ADMIN, enum.PLAYER},
Handler: http.HandlerFunc((handlers.DeleteHandler)),
})
}).Methods("DELETE")

r.Handle("/v0/players", &security.RoleGuard{
AllowedRoles: []string{enum.ADMIN, enum.PLATFORM_SUPER_ADMIN},
Handler: http.HandlerFunc((handlers.GetHandler)),
}).Methods("GET")
return r
}
8 changes: 8 additions & 0 deletions docker/auth/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FROM golang:latest

WORKDIR /go/src/app

COPY . .

RUN go mod download

1 change: 1 addition & 0 deletions docker/core/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
FROM golang:latest
Empty file added docker/docker-compose.yml
Empty file.
Loading

0 comments on commit 6e503fe

Please sign in to comment.