Skip to content

Commit

Permalink
Merge pull request #27 from aau-network-security/feature/add-booking-…
Browse files Browse the repository at this point in the history
…helper-#000

Feature/add booking helper #000
  • Loading branch information
mrtrkmn authored Jul 8, 2020
2 parents f1c2e54 + 4b199df commit 90e67e7
Show file tree
Hide file tree
Showing 13 changed files with 1,189 additions and 257 deletions.
20 changes: 14 additions & 6 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,13 @@ jobs:

- name: Download example config file
run: |
curl -o config.yml https://gist.githubusercontent.com/mrturkmen06/cc5becf2d8413ea18c27a5bb2aa4106f/raw/7c95ab9747124766357eaf910834364acab7e897/config.yml
curl -o config.yml https://gist.githubusercontent.com/mrturkmencom/cc5becf2d8413ea18c27a5bb2aa4106f/raw/2fc5b3fd415846f0b993a67d20d0094309f00698/config.yml
- name: Download certs
run: |
curl -o haaukins-store.com.crt https://gist.githubusercontent.com/mrturkmencom/da480dd97f74c7a9581d6a69d5b2e984/raw/cbc2e338800d81a904c320999e44ec38b721ff5c/haaukins-store.com.crt
curl -o localhost_50051.key https://gist.githubusercontent.com/mrturkmencom/12132d60247e24041b954ee43d5e5cb1/raw/f18d0f0f96539fb424d1c463ec7e60ae8f846d0c/localhost_50051.key
curl -o localhost_50051.crt https://gist.githubusercontent.com/mrturkmencom/fc57419e46a859a031e11aa10b97c9e1/raw/109b1e64340c7394dcd9f7295969659d3cbc72af/localhost_50051.crt
- name: Get dependencies
run: |
Expand All @@ -54,11 +60,13 @@ jobs:
./server &
- name: Run Tests
run: go test ./tests
run: go test -v ./...
env:
CERT: ./certs/localhost_50051.crt
CERT_KEY: ./certs/localhost_50051.key
CA: ./certs/haaukins-store.com.crt
CERT: ./../localhost_50051.crt
CERT_KEY: ./../localhost_50051.key
CA: ./../haaukins-store.com.crt

- name: Teardown resources # more stuff could be added in the future
run : rm -rf config.yml
run : |
rm -rf config.yml
rm -rf *.crt *.key
11 changes: 6 additions & 5 deletions client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import (
"crypto/x509"
"errors"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"google.golang.org/grpc/credentials"
"io/ioutil"
"log"
"time"

jwt "github.com/dgrijalva/jwt-go"
"google.golang.org/grpc/credentials"

pb "github.com/aau-network-security/haaukins-store/proto"
"google.golang.org/grpc"
)
Expand Down Expand Up @@ -47,7 +48,7 @@ func main() {
test_auth_key := "c41ec030-db76-473f-a504-5a7323aa04ec"
test_sign_key := "34b16c10-1a2c-4533-83e8-cfde78817501"
testCertPath := "/home/ubuntu/haaukins_main/configs/certs/localhost.crt"
testCertKeyPath:= "/home/ubuntu/haaukins_main/configs/certs/localhost.key"
testCertKeyPath := "/home/ubuntu/haaukins_main/configs/certs/localhost.key"
testCAPath := "/home/ubuntu/haaukins_main/configs/certs/haaukins-store.com.crt"

token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
Expand Down Expand Up @@ -88,7 +89,7 @@ func main() {
RootCAs: certPool,
})

dialOpts = append(dialOpts, grpc.WithTransportCredentials(creds),grpc.WithPerRPCCredentials(authCreds))
dialOpts = append(dialOpts, grpc.WithTransportCredentials(creds), grpc.WithPerRPCCredentials(authCreds))

} else {
authCreds.Insecure = true
Expand All @@ -107,7 +108,7 @@ func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

r, err := c.GetEvents(ctx, &pb.EmptyRequest{})
r, err := c.GetEvents(ctx, &pb.GetEventRequest{})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
Expand Down
29 changes: 19 additions & 10 deletions database/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ var (
"status integer, " +
"frontends text, " +
"exercises text, " +
"started_at varchar (100), " +
"finish_expected varchar (100), " +
"finished_at varchar (100));"
"started_at timestamp, " +
"finish_expected timestamp, " +
"finished_at timestamp);"

CreateTeamsTable = "CREATE TABLE IF NOT EXISTS Team(" +
"id serial primary key, " +
Expand All @@ -21,27 +21,36 @@ var (
"email varchar (50), " +
"name varchar (50), " +
"password varchar (250), " +
"created_at varchar (100), " +
"last_access varchar (100), " +
"created_at timestamp, " +
"last_access timestamp, " +
"solved_challenges text);"

AddTeamQuery = "INSERT INTO team (tag, event_id, email, name, password, created_at, last_access, solved_challenges)" +
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"

AddEventQuery = "INSERT INTO event (tag, name, available, capacity, frontends, status, exercises, started_at, finish_expected)" +
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)"
AddEventQuery = "INSERT INTO event (tag, name, available, capacity, frontends, status, exercises, started_at, finish_expected, finished_at)" +
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"

UpdateCloseEvent = "UPDATE event SET tag = $2, finished_at = $3 WHERE tag = $1"
UpdateEventStatus = "UPDATE event SET status = $2 WHERE tag = $1 "

UpdateEventFinishDate = "UPDATE event SET finished_at = $2 WHERE tag = $1"
UpdateEventStatus = "UPDATE event SET status = $2 WHERE tag = $1 "
UpdateEventLastaccessedDate = "UPDATE team SET last_access = $2 WHERE tag = $1"
UpdateTeamSolvedChl = "UPDATE team SET solved_challenges = $2 WHERE tag = $1"

QuerySolvedChls = "SELECT solved_challenges FROM team WHERE tag=$1"
QueryEventTable = "SELECT * FROM event"

QueryEventId = "SELECT id FROM event WHERE tag=$1 and finished_at is null"
// finished_at '0001-01-01 00:00:00 means event does not finished yet '
QueryEventId = "SELECT id FROM event WHERE tag=$1 and finished_at = date('0001-01-01 00:00:00'); "
QueryEventTeams = "SELECT * FROM team WHERE event_id=$1"
QueryTeamCount = "SELECT count(team.id) FROM team WHERE team.event_id=$1"

QueryEventStatus = "SELECT status FROM event WHERE tag=$1"
QueryEventsByStatus = "SELECT * FROM event WHERE status=$1"
QueryIsEventExist = "SELECT EXISTS (select 1 from event where tag=$1 and status!=$2)"
// finished_at '0001-01-01 00:00:00 means event does not finished yet '
EarliestDate = "SELECT started_at FROM event WHERE started_at=(SELECT MIN(started_at) FROM event) and finished_at = date('0001-01-01 00:00:00');"
LatestDate = "SELECT finish_expected FROM event WHERE finish_expected =(SELECT max(finish_expected) FROM event) and finished_at = date('0001-01-01 00:00:00');"
// DropEvent is used in dropping booked events
DropEvent = "DELETE FROM event WHERE tag=$1 and status=$2"
)
59 changes: 48 additions & 11 deletions database/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
const handleNullConversionError = "converting NULL to string is unsupported"

var (
timeFormat = "2006-01-02 15:04:05"
TimeFormat = "2006-01-02 15:04:05"
OK = "ok"
Error = int32(3)

Expand All @@ -39,12 +39,14 @@ type Store interface {
AddTeam(*pb.AddTeamRequest) (string, error)
GetEvents(*pb.GetEventRequest) ([]model.Event, error)
GetTeams(string) ([]model.Team, error)

IsEventExists(*pb.GetEventByTagReq) (bool, error)
DropEvent(req *pb.DropEventReq) (bool, error)
GetCostsInTime() (map[string]int32, error)
GetEventStatus(*pb.GetEventStatusRequest) (int32, error)
SetEventStatus(*pb.SetEventStatusRequest) (int32, error)
UpdateTeamSolvedChallenge(*pb.UpdateTeamSolvedChallengeRequest) (string, error)
UpdateTeamLastAccess(*pb.UpdateTeamLastAccessRequest) (string, error)
UpdateEventFinishDate(*pb.UpdateEventRequest) (string, error)
UpdateCloseEvent(*pb.UpdateEventRequest) (string, error)
}

func NewStore(conf *model.Config) (Store, error) {
Expand Down Expand Up @@ -84,7 +86,11 @@ func (s *store) AddEvent(in *pb.AddEventRequest) (string, error) {
s.m.Lock()
defer s.m.Unlock()

_, err := s.db.Exec(AddEventQuery, in.Tag, in.Name, in.Available, in.Capacity, in.Frontends, in.Status, in.Exercises, in.StartTime, in.ExpectedFinishTime)
startTime, _ := time.Parse(TimeFormat, in.StartTime)
finishTime, _ := time.Parse(TimeFormat, in.FinishedAt)
expectedFinishTime, _ := time.Parse(TimeFormat, in.ExpectedFinishTime)

_, err := s.db.Exec(AddEventQuery, in.Tag, in.Name, in.Available, in.Capacity, in.Frontends, in.Status, in.Exercises, startTime, expectedFinishTime, finishTime)

if err != nil {
return "", err
Expand All @@ -97,14 +103,13 @@ func (s *store) AddTeam(in *pb.AddTeamRequest) (string, error) {
defer s.m.Unlock()

now := time.Now()
nowString := now.Format(timeFormat)

var eventId int
if err := s.db.QueryRow(QueryEventId, in.EventTag).Scan(&eventId); err != nil {
return "", err
}

_, err := s.db.Exec(AddTeamQuery, in.Id, eventId, in.Email, in.Name, in.Password, nowString, nowString, "[]")
_, err := s.db.Exec(AddTeamQuery, in.Id, eventId, in.Email, in.Name, in.Password, now, now, "[]")
if err != nil {
return "", err
}
Expand Down Expand Up @@ -188,6 +193,16 @@ func (s *store) GetTeams(tag string) ([]model.Team, error) {
return teams, nil
}

func (s *store) GetCostsInTime() (map[string]int32, error) {
s.m.Lock()
defer s.m.Unlock()
m, err := calculateCost(s.db)
if err != nil {
return nil, err
}
return m, nil
}

func (s *store) UpdateTeamSolvedChallenge(in *pb.UpdateTeamSolvedChallengeRequest) (string, error) {
s.m.Lock()
defer s.m.Unlock()
Expand Down Expand Up @@ -241,11 +256,11 @@ func (s *store) UpdateTeamLastAccess(in *pb.UpdateTeamLastAccessRequest) (string
return OK, nil
}

func (s *store) UpdateEventFinishDate(in *pb.UpdateEventRequest) (string, error) {
func (s *store) UpdateCloseEvent(in *pb.UpdateEventRequest) (string, error) {
s.m.Lock()
defer s.m.Unlock()

_, err := s.db.Exec(UpdateEventFinishDate, in.EventId, in.FinishedAt)
_, err := s.db.Exec(UpdateCloseEvent, in.OldTag, in.NewTag, in.FinishedAt)
if err != nil {
return "", err
}
Expand All @@ -262,8 +277,6 @@ func (s *store) GetEventStatus(in *pb.GetEventStatusRequest) (int32, error) {
return Error, err
}

log.Printf("Status for event: %s, event: %s \n", status, in.EventTag)

return status, nil

}
Expand All @@ -275,11 +288,35 @@ func (s *store) SetEventStatus(in *pb.SetEventStatusRequest) (int32, error) {
if err != nil {
return Error, err
}
log.Printf("Status updated for event: %s, status: %s \n", in.EventTag, in.Status)

return in.Status, nil
}

func (s *store) IsEventExists(in *pb.GetEventByTagReq) (bool, error) {
var isEventExists bool
r := s.db.QueryRow(QueryIsEventExist, in.EventTag, in.Status)
if err := r.Scan(&isEventExists); err != nil {
return false, err
}
return isEventExists, nil
}

func (s *store) DropEvent(in *pb.DropEventReq) (bool, error) {
r, err := s.db.Exec(DropEvent, in.Tag, in.Status)
if err != nil {
return false, err
}
count, err := r.RowsAffected()
if err != nil {
return false, fmt.Errorf("affected number of rows error %v", err)
}
if count > 0 {
return true, nil
}
return false, fmt.Errorf("either no such an event or something else happened")

}

//
//func (s *store) GetEventsByStatus () ([]model.Event, error) {
// s.m.Lock()
Expand Down
40 changes: 32 additions & 8 deletions tests/store_test.go → database/store_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package tests
package database

import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"os"
"strconv"
"testing"
"time"

pb "github.com/aau-network-security/haaukins-store/proto"
"github.com/dgrijalva/jwt-go"
Expand Down Expand Up @@ -65,7 +68,6 @@ func TestStoreConnection(t *testing.T) {

for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {

tokenString, err := tc.token.SignedString([]byte(SIGNIN_VALUE))
if err != nil {
t.Fatalf("Error creating the token")
Expand Down Expand Up @@ -186,7 +188,13 @@ func createTestClientConn() (*grpc.ClientConn, error) {
}

func TestAddEvent(t *testing.T) {
t.Log("Testing AddEvent and GetEvents functions")
dbConn, err := createDBConnection()
if err != nil {
t.Fatalf("error on database connection create %v", err)
}
if err := cleanRecords(dbConn); err != nil {
t.Fatalf("error on cleaning records %v", err)
}
conn, err := createTestClientConn()
if err != nil {
t.Fatal(err)
Expand All @@ -202,17 +210,23 @@ func TestAddEvent(t *testing.T) {
Available: 1,
Capacity: 2,
StartTime: "2020-05-20 14:35:01",
Status: 1,
ExpectedFinishTime: "2020-05-21 14:35:01",
FinishedAt: "0001-01-01 00:00:00", // it means that event is not finished yet
}

_, err = c.AddEvent(context.Background(), &req)
resp, err := c.AddEvent(context.Background(), &req)
if err != nil {
t.Fatal(err)
}
events, err := c.GetEvents(context.Background(), &pb.GetEventRequest{})
if resp.ErrorMessage != "" {
t.Fatal(errors.New(resp.ErrorMessage))
}
events, err := c.GetEvents(context.Background(), &pb.GetEventRequest{Status: 1})
if err != nil {
t.Fatal(err)
}

if len(events.Events) != 1 {
t.Fatal("Error getting the stored events")
}
Expand Down Expand Up @@ -287,16 +301,18 @@ func TestTeamUpdateLastAccess(t *testing.T) {
}

func TestCloseEvent(t *testing.T) {

t.Log("Testing UpdateEventFinishDate function")
conn, err := createTestClientConn()
if err != nil {
t.Fatal(err)
}
defer conn.Close()
c := pb.NewStoreClient(conn)

_, err = c.UpdateEventFinishDate(context.Background(), &pb.UpdateEventRequest{
EventId: "test",
newTag := fmt.Sprintf("%s-%s", "test", strconv.Itoa(int(time.Now().Unix())))
_, err = c.UpdateCloseEvent(context.Background(), &pb.UpdateEventRequest{
OldTag: "test",
NewTag: newTag,
FinishedAt: "2020-05-21 14:35:00",
})
if err != nil {
Expand All @@ -305,6 +321,13 @@ func TestCloseEvent(t *testing.T) {
}

func TestMultipleEventWithSameTag(t *testing.T) {
dbConn, err := createDBConnection()
if err != nil {
t.Fatalf("error on database connection create %v", err)
}
if err := cleanRecords(dbConn); err != nil {
t.Fatalf("error on cleaning records %v", err)
}
t.Log("Testing Multiple Events with same Tags")
conn, err := createTestClientConn()
if err != nil {
Expand All @@ -319,6 +342,7 @@ func TestMultipleEventWithSameTag(t *testing.T) {
Frontends: "kali",
Exercises: "ftp,xss,wc,jwt",
Available: 1,
Status: 1,
Capacity: 2,
StartTime: "2020-06-20 14:35:01",
ExpectedFinishTime: "2020-06-21 14:35:01",
Expand Down
Loading

0 comments on commit 90e67e7

Please sign in to comment.