diff --git a/code_of_conduct.md b/code_of_conduct.md new file mode 100644 index 00000000..429503c7 --- /dev/null +++ b/code_of_conduct.md @@ -0,0 +1,37 @@ +# Code Of Conduct + +## Our Pledge +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards +Examples of behaviour that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologising to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community +Examples of unacceptable behaviour include: + +* The use of sexualised language or imagery, and sexual attention or advances +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting +## Our Responsibilities +Project maintainers are responsible for clarifying and enforcing our standards of acceptable behaviour and will take appropriate and fair corrective action in response to any instances of unacceptable behaviour. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviours that they deem inappropriate, threatening, offensive, or harmful. + +## Scope +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + + +## Enforcement +Instances of abusive, harassing, or otherwise unacceptable behaviour may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. +## Attribution +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4 + + +Attribution +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4 diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index 3428656e..56615249 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -386,10 +386,10 @@ func TestMentorDashboardOK(t *testing.T) { var resMentor controllers.MentorDashboard _ = json.NewDecoder(res.Body).Decode(&resMentor) - fmt.Printf("%+v %+v", testMentor, resMentor) - expectStatusCodeToBe(t, res, http.StatusOK) if !reflect.DeepEqual(testMentor, resMentor) { t.Fatalf("Incorrect data returned from /mentor/dashboard/") + fmt.Printf("Expected mentor dashboard: %#v\n\n", testMentor) + fmt.Printf("Received mentor dashboard: %#v\n", resMentor) } } diff --git a/controllers/profile.go b/controllers/profile.go new file mode 100644 index 00000000..2d59f2ee --- /dev/null +++ b/controllers/profile.go @@ -0,0 +1,86 @@ +package controllers + +import ( + "net/http" + + "github.com/kossiitkgp/kwoc-backend/v2/middleware" + "github.com/kossiitkgp/kwoc-backend/v2/utils" + "gorm.io/gorm" + + "github.com/kossiitkgp/kwoc-backend/v2/models" +) + +type ProfileResBodyFields struct { + Username string `json:"username"` + Name string `json:"name"` + Email string `json:"email"` + // `mentor` or `student` + Type string `json:"type"` +} + +// FetchProfile godoc +// @Summary Fetches user profile +// @Description Fetches the user's profile from the JWT, if it is valid. If invalid, returns an error. +// @Accept plain +// @Produce json +// @Success 200 {object} ProfileResBodyFields "Succesfully authenticated." +// @Failure 400 {object} utils.HTTPMessage "User is not registered." +// @Failure 401 {object} utils.HTTPMessage "JWT session token invalid." +// @Failure 500 {object} utils.HTTPMessage "Error parsing JWT string." +// +// @Security JWT +// +// @Router /profile [get] +func FetchProfile(w http.ResponseWriter, r *http.Request) { + app := r.Context().Value(middleware.APP_CTX_KEY).(*middleware.App) + db := app.Db + + username := r.Context().Value(middleware.LOGIN_CTX_USERNAME_KEY).(string) + + // Check if the student already exists in the db + student := models.Student{} + tx := db. + Table("students"). + Where("username = ?", username). + First(&student) + + if tx.Error != nil && tx.Error != gorm.ErrRecordNotFound { + utils.LogErrAndRespond(r, w, tx.Error, "Database error.", http.StatusInternalServerError) + return + } + + student_exists := student.Username == username + if student_exists { + utils.RespondWithJson(r, w, ProfileResBodyFields{ + Username: student.Username, + Name: student.Name, + Email: student.Email, + Type: "student", + }) + return + } + + // Check if a mentor of the same username exists + mentor := models.Mentor{} + tx = db. + Table("mentors"). + Where("username = ?", username). + First(&mentor) + if tx.Error != nil && tx.Error != gorm.ErrRecordNotFound { + utils.LogErrAndRespond(r, w, tx.Error, "Database error.", http.StatusInternalServerError) + return + } + mentor_exists := mentor.Username == username + + if mentor_exists { + utils.RespondWithJson(r, w, ProfileResBodyFields{ + Username: mentor.Username, + Name: mentor.Name, + Email: mentor.Email, + Type: "mentor", + }) + return + } + + utils.RespondWithHTTPMessage(r, w, http.StatusBadRequest, "User is not registered.") +} diff --git a/controllers/student.go b/controllers/student.go index 420ad034..b1948b01 100644 --- a/controllers/student.go +++ b/controllers/student.go @@ -100,7 +100,7 @@ func RegisterStudent(w http.ResponseWriter, r *http.Request) { First(&student) if tx.Error != nil && tx.Error != gorm.ErrRecordNotFound { - utils.LogErrAndRespond(r, w, err, "Database error.", http.StatusInternalServerError) + utils.LogErrAndRespond(r, w, tx.Error, "Database error.", http.StatusInternalServerError) return } diff --git a/middleware/login.go b/middleware/login.go index 67dbde30..0134cde7 100644 --- a/middleware/login.go +++ b/middleware/login.go @@ -29,6 +29,11 @@ func WithLogin(inner http.HandlerFunc) http.HandlerFunc { return } + if err == utils.ErrJwtTokenExpired { + utils.LogErrAndRespond(r, w, err, "Error: JWT session token expired.", http.StatusUnauthorized) + return + } + utils.LogErrAndRespond(r, w, err, "Error parsing JWT string.", http.StatusInternalServerError) return } diff --git a/server/routes.go b/server/routes.go index a2dd202e..0968b3b0 100644 --- a/server/routes.go +++ b/server/routes.go @@ -28,6 +28,12 @@ func getRoutes(app *middleware.App) []Route { "/oauth/", middleware.WrapApp(app, controllers.OAuth), }, + { + "Profile", + "GET", + "/profile/", + middleware.WithLogin(middleware.WrapApp(app, controllers.FetchProfile)), + }, { "Fetch Student Details", "GET", @@ -40,12 +46,12 @@ func getRoutes(app *middleware.App) []Route { "/mentor/", middleware.WithLogin(middleware.WrapApp(app, controllers.GetMentorDetails)), }, - { - "Student Registration", - "POST", - "/student/form/", - middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterStudent)), - }, + // { + // "Student Registration", + // "POST", + // "/student/form/", + // middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterStudent)), + // }, { "Update Student Details", "PUT", @@ -64,12 +70,12 @@ func getRoutes(app *middleware.App) []Route { "/student/dashboard/", middleware.WithLogin(middleware.WrapApp(app, controllers.FetchStudentDashboard)), }, - { - "Mentor Registration", - "POST", - "/mentor/form/", - middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterMentor)), - }, + // { + // "Mentor Registration", + // "POST", + // "/mentor/form/", + // middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterMentor)), + // }, { "Update Mentor Details", "PUT", @@ -100,12 +106,12 @@ func getRoutes(app *middleware.App) []Route { "/healthcheck/ping/", controllers.Ping, }, - { - "Project Registration", - "POST", - "/project/", - middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterProject)), - }, + // { + // "Project Registration", + // "POST", + // "/project/", + // middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterProject)), + // }, { "Fetch All Projects", "GET", diff --git a/utils/jwt.go b/utils/jwt.go index cb145159..86679af3 100644 --- a/utils/jwt.go +++ b/utils/jwt.go @@ -2,6 +2,7 @@ package utils import ( "errors" + "fmt" "os" "strconv" "time" @@ -11,6 +12,7 @@ import ( ) var ErrJwtSecretKeyNotFound = errors.New("ERROR: JWT SECRET KEY NOT FOUND") +var ErrJwtTokenExpired = errors.New("ERROR: JWT TOKEN EXPIRED") var ErrJwtTokenInvalid = errors.New("ERROR: JWT TOKEN INVALID") func getJwtKey() (string, error) { @@ -46,6 +48,10 @@ func ParseLoginJwtString(tokenString string) (*jwt.Token, *LoginJwtClaims, error var loginClaims = LoginJwtClaims{} token, err := jwt.ParseWithClaims(tokenString, &loginClaims, jwtKeyFunc) + if err.Error() == fmt.Sprintf("%s: %s", jwt.ErrTokenInvalidClaims.Error(), jwt.ErrTokenExpired.Error()) { + return nil, nil, ErrJwtTokenExpired + } + if err != nil { return nil, nil, err } @@ -66,7 +72,7 @@ func GenerateLoginJwtString(loginJwtFields LoginJwtFields) (string, error) { if err != nil { // Default of 30 days - jwtValidityTime = 30 * 24 + jwtValidityTime = 0 log.Warn().Msgf("Could not parse JWT validity time from the environment. Set to default of %d hours.", jwtValidityTime) }