Exemplo n.º 1
0
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
	}
}
Exemplo n.º 2
0
func handleViewStagingRecomms(resp http.ResponseWriter, req *http.Request) {
	user_id, _ := public.GetSessionUserId(req)

	stagingDb := public.GetNewStagingDatabase()
	defer stagingDb.Session.Close()

	recomms := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)
	q := recomms.Find(bson.M{
		"recommender": user_id,
	})
	var result []public.RecommView
	recomm_item := db.RecommEntity{}
	it := q.Iter()
	for it.Next(&recomm_item) {

		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_item.Attachment), expireTime)
		}

		result = append(result, public.RecommView{
			Hash:         recomm_item.Hash,
			ApplyUser:    recomm_item.ApplyUser,
			Topic:        recomm_item.Topic,
			LastModified: recomm_item.LastModified,
			Content:      recomm_item.Content,
			Attachment:   signed_url,
		})
	}

	public.ResponseOkAsJson(resp, &result)
}
Exemplo n.º 3
0
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)
	}
}
Exemplo n.º 4
0
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)
	}
}
Exemplo n.º 5
0
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)
}
Exemplo n.º 6
0
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",
		})
	}
}
Exemplo n.º 7
0
func getUserRecomms(resp http.ResponseWriter, req *http.Request) {
	user_id, _ := public.GetSessionUserId(req)

	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	forms := appDb.C(public.APPLICATION_DB_FORM_COLLECTION)
	q := forms.Find(bson.M{"ownerid": user_id}).Sort("-timestamp")
	it := q.Iter()

	form := db.ApplicationForm{}
	var recommList []public.RecommResult
	topicMap := make(map[public.TopicId]bool)
	for it.Next(&form) {
		if _, exist := topicMap[form.Topic]; exist {
			//Skip
			continue
		}

		recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)

		for _, h := range form.Recommendations {
			//Transform recommendation from hash to structures
			q := recomm.Find(bson.M{
				"hash": h,
			})

			if n, e := q.Count(); e == nil && n > 0 {
				r := db.Recomm{}
				if e := q.One(&r); e == nil {
					r := public.RecommResult{
						Recommender: r.Recommender,
						ApplyUser:   r.ApplyUser,
						Done:        r.Submitted,
						Hash:        h,
					}
					recommList = append(recommList, r)
				}
			}
		}

		topicMap[form.Topic] = true
	}

	public.ResponseOkAsJson(resp, &recommList)
}
Exemplo n.º 8
0
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",
		})
	}
}
Exemplo n.º 9
0
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,
	})
}
Exemplo n.º 10
0
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)
	}
}
Exemplo n.º 11
0
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)
	}
}
Exemplo n.º 12
0
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",
		})
	}
}
Exemplo n.º 13
0
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",
	})
}
Exemplo n.º 14
0
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)
	}
}
Exemplo n.º 15
0
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)
}
Exemplo n.º 16
0
/**
	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)
	}
}
Exemplo n.º 17
0
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",
				})
			}
		*/
	}
}
Exemplo n.º 18
0
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",
		})
	}
}
Exemplo n.º 19
0
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)
			}
		}
	}
}
Exemplo n.º 20
0
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
	}
}
Exemplo n.º 21
0
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)
}
Exemplo n.º 22
0
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)
	}
}
Exemplo n.º 23
0
func handleApplicationStatus(resp http.ResponseWriter, req *http.Request) {
	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	appC := appDb.C(public.APPLICATION_DB_FORM_COLLECTION)
	q := appC.Find(bson.M{})

	result := resultAppStatus{
		TotalApplicationNum: 0,
		TopicsNum:           make([]int, len(TOPICS), len(TOPICS)),

		AccountNum:         0,
		AccountNotApplyNum: 0,
	}
	form := db.ApplicationForm{}
	it := q.Iter()
	for it.Next(&form) {
		result.TotalApplicationNum++

		switch uint(form.Topic) {
		case 0:
			result.TopicsNum[0] += 1
			break

		case 1:
			result.TopicsNum[1] += 1
			break

		case 2:
			result.TopicsNum[2] += 1
			break

		case 3:
			result.TopicsNum[3] += 1
			break

		case 4:
			result.TopicsNum[4] += 1
			break
		}
	}

	userDb := public.GetNewUserDatabase()
	defer userDb.Session.Close()

	profileC := userDb.C(USER_DB_PROFILE_COLLECTION)
	q = profileC.Find(bson.M{})
	it = q.Iter()

	userResult := db.User{}
	for it.Next(&userResult) {
		result.AccountNum += 1

		appQ := appC.Find(bson.M{
			"ownerid": userResult.Id,
		})
		if n, _ := appQ.Count(); n < 1 {
			result.AccountNotApplyNum += 1
		}
	}

	public.ResponseOkAsJson(resp, &result)
}