Skip to content

Commit

Permalink
Add /role endpoint for provide role to user
Browse files Browse the repository at this point in the history
Signed-off-by: anisurrahman75 <sunny.cse7575@gmail.com>
  • Loading branch information
anisurrahman75 committed Feb 18, 2024
1 parent 207bccd commit 49c7fa3
Show file tree
Hide file tree
Showing 17 changed files with 343 additions and 107 deletions.
9 changes: 0 additions & 9 deletions handlers/user/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,3 @@ func (u *User) validate(w http.ResponseWriter) bool {
// TODO
return true
}

func (u *User) verify() (bool, error) {
//valid, err := user.VerifyLoginData(u.FClient, u.User)
//if err != nil {
// return false, err
//}
//return valid, nil
return true, nil
}
35 changes: 31 additions & 4 deletions handlers/user/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,16 @@ func (u *User) SignUp(w http.ResponseWriter, r *http.Request) {
return
}
u.UUID = uuid.NewString()
u.Role = string(models.Student)
if err := u.User.AddFormDataToMongo(); err != nil {
error.HandleError(w, http.StatusBadRequest, "failed to add form data into database", err)
if u.Email == "praromvik.hq@gmail.com" {
u.Role = string(models.Admin)
} else {
u.Role = string(models.Student)
}
if err := u.User.AddUserDataToMongo(); err != nil {
error.HandleError(w, http.StatusBadRequest, "failed to add form data into mongodb", err)
}
if err := u.User.AddUserAuthDataToFirestore(); err != nil {
error.HandleError(w, http.StatusBadRequest, "failed to add form data into firestore", err)
}
w.WriteHeader(http.StatusOK)
} else {
Expand All @@ -68,7 +75,7 @@ func (u *User) SignIn(w http.ResponseWriter, r *http.Request) {
error.HandleError(w, http.StatusBadRequest, "Error on parsing JSON", err)
return
}
valid, err := u.verify()
valid, err := u.User.VerifyLoginData()
if err != nil && status.Code(err) != codes.NotFound {
error.HandleError(w, http.StatusUnauthorized, "failed to login", err)
return
Expand All @@ -92,3 +99,23 @@ func (u *User) SignOut(w http.ResponseWriter, r *http.Request) {
return
}
}

func (u User) ProvideRoleToUser(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if err := json.NewDecoder(r.Body).Decode(&u.User); err != nil {
error.HandleError(w, http.StatusBadRequest, "Error on parsing JSON", err)
return
}
if err := u.UpdateUserDataToMongo(); err != nil {
error.HandleError(w, http.StatusBadRequest, "Error on Update User", err)
return
}
if err := u.UpdateUserAuthDataToFirestore(); err != nil {
error.HandleError(w, http.StatusBadRequest, "Error on Update User", err)
return
}
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusBadRequest)
}
}
9 changes: 5 additions & 4 deletions models/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ package models
type RoleType string

const (
Admin RoleType = "Admin"
Moderator RoleType = "Moderator"
Trainer RoleType = "Trainer"
Student RoleType = "Student"
Admin RoleType = "admin"
Moderator RoleType = "moderator"
Trainer RoleType = "trainer"
Student RoleType = "student"
None RoleType = ""
)

// Constant for Session base Auth
Expand Down
21 changes: 10 additions & 11 deletions models/course/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,20 @@ SOFTWARE.
package course

import (
"github.com/praromvik/praromvik/models/user"
"google.golang.org/genproto/googleapis/type/date"
)

type Course struct {
CourseId string `json:"courseId"`
Title string `json:"title"`
Description string `json:"description"`
Instructors []user.Instructor `json:"instructors"`
StartDate date.Date `json:"startDate"`
EndDate date.Date `json:"endDate"`
Duration int `json:"duration"` // Duration in week
EnrollmentCapacity int `json:"enrollmentCapacity"`
EnrollmentStudents []user.User `json:"enrollmentStudents"`
Lessons []Lesson `json:"lessons"`
CourseId string `json:"courseId"`
Title string `json:"title"`
Description string `json:"description"`
Instructors []string `json:"instructors"`
StartDate date.Date `json:"startDate"`
EndDate date.Date `json:"endDate"`
Duration int `json:"duration"` // Duration in week
EnrollmentCapacity int `json:"enrollmentCapacity"`
EnrollmentStudents []string `json:"enrollmentStudents"`
Lessons []Lesson `json:"lessons"`
}

type Lesson struct {
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
64 changes: 64 additions & 0 deletions models/db/firestore.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
MIT License
Copyright (c) 2024 Praromvik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package db

import (
"cloud.google.com/go/firestore"

"context"
"fmt"

"github.com/praromvik/praromvik/models/db/client"
)

type Firestore struct{}

func (_ Firestore) GetDocument(collName string, id string) (*firestore.DocumentSnapshot, error) {
dSnap, err := client.Firestore.Collection(collName).Doc(id).Get(context.Background())
if err != nil {
return nil, err
}
return dSnap, nil
}

func (_ Firestore) AddDocument(collName string, id string, data interface{}) error {
_, err := client.Firestore.Collection(collName).Doc(id).Create(context.Background(), data)
if err != nil {
return err
}

fmt.Printf("Inserted document with _id: %v\n", id)
return nil
}

func (_ Firestore) UpdateDocument(collName string, id string, data interface{}) error {
_, err := client.Firestore.Collection(collName).Doc(id).Set(context.Background(), data)
if err != nil {
return err
}

fmt.Printf("Update Document with id %s\n", id)
return nil
}
64 changes: 64 additions & 0 deletions models/db/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
MIT License
Copyright (c) 2024 Praromvik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package db

import (
"fmt"

"github.com/praromvik/praromvik/models/db/client"

"go.mongodb.org/mongo-driver/mongo"

"reflect"
)

func getDBCollection(dbAndCollList []string) (*mongo.Collection, error) {
if len(dbAndCollList) == 0 {
return nil, fmt.Errorf("empty database name")
} else if len(dbAndCollList)%2 == 1 {
return nil, fmt.Errorf("invalid number of DB and collection names provided, must be even")
}
db, collection := &mongo.Database{}, &mongo.Collection{}
for i, val := range dbAndCollList {
if i%2 == 0 {
db = client.Mongo.Database(val)
} else {
collection = db.Collection(val)
}
}
return collection, nil
}

func MergeStruct(oldStruct interface{}, newStruct interface{}) {
oldValue, newValue := reflect.ValueOf(oldStruct).Elem(), reflect.ValueOf(newStruct)
for i := 0; i < oldValue.NumField(); i++ {
oldFieldValue, newFieldValue := oldValue.Field(i), newValue.Field(i)
if oldFieldValue.Kind() == reflect.Struct {
MergeStruct(oldFieldValue.Addr().Interface(), newFieldValue.Interface())
} else if !reflect.DeepEqual(newFieldValue.Interface(), reflect.Zero(newFieldValue.Type()).Interface()) {
oldFieldValue.Set(newFieldValue)
}
}
}
70 changes: 70 additions & 0 deletions models/db/mongo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
MIT License
Copyright (c) 2024 Praromvik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package db

import (
"context"
"fmt"

"go.mongodb.org/mongo-driver/mongo"
)

type Mongo struct{}

func (_ Mongo) GetDocument(dbAndCollList []string, filter interface{}) (*mongo.SingleResult, error) {
collection, err := getDBCollection(dbAndCollList)
if err != nil {
return nil, err
}
result := collection.FindOne(context.TODO(), filter)
return result, nil
}

func (_ Mongo) AddDocument(dbAndCollList []string, data interface{}) error {
collection, err := getDBCollection(dbAndCollList)
if err != nil {
return err
}
result, err := collection.InsertOne(context.TODO(), data)
if err != nil {
return err
}
fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)
return nil
}

func (_ Mongo) UpdateDocument(dbAndCollList []string, filter interface{}, newDocument interface{}) error {
collection, err := getDBCollection(dbAndCollList)
if err != nil {
return err
}
result, err := collection.ReplaceOne(context.TODO(), filter, newDocument)
if err != nil {
return fmt.Errorf("failed to update document: %v", err)
}
fmt.Printf("Update Document. Result. MatchedCount:"+
" %d, UpsertedCount: %d, ModifiedCount: %d.\n", result.MatchedCount, result.UpsertedCount, result.ModifiedCount)
return nil
}
17 changes: 5 additions & 12 deletions models/user/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,10 @@ SOFTWARE.
package user

type User struct {
UserName string `json:"userName"`
Email string `json:"email"`
Password string `json:"password"`
Phone string `json:"phone"`
Role string `json:"role"`
UserName string `json:"userName" bson:"userName"`
Email string `json:"email" bson:"email"`
Password string `json:"password" bson:"password"`
Phone string `json:"phone" bson:"phone"`
Role string `json:"role" bson:"role"`
UUID string
}

type Instructor struct {
InstructorId string `json:"instructorId"`
Name string `json:"name"`
Phone string `json:"phone"`
Email string `json:"email"`
}
Loading

0 comments on commit 49c7fa3

Please sign in to comment.