func handleGMRecommsResend(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) hash := vars["recommHash"] appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := recomm.Find(bson.M{ "hash": hash, }) recommObj := db.Recomm{} if err := q.One(&recommObj); err != nil || len(hash) <= 0 { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "Error", Description: "No Such page", }) return } url := "https://application.nthuaplus.org/recomm.html?hash=" + hash if e := public.SendMail(recommObj.Recommender.Email, recommObj.ApplyUser, url); e != nil { public.LogE.Printf("Error sending email: %s\n", e.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", }) } else { public.ResponseOkAsJson(resp, nil) } }
func removeStagingRecomm(resp http.ResponseWriter, req *http.Request) { user_id, _ := public.GetSessionUserId(req) vars := mux.Vars(req) hash := vars["hash"] stagingDb := public.GetNewStagingDatabase() defer stagingDb.Session.Close() recomm := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := recomm.Find(bson.M{ "hash": hash, "recommender": user_id, }) recomm_result := db.RecommEntity{} if e := q.One(&recomm_result); e != nil { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "No such recomm entry", }) return } if e := recomm.RemoveId(recomm_result.Id); e != nil { public.LogE.Printf("Remove recomm entity failed: %s\n", e.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Remove recomm failed", }) } else { public.ResponseOkAsJson(resp, nil) } }
func gmMockWrapper(resp http.ResponseWriter, req *http.Request, handler http.HandlerFunc) { email := req.URL.Query().Get("email") if len(email) <= 0 { public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Need email", }) return } userDb := public.GetNewUserDatabase() defer userDb.Session.Close() profiles := userDb.C(USER_DB_PROFILE_COLLECTION) q := profiles.Find(bson.M{"email": email}) user := db.User{} if e := q.One(&user); e != nil { public.LogE.Printf("Get controlled user failed: %s\n", e.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Need email", }) return } req.Header.Set(public.GM_PERMITTED_HEADER_KEY, user.Id.Hex()) handler(resp, req) }
func handleInspectStagingRecomm(resp http.ResponseWriter, req *http.Request) { user_perm, _ := public.GetSessionUserPermission(req) if !user_perm.ContainsPermission(public.USER_PERMISSION_RECOMM) { public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{ Message: "Not Recommender", }) return } switch strings.ToLower(req.Method) { case "get": viewStagingRecomm(resp, req) break case "post": editStagingRecomm(resp, req) break case "put": editStagingRecomm(resp, req) break case "delete": removeStagingRecomm(resp, req) break default: public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "No such http method", }) } }
func handleReviewLogin(resp http.ResponseWriter, req *http.Request) { email := public.EmailFilter(req.FormValue("email")) password := req.FormValue("password") if len(email) <= 0 || len(password) <= 0 { r := public.SimpleResult{ Message: "Error", Description: "Incorrect email or password", } public.ResponseStatusAsJson(resp, 403, &r) return } //Check login status if _, err := public.GetSessionReviewerId(req); err == nil { r := public.SimpleResult{ Message: "Already Login", Description: email, } public.ResponseOkAsJson(resp, &r) return } reviewerDb := public.GetNewReviewerDatabase() defer reviewerDb.Session.Close() profiles := reviewerDb.C(REVIEWER_DB_PROFILE_COLLECTION) q := profiles.Find(bson.M{"baseprofile.email": email}) reviewer := db.Reviewer{} if q.One(&reviewer) == nil { //Check password if bcrypt.CompareHashAndPassword([]byte(reviewer.BaseProfile.AuthInfo.BcyptHash), []byte(password)) != nil { r := public.SimpleResult{ Message: "Error", Description: "Incorrect email or password", } public.ResponseStatusAsJson(resp, 403, &r) return } if err := public.SetReviewerSessionValue(req, resp, public.REVIEWER_ID_SESSION_KEY, reviewer.Id.Hex()); err != nil { public.LogE.Printf("Error setting session user id: %s\n", err.Error()) } r := public.SimpleResult{ Message: "Login Successed", Description: email, } public.ResponseOkAsJson(resp, &r) } else { r := public.SimpleResult{ Message: "Error", Description: "Incorrect email or password", } public.ResponseStatusAsJson(resp, 403, &r) return } }
func handleSubmitRecomm(resp http.ResponseWriter, req *http.Request) { user_id, _ := public.GetSessionUserId(req) user_perm, _ := public.GetSessionUserPermission(req) vars := mux.Vars(req) hash_str := vars["hash"] stagingDb := public.GetNewStagingDatabase() defer stagingDb.Session.Close() staging_recomm := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := staging_recomm.Find(bson.M{ "hash": hash_str, }) recomm_result := db.RecommEntity{} if e := q.One(&recomm_result); e != nil { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "No such recomm entity", }) return } // Permission check if recomm_result.Recommender != user_id && user_perm != public.USER_PERMISSION_GM { public.ResponseStatusAsJson(resp, 403, nil) return } // Migrate from staging db to application db staging_recomm.RemoveId(recomm_result.Id) appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) new_recomm := recomm_result new_recomm.Id = bson.NewObjectId() new_recomm.LastModified = time.Now() if e := recomm.Insert(new_recomm); e != nil { public.LogE.Printf("Error migrating recomm from staging db to application db: %s\n", e.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Submit failed", }) } }
func handleBulletinNotes(resp http.ResponseWriter, req *http.Request) { miscDb := public.GetNewMiscDatabase() defer miscDb.Session.Close() bulletin := miscDb.C(MISC_DB_BULLETIN_COLLECTION) q := bulletin.Find(bson.M{}) if _, e := q.Count(); e != nil { public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", Description: "Failed fetching bulletin notes", }) return } var results []bulletinNoteResult it := q.Iter() result := db.BulletinNote{} for it.Next(&result) { results = append(results, bulletinNoteResult{ Title: result.Title, Content: result.Content, TimeStamp: result.TimeStamp, }) } public.ResponseOkAsJson(resp, &results) }
func editStagingRecomm(resp http.ResponseWriter, req *http.Request) { user_id, _ := public.GetSessionUserId(req) vars := mux.Vars(req) hash := vars["hash"] stagingDb := public.GetNewStagingDatabase() defer stagingDb.Session.Close() recomm := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := recomm.Find(bson.M{ "hash": hash, "recommender": user_id, }) recomm_result := db.RecommEntity{} if e := q.One(&recomm_result); e != nil { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "No such recomm entry", }) return } content := req.FormValue("content") attachment := req.FormValue("attachment") if len(content) > 0 { recomm_result.Content = content recomm_result.LastModified = time.Now() } if len(attachment) > 0 { recomm_result.Attachment = public.FileStoragePath(attachment) recomm_result.LastModified = time.Now() } if e := recomm.UpdateId(recomm_result.Id, &recomm_result); e != nil { public.LogE.Printf("Update recomm entity failed: %s\n", e.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Update recomm failed", }) } else { public.ResponseOkAsJson(resp, nil) } }
func handleViewRecomm(resp http.ResponseWriter, req *http.Request) { user_id, _ := public.GetSessionUserId(req) user_perm, _ := public.GetSessionUserPermission(req) vars := mux.Vars(req) hash_str := vars["hash"] appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := recomm.Find(bson.M{ "hash": hash_str, }) recomm_result := db.RecommEntity{} if e := q.One(&recomm_result); e != nil { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "No such recomm entity", }) return } // Permission check if recomm_result.Recommender != user_id && user_perm != public.USER_PERMISSION_GM { public.ResponseStatusAsJson(resp, 403, nil) return } signed_url := "" if client, err := storage.GetNewStorageClient(); err == nil { expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour signed_url, _ = client.GetNewSignedURL(string(recomm_result.Attachment), expireTime) } public.ResponseOkAsJson(resp, &public.RecommView{ Hash: recomm_result.Hash, ApplyUser: recomm_result.ApplyUser, Topic: recomm_result.Topic, LastModified: recomm_result.LastModified, Content: recomm_result.Content, Attachment: signed_url, }) }
func handleFormFileUpload(resp http.ResponseWriter, req *http.Request) { if f, h, e := req.FormFile("file"); e == nil && f != nil && h != nil { if objName, err := saveFile(h, f); err == nil { public.ResponseOkAsJson(resp, &public.SimpleResult{ Message: "Success", Description: objName, }) } else { public.LogE.Printf("Error storing file: %s\n", err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", }) } } else { public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", }) } }
func handleQueryAccount(resp http.ResponseWriter, req *http.Request) { email := req.URL.Query().Get("email") if len(email) > 0 { userDb := public.GetNewUserDatabase() defer userDb.Session.Close() profiles := userDb.C(USER_DB_PROFILE_COLLECTION) q := profiles.Find(bson.M{"email": email}) user := db.User{} if e := q.One(&user); e == nil { //GM can get more information public.ResponseOkAsJson(resp, &user) } else { public.ResponseStatusAsJson(resp, 404, nil) } } else { public.ResponseStatusAsJson(resp, 404, nil) } }
func handleRecommDoorBell(resp http.ResponseWriter, req *http.Request) { _, user_err := public.GetSessionUserId(req) if user_err != nil { public.ResponseStatusAsJson(resp, 403, nil) return } user_perm, _ := public.GetSessionUserPermission(req) if !user_perm.ContainsPermission(public.USER_PERMISSION_RECOMM) { public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{ Message: "Not Recommender", }) return } public.ResponseOkAsJson(resp, &public.SimpleResult{ Message: "Ok", }) }
func handleRecommFileUpload(resp http.ResponseWriter, req *http.Request) { user_perm, _ := public.GetSessionUserPermission(req) if user_perm.ContainsPermission(public.USER_PERMISSION_RECOMM) { handleFormFileUpload(resp, req) } else { public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{ Message: "Not Recommender", }) } }
func handleReviewerLogout(resp http.ResponseWriter, req *http.Request) { if err := public.SetReviewerSessionValue(req, resp, public.REVIEWER_ID_SESSION_KEY, nil); err != nil { public.LogE.Printf("Logout Failed: %s\n", err.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", Description: "Logout Failed", }) } else { public.ResponseOkAsJson(resp, &public.SimpleResult{ Message: "Logout Success", }) } }
func handleInspectRecomm(resp http.ResponseWriter, req *http.Request) { user_perm, _ := public.GetSessionUserPermission(req) if !user_perm.ContainsPermission(public.USER_PERMISSION_RECOMM) { public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{ Message: "Not Recommender", }) return } switch strings.ToLower(req.Method) { case "get": { // View formal recommendation handleViewRecomm(resp, req) break } case "put": { // Submit as formal recommendation handleSubmitRecomm(resp, req) break } case "post": { // Submit as formal recommendation handleSubmitRecomm(resp, req) break } default: public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "No such http method", }) } }
func handleLogout(resp http.ResponseWriter, req *http.Request) { if e := public.SetUserSessionValue(req, resp, public.USER_PERMISSION_SESSION_KEY, nil); e != nil { public.LogE.Printf("Error cleaning session user permission: %s\n", e.Error()) } if err := public.SetUserSessionValue(req, resp, public.USER_ID_SESSION_KEY, nil); err != nil { public.LogE.Printf("Logout Failed: %s\n", err.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", Description: "Logout Failed", }) } else { public.ResponseOkAsJson(resp, &public.SimpleResult{ Message: "Logout Success", }) } }
func handleRecommendationUpload(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) hash := vars["hash"] appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := recomm.Find(bson.M{ "hash": hash, }) if n, err := q.Count(); err != nil || n <= 0 || len(hash) <= 0 { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "Error", Description: "No Such page", }) return } handleFormFileUpload(resp, req) }
func handleReviewerProfile(resp http.ResponseWriter, req *http.Request) { userId, _ := public.GetSessionReviewerId(req) reviewerDb := public.GetNewReviewerDatabase() defer reviewerDb.Session.Close() profile := reviewerDb.C(REVIEWER_DB_PROFILE_COLLECTION) q := profile.FindId(userId) if c, err := q.Count(); c == 0 || err != nil { r := public.SimpleResult{ Message: "Error", Description: "User Not Found", } public.ResponseStatusAsJson(resp, 500, &r) } else { reviewer := db.Reviewer{} q.One(&reviewer) r := public.ReviewerProfile{ Email: reviewer.BaseProfile.Email, Username: reviewer.BaseProfile.Username, FormalId: reviewer.BaseProfile.FormalId, Topics: reviewer.Topics, Permissions: reviewer.Permissions, } if client, err := storage.GetNewStorageClient(); err == nil && len(reviewer.BaseProfile.Thumbnail) > 0 { defer client.Close() expire := time.Now().Add(time.Duration(12) * time.Hour) if r.Thumbnail, err = client.GetNewSignedURL(reviewer.BaseProfile.Thumbnail, expire); err != nil { r.Thumbnail = "" } } public.ResponseOkAsJson(resp, &r) } }
func handleReviewerRecommView(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) hashStr := vars["recommHash"] appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := recomm.Find(bson.M{ "hash": hashStr, }) recommInstance := db.Recomm{} if err := q.One(&recommInstance); err != nil { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "Error", Description: "Hash not found", }) return } recommResult := reviewerRecommResult{ Content: recommInstance.Content, } if len(recommInstance.Attachment) > 0 { //Create temp url if client, err := storage.GetNewStorageClient(); err == nil { expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour if obj, e := client.GetNewSignedURL(recommInstance.Attachment, expireTime); e == nil { recommResult.AttachmentUrl = obj } else { public.LogE.Println("Get object error: " + e.Error()) } } } public.ResponseOkAsJson(resp, &recommResult) }
/** POST/PUT: submit GET(or else): Get info **/ func handleRecommendation(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) hash := vars["hash"] appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION) q := recomm.Find(bson.M{ "hash": hash, }) if n, err := q.Count(); err != nil || n <= 0 || len(hash) <= 0 { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "Error", Description: "No Such page", }) return } result := db.Recomm{} if err := q.One(&result); err != nil { public.LogE.Printf("Error fetching recommendation data for %s\n", hash) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", }) return } if req.Method == "POST" || req.Method == "PUT" { //Submit if result.Submitted { //Already submitted public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", }) return } textContent := req.FormValue("textContent") fileObj := req.FormValue("fileObj") result.Content = textContent result.Attachment = fileObj result.Submitted = true err := recomm.UpdateId(result.Id, &result) if err != nil { public.LogE.Println("Update recommendation fields error: " + err.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", }) } else { public.ResponseOkAsJson(resp, &public.SimpleResult{ Message: "Success", }) } } else { //Get info displayResult := public.RecommResult{ Recommender: result.Recommender, ApplyUser: result.ApplyUser, Done: result.Submitted, } public.ResponseOkAsJson(resp, &displayResult) } }
func handleFormView(resp http.ResponseWriter, req *http.Request) { userId, _ := public.GetSessionUserId(req) appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() forms := appDb.C(public.APPLICATION_DB_FORM_COLLECTION) q := forms.Find(bson.M{ "ownerid": userId, }) if _, e := q.Count(); e != nil { public.LogE.Println("Query user form error: " + e.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", }) } else { var formResults []exportApplication form := db.ApplicationForm{} it := q.Iter() for it.Next(&form) { exportForm := exportApplication{} (&exportForm).fromDbApplication(&form, false) formResults = append(formResults, exportForm) } public.ResponseOkAsJson(resp, formResults) /* if client, err := storage.GetNewStorageClient(); err == nil { defer client.Close() var formResults []db.ApplicationForm form := db.ApplicationForm{} it := q.Iter() expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour for it.Next(&form) { form.Id = bson.ObjectId("") form.OwnerId = bson.ObjectId("") //Handle the file objects if obj,e := client.GetNewSignedURL(form.ResearchPlan, expireTime); e == nil { form.ResearchPlan = obj }else{ public.LogE.Println("Get object error: " + e.Error()) } if obj,e := client.GetNewSignedURL(form.Transcript, expireTime); e == nil { form.Transcript = obj }else{ public.LogE.Println("Get object error: " + e.Error()) } if len(form.Others) > 0 { if obj,e := client.GetNewSignedURL(form.Others, expireTime); e == nil { form.Others = obj }else{ public.LogE.Println("Get object error: " + e.Error()) } } formResults = append(formResults, form) } public.ResponseOkAsJson(resp, formResults) }else{ public.LogE.Println("Error getting storage client: " + err.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", }) } */ } }
func handleGMLogin(resp http.ResponseWriter, req *http.Request) { email := public.EmailFilter(req.FormValue("email")) password := req.FormValue("password") if len(email) <= 0 || len(password) <= 0 { r := public.SimpleResult{ Message: "Error", Description: "Incorrect email or password", } public.ResponseStatusAsJson(resp, 403, &r) return } //Check login status if _, err := public.GetSessionGMId(req); err == nil { r := public.SimpleResult{ Message: "Already Login", Description: email, } public.ResponseOkAsJson(resp, &r) return } userDb := public.GetNewUserDatabase() defer userDb.Session.Close() profiles := userDb.C(USER_DB_PROFILE_COLLECTION) q := profiles.Find(bson.M{"email": email}) user := db.User{} if q.One(&user) == nil { //Check password if bcrypt.CompareHashAndPassword([]byte(user.AuthInfo.BcyptHash), []byte(password)) != nil { r := public.SimpleResult{ Message: "Error", Description: "Incorrect email or password", } public.ResponseStatusAsJson(resp, 403, &r) return } //Check whether is GM admin := userDb.C(USER_DB_GM_COLLECTION) admin_q := admin.Find(bson.M{"userid": user.Id}) if n, _ := admin_q.Count(); n <= 0 { //Not GM public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{ Message: "Error", Description: "Not GM, YOU SHALL NOT PASS", }) return } if err := public.SetGMSessionValue(req, resp, public.GM_ID_SESSION_KEY, user.Id.Hex()); err != nil { public.LogE.Printf("Error setting session user id: %s\n", err.Error()) } r := public.SimpleResult{ Message: "Login Successed", Description: email, } public.ResponseOkAsJson(resp, &r) } else { r := public.SimpleResult{ Message: "Error", Description: "Incorrect email or password", } public.ResponseStatusAsJson(resp, 403, &r) return } }
func handleFormSubmit(resp http.ResponseWriter, req *http.Request) { ownerId, _ := public.GetSessionUserId(req) form := db.ApplicationForm{ OwnerId: ownerId, Timestamp: time.Now(), Name: req.FormValue("name"), School: req.FormValue("school"), Department: req.FormValue("department"), Email: req.FormValue("email"), Phone: req.FormValue("phoneNumber"), Address: req.FormValue("address"), FormalId: req.FormValue("formalId"), //TODO: Verify Teacher: req.FormValue("teacher"), ResearchArea: req.FormValue("researchArea"), RelatedSkills: req.FormValue("relatedSkills"), ResearchPlan: req.FormValue("researchPlan"), Transcript: req.FormValue("transcript"), Others: req.FormValue("others"), } if topic, err := parseTopic(req); err != nil { public.LogE.Println(err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong form format", }) return } else { form.Topic = public.TopicId(topic) } if grade, err := parseSchoolGrade(req); err != nil { public.LogE.Println(err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong form format", }) return } else { form.SchoolGrade = grade } if birthday, err := parseBirthday(req); err != nil { public.LogE.Println(err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong form format", }) return } else { form.Birthday = birthday } if classes, err := parseStudiedClasses(req); err != nil { public.LogE.Println(err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong form format", }) return } else { form.ClassHistories = classes } if languages, err := parseLanguageAbility(req); err != nil { public.LogE.Println(err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong form format", }) return } else { form.LangAbilities = languages } if average, ranking, err := parseAcademicGrades(req); err != nil { public.LogE.Println(err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong form format", }) return } else { form.AcademicGrade = db.AcademicGrade{ Average: average, Rank: ranking, } } if letters, err := parseRecommendationLetters(req); err != nil { public.LogE.Println(err.Error()) public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong form format", }) return } else { form.Recommendations = handleRecommendationLetters(letters, form.Name, form.Email) } appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() forms := appDb.C(public.APPLICATION_DB_FORM_COLLECTION) if err := forms.Insert(&form); err != nil { public.LogE.Printf("Insert new form error: " + err.Error()) public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{ Message: "Error", Description: "Add Form Error", }) } else { public.ResponseOkAsJson(resp, &public.SimpleResult{ Message: "Success", }) } }
func handleReviewRegister(resp http.ResponseWriter, req *http.Request) { email := public.EmailFilter(req.FormValue("email")) username := req.FormValue("username") formalId := req.FormValue("formalId") password := req.FormValue("password") //Verify values first var errorFields []string if len(email) <= 0 { errorFields = append(errorFields, "Email") } if len(username) <= 0 { errorFields = append(errorFields, "Username") } if len(password) <= 0 { errorFields = append(errorFields, "Password") } if len(formalId) != 10 { errorFields = append(errorFields, "FormalId") } else { if match, _ := regexp.MatchString("[A-Z][12][0-9]{8}", formalId); match { if !public.FormalIdVerifier(formalId) { errorFields = append(errorFields, "FormalId") } } else { errorFields = append(errorFields, "FormalId") } } if len(errorFields) > 0 { r := public.SimpleResult{ Message: "Error", Description: "Wrong Format: " + strings.Join(errorFields, ","), } public.ResponseStatusAsJson(resp, 400, &r) } else { //Get thumbnail if exist var thumb multipart.File = nil var thumbHeader *multipart.FileHeader = nil if f, h, err := req.FormFile("thumbnail"); err == nil && f != nil { thumb = f thumbHeader = h } reviewerDb := public.GetNewReviewerDatabase() defer reviewerDb.Session.Close() profile := reviewerDb.C(REVIEWER_DB_PROFILE_COLLECTION) q := profile.Find(bson.M{"baseprofile.email": email}) if cnt, err := q.Count(); cnt != 0 || err != nil { if err != nil { r := public.SimpleResult{ Message: "Error", Description: err.Error(), } public.ResponseStatusAsJson(resp, 500, &r) } else { //User exist r := public.SimpleResult{ Message: "Error", Description: "User Exists", } public.ResponseStatusAsJson(resp, 400, &r) } } else { baseUser := db.User{ Email: email, Username: username, FormalId: formalId, } hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) baseUser.AuthInfo = db.UserAuth{ BcryptCost: bcrypt.DefaultCost, BcyptHash: string(hash), } //Store thumbnail if thumb != nil { defer thumb.Close() if client, err := storage.GetNewStorageClient(); err == nil { h := public.NewHashString() objName := storage.PathJoin(storage.THUMBNAILS_FOLDER_NAME, h) //Determine the extension var ext string = "" if thumbHeader != nil { if segs := strings.Split(thumbHeader.Filename, "."); len(segs) > 1 { ext = "." + segs[len(segs)-1] objName = (objName + ext) } } obj := client.GetDefaultBucket().Object(objName) if attr, _ := obj.Attrs(client.Ctx); attr != nil { if mimeStr := mime.TypeByExtension(ext); len(mimeStr) > 0 { attr.ContentType = mimeStr } } objWriter := obj.NewWriter(client.Ctx) defer objWriter.Close() _, err = io.Copy(objWriter, thumb) if err == nil { baseUser.Thumbnail = objName } } } newUser := db.Reviewer{ BaseProfile: baseUser, } if err := profile.Insert(&newUser); err != nil { r := public.SimpleResult{ Message: "Register Failed", Description: err.Error(), } public.ResponseStatusAsJson(resp, 400, &r) } else { if err := public.SetReviewerSessionValue(req, resp, public.REVIEWER_ID_SESSION_KEY, newUser.Id.Hex()); err != nil { public.LogE.Printf("Error setting session user id: %s\n", err.Error()) } r := public.SimpleResult{ Message: "Register Successed", Description: email, } public.ResponseOkAsJson(resp, &r) } } } }
func handleSubmitReview(resp http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) appHash := vars["appHash"] appId, ok := exportAppHashMap[appHash] if !ok { public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{ Message: "Error", Description: "Hash not found", }) return } delete(exportAppHashMap, appHash) userId, _ := public.GetSessionReviewerId(req) reviewDb := public.GetNewReviewerDatabase() defer reviewDb.Session.Close() userDb := public.GetNewUserDatabase() defer userDb.Session.Close() results := reviewDb.C(REVIEWER_DB_RESULT_COLLECTION) profiles := reviewDb.C(REVIEWER_DB_PROFILE_COLLECTION) //See if exist //Re-submit is not allowed q := results.Find(bson.M{ "applicationid": appId, "reviewerid": userId, }) if n, _ := q.Count(); n > 0 { public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{ Message: "Error", Description: "Data exist", }) return } //Get user profile info q = profiles.FindId(userId) user := db.User{} if err := q.One(&user); err != nil { public.ResponseStatusAsJson(resp, 404, nil) return } //Get review json data reviewData := public.ReviewResponse{} body, _ := ioutil.ReadAll(req.Body) if err := json.Unmarshal(body, &reviewData); err != nil { public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{ Message: "Error", Description: "Wrong review response", }) return } reviewResult := db.ReviewResult{ ApplicationId: appId, ReviewerId: userId, } (&reviewResult).CopyFromReviewResponse(reviewData) if err := results.Insert(&reviewResult); err != nil { public.LogE.Printf("Error inserting new review result: %s\n", err) } public.ResponseOkAsJson(resp, nil) }
func handleGetReviewApplications(resp http.ResponseWriter, req *http.Request) { userId, _ := public.GetSessionReviewerId(req) reviewerDb := public.GetNewReviewerDatabase() defer reviewerDb.Session.Close() profile := reviewerDb.C(REVIEWER_DB_PROFILE_COLLECTION) q := profile.FindId(userId) if c, err := q.Count(); c == 0 || err != nil { r := public.SimpleResult{ Message: "Error", Description: "User Not Found", } public.ResponseStatusAsJson(resp, 500, &r) } else { reviewer := db.Reviewer{} q.One(&reviewer) appDb := public.GetNewApplicationDatabase() defer appDb.Session.Close() forms := appDb.C(public.APPLICATION_DB_FORM_COLLECTION) results := reviewerDb.C(REVIEWER_DB_RESULT_COLLECTION) var exportApps []exportApplication for _, t := range reviewer.Topics { q := forms.Find(bson.M{ "topic": t, }).Sort("-timestamp") //From new to old //Remove the duplicate application //Keep the latest one ownerSet := make(map[bson.ObjectId]bool) it := q.Iter() appData := db.ApplicationForm{} for it.Next(&appData) { if _, ok := ownerSet[appData.OwnerId]; ok { //Exist duplicate application continue } //Check if reviewed q_r := results.Find(bson.M{ "applicationid": appData.Id, }) if n, _ := q_r.Count(); n > 0 { //Has reviewed continue } exportApp := exportApplication{} (&exportApp).fromDbApplication(&appData, true) exportApps = append(exportApps, exportApp) exportAppHashMap[exportApp.Hash] = appData.Id ownerSet[appData.OwnerId] = true } } //Output reviewed topics public.ResponseOkAsJson(resp, &exportApps) } }